lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
JavaScript
mit
18643eb18a70d775a466ffb74b30369e8113be39
0
jorix/OL-FeaturePopups,jorix/OL-FeaturePopups
// Create control and add some layers // ---------------------------------- var fpControl = new OpenLayers.Control.FeaturePopups({ // External div for list popups popupOptions: { list: { // Uses an existing div having an id 'divList' popupClass: 'divList' }, single: null // Show a list instead of single popup if the list // has only an item. }, boxSelectionOptions: {}, layers: [ [ // Uses: Templates for hover & select and safe selection sundialsLayer, {templates: { // hover: single & list hover: '${.name}', hoverList: '<b>${count}</b><br>${html}', hoverItem: '${.name}<br>', // select: single & list single: '<div><h2>${.name}</h2>${.description}</div>', item: '<li><a href="#" ${showPopup()}>${.name}</a></li>' }}], [ // Uses: Internationalized templates. sprintersLayer, {templates: { hover: '${.Name}', single: '${i18n("Name")}: ${.Name}<br>' + '${i18n("Country")}: ${.Country}<br>' + '${i18n("City")}: ${.City}<br>', item: '<li><a href="#" ${showPopup()}>${.Name}</a></li>' }}], [ // Uses: Templates as functions (only from hover-single and select-list) tasmaniaRoadsLayer, {templates: { hover: function(feature) { return 'Length: ' + Math.round(feature.geometry.getLength() / 10) / 100 + ' km'; }, item: function(feature) { return '<li>' + Math.round(feature.geometry.getLength() / 10) / 100 + ' km</li>'; } }}] ] }); map.addControl(fpControl); // Add a layer to the control using addLayer // ----------------------------------------- fpControl.addLayer( // poisLayer uses "fid", so by default SAFE_SELECTION uses "fid" (if it // exists) instead of "id". poisLayer, {templates: { hover: '${.title}', single: '<h2>${.title}</h2>${.description}', item: '<li><a href="#" ${showPopup()}>${.title}</a></li>' }} );
examples/feature-popups-external.js
// Create control and add some layers // ---------------------------------- var fpControl = new OpenLayers.Control.FeaturePopups({ // External div for list popups popupOptions: { list: { // Uses an existing div having an id 'divList' popupClass: 'divList' }, single: null // Show a list instead of single popup if the list // has only an item. } }, boxSelectionOptions: {}, layers: [ [ // Uses: Templates for hover & select and safe selection sundialsLayer, {templates: { // hover: single & list hover: '${.name}', hoverList: '<b>${count}</b><br>${html}', hoverItem: '${.name}<br>', // select: single & list single: '<div><h2>${.name}</h2>${.description}</div>', item: '<li><a href="#" ${showPopup()}>${.name}</a></li>' }}], [ // Uses: Internationalized templates. sprintersLayer, {templates: { hover: '${.Name}', single: '${i18n("Name")}: ${.Name}<br>' + '${i18n("Country")}: ${.Country}<br>' + '${i18n("City")}: ${.City}<br>', item: '<li><a href="#" ${showPopup()}>${.Name}</a></li>' }}], [ // Uses: Templates as functions (only from hover-single and select-list) tasmaniaRoadsLayer, {templates: { hover: function(feature) { return 'Length: ' + Math.round(feature.geometry.getLength() / 10) / 100 + ' km'; }, item: function(feature) { return '<li>' + Math.round(feature.geometry.getLength() / 10) / 100 + ' km</li>'; } }}] ] }); map.addControl(fpControl); // Add a layer to the control using addLayer // ----------------------------------------- fpControl.addLayer( // poisLayer uses "fid", so by default SAFE_SELECTION uses "fid" (if it // exists) instead of "id". poisLayer, {templates: { hover: '${.title}', single: '<h2>${.title}</h2>${.description}', item: '<li><a href="#" ${showPopup()}>${.title}</a></li>' }} );
Fix js typo.
examples/feature-popups-external.js
Fix js typo.
<ide><path>xamples/feature-popups-external.js <ide> }, <ide> single: null // Show a list instead of single popup if the list <ide> // has only an item. <del> } <ide> }, <ide> boxSelectionOptions: {}, <ide> layers: [
Java
apache-2.0
0ff227ff0acbfb27f86d5a81194616f085bc683b
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
package org.apache.lucene.analysis; import junit.framework.TestCase; import java.io.StringReader; public class TestISOLatin1AccentFilter extends TestCase { public void testU() throws Exception { TokenStream stream = new WhitespaceTokenizer(new StringReader("\u00FC")); ISOLatin1AccentFilter filter = new ISOLatin1AccentFilter(stream); Token token = filter.next(); assertEquals("u", token.termText); assertNull(filter.next()); } }
contrib/analyzers/src/test/org/apache/lucene/analysis/TestISOLatin1AccentFilter.java
package org.apache.lucene.analysis; import junit.framework.TestCase; import java.io.StringReader; public class TestISOLatin1AccentFilter extends TestCase { public void testU() throws Exception { TokenStream stream = new WhitespaceTokenizer(new StringReader("ü")); ISOLatin1AccentFilter filter = new ISOLatin1AccentFilter(stream); Token token = filter.next(); assertEquals("u", token.termText); assertNull(filter.next()); } }
switch dotted u character to use unicode value reference git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@160023 13f79535-47bb-0310-9956-ffa450edef68
contrib/analyzers/src/test/org/apache/lucene/analysis/TestISOLatin1AccentFilter.java
switch dotted u character to use unicode value reference
<ide><path>ontrib/analyzers/src/test/org/apache/lucene/analysis/TestISOLatin1AccentFilter.java <ide> <ide> public class TestISOLatin1AccentFilter extends TestCase { <ide> public void testU() throws Exception { <del> TokenStream stream = new WhitespaceTokenizer(new StringReader("ü")); <add> TokenStream stream = new WhitespaceTokenizer(new StringReader("\u00FC")); <ide> ISOLatin1AccentFilter filter = new ISOLatin1AccentFilter(stream); <ide> Token token = filter.next(); <ide> assertEquals("u", token.termText);
Java
apache-2.0
error: pathspec 'src/test/java/org/mapdb/issues/MailList_HeapReopen.java' did not match any file(s) known to git
9241f1efa1f3e70d608db161c2a3f34b25e45a0d
1
jankotek/MapDB,jankotek/MapDB,jankotek/mapdb,jankotek/mapdb
package org.mapdb.issues; import org.junit.Test; import org.mapdb.*; import java.util.concurrent.ConcurrentMap; import static org.junit.Assert.assertEquals; public class MailList_HeapReopen { @Test public void test(){ DB store = DBMaker.heapDB().make(); ConcurrentMap map = store.hashMap("map").createOrOpen(); map.put("fooKey","fooValue"); //get the map from store ConcurrentMap mapExisting = store.hashMap("map").createOrOpen(); assertEquals("fooValue",mapExisting.get("fooKey")); } }
src/test/java/org/mapdb/issues/MailList_HeapReopen.java
Add test case from mailing list
src/test/java/org/mapdb/issues/MailList_HeapReopen.java
Add test case from mailing list
<ide><path>rc/test/java/org/mapdb/issues/MailList_HeapReopen.java <add>package org.mapdb.issues; <add> <add>import org.junit.Test; <add>import org.mapdb.*; <add> <add>import java.util.concurrent.ConcurrentMap; <add> <add>import static org.junit.Assert.assertEquals; <add> <add>public class MailList_HeapReopen { <add> <add> @Test <add> public void test(){ <add> DB store = DBMaker.heapDB().make(); <add> <add> ConcurrentMap map = store.hashMap("map").createOrOpen(); <add> map.put("fooKey","fooValue"); <add> <add>//get the map from store <add> ConcurrentMap mapExisting = store.hashMap("map").createOrOpen(); <add> assertEquals("fooValue",mapExisting.get("fooKey")); <add> } <add>}
Java
apache-2.0
701451a197afbfd1fb4657fce9f432b59148cd3b
0
fabric8io/kubernetes-client,fabric8io/kubernetes-client,fabric8io/kubernetes-client
/** * Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.client.dsl.internal; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.kubernetes.api.model.DeleteOptions; import io.fabric8.kubernetes.api.model.DeletionPropagation; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.Preconditions; import io.fabric8.kubernetes.api.model.Status; import io.fabric8.kubernetes.api.model.StatusBuilder; import io.fabric8.kubernetes.api.model.autoscaling.v1.Scale; import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.base.PatchContext; import io.fabric8.kubernetes.client.dsl.base.PatchType; import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.client.http.HttpRequest; import io.fabric8.kubernetes.client.http.HttpResponse; import io.fabric8.kubernetes.client.internal.PatchUtils; import io.fabric8.kubernetes.client.internal.VersionUsageUtils; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.kubernetes.client.utils.internal.ExponentialBackoffIntervalCalculator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; public class OperationSupport { public static final String JSON = "application/json"; public static final String JSON_PATCH = "application/json-patch+json"; public static final String STRATEGIC_MERGE_JSON_PATCH = "application/strategic-merge-patch+json"; public static final String JSON_MERGE_PATCH = "application/merge-patch+json"; protected static final ObjectMapper JSON_MAPPER = Serialization.jsonMapper(); private static final Logger LOG = LoggerFactory.getLogger(OperationSupport.class); private static final String CLIENT_STATUS_FLAG = "CLIENT_STATUS_FLAG"; private static final int maxRetryIntervalExponent = 5; protected OperationContext context; protected final HttpClient httpClient; protected final Config config; protected final String resourceT; protected String namespace; protected String name; protected String apiGroupName; protected String apiGroupVersion; protected boolean dryRun; private final ExponentialBackoffIntervalCalculator retryIntervalCalculator; private final int requestRetryBackoffLimit; public OperationSupport(Client client) { this(new OperationContext().withClient(client)); } public OperationSupport(OperationContext ctx) { this.context = ctx; this.httpClient = ctx.getHttpClient(); this.config = ctx.getConfig(); this.resourceT = ctx.getPlural(); this.namespace = ctx.getNamespace(); this.name = ctx.getName(); this.apiGroupName = ctx.getApiGroupName(); this.dryRun = ctx.getDryRun(); if (Utils.isNotNullOrEmpty(ctx.getApiGroupVersion())) { this.apiGroupVersion = ctx.getApiGroupVersion(); } else if (ctx.getConfig() != null && Utils.isNotNullOrEmpty(ctx.getConfig().getApiVersion())) { this.apiGroupVersion = ctx.getConfig().getApiVersion(); } else { this.apiGroupVersion = "v1"; } final int requestRetryBackoffInterval; if (ctx.getConfig() != null) { requestRetryBackoffInterval = ctx.getConfig().getRequestRetryBackoffInterval(); this.requestRetryBackoffLimit = ctx.getConfig().getRequestRetryBackoffLimit(); } else { requestRetryBackoffInterval = Config.DEFAULT_REQUEST_RETRY_BACKOFFINTERVAL; this.requestRetryBackoffLimit = Config.DEFAULT_REQUEST_RETRY_BACKOFFLIMIT; } this.retryIntervalCalculator = new ExponentialBackoffIntervalCalculator(requestRetryBackoffInterval, maxRetryIntervalExponent); } public String getAPIGroupName() { return apiGroupName; } public String getAPIGroupVersion() { return apiGroupVersion; } public String getResourceT() { return resourceT; } public String getNamespace() { return namespace; } public String getName() { return name; } public boolean isResourceNamespaced() { return true; } public URL getRootUrl() { try { if (!Utils.isNullOrEmpty(apiGroupName)) { return new URL(URLUtils.join(config.getMasterUrl().toString(), "apis", apiGroupName, apiGroupVersion)); } return new URL(URLUtils.join(config.getMasterUrl().toString(), "api", apiGroupVersion)); } catch (MalformedURLException e) { throw KubernetesClientException.launderThrowable(e); } } public URL getNamespacedUrl(String namespace) throws MalformedURLException { URL requestUrl = getRootUrl(); if (!isResourceNamespaced()) { //if resource is not namespaced don't even bother to check the namespace. } else if (Utils.isNotNullOrEmpty(namespace)) { requestUrl = new URL(URLUtils.join(requestUrl.toString(), "namespaces", namespace)); } requestUrl = new URL(URLUtils.join(requestUrl.toString(), resourceT)); return requestUrl; } public URL getNamespacedUrl() throws MalformedURLException { return getNamespacedUrl(getNamespace()); } public URL getResourceUrl(String namespace, String name) throws MalformedURLException { return getResourceUrl(namespace, name, false); } public URL getResourceUrl(String namespace, String name, boolean status) throws MalformedURLException { if (name == null) { if (status) { throw new KubernetesClientException("name not specified for an operation requiring one."); } return getNamespacedUrl(namespace); } if (status) { return new URL(URLUtils.join(getNamespacedUrl(namespace).toString(), name, "status")); } return new URL(URLUtils.join(getNamespacedUrl(namespace).toString(), name)); } public URL getResourceUrl() throws MalformedURLException { if (name == null) { return getNamespacedUrl(); } return new URL(URLUtils.join(getNamespacedUrl().toString(), name)); } public URL getResourceURLForWriteOperation(URL resourceURL) throws MalformedURLException { if (dryRun) { return new URL(URLUtils.join(resourceURL.toString(), "?dryRun=All")); } return resourceURL; } public URL getResourceURLForPatchOperation(URL resourceUrl, PatchContext patchContext) throws MalformedURLException { if (patchContext != null) { String url = resourceUrl.toString(); if (patchContext.getForce() != null) { url = URLUtils.join(url, "?force=" + patchContext.getForce()); } if ((patchContext.getDryRun() != null && !patchContext.getDryRun().isEmpty()) || dryRun) { url = URLUtils.join(url, "?dryRun=All"); } String fieldManager = patchContext.getFieldManager(); if (fieldManager == null && patchContext.getPatchType() == PatchType.SERVER_SIDE_APPLY) { fieldManager = "fabric8"; } if (fieldManager != null) { url = URLUtils.join(url, "?fieldManager=" + fieldManager); } if (patchContext.getFieldValidation() != null) { url = URLUtils.join(url, "?fieldValidation=" + patchContext.getFieldValidation()); } return new URL(url); } return resourceUrl; } protected <T> T correctNamespace(T item) { if (!isResourceNamespaced() || this.context.isDefaultNamespace() || !(item instanceof HasMetadata)) { return item; } String itemNs = KubernetesResourceUtil.getNamespace((HasMetadata) item); if (Utils.isNotNullOrEmpty(namespace) && Utils.isNotNullOrEmpty(itemNs) && !namespace.equals(itemNs)) { item = Serialization.clone(item); KubernetesResourceUtil.setNamespace((HasMetadata) item, namespace); } return item; } protected <T> String checkNamespace(T item) { if (!isResourceNamespaced()) { return null; } String operationNs = getNamespace(); String itemNs = (item instanceof HasMetadata) ? KubernetesResourceUtil.getNamespace((HasMetadata) item) : null; if (Utils.isNullOrEmpty(operationNs) && Utils.isNullOrEmpty(itemNs)) { if (context.isDefaultNamespace()) { throw new KubernetesClientException( "namespace not specified for an operation requiring one and no default was found in the Config."); } throw new KubernetesClientException("namespace not specified for an operation requiring one."); } else if (!Utils.isNullOrEmpty(itemNs) && (Utils.isNullOrEmpty(operationNs) || this.context.isDefaultNamespace())) { return itemNs; } return operationNs; } protected <T> String checkName(T item) { String operationName = getName(); ObjectMeta metadata = item instanceof HasMetadata ? ((HasMetadata) item).getMetadata() : null; String itemName = metadata != null ? metadata.getName() : null; if (Utils.isNullOrEmpty(operationName) && Utils.isNullOrEmpty(itemName)) { return null; } else if (Utils.isNullOrEmpty(itemName)) { return operationName; } else if (Utils.isNullOrEmpty(operationName)) { return itemName; } else if (itemName.equals(operationName)) { return itemName; } throw new KubernetesClientException("Name mismatch. Item name:" + itemName + ". Operation name:" + operationName + "."); } protected <T> T handleMetric(String resourceUrl, Class<T> type) throws InterruptedException, IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .uri(resourceUrl); return handleResponse(requestBuilder, type); } protected <T> void handleDelete(T resource, long gracePeriodSeconds, DeletionPropagation propagationPolicy, String resourceVersion, boolean cascading) throws InterruptedException, IOException { handleDelete(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(resource), checkName(resource))), gracePeriodSeconds, propagationPolicy, resourceVersion, cascading); } protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, String resourceVersion, boolean cascading) throws InterruptedException, IOException { DeleteOptions deleteOptions = new DeleteOptions(); if (gracePeriodSeconds >= 0) { deleteOptions.setGracePeriodSeconds(gracePeriodSeconds); } if (resourceVersion != null) { deleteOptions.setPreconditions(new Preconditions(resourceVersion, null)); } /* * Either the propagation policy or the orphan dependent (deprecated) property must be set, but not both. */ if (propagationPolicy != null) { deleteOptions.setPropagationPolicy(propagationPolicy.toString()); } else { deleteOptions.setOrphanDependents(!cascading); } if (dryRun) { deleteOptions.setDryRun(Collections.singletonList("All")); } HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .delete(JSON, JSON_MAPPER.writeValueAsString(deleteOptions)).url(requestUrl); handleResponse(requestBuilder, null, Collections.<String, String> emptyMap()); } /** * Create a resource. * * @param resource resource provided * @param outputType resource type you want as output * @param <T> template argument for output type * @param <I> template argument for resource * * @return returns de-serialized version of apiserver response in form of type provided * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T, I> T handleCreate(I resource, Class<T> outputType) throws InterruptedException, IOException { resource = correctNamespace(resource); HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .post(JSON, JSON_MAPPER.writeValueAsString(resource)) .url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(resource), null))); return handleResponse(requestBuilder, outputType, Collections.<String, String> emptyMap()); } /** * Replace a resource. * * @param updated updated object * @param type type of the object provided * @param status if this is only the status subresource * @param <T> template argument provided * * @return returns de-serialized version of api server response * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleUpdate(T updated, Class<T> type, boolean status) throws InterruptedException, IOException { return handleUpdate(updated, type, Collections.<String, String> emptyMap(), status); } /** * Update a resource, optionally performing placeholder substitution to the response. * * @param updated updated object * @param type type of object provided * @param parameters a HashMap containing parameters for processing object * @param status if this is only the status subresource * @param <T> template argument provided * * @return returns de-serialized version of api server response. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleUpdate(T updated, Class<T> type, Map<String, String> parameters, boolean status) throws InterruptedException, IOException { updated = correctNamespace(updated); HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .put(JSON, JSON_MAPPER.writeValueAsString(updated)) .url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(updated), checkName(updated), status))); return handleResponse(requestBuilder, type, parameters); } /** * Send an http patch and handle the response. * * If current is not null and patchContext does not specify a patch type, then a JSON patch is assumed. Otherwise a STRATEGIC * MERGE is assumed. * * @param patchContext patch options for patch request * @param current current object * @param updated updated object * @param type type of object * @param status if this is only the status subresource * @param <T> template argument provided * * @return returns de-serialized version of api server response * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handlePatch(PatchContext patchContext, T current, T updated, Class<T> type, boolean status) throws InterruptedException, IOException { String patchForUpdate = null; if (current != null && (patchContext == null || patchContext.getPatchType() == PatchType.JSON)) { // we can't omit status unless this is not a status operation and we know this has a status subresource patchForUpdate = PatchUtils.jsonDiff(current, updated, false); if (patchContext == null) { patchContext = new PatchContext.Builder().withPatchType(PatchType.JSON).build(); } } else { if (patchContext != null && patchContext.getPatchType() == PatchType.SERVER_SIDE_APPLY) { // TODO: it would probably be better to do this with a mixin if (updated instanceof HasMetadata) { ObjectMeta meta = ((HasMetadata) updated).getMetadata(); if (meta != null && meta.getManagedFields() != null && !meta.getManagedFields().isEmpty()) { // the item should have already been cloned meta.setManagedFields(null); } } } patchForUpdate = Serialization.asJson(updated); current = updated; // use the updated to determine the path } return handlePatch(patchContext, current, patchForUpdate, type, status); } /** * Send an http patch and handle the response. * * @param current current object * @param patchForUpdate updated object spec as json string * @param type type of object * @param <T> template argument provided * * @return returns de-serialized version of api server response * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handlePatch(T current, Map<String, Object> patchForUpdate, Class<T> type) throws InterruptedException, IOException { return handlePatch(new PatchContext.Builder().withPatchType(PatchType.STRATEGIC_MERGE).build(), current, JSON_MAPPER.writeValueAsString(patchForUpdate), type, false); } /** * Send an http patch and handle the response. * * @param patchContext patch options for patch request * @param current current object * @param patchForUpdate Patch string * @param type type of object * @param status if this is only the status subresource * @param <T> template argument provided * @return returns de-serialized version of api server response * @throws InterruptedException Interrupted Exception * @throws IOException IOException in case of network errors */ protected <T> T handlePatch(PatchContext patchContext, T current, String patchForUpdate, Class<T> type, boolean status) throws InterruptedException, IOException { String bodyContentType = getContentTypeFromPatchContextOrDefault(patchContext); HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .patch(bodyContentType, patchForUpdate) .url(getResourceURLForPatchOperation(getResourceUrl(checkNamespace(current), checkName(current), status), patchContext)); return handleResponse(requestBuilder, type, Collections.emptyMap()); } /** * Replace Scale of specified Kubernetes Resource * * @param resourceUrl Kubernetes resource URL * @param scale Scale object which we want to inject * @return updated Scale object * @throws InterruptedException in case thread is interrupted * @throws IOException in some other I/O problem */ protected Scale handleScale(String resourceUrl, Scale scale) throws InterruptedException, IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().uri(resourceUrl + "/scale"); if (scale != null) { requestBuilder.put(JSON, JSON_MAPPER.writeValueAsString(scale)); } return handleResponse(requestBuilder, Scale.class); } /** * Create rollback of a Deployment * * @param resourceUrl resource url * @param deploymentRollback DeploymentRollback resource * @return Status * @throws InterruptedException in case thread is interrupted * @throws IOException in some other I/O problem */ protected Status handleDeploymentRollback(String resourceUrl, DeploymentRollback deploymentRollback) throws InterruptedException, IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().uri(resourceUrl + "/rollback").post(JSON, JSON_MAPPER.writeValueAsString(deploymentRollback)); return handleResponse(requestBuilder, Status.class); } /** * Send an http get. * * @param resourceUrl resource URL to be processed * @param type type of resource * @param <T> template argument provided * * @return returns a deserialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleGet(URL resourceUrl, Class<T> type) throws InterruptedException, IOException { return handleGet(resourceUrl, type, Collections.<String, String> emptyMap()); } /** * Send a raw get - where the type should be one of String, Reader, InputStream * <br> * NOTE: Currently does not utilize the retry logic */ protected <T> T handleRawGet(URL resourceUrl, Class<T> type) throws IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().url(resourceUrl); HttpRequest request = requestBuilder.build(); HttpResponse<T> response = httpClient.send(request, type); assertResponseCode(request, response); return response.body(); } /** * Send an http, optionally performing placeholder substitution to the response. * * @param resourceUrl resource URL to be processed * @param type type of resource * @param parameters A HashMap of strings containing parameters to be passed in request * @param <T> template argument provided * * @return Returns a deserialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleGet(URL resourceUrl, Class<T> type, Map<String, String> parameters) throws InterruptedException, IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().url(resourceUrl); return handleResponse(requestBuilder, type, parameters); } /** * Send an http request and handle the response. * * @param requestBuilder Request Builder object * @param type type of resource * @param <T> template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(HttpRequest.Builder requestBuilder, Class<T> type) throws InterruptedException, IOException { return handleResponse(requestBuilder, type, Collections.<String, String> emptyMap()); } /** * Send an http request and handle the response, optionally performing placeholder substitution to the response. * * @param requestBuilder request builder * @param type type of object * @param parameters a hashmap containing parameters * @param <T> template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(HttpRequest.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws InterruptedException, IOException { return handleResponse(httpClient, requestBuilder, type, parameters); } /** * Send an http request and handle the response. * * @param client the client * @param requestBuilder request builder * @param type type of object * @param <T> template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(HttpClient client, HttpRequest.Builder requestBuilder, Class<T> type) throws InterruptedException, IOException { return handleResponse(client, requestBuilder, type, Collections.<String, String> emptyMap()); } /** * Send an http request and handle the response, optionally performing placeholder substitution to the response. * * @param client the client * @param requestBuilder Request builder * @param type Type of object provided * @param parameters A hashmap containing parameters * @param <T> Template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(HttpClient client, HttpRequest.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws InterruptedException, IOException { VersionUsageUtils.log(this.resourceT, this.apiGroupVersion); HttpRequest request = requestBuilder.build(); HttpResponse<InputStream> response = retryWithExponentialBackoff(client, request); try (InputStream bodyInputStream = response.body()) { assertResponseCode(request, response); if (type != null) { return Serialization.unmarshal(bodyInputStream, type, parameters); } else { return null; } } catch (Exception e) { if (e instanceof KubernetesClientException) { throw e; } throw requestException(request, e); } } protected HttpResponse<InputStream> retryWithExponentialBackoff(HttpClient client, HttpRequest request) throws InterruptedException, IOException { int numRetries = 0; long retryInterval; while (true) { try { HttpResponse<InputStream> response = client.send(request, InputStream.class); if (numRetries < requestRetryBackoffLimit && response.code() >= 500) { retryInterval = retryIntervalCalculator.getInterval(numRetries); LOG.debug("HTTP operation on url: {} should be retried as the response code was {}, retrying after {} millis", request.uri(), response.code(), retryInterval); if (response.body() != null) { response.body().close(); } } else { return response; } } catch (IOException ie) { if (numRetries < requestRetryBackoffLimit) { retryInterval = retryIntervalCalculator.getInterval(numRetries); LOG.debug(String.format("HTTP operation on url: %s should be retried after %d millis because of IOException", request.uri(), retryInterval), ie); } else { throw ie; } } Thread.sleep(retryInterval); numRetries++; } } /** * Checks if the response status code is the expected and throws the appropriate KubernetesClientException if not. * * @param request The {#link HttpRequest} object. * @param response The {@link HttpResponse} object. */ protected void assertResponseCode(HttpRequest request, HttpResponse<?> response) { if (response.isSuccessful()) { return; } int statusCode = response.code(); String customMessage = config.getErrorMessages().get(statusCode); if (customMessage != null) { throw requestFailure(request, createStatus(statusCode, combineMessages(customMessage, createStatus(response)))); } else { throw requestFailure(request, createStatus(response)); } } private String combineMessages(String customMessage, Status defaultStatus) { if (defaultStatus != null) { String message = defaultStatus.getMessage(); if (message != null && message.length() > 0) { return customMessage + " " + message; } } return customMessage; } public static Status createStatus(HttpResponse<?> response) { String statusMessage = ""; int statusCode = response != null ? response.code() : 0; if (response == null) { statusMessage = "No response"; } else { try { String bodyString = response.bodyString(); if (Utils.isNotNullOrEmpty(bodyString)) { Status status = JSON_MAPPER.readValue(bodyString, Status.class); if (status.getCode() == null) { status = new StatusBuilder(status).withCode(statusCode).build(); } return status; } } catch (IOException e) { // ignored } if (response.message() != null) { statusMessage = response.message(); } } return createStatus(statusCode, statusMessage); } public static Status createStatus(int statusCode, String message) { Status status = new StatusBuilder() .withCode(statusCode) .withMessage(message) .build(); status.getAdditionalProperties().put(CLIENT_STATUS_FLAG, "true"); return status; } public static KubernetesClientException requestFailure(HttpRequest request, Status status) { return requestFailure(request, status, null); } public static KubernetesClientException requestFailure(HttpRequest request, Status status, String message) { StringBuilder sb = new StringBuilder(); if (message != null && !message.isEmpty()) { sb.append(message).append(". "); } sb.append("Failure executing: ").append(request.method()) .append(" at: ").append(request.uri()).append("."); if (status.getMessage() != null && !status.getMessage().isEmpty()) { sb.append(" Message: ").append(status.getMessage()).append("."); } if (!status.getAdditionalProperties().containsKey(CLIENT_STATUS_FLAG)) { sb.append(" Received status: ").append(status).append("."); } final RequestMetadata metadata = RequestMetadata.from(request); return new KubernetesClientException(sb.toString(), status.getCode(), status, metadata.group, metadata.version, metadata.plural, metadata.namespace); } public static KubernetesClientException requestException(HttpRequest request, Throwable e, String message) { StringBuilder sb = new StringBuilder(); if (message != null && !message.isEmpty()) { sb.append(message).append(". "); } sb.append("Error executing: ").append(request.method()) .append(" at: ").append(request.uri()) .append(". Cause: ").append(e.getMessage()); final RequestMetadata metadata = RequestMetadata.from(request); return new KubernetesClientException(sb.toString(), e, metadata.group, metadata.version, metadata.plural, metadata.namespace); } public static KubernetesClientException requestException(HttpRequest request, Exception e) { return requestException(request, e, null); } private static class RequestMetadata { private final String group; private final String version; private final String plural; private final String namespace; private static final RequestMetadata EMPTY = new RequestMetadata(null, null, null, null); private RequestMetadata(String group, String version, String plural, String namespace) { this.group = group; this.version = version; this.plural = plural; this.namespace = namespace; } static RequestMetadata from(HttpRequest request) { final List<String> segments = Arrays.asList(request.uri().getRawPath().split("\\/")); switch (segments.size()) { case 4: // cluster URL return new RequestMetadata(segments.get(1), segments.get(2), segments.get(3), null); case 6: // namespaced URL return new RequestMetadata(segments.get(1), segments.get(2), segments.get(5), segments.get(4)); default: return EMPTY; } } } protected static <T> T unmarshal(InputStream is) { return Serialization.unmarshal(is); } protected static <T> T unmarshal(InputStream is, final Class<T> type) { return Serialization.unmarshal(is, type); } protected static <T> T unmarshal(InputStream is, TypeReference<T> type) { return Serialization.unmarshal(is, type); } protected static <T> Map getObjectValueAsMap(T object) { return JSON_MAPPER.convertValue(object, Map.class); } public Config getConfig() { return config; } private String getContentTypeFromPatchContextOrDefault(PatchContext patchContext) { if (patchContext != null && patchContext.getPatchType() != null) { return patchContext.getPatchType().getContentType(); } return STRATEGIC_MERGE_JSON_PATCH; } public <R1> R1 restCall(Class<R1> result, String... path) { try { URL requestUrl = new URL(config.getMasterUrl()); String url = requestUrl.toString(); if (path != null && path.length > 0) { url = URLUtils.join(url, URLUtils.pathJoin(path)); } HttpRequest.Builder req = httpClient.newHttpRequestBuilder().uri(url); return handleResponse(req, result); } catch (KubernetesClientException e) { if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) { throw e; } return null; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(ie); } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } }
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/OperationSupport.java
/** * Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.client.dsl.internal; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.kubernetes.api.model.DeleteOptions; import io.fabric8.kubernetes.api.model.DeletionPropagation; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.Preconditions; import io.fabric8.kubernetes.api.model.Status; import io.fabric8.kubernetes.api.model.StatusBuilder; import io.fabric8.kubernetes.api.model.autoscaling.v1.Scale; import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.base.PatchContext; import io.fabric8.kubernetes.client.dsl.base.PatchType; import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.client.http.HttpRequest; import io.fabric8.kubernetes.client.http.HttpResponse; import io.fabric8.kubernetes.client.internal.PatchUtils; import io.fabric8.kubernetes.client.internal.VersionUsageUtils; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.kubernetes.client.utils.internal.ExponentialBackoffIntervalCalculator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; public class OperationSupport { public static final String JSON = "application/json"; public static final String JSON_PATCH = "application/json-patch+json"; public static final String STRATEGIC_MERGE_JSON_PATCH = "application/strategic-merge-patch+json"; public static final String JSON_MERGE_PATCH = "application/merge-patch+json"; protected static final ObjectMapper JSON_MAPPER = Serialization.jsonMapper(); private static final Logger LOG = LoggerFactory.getLogger(OperationSupport.class); private static final String CLIENT_STATUS_FLAG = "CLIENT_STATUS_FLAG"; private static final int maxRetryIntervalExponent = 5; protected OperationContext context; protected final HttpClient httpClient; protected final Config config; protected final String resourceT; protected String namespace; protected String name; protected String apiGroupName; protected String apiGroupVersion; protected boolean dryRun; private final ExponentialBackoffIntervalCalculator retryIntervalCalculator; private final int requestRetryBackoffLimit; public OperationSupport(Client client) { this(new OperationContext().withClient(client)); } public OperationSupport(OperationContext ctx) { this.context = ctx; this.httpClient = ctx.getHttpClient(); this.config = ctx.getConfig(); this.resourceT = ctx.getPlural(); this.namespace = ctx.getNamespace(); this.name = ctx.getName(); this.apiGroupName = ctx.getApiGroupName(); this.dryRun = ctx.getDryRun(); if (Utils.isNotNullOrEmpty(ctx.getApiGroupVersion())) { this.apiGroupVersion = ctx.getApiGroupVersion(); } else if (ctx.getConfig() != null && Utils.isNotNullOrEmpty(ctx.getConfig().getApiVersion())) { this.apiGroupVersion = ctx.getConfig().getApiVersion(); } else { this.apiGroupVersion = "v1"; } final int requestRetryBackoffInterval; if (ctx.getConfig() != null) { requestRetryBackoffInterval = ctx.getConfig().getRequestRetryBackoffInterval(); this.requestRetryBackoffLimit = ctx.getConfig().getRequestRetryBackoffLimit(); } else { requestRetryBackoffInterval = Config.DEFAULT_REQUEST_RETRY_BACKOFFINTERVAL; this.requestRetryBackoffLimit = Config.DEFAULT_REQUEST_RETRY_BACKOFFLIMIT; } this.retryIntervalCalculator = new ExponentialBackoffIntervalCalculator(requestRetryBackoffInterval, maxRetryIntervalExponent); } public String getAPIGroupName() { return apiGroupName; } public String getAPIGroupVersion() { return apiGroupVersion; } public String getResourceT() { return resourceT; } public String getNamespace() { return namespace; } public String getName() { return name; } public boolean isResourceNamespaced() { return true; } public URL getRootUrl() { try { if (!Utils.isNullOrEmpty(apiGroupName)) { return new URL(URLUtils.join(config.getMasterUrl().toString(), "apis", apiGroupName, apiGroupVersion)); } return new URL(URLUtils.join(config.getMasterUrl().toString(), "api", apiGroupVersion)); } catch (MalformedURLException e) { throw KubernetesClientException.launderThrowable(e); } } public URL getNamespacedUrl(String namespace) throws MalformedURLException { URL requestUrl = getRootUrl(); if (!isResourceNamespaced()) { //if resource is not namespaced don't even bother to check the namespace. } else if (Utils.isNotNullOrEmpty(namespace)) { requestUrl = new URL(URLUtils.join(requestUrl.toString(), "namespaces", namespace)); } requestUrl = new URL(URLUtils.join(requestUrl.toString(), resourceT)); return requestUrl; } public URL getNamespacedUrl() throws MalformedURLException { return getNamespacedUrl(getNamespace()); } public URL getResourceUrl(String namespace, String name) throws MalformedURLException { return getResourceUrl(namespace, name, false); } public URL getResourceUrl(String namespace, String name, boolean status) throws MalformedURLException { if (name == null) { if (status) { throw new KubernetesClientException("name not specified for an operation requiring one."); } return getNamespacedUrl(namespace); } if (status) { return new URL(URLUtils.join(getNamespacedUrl(namespace).toString(), name, "status")); } return new URL(URLUtils.join(getNamespacedUrl(namespace).toString(), name)); } public URL getResourceUrl() throws MalformedURLException { if (name == null) { return getNamespacedUrl(); } return new URL(URLUtils.join(getNamespacedUrl().toString(), name)); } public URL getResourceURLForWriteOperation(URL resourceURL) throws MalformedURLException { if (dryRun) { return new URL(URLUtils.join(resourceURL.toString(), "?dryRun=All")); } return resourceURL; } public URL getResourceURLForPatchOperation(URL resourceUrl, PatchContext patchContext) throws MalformedURLException { if (patchContext != null) { String url = resourceUrl.toString(); if (patchContext.getForce() != null) { url = URLUtils.join(url, "?force=" + patchContext.getForce()); } if ((patchContext.getDryRun() != null && !patchContext.getDryRun().isEmpty()) || dryRun) { url = URLUtils.join(url, "?dryRun=All"); } String fieldManager = patchContext.getFieldManager(); if (fieldManager == null && patchContext.getPatchType() == PatchType.SERVER_SIDE_APPLY) { fieldManager = "fabric8"; } if (fieldManager != null) { url = URLUtils.join(url, "?fieldManager=" + fieldManager); } if (patchContext.getFieldValidation() != null) { url = URLUtils.join(url, "?fieldValidation=" + patchContext.getFieldValidation()); } return new URL(url); } return resourceUrl; } protected <T> T correctNamespace(T item) { if (!isResourceNamespaced() || this.context.isDefaultNamespace() || !(item instanceof HasMetadata)) { return item; } String itemNs = KubernetesResourceUtil.getNamespace((HasMetadata) item); if (Utils.isNotNullOrEmpty(namespace) && Utils.isNotNullOrEmpty(itemNs) && !namespace.equals(itemNs)) { item = Serialization.clone(item); KubernetesResourceUtil.setNamespace((HasMetadata) item, namespace); } return item; } protected <T> String checkNamespace(T item) { if (!isResourceNamespaced()) { return null; } String operationNs = getNamespace(); String itemNs = (item instanceof HasMetadata) ? KubernetesResourceUtil.getNamespace((HasMetadata) item) : null; if (Utils.isNullOrEmpty(operationNs) && Utils.isNullOrEmpty(itemNs)) { if (context.isDefaultNamespace()) { throw new KubernetesClientException( "namespace not specified for an operation requiring one and no default was found in the Config."); } throw new KubernetesClientException("namespace not specified for an operation requiring one."); } else if (!Utils.isNullOrEmpty(itemNs) && (Utils.isNullOrEmpty(operationNs) || this.context.isDefaultNamespace())) { return itemNs; } return operationNs; } protected <T> String checkName(T item) { String operationName = getName(); ObjectMeta metadata = item instanceof HasMetadata ? ((HasMetadata) item).getMetadata() : null; String itemName = metadata != null ? metadata.getName() : null; if (Utils.isNullOrEmpty(operationName) && Utils.isNullOrEmpty(itemName)) { return null; } else if (Utils.isNullOrEmpty(itemName)) { return operationName; } else if (Utils.isNullOrEmpty(operationName)) { return itemName; } else if (itemName.equals(operationName)) { return itemName; } throw new KubernetesClientException("Name mismatch. Item name:" + itemName + ". Operation name:" + operationName + "."); } protected <T> T handleMetric(String resourceUrl, Class<T> type) throws InterruptedException, IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .uri(resourceUrl); return handleResponse(requestBuilder, type); } protected <T> void handleDelete(T resource, long gracePeriodSeconds, DeletionPropagation propagationPolicy, String resourceVersion, boolean cascading) throws InterruptedException, IOException { handleDelete(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(resource), checkName(resource))), gracePeriodSeconds, propagationPolicy, resourceVersion, cascading); } protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, String resourceVersion, boolean cascading) throws InterruptedException, IOException { DeleteOptions deleteOptions = new DeleteOptions(); if (gracePeriodSeconds >= 0) { deleteOptions.setGracePeriodSeconds(gracePeriodSeconds); } if (resourceVersion != null) { deleteOptions.setPreconditions(new Preconditions(resourceVersion, null)); } /* * Either the propagation policy or the orphan dependent (deprecated) property must be set, but not both. */ if (propagationPolicy != null) { deleteOptions.setPropagationPolicy(propagationPolicy.toString()); } else { deleteOptions.setOrphanDependents(!cascading); } if (dryRun) { deleteOptions.setDryRun(Collections.singletonList("All")); } HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .delete(JSON, JSON_MAPPER.writeValueAsString(deleteOptions)).url(requestUrl); handleResponse(requestBuilder, null, Collections.<String, String> emptyMap()); } /** * Create a resource. * * @param resource resource provided * @param outputType resource type you want as output * @param <T> template argument for output type * @param <I> template argument for resource * * @return returns de-serialized version of apiserver response in form of type provided * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T, I> T handleCreate(I resource, Class<T> outputType) throws InterruptedException, IOException { resource = correctNamespace(resource); HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .post(JSON, JSON_MAPPER.writeValueAsString(resource)) .url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(resource), null))); return handleResponse(requestBuilder, outputType, Collections.<String, String> emptyMap()); } /** * Replace a resource. * * @param updated updated object * @param type type of the object provided * @param status if this is only the status subresource * @param <T> template argument provided * * @return returns de-serialized version of api server response * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleUpdate(T updated, Class<T> type, boolean status) throws InterruptedException, IOException { return handleUpdate(updated, type, Collections.<String, String> emptyMap(), status); } /** * Update a resource, optionally performing placeholder substitution to the response. * * @param updated updated object * @param type type of object provided * @param parameters a HashMap containing parameters for processing object * @param status if this is only the status subresource * @param <T> template argument provided * * @return returns de-serialized version of api server response. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleUpdate(T updated, Class<T> type, Map<String, String> parameters, boolean status) throws InterruptedException, IOException { updated = correctNamespace(updated); HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .put(JSON, JSON_MAPPER.writeValueAsString(updated)) .url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(updated), checkName(updated), status))); return handleResponse(requestBuilder, type, parameters); } /** * Send an http patch and handle the response. * * If current is not null and patchContext does not specify a patch type, then a JSON patch is assumed. Otherwise a STRATEGIC * MERGE is assumed. * * @param patchContext patch options for patch request * @param current current object * @param updated updated object * @param type type of object * @param status if this is only the status subresource * @param <T> template argument provided * * @return returns de-serialized version of api server response * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handlePatch(PatchContext patchContext, T current, T updated, Class<T> type, boolean status) throws InterruptedException, IOException { String patchForUpdate = null; if (current != null && (patchContext == null || patchContext.getPatchType() == PatchType.JSON)) { // we can't omit status unless this is not a status operation and we know this has a status subresource patchForUpdate = PatchUtils.jsonDiff(current, updated, false); if (patchContext == null) { patchContext = new PatchContext.Builder().withPatchType(PatchType.JSON).build(); } } else { if (patchContext != null && patchContext.getPatchType() == PatchType.SERVER_SIDE_APPLY) { // TODO: it would probably be better to do this with a mixin if (updated instanceof HasMetadata) { ObjectMeta meta = ((HasMetadata) updated).getMetadata(); if (meta != null && meta.getManagedFields() != null && !meta.getManagedFields().isEmpty()) { // the item should have already been cloned meta.setManagedFields(null); } } } patchForUpdate = Serialization.asJson(updated); current = updated; // use the updated to determine the path } return handlePatch(patchContext, current, patchForUpdate, type, status); } /** * Send an http patch and handle the response. * * @param current current object * @param patchForUpdate updated object spec as json string * @param type type of object * @param <T> template argument provided * * @return returns de-serialized version of api server response * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handlePatch(T current, Map<String, Object> patchForUpdate, Class<T> type) throws InterruptedException, IOException { return handlePatch(new PatchContext.Builder().withPatchType(PatchType.STRATEGIC_MERGE).build(), current, JSON_MAPPER.writeValueAsString(patchForUpdate), type, false); } /** * Send an http patch and handle the response. * * @param patchContext patch options for patch request * @param current current object * @param patchForUpdate Patch string * @param type type of object * @param status if this is only the status subresource * @param <T> template argument provided * @return returns de-serialized version of api server response * @throws InterruptedException Interrupted Exception * @throws IOException IOException in case of network errors */ protected <T> T handlePatch(PatchContext patchContext, T current, String patchForUpdate, Class<T> type, boolean status) throws InterruptedException, IOException { String bodyContentType = getContentTypeFromPatchContextOrDefault(patchContext); HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder() .patch(bodyContentType, patchForUpdate) .url(getResourceURLForPatchOperation(getResourceUrl(checkNamespace(current), checkName(current), status), patchContext)); return handleResponse(requestBuilder, type, Collections.emptyMap()); } /** * Replace Scale of specified Kubernetes Resource * * @param resourceUrl Kubernetes resource URL * @param scale Scale object which we want to inject * @return updated Scale object * @throws InterruptedException in case thread is interrupted * @throws IOException in some other I/O problem */ protected Scale handleScale(String resourceUrl, Scale scale) throws InterruptedException, IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().uri(resourceUrl + "/scale"); if (scale != null) { requestBuilder.put(JSON, JSON_MAPPER.writeValueAsString(scale)); } return handleResponse(requestBuilder, Scale.class); } /** * Create rollback of a Deployment * * @param resourceUrl resource url * @param deploymentRollback DeploymentRollback resource * @return Status * @throws InterruptedException in case thread is interrupted * @throws IOException in some other I/O problem */ protected Status handleDeploymentRollback(String resourceUrl, DeploymentRollback deploymentRollback) throws InterruptedException, IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().uri(resourceUrl + "/rollback").post(JSON, JSON_MAPPER.writeValueAsString(deploymentRollback)); return handleResponse(requestBuilder, Status.class); } /** * Send an http get. * * @param resourceUrl resource URL to be processed * @param type type of resource * @param <T> template argument provided * * @return returns a deserialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleGet(URL resourceUrl, Class<T> type) throws InterruptedException, IOException { return handleGet(resourceUrl, type, Collections.<String, String> emptyMap()); } /** * Send a raw get - where the type should be one of String, Reader, InputStream * <br> * NOTE: Currently does not utilize the retry logic */ protected <T> T handleRawGet(URL resourceUrl, Class<T> type) throws IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().url(resourceUrl); HttpRequest request = requestBuilder.build(); HttpResponse<T> response = httpClient.send(request, type); assertResponseCode(request, response); return response.body(); } /** * Send an http, optionally performing placeholder substitution to the response. * * @param resourceUrl resource URL to be processed * @param type type of resource * @param parameters A HashMap of strings containing parameters to be passed in request * @param <T> template argument provided * * @return Returns a deserialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleGet(URL resourceUrl, Class<T> type, Map<String, String> parameters) throws InterruptedException, IOException { HttpRequest.Builder requestBuilder = httpClient.newHttpRequestBuilder().url(resourceUrl); return handleResponse(requestBuilder, type, parameters); } /** * Send an http request and handle the response. * * @param requestBuilder Request Builder object * @param type type of resource * @param <T> template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(HttpRequest.Builder requestBuilder, Class<T> type) throws InterruptedException, IOException { return handleResponse(requestBuilder, type, Collections.<String, String> emptyMap()); } /** * Send an http request and handle the response, optionally performing placeholder substitution to the response. * * @param requestBuilder request builder * @param type type of object * @param parameters a hashmap containing parameters * @param <T> template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(HttpRequest.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws InterruptedException, IOException { return handleResponse(httpClient, requestBuilder, type, parameters); } /** * Send an http request and handle the response. * * @param client the client * @param requestBuilder request builder * @param type type of object * @param <T> template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(HttpClient client, HttpRequest.Builder requestBuilder, Class<T> type) throws InterruptedException, IOException { return handleResponse(client, requestBuilder, type, Collections.<String, String> emptyMap()); } /** * Send an http request and handle the response, optionally performing placeholder substitution to the response. * * @param client the client * @param requestBuilder Request builder * @param type Type of object provided * @param parameters A hashmap containing parameters * @param <T> Template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(HttpClient client, HttpRequest.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws InterruptedException, IOException { VersionUsageUtils.log(this.resourceT, this.apiGroupVersion); HttpRequest request = requestBuilder.build(); HttpResponse<InputStream> response = retryWithExponentialBackoff(client, request); try (InputStream bodyInputStream = response.body()) { assertResponseCode(request, response); if (type != null) { return Serialization.unmarshal(bodyInputStream, type, parameters); } else { return null; } } catch (Exception e) { if (e instanceof KubernetesClientException) { throw e; } throw requestException(request, e); } } protected HttpResponse<InputStream> retryWithExponentialBackoff(HttpClient client, HttpRequest request) throws InterruptedException, IOException { int numRetries = 0; long retryInterval; while (true) { try { HttpResponse<InputStream> response = client.send(request, InputStream.class); if (numRetries < requestRetryBackoffLimit && response.code() >= 500) { retryInterval = retryIntervalCalculator.getInterval(numRetries); LOG.debug("HTTP operation on url: {} should be retried as the response code was {}, retrying after {} millis", request.uri(), response.code(), retryInterval); if (response.body() != null) { response.body().close(); } } else { return response; } } catch (IOException ie) { if (numRetries < requestRetryBackoffLimit) { retryInterval = retryIntervalCalculator.getInterval(numRetries); LOG.debug(String.format("HTTP operation on url: %s should be retried after %d millis because of IOException", request.uri(), retryInterval), ie); } else { throw ie; } } Thread.sleep(retryInterval); numRetries++; } } /** * Checks if the response status code is the expected and throws the appropriate KubernetesClientException if not. * * @param request The {#link HttpRequest} object. * @param response The {@link HttpResponse} object. */ protected void assertResponseCode(HttpRequest request, HttpResponse<?> response) { int statusCode = response.code(); String customMessage = config.getErrorMessages().get(statusCode); if (response.isSuccessful()) { return; } else if (customMessage != null) { throw requestFailure(request, createStatus(statusCode, combineMessages(customMessage, createStatus(response)))); } else { throw requestFailure(request, createStatus(response)); } } private String combineMessages(String customMessage, Status defaultStatus) { if (defaultStatus != null) { String message = defaultStatus.getMessage(); if (message != null && message.length() > 0) { return customMessage + " " + message; } } return customMessage; } public static Status createStatus(HttpResponse<?> response) { String statusMessage = ""; int statusCode = response != null ? response.code() : 0; if (response == null) { statusMessage = "No response"; } else { try { String bodyString = response.bodyString(); if (Utils.isNotNullOrEmpty(bodyString)) { Status status = JSON_MAPPER.readValue(bodyString, Status.class); if (status.getCode() == null) { status = new StatusBuilder(status).withCode(statusCode).build(); } return status; } } catch (IOException e) { // ignored } if (response.message() != null) { statusMessage = response.message(); } } return createStatus(statusCode, statusMessage); } public static Status createStatus(int statusCode, String message) { Status status = new StatusBuilder() .withCode(statusCode) .withMessage(message) .build(); status.getAdditionalProperties().put(CLIENT_STATUS_FLAG, "true"); return status; } public static KubernetesClientException requestFailure(HttpRequest request, Status status) { return requestFailure(request, status, null); } public static KubernetesClientException requestFailure(HttpRequest request, Status status, String message) { StringBuilder sb = new StringBuilder(); if (message != null && !message.isEmpty()) { sb.append(message).append(". "); } sb.append("Failure executing: ").append(request.method()) .append(" at: ").append(request.uri()).append("."); if (status.getMessage() != null && !status.getMessage().isEmpty()) { sb.append(" Message: ").append(status.getMessage()).append("."); } if (!status.getAdditionalProperties().containsKey(CLIENT_STATUS_FLAG)) { sb.append(" Received status: ").append(status).append("."); } final RequestMetadata metadata = RequestMetadata.from(request); return new KubernetesClientException(sb.toString(), status.getCode(), status, metadata.group, metadata.version, metadata.plural, metadata.namespace); } public static KubernetesClientException requestException(HttpRequest request, Throwable e, String message) { StringBuilder sb = new StringBuilder(); if (message != null && !message.isEmpty()) { sb.append(message).append(". "); } sb.append("Error executing: ").append(request.method()) .append(" at: ").append(request.uri()) .append(". Cause: ").append(e.getMessage()); final RequestMetadata metadata = RequestMetadata.from(request); return new KubernetesClientException(sb.toString(), e, metadata.group, metadata.version, metadata.plural, metadata.namespace); } public static KubernetesClientException requestException(HttpRequest request, Exception e) { return requestException(request, e, null); } private static class RequestMetadata { private final String group; private final String version; private final String plural; private final String namespace; private final static RequestMetadata EMPTY = new RequestMetadata(null, null, null, null); private RequestMetadata(String group, String version, String plural, String namespace) { this.group = group; this.version = version; this.plural = plural; this.namespace = namespace; } static RequestMetadata from(HttpRequest request) { final List<String> segments = Arrays.asList(request.uri().getRawPath().split("\\/")); switch (segments.size()) { case 4: // cluster URL return new RequestMetadata(segments.get(1), segments.get(2), segments.get(3), null); case 6: // namespaced URL return new RequestMetadata(segments.get(1), segments.get(2), segments.get(5), segments.get(4)); default: return EMPTY; } } } protected static <T> T unmarshal(InputStream is) { return Serialization.unmarshal(is); } protected static <T> T unmarshal(InputStream is, final Class<T> type) { return Serialization.unmarshal(is, type); } protected static <T> T unmarshal(InputStream is, TypeReference<T> type) { return Serialization.unmarshal(is, type); } protected static <T> Map getObjectValueAsMap(T object) { return JSON_MAPPER.convertValue(object, Map.class); } public Config getConfig() { return config; } private String getContentTypeFromPatchContextOrDefault(PatchContext patchContext) { if (patchContext != null && patchContext.getPatchType() != null) { return patchContext.getPatchType().getContentType(); } return STRATEGIC_MERGE_JSON_PATCH; } public <R1> R1 restCall(Class<R1> result, String... path) { try { URL requestUrl = new URL(config.getMasterUrl()); String url = requestUrl.toString(); if (path != null && path.length > 0) { url = URLUtils.join(url, URLUtils.pathJoin(path)); } HttpRequest.Builder req = httpClient.newHttpRequestBuilder().uri(url); return handleResponse(req, result); } catch (KubernetesClientException e) { if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) { throw e; } return null; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw KubernetesClientException.launderThrowable(ie); } catch (IOException e) { throw KubernetesClientException.launderThrowable(e); } } }
refactor(iss_3892): trivial refactoring on OperationSupport
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/OperationSupport.java
refactor(iss_3892): trivial refactoring on OperationSupport
<ide><path>ubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/OperationSupport.java <ide> * @param response The {@link HttpResponse} object. <ide> */ <ide> protected void assertResponseCode(HttpRequest request, HttpResponse<?> response) { <add> if (response.isSuccessful()) { <add> return; <add> } <add> <ide> int statusCode = response.code(); <ide> String customMessage = config.getErrorMessages().get(statusCode); <ide> <del> if (response.isSuccessful()) { <del> return; <del> } else if (customMessage != null) { <add> if (customMessage != null) { <ide> throw requestFailure(request, createStatus(statusCode, combineMessages(customMessage, createStatus(response)))); <ide> } else { <ide> throw requestFailure(request, createStatus(response)); <ide> private final String version; <ide> private final String plural; <ide> private final String namespace; <del> private final static RequestMetadata EMPTY = new RequestMetadata(null, null, null, null); <add> private static final RequestMetadata EMPTY = new RequestMetadata(null, null, null, null); <ide> <ide> private RequestMetadata(String group, String version, String plural, String namespace) { <ide> this.group = group;
Java
apache-2.0
6c318181d8d5fcdc5e0a2f4d253d4bcd152d4422
0
kwon37xi/hibernate4-memcached
package kr.pe.kwonnam.hibernate4memcached.regions; import kr.pe.kwonnam.hibernate4memcached.memcached.CacheNamespace; import kr.pe.kwonnam.hibernate4memcached.memcached.MemcachedAdapter; import kr.pe.kwonnam.hibernate4memcached.timestamper.HibernateCacheTimestamper; import kr.pe.kwonnam.hibernate4memcached.util.OverridableReadOnlyProperties; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.CacheDataDescription; import org.hibernate.cache.spi.GeneralDataRegion; import org.hibernate.cfg.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static kr.pe.kwonnam.hibernate4memcached.Hibernate4MemcachedRegionFactory.REGION_EXPIRY_SECONDS_PROPERTY_KEY_PREFIX; /** * @author KwonNam Son ([email protected]) */ public class GeneralDataMemcachedRegion extends MemcachedRegion implements GeneralDataRegion { private Logger log = LoggerFactory.getLogger(GeneralDataMemcachedRegion.class); private int expirySeconds; public GeneralDataMemcachedRegion(CacheNamespace cacheNamespace, OverridableReadOnlyProperties properties, CacheDataDescription metadata, Settings settings, MemcachedAdapter memcachedAdapter, HibernateCacheTimestamper hibernateCacheTimestamper) { super(cacheNamespace, properties, metadata, settings, memcachedAdapter, hibernateCacheTimestamper); populateExpirySeconds(properties); } void populateExpirySeconds(OverridableReadOnlyProperties properties) { String regionExpirySecondsKey = REGION_EXPIRY_SECONDS_PROPERTY_KEY_PREFIX + "." + getCacheNamespace().getName(); String expirySecondsProperty = properties.getProperty(regionExpirySecondsKey); if (expirySecondsProperty == null) { expirySecondsProperty = properties.getProperty(REGION_EXPIRY_SECONDS_PROPERTY_KEY_PREFIX); } if (expirySecondsProperty == null) { throw new IllegalStateException(regionExpirySecondsKey + " or " + REGION_EXPIRY_SECONDS_PROPERTY_KEY_PREFIX + "(for default expiry seconds) required!"); } expirySeconds = Integer.parseInt(expirySecondsProperty); log.info("expirySeconds of cache region [{}] - {} seconds.", getCacheNamespace().getName(), expirySeconds); } @Override public Object get(Object key) throws CacheException { String refinedKey = refineKey(key); log.debug("Cache get [{}] : key[{}]", getCacheNamespace(), refinedKey); Object cachedData = getMemcachedAdapter().get(getCacheNamespace(), refinedKey); if (cachedData == null) { return null; } if (!(cachedData instanceof CacheItem)) { log.debug("get cachedData is not CacheItem."); return cachedData; } CacheItem cacheItem = (CacheItem) cachedData; boolean targetClassAndCurrentJvmTargetClassMatch = cacheItem.isTargetClassAndCurrentJvmTargetClassMatch(); log.debug("cacheItem and targetClassAndCurrentJvmTargetClassMatch : {} / {}", targetClassAndCurrentJvmTargetClassMatch, cacheItem); if (cacheItem.isTargetClassAndCurrentJvmTargetClassMatch()) { return cacheItem.getCacheEntry(); } return null; } @Override public void put(Object key, Object value) throws CacheException { Object valueToCache = value; boolean classVersionApplicable = CacheItem.checkIfClassVersionApplicable(value, getSettings().isStructuredCacheEntriesEnabled()); if (classVersionApplicable) { valueToCache = new CacheItem(value, getSettings().isStructuredCacheEntriesEnabled()); } String refinedKey = refineKey(key); log.debug("Cache put [{}] : key[{}], value[{}], classVersionApplicable : {}", getCacheNamespace(), refinedKey, valueToCache, classVersionApplicable); getMemcachedAdapter().set(getCacheNamespace(), refinedKey, valueToCache, getExpiryInSeconds()); } @Override public void evict(Object key) throws CacheException { String refinedKey = refineKey(key); log.debug("Cache evict[{}] : key[{}]", getCacheNamespace(), refinedKey); getMemcachedAdapter().delete(getCacheNamespace(), refinedKey); } @Override public void evictAll() throws CacheException { log.debug("Cache evictAll [{}].", getCacheNamespace()); getMemcachedAdapter().evictAll(getCacheNamespace()); } /** * Read expiry seconds from configuration properties */ protected int getExpiryInSeconds() { return expirySeconds; } /** * Memcached has limitation of key size. Shorten the key to avoid the limitation if needed. */ protected String refineKey(Object key) { return String.valueOf(key); } }
hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/regions/GeneralDataMemcachedRegion.java
package kr.pe.kwonnam.hibernate4memcached.regions; import kr.pe.kwonnam.hibernate4memcached.memcached.CacheNamespace; import kr.pe.kwonnam.hibernate4memcached.memcached.MemcachedAdapter; import kr.pe.kwonnam.hibernate4memcached.timestamper.HibernateCacheTimestamper; import kr.pe.kwonnam.hibernate4memcached.util.OverridableReadOnlyProperties; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.CacheDataDescription; import org.hibernate.cache.spi.GeneralDataRegion; import org.hibernate.cfg.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static kr.pe.kwonnam.hibernate4memcached.Hibernate4MemcachedRegionFactory.REGION_EXPIRY_SECONDS_PROPERTY_KEY_PREFIX; /** * @author KwonNam Son ([email protected]) */ public class GeneralDataMemcachedRegion extends MemcachedRegion implements GeneralDataRegion { private Logger log = LoggerFactory.getLogger(GeneralDataMemcachedRegion.class); private int expirySeconds; public GeneralDataMemcachedRegion(CacheNamespace cacheNamespace, OverridableReadOnlyProperties properties, CacheDataDescription metadata, Settings settings, MemcachedAdapter memcachedAdapter, HibernateCacheTimestamper hibernateCacheTimestamper) { super(cacheNamespace, properties, metadata, settings, memcachedAdapter, hibernateCacheTimestamper); populateExpirySeconds(properties); } void populateExpirySeconds(OverridableReadOnlyProperties properties) { String regionExpirySecondsKey = REGION_EXPIRY_SECONDS_PROPERTY_KEY_PREFIX + "." + getCacheNamespace().getName(); String expirySecondsProperty = properties.getProperty(regionExpirySecondsKey); if (expirySecondsProperty == null) { expirySecondsProperty = properties.getProperty(REGION_EXPIRY_SECONDS_PROPERTY_KEY_PREFIX); } if (expirySecondsProperty == null) { throw new IllegalStateException(regionExpirySecondsKey + " or " + REGION_EXPIRY_SECONDS_PROPERTY_KEY_PREFIX + "(for default expiry seconds) required!"); } expirySeconds = Integer.parseInt(expirySecondsProperty); log.info("expirySeconds of cache region [{}] - {} seconds.", getCacheNamespace().getName(), expirySeconds); } @Override public Object get(Object key) throws CacheException { String refinedKey = refineKey(key); log.debug("Cache get [{}] : key[{}]", getCacheNamespace(), refinedKey); Object cachedData = getMemcachedAdapter().get(getCacheNamespace(), refinedKey); if (cachedData == null) { return null; } if (!(cachedData instanceof CacheItem)) { log.debug("get cachedDate is not CacheItem."); return cachedData; } CacheItem cacheItem = (CacheItem) cachedData; boolean targetClassAndCurrentJvmTargetClassMatch = cacheItem.isTargetClassAndCurrentJvmTargetClassMatch(); log.debug("cacheItem and targetClassAndCurrentJvmTargetClassMatch : {} / {}", targetClassAndCurrentJvmTargetClassMatch, cacheItem); if (cacheItem.isTargetClassAndCurrentJvmTargetClassMatch()) { return cacheItem.getCacheEntry(); } return null; } @Override public void put(Object key, Object value) throws CacheException { Object valueToCache = value; boolean classVersionApplicable = CacheItem.checkIfClassVersionApplicable(value, getSettings().isStructuredCacheEntriesEnabled()); if (classVersionApplicable) { valueToCache = new CacheItem(value, getSettings().isStructuredCacheEntriesEnabled()); } String refinedKey = refineKey(key); log.debug("Cache put [{}] : key[{}], value[{}], classVersionApplicable : {}", getCacheNamespace(), refinedKey, valueToCache, classVersionApplicable); getMemcachedAdapter().set(getCacheNamespace(), refinedKey, valueToCache, getExpiryInSeconds()); } @Override public void evict(Object key) throws CacheException { String refinedKey = refineKey(key); log.debug("Cache evict[{}] : key[{}]", getCacheNamespace(), refinedKey); getMemcachedAdapter().delete(getCacheNamespace(), refinedKey); } @Override public void evictAll() throws CacheException { log.debug("Cache evictAll [{}].", getCacheNamespace()); getMemcachedAdapter().evictAll(getCacheNamespace()); } /** * Read expiry seconds from configuration properties */ protected int getExpiryInSeconds() { return expirySeconds; } /** * Memcached has limitation of key size. Shorten the key to avoid the limitation if needed. */ protected String refineKey(Object key) { return String.valueOf(key); } }
cachedDate -> cachedData
hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/regions/GeneralDataMemcachedRegion.java
cachedDate -> cachedData
<ide><path>ibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/regions/GeneralDataMemcachedRegion.java <ide> } <ide> <ide> if (!(cachedData instanceof CacheItem)) { <del> log.debug("get cachedDate is not CacheItem."); <add> log.debug("get cachedData is not CacheItem."); <ide> return cachedData; <ide> } <ide>
Java
apache-2.0
7f9f65060406e392d14ee3bba8e1a9c86ecc961d
0
ops4j/org.ops4j.pax.logging,ops4j/org.ops4j.pax.logging
/* * Copyright 2005 Niclas Hedhman. * Copyright 2011 Avid Technology, 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 org.ops4j.pax.logging.logback.internal; import org.ops4j.pax.logging.EventAdminPoster; import org.ops4j.pax.logging.PaxLoggingService; import org.ops4j.pax.logging.internal.eventadmin.EventAdminTracker; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.ManagedService; import org.osgi.service.log.LogEntry; import org.osgi.service.log.LogReaderService; import org.osgi.service.log.LogService; import java.util.Hashtable; import java.util.Map; import java.util.logging.Handler; import java.util.logging.LogManager; import java.util.logging.Logger; /** * Starts the logback log services. * * <p> * This code was originally derived from org.ops4j.pax.logging.service.internal.Activator v1.6.0. Changes include: * <ul> * <li>added a call to stop the service</li> * <li>added more logging to detect failures at start, which may be otherwise lost in early boot</li> * </ul> * * @author Chris Dolan -- some code derived from from pax-logging-service v1.6.0 */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE") public class Activator implements BundleActivator { /** * The Managed Service PID for the Logback configuration */ public static final String CONFIGURATION_PID = "org.ops4j.pax.logging"; private static final String[] LOG_SERVICE_INTERFACE_NAMES = { LogService.class.getName(), org.knopflerfish.service.log.LogService.class.getName(), PaxLoggingService.class.getName(), ManagedService.class.getName(), }; /** * Reference to the registered service */ private ServiceRegistration m_RegistrationPaxLogging; private JdkHandler m_JdkHandler; private ServiceRegistration m_registrationLogReaderService; private FrameworkHandler m_frameworkHandler; private EventAdminPoster m_eventAdmin; private PaxLoggingServiceImpl m_paxLogging; /** * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start( BundleContext bundleContext ) throws Exception { // This try/catch is to detect failures to load the logging framework, which otherwise are silent... try { startInternal(bundleContext); } catch (Exception e) { e.printStackTrace(); throw e; } catch (Error e) { e.printStackTrace(); throw e; } catch (Throwable e) { // NOPMD e.printStackTrace(); throw new RuntimeException(e); } } private void startInternal( BundleContext bundleContext ) { // register the LogReaderService LogReaderServiceImpl logReader = new LogReaderServiceImpl( 100 ); String readerServiceName = LogReaderService.class.getName(); m_registrationLogReaderService = bundleContext.registerService( readerServiceName, logReader, null ); // Tracking for the EventAdmin try { m_eventAdmin = new EventAdminTracker( bundleContext ); } catch( NoClassDefFoundError e ) { // If we hit a NoClassDefFoundError, this means the event admin package is not available, // so use a dummy poster m_eventAdmin = new EventAdminPoster() { public void postEvent( Bundle bundle, int level, LogEntry entry, String message, Throwable exception, ServiceReference sr, Map context ) { } public void destroy() { } }; } // register the Pax Logging service m_paxLogging = new PaxLoggingServiceImpl( bundleContext, logReader.getAccessDelegate(), m_eventAdmin ); Hashtable<String, String> serviceProperties = new Hashtable<String, String>(); serviceProperties.put( Constants.SERVICE_ID, "org.ops4j.pax.logging.configuration" ); serviceProperties.put( Constants.SERVICE_PID, CONFIGURATION_PID ); m_RegistrationPaxLogging = bundleContext.registerService(LOG_SERVICE_INTERFACE_NAMES, m_paxLogging, serviceProperties); // Add a global handler for all JDK Logging (java.util.logging). if( !Boolean.valueOf(bundleContext.getProperty("org.ops4j.pax.logging.skipJUL")) ) { LogManager manager = LogManager.getLogManager(); if( !Boolean.valueOf(bundleContext.getProperty("org.ops4j.pax.logging.skipJULReset")) ) { manager.reset(); } // clear out old handlers Logger rootLogger = manager.getLogger( "" ); Handler[] handlers = rootLogger.getHandlers(); for (Handler handler : handlers) { rootLogger.removeHandler(handler); } rootLogger.setFilter(null); m_JdkHandler = new JdkHandler(m_paxLogging); rootLogger.addHandler( m_JdkHandler ); } m_frameworkHandler = new FrameworkHandler(m_paxLogging); bundleContext.addBundleListener( m_frameworkHandler ); bundleContext.addFrameworkListener( m_frameworkHandler ); bundleContext.addServiceListener( m_frameworkHandler ); } /** * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop( BundleContext bundleContext ) { // shut down the trackers. m_eventAdmin.destroy(); // Clean up the listeners. bundleContext.removeBundleListener( m_frameworkHandler ); bundleContext.removeFrameworkListener( m_frameworkHandler ); bundleContext.removeServiceListener( m_frameworkHandler ); // Remove the global handler for all JDK Logging (java.util.logging). if( m_JdkHandler != null ) { Logger rootLogger = LogManager.getLogManager().getLogger( "" ); rootLogger.removeHandler( m_JdkHandler ); m_JdkHandler.flush(); m_JdkHandler.close(); m_JdkHandler = null; } m_RegistrationPaxLogging.unregister(); m_RegistrationPaxLogging = null; m_registrationLogReaderService.unregister(); m_registrationLogReaderService = null; m_paxLogging.stop(); m_paxLogging = null; } }
pax-logging-logback/src/main/java/org/ops4j/pax/logging/logback/internal/Activator.java
/* * Copyright 2005 Niclas Hedhman. * Copyright 2011 Avid Technology, 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 org.ops4j.pax.logging.logback.internal; import org.ops4j.pax.logging.EventAdminPoster; import org.ops4j.pax.logging.PaxLoggingService; import org.ops4j.pax.logging.internal.eventadmin.EventAdminTracker; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.ManagedService; import org.osgi.service.log.LogEntry; import org.osgi.service.log.LogReaderService; import org.osgi.service.log.LogService; import java.util.Hashtable; import java.util.Map; import java.util.logging.Handler; import java.util.logging.LogManager; import java.util.logging.Logger; /** * Starts the logback log services. * * <p> * This code was originally derived from org.ops4j.pax.logging.service.internal.Activator v1.6.0. Changes include: * <ul> * <li>added a call to stop the service</li> * <li>added more logging to detect failures at start, which may be otherwise lost in early boot</li> * </ul> * * @author Chris Dolan -- some code derived from from pax-logging-service v1.6.0 */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE") public class Activator implements BundleActivator { /** * The Managed Service PID for the Logback configuration */ public static final String CONFIGURATION_PID = "org.ops4j.pax.logging"; private static final String[] LOG_SERVICE_INTERFACE_NAMES = { LogService.class.getName(), org.knopflerfish.service.log.LogService.class.getName(), PaxLoggingService.class.getName(), ManagedService.class.getName(), }; /** * Reference to the registered service */ private ServiceRegistration m_RegistrationPaxLogging; private JdkHandler m_JdkHandler; private ServiceRegistration m_registrationLogReaderService; private FrameworkHandler m_frameworkHandler; private EventAdminPoster m_eventAdmin; private PaxLoggingServiceImpl m_paxLogging; /** * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start( BundleContext bundleContext ) throws Exception { // This try/catch is to detect failures to load the logging framework, which otherwise are silent... try { startInternal(bundleContext); } catch (Exception e) { e.printStackTrace(); throw e; } catch (Error e) { e.printStackTrace(); throw e; } catch (Throwable e) { // NOPMD e.printStackTrace(); throw new RuntimeException(e); } } private void startInternal( BundleContext bundleContext ) { // register the LogReaderService LogReaderServiceImpl logReader = new LogReaderServiceImpl( 100 ); String readerServiceName = LogReaderService.class.getName(); m_registrationLogReaderService = bundleContext.registerService( readerServiceName, logReader, null ); // Tracking for the EventAdmin try { m_eventAdmin = new EventAdminTracker( bundleContext ); } catch( NoClassDefFoundError e ) { // If we hit a NoClassDefFoundError, this means the event admin package is not available, // so use a dummy poster m_eventAdmin = new EventAdminPoster() { public void postEvent( Bundle bundle, int level, LogEntry entry, String message, Throwable exception, ServiceReference sr, Map context ) { } public void destroy() { } }; } // register the Pax Logging service m_paxLogging = new PaxLoggingServiceImpl( bundleContext, logReader.getAccessDelegate(), m_eventAdmin ); Hashtable<String, String> serviceProperties = new Hashtable<String, String>(); serviceProperties.put( Constants.SERVICE_ID, "org.ops4j.pax.logging.configuration" ); serviceProperties.put( Constants.SERVICE_PID, CONFIGURATION_PID ); m_RegistrationPaxLogging = bundleContext.registerService(LOG_SERVICE_INTERFACE_NAMES, m_paxLogging, serviceProperties); // Add a global handler for all JDK Logging (java.util.logging). if( !Boolean.valueOf(bundleContext.getProperty("org.ops4j.pax.logging.skipJUL")) ) { LogManager manager = LogManager.getLogManager(); manager.reset(); // clear out old handlers Logger rootLogger = manager.getLogger( "" ); Handler[] handlers = rootLogger.getHandlers(); for (Handler handler : handlers) { rootLogger.removeHandler(handler); } rootLogger.setFilter(null); m_JdkHandler = new JdkHandler(m_paxLogging); rootLogger.addHandler( m_JdkHandler ); } m_frameworkHandler = new FrameworkHandler(m_paxLogging); bundleContext.addBundleListener( m_frameworkHandler ); bundleContext.addFrameworkListener( m_frameworkHandler ); bundleContext.addServiceListener( m_frameworkHandler ); } /** * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop( BundleContext bundleContext ) { // shut down the trackers. m_eventAdmin.destroy(); // Clean up the listeners. bundleContext.removeBundleListener( m_frameworkHandler ); bundleContext.removeFrameworkListener( m_frameworkHandler ); bundleContext.removeServiceListener( m_frameworkHandler ); // Remove the global handler for all JDK Logging (java.util.logging). if( m_JdkHandler != null ) { Logger rootLogger = LogManager.getLogManager().getLogger( "" ); rootLogger.removeHandler( m_JdkHandler ); m_JdkHandler.flush(); m_JdkHandler.close(); m_JdkHandler = null; } m_RegistrationPaxLogging.unregister(); m_RegistrationPaxLogging = null; m_registrationLogReaderService.unregister(); m_registrationLogReaderService = null; m_paxLogging.stop(); m_paxLogging = null; } }
Introduced property org.ops4j.pax.logging.skipJULReset to allow skipping the reset of JUL such that the LevelChangePropagator can function properly
pax-logging-logback/src/main/java/org/ops4j/pax/logging/logback/internal/Activator.java
Introduced property org.ops4j.pax.logging.skipJULReset to allow skipping the reset of JUL such that the LevelChangePropagator can function properly
<ide><path>ax-logging-logback/src/main/java/org/ops4j/pax/logging/logback/internal/Activator.java <ide> if( !Boolean.valueOf(bundleContext.getProperty("org.ops4j.pax.logging.skipJUL")) ) <ide> { <ide> LogManager manager = LogManager.getLogManager(); <del> manager.reset(); <add> <add> if( !Boolean.valueOf(bundleContext.getProperty("org.ops4j.pax.logging.skipJULReset")) ) <add> { <add> manager.reset(); <add> } <ide> <ide> // clear out old handlers <ide> Logger rootLogger = manager.getLogger( "" );
Java
epl-1.0
8ad9ab4182e67d6b99b1575627ae1f49f4de5f1d
0
ubc-cs-spl/command-recommender,ubc-cs-spl/command-recommender,ubc-cs-spl/command-recommender,ubc-cs-spl/command-recommender,ubc-cs-spl/command-recommender
package ca.ubc.ca.ocrreader; import java.io.File; public class ContextCompareLoader { public static void main(String[] args) { ContextManager manager = new ContextManager(); // the folder where images are stored should be passed as the param // FIXME currently hard coded for testing purposes // TODO add last modified time to files, ContextManager and Context // constructor // get the directory where images are stored File imgDir = new File("~/Desktop/testImageFiles"); // iterate over all files and pass to ContextManager File[] files = imgDir.listFiles(); for (File file : files) { // TODO check if this is an image file, not other or dir manager.addContext(file); } } }
src/ca/ubc/ca/ocrreader/ContextCompareLoader.java
package ca.ubc.ca.ocrreader; public class ContextCompareLoader { public static void main(String[] args) { // get the file where images are stored // iterate over all files and pass to ContextManager // delete files when done? } }
Implement first shot at main method
src/ca/ubc/ca/ocrreader/ContextCompareLoader.java
Implement first shot at main method
<ide><path>rc/ca/ubc/ca/ocrreader/ContextCompareLoader.java <ide> package ca.ubc.ca.ocrreader; <add> <add>import java.io.File; <ide> <ide> public class ContextCompareLoader { <ide> <add> <ide> public static void main(String[] args) { <del> // get the file where images are stored <add> ContextManager manager = new ContextManager(); <add> // the folder where images are stored should be passed as the param <add> // FIXME currently hard coded for testing purposes <add> // TODO add last modified time to files, ContextManager and Context <add> // constructor <add> <add> // get the directory where images are stored <add> File imgDir = new File("~/Desktop/testImageFiles"); <add> <ide> // iterate over all files and pass to ContextManager <del> // delete files when done? <add> File[] files = imgDir.listFiles(); <add> <add> for (File file : files) { <add> // TODO check if this is an image file, not other or dir <add> manager.addContext(file); <add> } <ide> } <ide> }
Java
mit
03de2db0a4d96c6807decb85d0947d7413419227
0
webjars/webjars-locator-core,webjars/webjars-locator-core
package org.webjars; import org.apache.catalina.LifecycleException; import org.apache.catalina.core.StandardContext; import org.apache.catalina.webresources.StandardRoot; import org.apache.catalina.webresources.WarResourceSet; import org.junit.Test; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedWebappClassLoader; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.*; public class WebJarAssetLocatorTest { private HashMap<String, WebJarAssetLocator.WebJarInfo> withList(List<String> paths) throws URISyntaxException { HashMap<String, WebJarAssetLocator.WebJarInfo> webJars = new HashMap<>(); WebJarAssetLocator.WebJarInfo webJarInfo = new WebJarAssetLocator.WebJarInfo("1.0.0", "foo", new URI("asdf"), paths); webJars.put("foo", webJarInfo); return webJars; } @Test public void should_find_full_path() throws Exception { WebJarAssetLocator locator = new WebJarAssetLocator(withList(asList("META-INF/resources/myapp/app.js", "assets/users/login.css"))); assertEquals("META-INF/resources/myapp/app.js", locator.getFullPath("app.js")); assertEquals("META-INF/resources/myapp/app.js", locator.getFullPath("myapp/app.js")); assertEquals("assets/users/login.css", locator.getFullPath("login.css")); assertEquals("assets/users/login.css", locator.getFullPath("users/login.css")); } @Test public void should_list_assets() throws Exception { WebJarAssetLocator locator = new WebJarAssetLocator(withList(asList("META-INF/resources/myapp/app.js", "assets/users/login.css", "META-INF/resources/webjars/third_party/1.5.2/file.js"))); assertThat(locator.listAssets("META-INF"), containsInAnyOrder("META-INF/resources/myapp/app.js", "META-INF/resources/webjars/third_party/1.5.2/file.js")); assertThat(locator.listAssets("assets"), contains("assets/users/login.css")); assertThat(locator.listAssets("third_party"), contains("META-INF/resources/webjars/third_party/1.5.2/file.js")); assertThat(locator.listAssets(), containsInAnyOrder("META-INF/resources/myapp/app.js", "assets/users/login.css", "META-INF/resources/webjars/third_party/1.5.2/file.js")); } @Test public void get_paths_of_asset_in_nested_folder() { WebJarAssetLocator locator = new WebJarAssetLocator(); String jsPath1 = locator.getFullPath("angular-translate.js"); assertEquals("META-INF/resources/webjars/angular-translate/2.1.0/angular-translate.js", jsPath1); String jsPath2 = locator.getFullPath("require.js"); assertEquals("META-INF/resources/webjars/requirejs/2.3.6/require.js", jsPath2); } @Test public void get_full_path_of_asset_in_root_folder() { String jsFullPath = new WebJarAssetLocator().getFullPath("jquery.js"); assertEquals("META-INF/resources/webjars/jquery/2.1.0/jquery.js", jsFullPath); } @Test public void lookup_asset_multiple_times() { WebJarAssetLocator locator = new WebJarAssetLocator(); String jsPath1 = locator.getFullPath("jquery.js"); String jsPath2 = locator.getFullPath("jquery.js"); assertEquals("META-INF/resources/webjars/jquery/2.1.0/jquery.js", jsPath1); assertEquals("META-INF/resources/webjars/jquery/2.1.0/jquery.js", jsPath2); } @Test public void get_a_file_when_another_file_exists_that_starts_with_the_same_string() { String fooJsPath = new WebJarAssetLocator().getFullPath("foo.js"); assertEquals("META-INF/resources/webjars/foo/1.0.0/foo.js", fooJsPath); } @Test public void get_full_path_from_partial_path_with_folders() { WebJarAssetLocator locator = new WebJarAssetLocator(); String jsPath1 = locator.getFullPath("i18n/angular-locale_en.js"); String jsPath2 = locator.getFullPath("/1.2.11/i18n/angular-locale_en.js"); String jsPath3 = locator.getFullPath("angularjs/1.2.11/i18n/angular-locale_en.js"); String jsPath4 = locator.getFullPath("/angularjs/1.2.11/i18n/angular-locale_en.js"); String expected = "META-INF/resources/webjars/angularjs/1.2.11/i18n/angular-locale_en.js"; assertEquals(expected, jsPath1); assertEquals(expected, jsPath2); assertEquals(expected, jsPath3); assertEquals(expected, jsPath4); } @Test public void should_throw_exception_when_asset_not_found() { try { new WebJarAssetLocator().getFullPath("asset-unknown.js"); fail("Exception should have been thrown!"); } catch (IllegalArgumentException e) { assertEquals("asset-unknown.js could not be found. Make sure you've added the corresponding WebJar and please check for typos.", e.getMessage()); } try { new WebJarAssetLocator().getFullPath("unknown.js"); fail("Exception should have been thrown!"); } catch (IllegalArgumentException e) { assertEquals("unknown.js could not be found. Make sure you've added the corresponding WebJar and please check for typos.", e.getMessage()); } } @Test public void should_distinguish_between_multiple_versions() { WebJarAssetLocator locator = new WebJarAssetLocator(); String v1Path = locator.getFullPath("1.0.0/multiple.js"); String v2Path = locator.getFullPath("2.0.0/multiple.js"); String moduleV2Path = locator.getFullPath("2.0.0/module/multiple_module.js"); assertEquals("META-INF/resources/webjars/multiple/1.0.0/multiple.js", v1Path); assertEquals("META-INF/resources/webjars/multiple/2.0.0/multiple.js", v2Path); assertEquals("META-INF/resources/webjars/multiple/2.0.0/module/multiple_module.js", moduleV2Path); } @Test public void should_accept_paths_with_spaces() { WebJarAssetLocator locator = new WebJarAssetLocator(); String path1 = locator.getFullPath("space space.js"); assertEquals("META-INF/resources/webjars/spaces/1.0.0/space space.js", path1); } @Test public void should_work_with_classpath_containing_spaces() throws java.net.MalformedURLException { WebJarAssetLocator locator = buildAssetLocatorWithPath(new File("src/test/resources/space space").toURI().toURL()); String path = locator.getFullPath("spaces/2.0.0/spaces.js"); assertEquals(path, "META-INF/resources/webjars/spaces/2.0.0/spaces.js"); } @Test public void should_work_with_classpath_containing_escaped_spaces() throws java.net.MalformedURLException { // this kind of escaped path is often created via URI.toUrl(), and should also work WebJarAssetLocator locator = buildAssetLocatorWithPath(new File("src/test/resources/space space").toURI().toURL()); String path = locator.getFullPath("spaces/2.0.0/spaces.js"); assertEquals(path, "META-INF/resources/webjars/spaces/2.0.0/spaces.js"); } private WebJarAssetLocator buildAssetLocatorWithPath(URL url) { URLClassLoader classLoader = new URLClassLoader(new java.net.URL[]{url}, ClassLoader.getSystemClassLoader()); return new WebJarAssetLocator(classLoader); } @Test public void should_throw_exceptions_when_several_matches_found() { try { new WebJarAssetLocator().getFullPath("multiple.js"); fail("Exception should have been thrown!"); } catch (MultipleMatchesException e) { assertEquals("Multiple matches found for multiple.js. Please provide a more specific path, for example by including a version number.", e.getMessage()); assertThat(e.getMatches(), containsInAnyOrder("META-INF/resources/webjars/multiple/2.0.0/multiple.js", "META-INF/resources/webjars/multiple/1.0.0/multiple.js")); } } @Test public void should_throw_exceptions_when_all_assets_match() { try { new WebJarAssetLocator(withList(Arrays.asList("a/multi.js", "b/multi.js"))).getFullPath("multi.js"); } catch (MultipleMatchesException e) { assertThat(e.getMatches(), containsInAnyOrder("b/multi.js", "a/multi.js")); } catch (URISyntaxException e) { fail("should not fail"); } } @Test public void should_throw_exceptions_when_several_matches_found_with_folder_in_path() { try { new WebJarAssetLocator().getFullPath("module/multiple_module.js"); fail("Exception should have been thrown!"); } catch (MultipleMatchesException e) { assertEquals("Multiple matches found for module/multiple_module.js. Please provide a more specific path, for example by including a version number.", e.getMessage()); } } @Test public void should_list_assets_in_folder() { String fullPathPrefix = "META-INF/resources/webjars/multiple/1.0.0/"; Set<String> assets = new WebJarAssetLocator().listAssets("/multiple/1.0.0"); assertThat(assets, hasItems(fullPathPrefix + "multiple.js", fullPathPrefix + "module/multiple_module.js")); } @Test public void should_find_assets_in_a_given_webjar() { // resolving bootstrap.js out of the bootstrap webjar should work String bootstrapJsPath = new WebJarAssetLocator().getFullPath("bootstrap", "bootstrap.js"); assertEquals(bootstrapJsPath, "META-INF/resources/webjars/bootstrap/3.1.1/js/bootstrap.js"); // resolving bootstrap.js out of the bootswatch-yeti webjar should work String bootswatchYetiJsPath = new WebJarAssetLocator().getFullPath("bootswatch-yeti", "bootstrap.js"); assertEquals(bootswatchYetiJsPath, "META-INF/resources/webjars/bootswatch-yeti/3.1.1/js/bootstrap.js"); // resolving a more specific path out of the bootstrap webjar should work String moreSpecificBootstrapJsPath = new WebJarAssetLocator().getFullPath("bootstrap", "js/bootstrap.js"); assertEquals(moreSpecificBootstrapJsPath, "META-INF/resources/webjars/bootstrap/3.1.1/js/bootstrap.js"); // resolving a non-existent file out of the bootstrap webjar should fail try { new WebJarAssetLocator().getFullPath("bootstrap", "asdf.js"); fail("Exception should have been thrown!"); } catch (NotFoundException e) { assertEquals("asdf.js could not be found. Make sure you've added the corresponding WebJar and please check for typos.", e.getMessage()); } // resolving the bootstrap.js file out of the jquery webjar should fail try { new WebJarAssetLocator().getFullPath("jquery", "bootstrap.js"); fail("Exception should have been thrown!"); } catch (NotFoundException e) { assertEquals("bootstrap.js could not be found. Make sure you've added the corresponding WebJar and please check for typos.", e.getMessage()); } } @Test public void should_parse_a_webjar_from_a_path() { Map.Entry<String, String> webjar1 = WebJarAssetLocator.getWebJar("META-INF/resources/webjars/foo/1.0.0/asdf.js"); assert webjar1 != null; assertEquals(webjar1.getKey(), "foo"); assertEquals(webjar1.getValue(), "1.0.0"); Map.Entry<String, String> webjar2 = WebJarAssetLocator.getWebJar("META-INF/resources/webjars/virtual-keyboard/1.30.1/dist/js/jquery.keyboard.min.js"); assert webjar2 != null; assertEquals(webjar2.getKey(), "virtual-keyboard"); assertEquals(webjar2.getValue(), "1.30.1"); } @Test public void invalid_webjar_path_should_return_null() { assertNull(WebJarAssetLocator.getWebJar("foo/1.0.0/asdf.js")); } @Test public void should_get_a_list_of_webjars() { Map<String, String> webjars = new WebJarAssetLocator().getWebJars(); assertEquals(webjars.size(), 36); // this is the pom.xml ones plus the test resources (spaces, foo, bar-node, multiple) assertEquals(webjars.get("bootstrap"), "3.1.1"); assertEquals(webjars.get("less-node"), "1.6.0"); assertEquals(webjars.get("jquery"), "2.1.0"); assertEquals(webjars.get("angularjs"), "1.2.11"); assertEquals(webjars.get("virtual-keyboard"), "1.30.1"); } @Test public void should_match_when_full_path_given() { WebJarAssetLocator locator = new WebJarAssetLocator(); assertEquals("META-INF/resources/webjars/bootstrap/3.1.1/less/.csscomb.json", locator.getFullPath("META-INF/resources/webjars/bootstrap/3.1.1/less/.csscomb.json")); } @Test public void should_throw_exceptions_when_several_matches_found_different_dependencies() { try { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); webJarAssetLocator.getFullPath("angular.js"); fail("Exception should have been thrown!"); // because it is in both dependencies } catch (MultipleMatchesException e) { assertEquals("Multiple matches found for angular.js. Please provide a more specific path, for example by including a version number.", e.getMessage()); } } @Test public void should_NOT_throw_exceptions_when_several_matches_found_different_dependencies_with_narrow_down() { try { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); webJarAssetLocator.getFullPath("angularjs", "angular.js"); } catch (MultipleMatchesException e) { fail("Exception should NOT have been thrown!"); // because it is supposed to look in first dependency only. } } @Test public void should_throw_an_exception_when_several_matches_are_found_in_a_single_dependency() { try { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); webJarAssetLocator.getFullPath("babel-core", "browser.js"); fail("Exception should have been thrown!"); } catch (MultipleMatchesException e) { assertEquals("Multiple matches found for browser.js. Please provide a more specific path, for example by including a version number.", e.getMessage()); } } @Test public void should_get_a_full_path_from_an_artifact_and_a_path() { try { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); String fullPath1 = webJarAssetLocator.getFullPathExact("babel-core", "browser.js"); assertEquals("META-INF/resources/webjars/babel-core/6.0.16/browser.js", fullPath1); String fullPath2 = webJarAssetLocator.getFullPathExact("virtual-keyboard", "dist/js/jquery.keyboard.min.js"); assertEquals("META-INF/resources/webjars/virtual-keyboard/1.30.1/dist/js/jquery.keyboard.min.js", fullPath2); } catch (MultipleMatchesException e) { fail("Exception should NOT have been thrown!"); } } @Test public void should_get_null_from_an_artifact_and_a_path_which_does_not_exist() { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); String fullPath = webJarAssetLocator.getFullPathExact("babel-core", "foo.js"); assertNull(fullPath); } @Test public void should_work_with_war_files() throws IOException, LifecycleException { URL fatjar = WebJarAssetLocatorTest.class.getClassLoader().getResource("fatjar.war"); assert fatjar != null; String fatJarWarFile = fatjar.getFile(); URL fatJarWarUrl = new URL("jar:file:" + fatJarWarFile + "!/"); URLClassLoader fatJarWarClassLoader = new URLClassLoader(new URL[]{fatJarWarUrl}, null); TomcatEmbeddedWebappClassLoader tomcatEmbeddedWebappClassLoader = new TomcatEmbeddedWebappClassLoader(fatJarWarClassLoader); StandardContext context = new StandardContext(); context.setName("test"); StandardRoot resources = new StandardRoot(); resources.setContext(context); resources.addJarResources(new WarResourceSet(resources, "/", fatJarWarFile)); resources.start(); tomcatEmbeddedWebappClassLoader.setResources(resources); tomcatEmbeddedWebappClassLoader.start(); WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(tomcatEmbeddedWebappClassLoader); tomcatEmbeddedWebappClassLoader.destroy(); assertEquals("META-INF/resources/webjars/jquery/1.10.2/jquery.js", webJarAssetLocator.getFullPath("jquery.js")); } // The org.webjars.npm:virtual-keyboard:1.30.1 jar contains root files named META-INF, resources, webjars which are not directories @Test public void should_work_with_a_bad_jar() { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); assertNotNull(webJarAssetLocator.getFullPathExact("virtual-keyboard", "dist/js/jquery.keyboard.min.js")); } @Test public void should_work_with_directoryless_jar() { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); Set<String> webjars = webJarAssetLocator.getWebJars().keySet(); assertTrue(webjars.contains("vaadin-form-layout")); } @Test public void should_get_groupids() { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); assertEquals("org.webjars.bowergithub.polymerelements", webJarAssetLocator.groupId("META-INF/resources/webjars/iron-flex-layout/iron-flex-layout.d.ts")); assertEquals("org.webjars.npm", webJarAssetLocator.groupId("META-INF/resources/webjars/angular-ui-router/0.2.15/release/angular-ui-router.js")); assertEquals("org.webjars", webJarAssetLocator.groupId("META-INF/resources/webjars/bootstrap/3.1.1/css/bootstrap.css")); } }
src/test/java/org/webjars/WebJarAssetLocatorTest.java
package org.webjars; import org.apache.catalina.LifecycleException; import org.apache.catalina.core.StandardContext; import org.apache.catalina.webresources.StandardRoot; import org.apache.catalina.webresources.WarResourceSet; import org.junit.Test; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedWebappClassLoader; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.*; public class WebJarAssetLocatorTest { private HashMap<String, WebJarAssetLocator.WebJarInfo> withList(List<String> paths) throws URISyntaxException { HashMap<String, WebJarAssetLocator.WebJarInfo> webJars = new HashMap<>(); WebJarAssetLocator.WebJarInfo webJarInfo = new WebJarAssetLocator.WebJarInfo("1.0.0", "foo", new URI("asdf"), paths); webJars.put("foo", webJarInfo); return webJars; } @Test public void should_find_full_path() throws Exception { WebJarAssetLocator locator = new WebJarAssetLocator(withList(asList("META-INF/resources/myapp/app.js", "assets/users/login.css"))); assertEquals("META-INF/resources/myapp/app.js", locator.getFullPath("app.js")); assertEquals("META-INF/resources/myapp/app.js", locator.getFullPath("myapp/app.js")); assertEquals("assets/users/login.css", locator.getFullPath("login.css")); assertEquals("assets/users/login.css", locator.getFullPath("users/login.css")); } @Test public void should_list_assets() throws Exception { WebJarAssetLocator locator = new WebJarAssetLocator(withList(asList("META-INF/resources/myapp/app.js", "assets/users/login.css", "META-INF/resources/webjars/third_party/1.5.2/file.js"))); assertThat(locator.listAssets("META-INF"), contains("META-INF/resources/myapp/app.js", "META-INF/resources/webjars/third_party/1.5.2/file.js")); assertThat(locator.listAssets("assets"), contains("assets/users/login.css")); assertThat(locator.listAssets("third_party"), contains("META-INF/resources/webjars/third_party/1.5.2/file.js")); assertThat(locator.listAssets(), contains("META-INF/resources/myapp/app.js", "assets/users/login.css", "META-INF/resources/webjars/third_party/1.5.2/file.js")); } @Test public void get_paths_of_asset_in_nested_folder() { WebJarAssetLocator locator = new WebJarAssetLocator(); String jsPath1 = locator.getFullPath("angular-translate.js"); assertEquals("META-INF/resources/webjars/angular-translate/2.1.0/angular-translate.js", jsPath1); String jsPath2 = locator.getFullPath("require.js"); assertEquals("META-INF/resources/webjars/requirejs/2.3.6/require.js", jsPath2); } @Test public void get_full_path_of_asset_in_root_folder() { String jsFullPath = new WebJarAssetLocator().getFullPath("jquery.js"); assertEquals("META-INF/resources/webjars/jquery/2.1.0/jquery.js", jsFullPath); } @Test public void lookup_asset_multiple_times() { WebJarAssetLocator locator = new WebJarAssetLocator(); String jsPath1 = locator.getFullPath("jquery.js"); String jsPath2 = locator.getFullPath("jquery.js"); assertEquals("META-INF/resources/webjars/jquery/2.1.0/jquery.js", jsPath1); assertEquals("META-INF/resources/webjars/jquery/2.1.0/jquery.js", jsPath2); } @Test public void get_a_file_when_another_file_exists_that_starts_with_the_same_string() { String fooJsPath = new WebJarAssetLocator().getFullPath("foo.js"); assertEquals("META-INF/resources/webjars/foo/1.0.0/foo.js", fooJsPath); } @Test public void get_full_path_from_partial_path_with_folders() { WebJarAssetLocator locator = new WebJarAssetLocator(); String jsPath1 = locator.getFullPath("i18n/angular-locale_en.js"); String jsPath2 = locator.getFullPath("/1.2.11/i18n/angular-locale_en.js"); String jsPath3 = locator.getFullPath("angularjs/1.2.11/i18n/angular-locale_en.js"); String jsPath4 = locator.getFullPath("/angularjs/1.2.11/i18n/angular-locale_en.js"); String expected = "META-INF/resources/webjars/angularjs/1.2.11/i18n/angular-locale_en.js"; assertEquals(expected, jsPath1); assertEquals(expected, jsPath2); assertEquals(expected, jsPath3); assertEquals(expected, jsPath4); } @Test public void should_throw_exception_when_asset_not_found() { try { new WebJarAssetLocator().getFullPath("asset-unknown.js"); fail("Exception should have been thrown!"); } catch (IllegalArgumentException e) { assertEquals("asset-unknown.js could not be found. Make sure you've added the corresponding WebJar and please check for typos.", e.getMessage()); } try { new WebJarAssetLocator().getFullPath("unknown.js"); fail("Exception should have been thrown!"); } catch (IllegalArgumentException e) { assertEquals("unknown.js could not be found. Make sure you've added the corresponding WebJar and please check for typos.", e.getMessage()); } } @Test public void should_distinguish_between_multiple_versions() { WebJarAssetLocator locator = new WebJarAssetLocator(); String v1Path = locator.getFullPath("1.0.0/multiple.js"); String v2Path = locator.getFullPath("2.0.0/multiple.js"); String moduleV2Path = locator.getFullPath("2.0.0/module/multiple_module.js"); assertEquals("META-INF/resources/webjars/multiple/1.0.0/multiple.js", v1Path); assertEquals("META-INF/resources/webjars/multiple/2.0.0/multiple.js", v2Path); assertEquals("META-INF/resources/webjars/multiple/2.0.0/module/multiple_module.js", moduleV2Path); } @Test public void should_accept_paths_with_spaces() { WebJarAssetLocator locator = new WebJarAssetLocator(); String path1 = locator.getFullPath("space space.js"); assertEquals("META-INF/resources/webjars/spaces/1.0.0/space space.js", path1); } @Test public void should_work_with_classpath_containing_spaces() throws java.net.MalformedURLException { WebJarAssetLocator locator = buildAssetLocatorWithPath(new File("src/test/resources/space space").toURI().toURL()); String path = locator.getFullPath("spaces/2.0.0/spaces.js"); assertEquals(path, "META-INF/resources/webjars/spaces/2.0.0/spaces.js"); } @Test public void should_work_with_classpath_containing_escaped_spaces() throws java.net.MalformedURLException { // this kind of escaped path is often created via URI.toUrl(), and should also work WebJarAssetLocator locator = buildAssetLocatorWithPath(new File("src/test/resources/space space").toURI().toURL()); String path = locator.getFullPath("spaces/2.0.0/spaces.js"); assertEquals(path, "META-INF/resources/webjars/spaces/2.0.0/spaces.js"); } private WebJarAssetLocator buildAssetLocatorWithPath(URL url) { URLClassLoader classLoader = new URLClassLoader(new java.net.URL[]{url}, ClassLoader.getSystemClassLoader()); return new WebJarAssetLocator(classLoader); } @Test public void should_throw_exceptions_when_several_matches_found() { try { new WebJarAssetLocator().getFullPath("multiple.js"); fail("Exception should have been thrown!"); } catch (MultipleMatchesException e) { assertEquals("Multiple matches found for multiple.js. Please provide a more specific path, for example by including a version number.", e.getMessage()); assertThat(e.getMatches(), containsInAnyOrder("META-INF/resources/webjars/multiple/2.0.0/multiple.js", "META-INF/resources/webjars/multiple/1.0.0/multiple.js")); } } @Test public void should_throw_exceptions_when_all_assets_match() { try { new WebJarAssetLocator(withList(Arrays.asList("a/multi.js", "b/multi.js"))).getFullPath("multi.js"); } catch (MultipleMatchesException e) { assertThat(e.getMatches(), containsInAnyOrder("b/multi.js", "a/multi.js")); } catch (URISyntaxException e) { fail("should not fail"); } } @Test public void should_throw_exceptions_when_several_matches_found_with_folder_in_path() { try { new WebJarAssetLocator().getFullPath("module/multiple_module.js"); fail("Exception should have been thrown!"); } catch (MultipleMatchesException e) { assertEquals("Multiple matches found for module/multiple_module.js. Please provide a more specific path, for example by including a version number.", e.getMessage()); } } @Test public void should_list_assets_in_folder() { String fullPathPrefix = "META-INF/resources/webjars/multiple/1.0.0/"; Set<String> assets = new WebJarAssetLocator().listAssets("/multiple/1.0.0"); assertThat(assets, hasItems(fullPathPrefix + "multiple.js", fullPathPrefix + "module/multiple_module.js")); } @Test public void should_find_assets_in_a_given_webjar() { // resolving bootstrap.js out of the bootstrap webjar should work String bootstrapJsPath = new WebJarAssetLocator().getFullPath("bootstrap", "bootstrap.js"); assertEquals(bootstrapJsPath, "META-INF/resources/webjars/bootstrap/3.1.1/js/bootstrap.js"); // resolving bootstrap.js out of the bootswatch-yeti webjar should work String bootswatchYetiJsPath = new WebJarAssetLocator().getFullPath("bootswatch-yeti", "bootstrap.js"); assertEquals(bootswatchYetiJsPath, "META-INF/resources/webjars/bootswatch-yeti/3.1.1/js/bootstrap.js"); // resolving a more specific path out of the bootstrap webjar should work String moreSpecificBootstrapJsPath = new WebJarAssetLocator().getFullPath("bootstrap", "js/bootstrap.js"); assertEquals(moreSpecificBootstrapJsPath, "META-INF/resources/webjars/bootstrap/3.1.1/js/bootstrap.js"); // resolving a non-existent file out of the bootstrap webjar should fail try { new WebJarAssetLocator().getFullPath("bootstrap", "asdf.js"); fail("Exception should have been thrown!"); } catch (NotFoundException e) { assertEquals("asdf.js could not be found. Make sure you've added the corresponding WebJar and please check for typos.", e.getMessage()); } // resolving the bootstrap.js file out of the jquery webjar should fail try { new WebJarAssetLocator().getFullPath("jquery", "bootstrap.js"); fail("Exception should have been thrown!"); } catch (NotFoundException e) { assertEquals("bootstrap.js could not be found. Make sure you've added the corresponding WebJar and please check for typos.", e.getMessage()); } } @Test public void should_parse_a_webjar_from_a_path() { Map.Entry<String, String> webjar1 = WebJarAssetLocator.getWebJar("META-INF/resources/webjars/foo/1.0.0/asdf.js"); assert webjar1 != null; assertEquals(webjar1.getKey(), "foo"); assertEquals(webjar1.getValue(), "1.0.0"); Map.Entry<String, String> webjar2 = WebJarAssetLocator.getWebJar("META-INF/resources/webjars/virtual-keyboard/1.30.1/dist/js/jquery.keyboard.min.js"); assert webjar2 != null; assertEquals(webjar2.getKey(), "virtual-keyboard"); assertEquals(webjar2.getValue(), "1.30.1"); } @Test public void invalid_webjar_path_should_return_null() { assertNull(WebJarAssetLocator.getWebJar("foo/1.0.0/asdf.js")); } @Test public void should_get_a_list_of_webjars() { Map<String, String> webjars = new WebJarAssetLocator().getWebJars(); assertEquals(webjars.size(), 36); // this is the pom.xml ones plus the test resources (spaces, foo, bar-node, multiple) assertEquals(webjars.get("bootstrap"), "3.1.1"); assertEquals(webjars.get("less-node"), "1.6.0"); assertEquals(webjars.get("jquery"), "2.1.0"); assertEquals(webjars.get("angularjs"), "1.2.11"); assertEquals(webjars.get("virtual-keyboard"), "1.30.1"); } @Test public void should_match_when_full_path_given() { WebJarAssetLocator locator = new WebJarAssetLocator(); assertEquals("META-INF/resources/webjars/bootstrap/3.1.1/less/.csscomb.json", locator.getFullPath("META-INF/resources/webjars/bootstrap/3.1.1/less/.csscomb.json")); } @Test public void should_throw_exceptions_when_several_matches_found_different_dependencies() { try { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); webJarAssetLocator.getFullPath("angular.js"); fail("Exception should have been thrown!"); // because it is in both dependencies } catch (MultipleMatchesException e) { assertEquals("Multiple matches found for angular.js. Please provide a more specific path, for example by including a version number.", e.getMessage()); } } @Test public void should_NOT_throw_exceptions_when_several_matches_found_different_dependencies_with_narrow_down() { try { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); webJarAssetLocator.getFullPath("angularjs", "angular.js"); } catch (MultipleMatchesException e) { fail("Exception should NOT have been thrown!"); // because it is supposed to look in first dependency only. } } @Test public void should_throw_an_exception_when_several_matches_are_found_in_a_single_dependency() { try { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); webJarAssetLocator.getFullPath("babel-core", "browser.js"); fail("Exception should have been thrown!"); } catch (MultipleMatchesException e) { assertEquals("Multiple matches found for browser.js. Please provide a more specific path, for example by including a version number.", e.getMessage()); } } @Test public void should_get_a_full_path_from_an_artifact_and_a_path() { try { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); String fullPath1 = webJarAssetLocator.getFullPathExact("babel-core", "browser.js"); assertEquals("META-INF/resources/webjars/babel-core/6.0.16/browser.js", fullPath1); String fullPath2 = webJarAssetLocator.getFullPathExact("virtual-keyboard", "dist/js/jquery.keyboard.min.js"); assertEquals("META-INF/resources/webjars/virtual-keyboard/1.30.1/dist/js/jquery.keyboard.min.js", fullPath2); } catch (MultipleMatchesException e) { fail("Exception should NOT have been thrown!"); } } @Test public void should_get_null_from_an_artifact_and_a_path_which_does_not_exist() { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); String fullPath = webJarAssetLocator.getFullPathExact("babel-core", "foo.js"); assertNull(fullPath); } @Test public void should_work_with_war_files() throws IOException, LifecycleException { URL fatjar = WebJarAssetLocatorTest.class.getClassLoader().getResource("fatjar.war"); assert fatjar != null; String fatJarWarFile = fatjar.getFile(); URL fatJarWarUrl = new URL("jar:file:" + fatJarWarFile + "!/"); URLClassLoader fatJarWarClassLoader = new URLClassLoader(new URL[]{fatJarWarUrl}, null); TomcatEmbeddedWebappClassLoader tomcatEmbeddedWebappClassLoader = new TomcatEmbeddedWebappClassLoader(fatJarWarClassLoader); StandardContext context = new StandardContext(); context.setName("test"); StandardRoot resources = new StandardRoot(); resources.setContext(context); resources.addJarResources(new WarResourceSet(resources, "/", fatJarWarFile)); resources.start(); tomcatEmbeddedWebappClassLoader.setResources(resources); tomcatEmbeddedWebappClassLoader.start(); WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(tomcatEmbeddedWebappClassLoader); tomcatEmbeddedWebappClassLoader.destroy(); assertEquals("META-INF/resources/webjars/jquery/1.10.2/jquery.js", webJarAssetLocator.getFullPath("jquery.js")); } // The org.webjars.npm:virtual-keyboard:1.30.1 jar contains root files named META-INF, resources, webjars which are not directories @Test public void should_work_with_a_bad_jar() { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); assertNotNull(webJarAssetLocator.getFullPathExact("virtual-keyboard", "dist/js/jquery.keyboard.min.js")); } @Test public void should_work_with_directoryless_jar() { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); Set<String> webjars = webJarAssetLocator.getWebJars().keySet(); assertTrue(webjars.contains("vaadin-form-layout")); } @Test public void should_get_groupids() { WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); assertEquals("org.webjars.bowergithub.polymerelements", webJarAssetLocator.groupId("META-INF/resources/webjars/iron-flex-layout/iron-flex-layout.d.ts")); assertEquals("org.webjars.npm", webJarAssetLocator.groupId("META-INF/resources/webjars/angular-ui-router/0.2.15/release/angular-ui-router.js")); assertEquals("org.webjars", webJarAssetLocator.groupId("META-INF/resources/webjars/bootstrap/3.1.1/css/bootstrap.css")); } }
classpath ordering fix
src/test/java/org/webjars/WebJarAssetLocatorTest.java
classpath ordering fix
<ide><path>rc/test/java/org/webjars/WebJarAssetLocatorTest.java <ide> public void should_list_assets() throws Exception { <ide> WebJarAssetLocator locator = new WebJarAssetLocator(withList(asList("META-INF/resources/myapp/app.js", "assets/users/login.css", "META-INF/resources/webjars/third_party/1.5.2/file.js"))); <ide> <del> assertThat(locator.listAssets("META-INF"), contains("META-INF/resources/myapp/app.js", "META-INF/resources/webjars/third_party/1.5.2/file.js")); <add> assertThat(locator.listAssets("META-INF"), containsInAnyOrder("META-INF/resources/myapp/app.js", "META-INF/resources/webjars/third_party/1.5.2/file.js")); <ide> assertThat(locator.listAssets("assets"), contains("assets/users/login.css")); <ide> assertThat(locator.listAssets("third_party"), contains("META-INF/resources/webjars/third_party/1.5.2/file.js")); <del> assertThat(locator.listAssets(), contains("META-INF/resources/myapp/app.js", "assets/users/login.css", "META-INF/resources/webjars/third_party/1.5.2/file.js")); <add> assertThat(locator.listAssets(), containsInAnyOrder("META-INF/resources/myapp/app.js", "assets/users/login.css", "META-INF/resources/webjars/third_party/1.5.2/file.js")); <ide> } <ide> <ide> @Test
JavaScript
mit
c258eb4f0d3039570ea042cbbd93c7a208640910
0
gmmorris/Modularizer
var dom = require('./utils/dom.js'), chai = require('chai'), expect = chai.expect, assert = require('simple-assert'), _ = require('underscore'); describe('Modularizer Module management', function() { // Create a fake global `window` and `document` object and inject default script dom.init(true); describe('load()', function() { it('should return false if no loader is specified', function() { var myModularizer = new window.Modularizer({ detectJQuery : false, loader : false }), PATH = 'path/to/file.js', MY_PRE_REQUISITE = 'my.module', pckg = myModularizer.register(PATH) .defines(MY_PRE_REQUISITE,function(){ return {}; }); assert(myModularizer.load('my.module') === false); }); it('should accept a single module name', function(done) { var PRE_REQ_PATH = '1/path/to/file.js',PATH = '2/path/to/file.js', MY_MODULE = 'my.module', MY_SECOND_MODULE = 'my.2.module', myModularizer = new window.Modularizer({ loader : function(pathToLoad){ pathToLoad.should.equal(PRE_REQ_PATH); done(); } }); myModularizer.register(PRE_REQ_PATH).defines(MY_MODULE); myModularizer.register(PATH).defines(MY_SECOND_MODULE); myModularizer.load(MY_MODULE); }); it('should accept an array of module names', function(done) { var PRE_REQ_PATH = '1/path/to/file.js', PATH = '2/path/to/file.js', MY_MODULE = 'my.module', MY_SECOND_MODULE = 'my.2.module', pathsThatShouldBeRequired = [PRE_REQ_PATH,PATH], myModularizer = new window.Modularizer({ loader : function(pathToLoad){ if(_.contains(pathsThatShouldBeRequired, pathToLoad)){ pathsThatShouldBeRequired = _.without(pathsThatShouldBeRequired,pathToLoad); } if(!pathsThatShouldBeRequired.length){ done(); } } }); myModularizer.register(PRE_REQ_PATH) .defines(MY_MODULE); myModularizer.register(PATH) .defines(MY_SECOND_MODULE); myModularizer.load([MY_MODULE,MY_SECOND_MODULE]); }); }); describe('knows()', function() { it('should return false if an invalid module is requested', function() { var myModularizer = new window.Modularizer({ loader : false }), moduleDef = function(){}; assert(myModularizer.knows() === false); assert(myModularizer.knows('') === false); assert(myModularizer.knows({}) === false); assert(myModularizer.knows(false) === false); }); it('should return true if the requested module defined in the package', function() { var MODULE_NAME = 'my.module', myModularizer = new window.Modularizer({ loader : false }); myModularizer.define(MODULE_NAME,function(){}); assert(myModularizer.knows(MODULE_NAME)); }); it('should return false if multiple modules have been requested and any of them is not defined', function() { var MODULE_NAME = 'my.module', myModularizer = new window.Modularizer({ loader : false }); myModularizer.define(MODULE_NAME,function(){}); assert(myModularizer.knows([MODULE_NAME,MODULE_NAME + '.unknown']) === false); }); it('should return true if the requested modules are all defined in the package', function() { var MODULE_NAME = 'my.module', myModularizer = new window.Modularizer({ loader : false }); myModularizer.define(MODULE_NAME+'1',function(){}); myModularizer.define(MODULE_NAME+'2',function(){}); assert(myModularizer.knows([MODULE_NAME+'1',MODULE_NAME+'2'])); }); it('should return false if the requested module defined in a resource which has not yet been loaded', function() { var PATH = '/path/to/file.js', MY_MODULE = 'my.module', myModularizer = new window.Modularizer({ loader : function(){} }); var pckg = myModularizer.register(PATH).defines(MY_MODULE); assert(myModularizer.knows(MY_MODULE) === false); }); it('should return true if the requested module defined in a resource which has been loaded', function() { var PATH = '/path/to/file.js', MY_MODULE = 'my.module', myModularizer = new window.Modularizer({ loader : function(){ myModularizer.define(MY_MODULE,function(){ }); } }); var pckg = myModularizer.register(PATH).defines(MY_MODULE); pckg.load(); assert(myModularizer.knows(MY_MODULE)); }); }); describe('require()', function() { it('should throw an error if no required module is specified', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.require(); }).to.throw(myModularizer.Error); }); it('should throw an error if an invalid module is specified', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.require(''); }).to.throw(myModularizer.Error); }); it('should throw an error for an undefined module requirment', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.require('my.module'); }).to.throw(myModularizer.Error); }); it('should throw an error for an undefined module requirment even when included with multiple modules', function() { var myModularizer = new window.Modularizer({ loader : function(){} }), MODULE_NAME = 'my.module', NON_EXISTANT_MODULE_NAME = 'my.missing.module'; myModularizer.define(MODULE_NAME,function(){}); expect(function(){ myModularizer.require([MODULE_NAME,NON_EXISTANT_MODULE_NAME]); }).to.throw(myModularizer.Error); }); it('should load defined but unloaded modules', function(done) { var PATH = '/path/to/file.js', MY_MODULE = 'my.module', myModularizer = new window.Modularizer({ loader : function(){ myModularizer.define(MY_MODULE,function(){ return {}; }); } }); myModularizer.register(PATH).defines(MY_MODULE); myModularizer.require(MY_MODULE,function(){ done(); }); }); it('should throw an error when a defined but unloaded module is required in synchronous mode', function() { var PATH = '/path/to/file.js', MY_MODULE = 'my.module', myModularizer = new window.Modularizer({ loader : function(){ myModularizer.define(MY_MODULE,function(){ return {}; }); } }); myModularizer.register(PATH).defines(MY_MODULE); expect(function(){ myModularizer.require(MY_MODULE,function(){ },{}, // syncro = true true); }).to.throw(myModularizer.Error); }); it('should pass the required modules, in order, to the callback when succesful', function(done) { var MY_MODULE = 'my.module.1',MY_2ND_MODULE = 'my.module.2',MY_3RD_MODULE = 'my.module.3', myModularizer = new window.Modularizer({ loader : function(){} }); myModularizer.define(MY_MODULE,function(){ return { name : MY_MODULE }; }); myModularizer.define(MY_2ND_MODULE,function(){ return { name : MY_2ND_MODULE }; }); myModularizer.define(MY_3RD_MODULE,function(){ return { name : MY_3RD_MODULE }; }); myModularizer.require([MY_MODULE,MY_2ND_MODULE,MY_3RD_MODULE],function(first,second,third){ first.name.should.be.eql(MY_MODULE); second.name.should.be.eql(MY_2ND_MODULE); third.name.should.be.eql(MY_3RD_MODULE); done(); }); }); it('should call the callback in the supplied context when succesful', function() { var MY_MODULE = 'my.module.1',myContext = {}, myModularizer = new window.Modularizer({ loader : function(){} }); myModularizer.define(MY_MODULE,function(){ return { name : MY_MODULE }; }); myModularizer.require(MY_MODULE,function(){ assert(myContext === this); },myContext); }); it('should call the callback in the global scope context when no context is specified', function() { var MY_MODULE = 'my.module.1',myContext = {}, myModularizer = new window.Modularizer({ loader : function(){} }); myModularizer.define(MY_MODULE,function(){ return { name : MY_MODULE }; }); myModularizer.require(MY_MODULE,function(){ assert(window === this); }); }); }); describe('define()', function() { it('should throw an error when a module name is omitted', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.define(function(){ return {}; }); }).to.throw(myModularizer.Error); }); it('should throw an error when a module name is empty', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.define('',function(){ return {}; }); }).to.throw(myModularizer.Error); }); it('should throw an error when a module name is not a string', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.define({},function(){ return {}; }); }).to.throw(myModularizer.Error); }); it('should throw an error when a module specified without a suitable definition callback', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.define('my.module'); }).to.throw(myModularizer.Error); expect(function(){ myModularizer.define('my.module',[]); }).to.throw(myModularizer.Error); expect(function(){ myModularizer.define('my.module',['my.other.module']); }).to.throw(myModularizer.Error); }); it('should allow a module to be defined based on a moduel name and a callback definition function', function() { var MODULE_NAME = 'my.module',myModularizer = new window.Modularizer({ loader : false }), moduleDef = function(){}; myModularizer.define(MODULE_NAME,moduleDef); expect(myModularizer.modules).to.be.a('object'); expect(myModularizer.modules.definitions).to.be.a('object'); assert(myModularizer.modules.definitions[MODULE_NAME] instanceof window.Modularizer.Module); assert(_.isFunction(myModularizer.modules.definitions[MODULE_NAME].callback)); assert(myModularizer.modules.definitions[MODULE_NAME].callback === moduleDef); }); it('should allow a module to be defined based on a module name, a single prerequisite and a callback definition function', function() { var PRE_REQ_MODULE = 'my.prereq', MODULE_NAME = 'my.module',myModularizer = new window.Modularizer({ loader : false }), moduleDef = function(){}; myModularizer.define(PRE_REQ_MODULE,function(){}); myModularizer.define(MODULE_NAME,PRE_REQ_MODULE,moduleDef); expect(myModularizer.modules).to.be.a('object'); expect(myModularizer.modules.definitions).to.be.a('object'); assert(myModularizer.modules.definitions[MODULE_NAME] instanceof window.Modularizer.Module); assert(_.isFunction(myModularizer.modules.definitions[MODULE_NAME].callback)); assert(myModularizer.modules.definitions[MODULE_NAME].callback === moduleDef); }); it('should allow a module to be defined based on a module name, multiple prerequisites and a callback definition function', function() { var PRE_REQ_MODULE = 'my.prereq', MODULE_NAME = 'my.module',myModularizer = new window.Modularizer({ loader : false }), moduleDef = function(){}; myModularizer.define(PRE_REQ_MODULE + '1',function(){}); myModularizer.define(PRE_REQ_MODULE + '2',function(){}); myModularizer.define(MODULE_NAME,[PRE_REQ_MODULE + '1',PRE_REQ_MODULE + '2'],moduleDef); expect(myModularizer.modules).to.be.a('object'); expect(myModularizer.modules.definitions).to.be.a('object'); assert(myModularizer.modules.definitions[MODULE_NAME] instanceof window.Modularizer.Module); assert(_.isFunction(myModularizer.modules.definitions[MODULE_NAME].callback)); assert(myModularizer.modules.definitions[MODULE_NAME].callback === moduleDef); }); it('should pass prerequisite modules in order to the definition function', function() { var MY_MODULE = 'my.module.1',MY_2ND_MODULE = 'my.module.2',MY_3RD_MODULE = 'my.module.3', myModularizer = new window.Modularizer({ loader : function(){} }); myModularizer.define(MY_MODULE,function(){ return { name : MY_MODULE }; }); myModularizer.define(MY_2ND_MODULE,function(){ return { name : MY_2ND_MODULE }; }); myModularizer.define(MY_3RD_MODULE,[MY_MODULE,MY_2ND_MODULE],function(first,second){ first.name.should.be.eql(MY_MODULE); second.name.should.be.eql(MY_2ND_MODULE); return { name : MY_3RD_MODULE }; }); myModularizer.require(MY_3RD_MODULE,function(third){ third.name.should.be.eql(MY_3RD_MODULE); }); }); }); });
test/Module.spec.js
var dom = require('./utils/dom.js'), chai = require('chai'), expect = chai.expect, assert = require('simple-assert'), _ = require('underscore'); describe('Modularizer Module management', function() { // Create a fake global `window` and `document` object and inject default script dom.init(true); describe('load()', function() { it('should return false if no loader is specified', function() { var myModularizer = new window.Modularizer({ detectJQuery : false, loader : false }), PATH = 'path/to/file.js', MY_PRE_REQUISITE = 'my.module', pckg = myModularizer.register(PATH) .defines(MY_PRE_REQUISITE,function(){ return {}; }); assert(myModularizer.load('my.module') === false); }); it('should accept a single module name', function(done) { var PRE_REQ_PATH = '1/path/to/file.js',PATH = '2/path/to/file.js', MY_MODULE = 'my.module', MY_SECOND_MODULE = 'my.2.module', myModularizer = new window.Modularizer({ loader : function(pathToLoad){ pathToLoad.should.equal(PRE_REQ_PATH); done(); } }); myModularizer.register(PRE_REQ_PATH).defines(MY_MODULE); myModularizer.register(PATH).defines(MY_SECOND_MODULE); myModularizer.load(MY_MODULE); }); it('should accept an array of module names', function(done) { var PRE_REQ_PATH = '1/path/to/file.js', PATH = '2/path/to/file.js', MY_MODULE = 'my.module', MY_SECOND_MODULE = 'my.2.module', pathsThatShouldBeRequired = [PRE_REQ_PATH,PATH], myModularizer = new window.Modularizer({ loader : function(pathToLoad){ if(_.contains(pathsThatShouldBeRequired, pathToLoad)){ pathsThatShouldBeRequired = _.without(pathsThatShouldBeRequired,pathToLoad); } if(!pathsThatShouldBeRequired.length){ done(); } } }); myModularizer.register(PRE_REQ_PATH) .defines(MY_MODULE); myModularizer.register(PATH) .defines(MY_SECOND_MODULE); myModularizer.load([MY_MODULE,MY_SECOND_MODULE]); }); }); describe('knows()', function() { it('should return false if an invalid module is requested', function() { var myModularizer = new window.Modularizer({ loader : false }), moduleDef = function(){}; assert(myModularizer.knows() === false); assert(myModularizer.knows('') === false); assert(myModularizer.knows({}) === false); assert(myModularizer.knows(false) === false); }); it('should return true if the requested module defined in the package', function() { var MODULE_NAME = 'my.module', myModularizer = new window.Modularizer({ loader : false }); myModularizer.define(MODULE_NAME,function(){}); assert(myModularizer.knows(MODULE_NAME)); }); it('should return false if multiple modules have been requested and any of them is not defined', function() { var MODULE_NAME = 'my.module', myModularizer = new window.Modularizer({ loader : false }); myModularizer.define(MODULE_NAME,function(){}); assert(myModularizer.knows([MODULE_NAME,MODULE_NAME + '.unknown']) === false); }); it('should return true if the requested modules are all defined in the package', function() { var MODULE_NAME = 'my.module', myModularizer = new window.Modularizer({ loader : false }); myModularizer.define(MODULE_NAME+'1',function(){}); myModularizer.define(MODULE_NAME+'2',function(){}); assert(myModularizer.knows([MODULE_NAME+'1',MODULE_NAME+'2'])); }); it('should return false if the requested module defined in a resource which has not yet been loaded', function() { var PATH = '/path/to/file.js', MY_MODULE = 'my.module', myModularizer = new window.Modularizer({ loader : function(){} }); var pckg = myModularizer.register(PATH).defines(MY_MODULE); assert(myModularizer.knows(MY_MODULE) === false); }); it('should return true if the requested module defined in a resource which has been loaded', function() { var PATH = '/path/to/file.js', MY_MODULE = 'my.module', myModularizer = new window.Modularizer({ loader : function(){ myModularizer.define(MY_MODULE,function(){ }); } }); var pckg = myModularizer.register(PATH).defines(MY_MODULE); pckg.load(); assert(myModularizer.knows(MY_MODULE)); }); }); describe('require()', function() { it('should throw an error if no required module is specified', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.require(); }).to.throw(myModularizer.Error); }); it('should throw an error if an invalid module is specified', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.require(''); }).to.throw(myModularizer.Error); }); it('should throw an error for an undefined module requirment', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.require('my.module'); }).to.throw(myModularizer.Error); }); it('should throw an error for an undefined module requirment even when included with multiple modules', function() { var myModularizer = new window.Modularizer({ loader : function(){} }), MODULE_NAME = 'my.module', NON_EXISTANT_MODULE_NAME = 'my.missing.module'; myModularizer.define(MODULE_NAME,function(){}); expect(function(){ myModularizer.require([MODULE_NAME,NON_EXISTANT_MODULE_NAME]); }).to.throw(myModularizer.Error); }); it('should load defined but unloaded modules', function(done) { var PATH = '/path/to/file.js', MY_MODULE = 'my.module', myModularizer = new window.Modularizer({ loader : function(){ myModularizer.define(MY_MODULE,function(){ return {}; }); } }); myModularizer.register(PATH).defines(MY_MODULE); myModularizer.require(MY_MODULE,function(){ done(); }); }); it('should throw an error when a defined but unloaded module is required in synchronous mode', function() { var PATH = '/path/to/file.js', MY_MODULE = 'my.module', myModularizer = new window.Modularizer({ loader : function(){ myModularizer.define(MY_MODULE,function(){ return {}; }); } }); myModularizer.register(PATH).defines(MY_MODULE); expect(function(){ myModularizer.require(MY_MODULE,function(){ },{}, // syncro = true true); }).to.throw(myModularizer.Error); }); it('should pass the required modules, in order, to the callback when succesful', function(done) { var MY_MODULE = 'my.module.1',MY_2ND_MODULE = 'my.module.2',MY_3RD_MODULE = 'my.module.3', myModularizer = new window.Modularizer({ loader : function(){} }); myModularizer.define(MY_MODULE,function(){ return { name : MY_MODULE }; }); myModularizer.define(MY_2ND_MODULE,function(){ return { name : MY_2ND_MODULE }; }); myModularizer.define(MY_3RD_MODULE,function(){ return { name : MY_3RD_MODULE }; }); myModularizer.require([MY_MODULE,MY_2ND_MODULE,MY_3RD_MODULE],function(first,second,third){ first.name.should.be.eql(MY_MODULE); second.name.should.be.eql(MY_2ND_MODULE); third.name.should.be.eql(MY_3RD_MODULE); done(); }); }); it('should call the callback in the supplied context when succesful', function() { var MY_MODULE = 'my.module.1',myContext = {}, myModularizer = new window.Modularizer({ loader : function(){} }); myModularizer.define(MY_MODULE,function(){ return { name : MY_MODULE }; }); myModularizer.require(MY_MODULE,function(){ assert(myContext === this); },myContext); }); it('should call the callback in the global scope context when no context is specified', function() { var MY_MODULE = 'my.module.1',myContext = {}, myModularizer = new window.Modularizer({ loader : function(){} }); myModularizer.define(MY_MODULE,function(){ return { name : MY_MODULE }; }); myModularizer.require(MY_MODULE,function(){ assert(window === this); }); }); }); //describe('fetchResource()', function() { // // it('', function() { // assert(false); // }); //}); describe('define()', function() { it('should throw an error when a module name is omitted', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.define(function(){ return {}; }); }).to.throw(myModularizer.Error); }); it('should throw an error when a module name is empty', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.define('',function(){ return {}; }); }).to.throw(myModularizer.Error); }); it('should throw an error when a module name is not a string', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.define({},function(){ return {}; }); }).to.throw(myModularizer.Error); }); it('should throw an error when a module specified without a suitable definition callback', function() { var myModularizer = new window.Modularizer({ loader : function(){} }); expect(function(){ myModularizer.define('my.module'); }).to.throw(myModularizer.Error); expect(function(){ myModularizer.define('my.module',[]); }).to.throw(myModularizer.Error); expect(function(){ myModularizer.define('my.module',['my.other.module']); }).to.throw(myModularizer.Error); }); it('should allow a module to be defined based on a moduel name and a callback definition function', function() { var MODULE_NAME = 'my.module',myModularizer = new window.Modularizer({ loader : false }), moduleDef = function(){}; myModularizer.define(MODULE_NAME,moduleDef); expect(myModularizer.modules).to.be.a('object'); expect(myModularizer.modules.definitions).to.be.a('object'); assert(myModularizer.modules.definitions[MODULE_NAME] instanceof window.Modularizer.Module); assert(_.isFunction(myModularizer.modules.definitions[MODULE_NAME].callback)); assert(myModularizer.modules.definitions[MODULE_NAME].callback === moduleDef); }); it('should allow a module to be defined based on a module name, a single prerequisite and a callback definition function', function() { var PRE_REQ_MODULE = 'my.prereq', MODULE_NAME = 'my.module',myModularizer = new window.Modularizer({ loader : false }), moduleDef = function(){}; myModularizer.define(PRE_REQ_MODULE,function(){}); myModularizer.define(MODULE_NAME,PRE_REQ_MODULE,moduleDef); expect(myModularizer.modules).to.be.a('object'); expect(myModularizer.modules.definitions).to.be.a('object'); assert(myModularizer.modules.definitions[MODULE_NAME] instanceof window.Modularizer.Module); assert(_.isFunction(myModularizer.modules.definitions[MODULE_NAME].callback)); assert(myModularizer.modules.definitions[MODULE_NAME].callback === moduleDef); }); it('should allow a module to be defined based on a module name, multiple prerequisites and a callback definition function', function() { var PRE_REQ_MODULE = 'my.prereq', MODULE_NAME = 'my.module',myModularizer = new window.Modularizer({ loader : false }), moduleDef = function(){}; myModularizer.define(PRE_REQ_MODULE + '1',function(){}); myModularizer.define(PRE_REQ_MODULE + '2',function(){}); myModularizer.define(MODULE_NAME,[PRE_REQ_MODULE + '1',PRE_REQ_MODULE + '2'],moduleDef); expect(myModularizer.modules).to.be.a('object'); expect(myModularizer.modules.definitions).to.be.a('object'); assert(myModularizer.modules.definitions[MODULE_NAME] instanceof window.Modularizer.Module); assert(_.isFunction(myModularizer.modules.definitions[MODULE_NAME].callback)); assert(myModularizer.modules.definitions[MODULE_NAME].callback === moduleDef); }); it('should pass prerequisite modules in order to the definition function', function() { var MY_MODULE = 'my.module.1',MY_2ND_MODULE = 'my.module.2',MY_3RD_MODULE = 'my.module.3', myModularizer = new window.Modularizer({ loader : function(){} }); myModularizer.define(MY_MODULE,function(){ return { name : MY_MODULE }; }); myModularizer.define(MY_2ND_MODULE,function(){ return { name : MY_2ND_MODULE }; }); myModularizer.define(MY_3RD_MODULE,[MY_MODULE,MY_2ND_MODULE],function(first,second){ first.name.should.be.eql(MY_MODULE); second.name.should.be.eql(MY_2ND_MODULE); return { name : MY_3RD_MODULE }; }); myModularizer.require(MY_3RD_MODULE,function(third){ third.name.should.be.eql(MY_3RD_MODULE); }); }); }); });
removed commented out code
test/Module.spec.js
removed commented out code
<ide><path>est/Module.spec.js <ide> }); <ide> }); <ide> <del> //describe('fetchResource()', function() { <del> // <del> // it('', function() { <del> // assert(false); <del> // }); <del> //}); <del> <ide> describe('define()', function() { <ide> <ide> it('should throw an error when a module name is omitted', function() {
Java
apache-2.0
38894e8776660f5437b8d300898880e38128e736
0
rholder/fauxflake
/* * Copyright 2012-2014 Ray Holder * * 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.github.rholder.fauxflake.provider; import com.github.rholder.fauxflake.api.MachineIdProvider; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.util.Arrays; import static com.github.rholder.fauxflake.util.MacUtils.macAddress; import static com.github.rholder.fauxflake.util.PidUtils.pid; /** * Use a combination of the MAC address and the current process id to uniquely * identify a machine. The returned encoding is such that the first 6 * bytes of an 8 byte long are the MAC address and the last 2 bytes are the * current PID % 65536. While a PID collision is unlikely, there is still a * chance that it might occur, resulting in a non-unique machine id being * generated on the same machine. This introduces the possibility of ultimately * generating a duplicate distributed identifier so use this class with caution. * Sequentially started processes are most likely going to have sequential (or * at least close enough) PID's within the range of 65536 such that a collision * is extremely unlikely (or in other words, this is probably "good enough"). */ public class MacPidMachineIdProvider implements MachineIdProvider { public static final long MACHINE_ID; static { long value = 0L; byte[] raw = Arrays.copyOf(macAddress(), 8); try { // first 6 bytes are MAC value = new DataInputStream(new ByteArrayInputStream(raw)).readLong(); // next 2 bytes are pid % 2^16 value |= pid() % 65536; } catch (IOException e) { e.printStackTrace(); } catch (UnsupportedOperationException e) { e.printStackTrace(); } MACHINE_ID = value; } /** * Return the unique machine id based on the MAC address and current PID of * the running JVM or 0 if an error occurs. */ @Override public long getMachineId() { return MACHINE_ID; } }
fauxflake-core/src/main/java/com/github/rholder/fauxflake/provider/MacPidMachineIdProvider.java
/* * Copyright 2012-2014 Ray Holder * * 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.github.rholder.fauxflake.provider; import com.github.rholder.fauxflake.api.MachineIdProvider; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.util.Arrays; import static com.github.rholder.fauxflake.util.MacUtils.macAddress; import static com.github.rholder.fauxflake.util.PidUtils.pid; /** * Use a combination of the MAC address and the current process id to uniquely * identify a machine. The returned encoding is such that the first 6 * bytes of an 8 byte long are the MAC address and the last 2 bytes are the * current PID % 65536. While a PID collision is unlikely, there is still a * chance that it might occur, resulting in a non-unique machine id being * generated on the same machine. This introduces the possibility of ultimately * generating a duplicate distributed identifier so use this class with caution. * Sequentially started processes are most likely going to have sequential (or * at least close enough) PID's within the range of 65536 such that a collision * is extremely unlikely (or in other words, this is probably "good enough"). */ public class MacPidMachineIdProvider implements MachineIdProvider { public static final long MACHINE_ID; static { long value = 0L; byte[] raw = Arrays.copyOf(macAddress(), 8); try { // first 6 bytes are MAC value = new DataInputStream(new ByteArrayInputStream(raw)).readLong(); // next 2 bytes are pid % 2^16 value |= pid() % 65536; } catch (IOException e) { e.printStackTrace(); } MACHINE_ID = value; } /** * Return the unique machine id based on the MAC address and current PID of * the running JVM or 0 if an error occurs. */ @Override public long getMachineId() { return MACHINE_ID; } }
more gracefully handle UnsupportedOperationException when the MAC cannot be retrieved for MacPid, too
fauxflake-core/src/main/java/com/github/rholder/fauxflake/provider/MacPidMachineIdProvider.java
more gracefully handle UnsupportedOperationException when the MAC cannot be retrieved for MacPid, too
<ide><path>auxflake-core/src/main/java/com/github/rholder/fauxflake/provider/MacPidMachineIdProvider.java <ide> value |= pid() % 65536; <ide> } catch (IOException e) { <ide> e.printStackTrace(); <add> } catch (UnsupportedOperationException e) { <add> e.printStackTrace(); <ide> } <ide> MACHINE_ID = value; <ide> }
Java
mit
f1e8357825b49d173f3fc404c588a030e5596cdc
0
jwfwessels/AFK,jwfwessels/AFK
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package afk.ge.tokyo; import afk.ge.tokyo.ems.Engine; import afk.ge.tokyo.ems.Entity; import afk.ge.tokyo.ems.components.*; import static afk.gfx.GfxUtils.*; import com.hackoeur.jglm.Mat4; import com.hackoeur.jglm.Matrices; import com.hackoeur.jglm.Vec3; import com.hackoeur.jglm.Vec4; import com.jogamp.graph.geom.AABBox; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayDeque; import java.util.Queue; import java.util.UUID; /** * * @author Jw */ public class EntityManager { public static final float WEAPON_RANGE = 50; public static final float WEAPON_DAMAGE = 20; public static final float BULLET_SPEED = 10; public static final float FIRE_RATE = 1f; public static final int WEAPON_AMMO = 0; public static final float SMALL_TANK_HP = 80; public static final float LARGE_TANK_HP = 100; public static final String SMALL_TANK_TYPE = "smallTank"; public static final String LARGE_TANK_TYPE = "largeTankBase"; public static final String LARGE_TANK_TURRET_TYPE = "largeTankTurret"; public static final String LARGE_TANK_BARREL_TYPE = "largeTankBarrel"; public static final Vec3 SMALL_TANK_EXTENTS = new Vec3(0.4385f, 0.2505f, 0.5f); public static final Vec3 SMALL_TANK_BBOX_OFFSET = new Vec3(0, SMALL_TANK_EXTENTS.getY(), 0); public static final Vec3 LARGE_TANK_EXTENTS = new Vec3(0.311f, 0.1355f, 0.5f); public static final Vec3 LARGE_TANK_BBOX_OFFSET = new Vec3(0, LARGE_TANK_EXTENTS.getY(), 0); public static final float SMALL_TANK_SCALE = 2; public static final float LARGE_TANK_SCALE = 3.5f; public static final int TANK_VDIST = 15; public static final int TANK_FOVY = 70; public static final int TANK_FOVX = 170; public static final Vec3 MAGENTA = new Vec3(1, 0, 1); int NUMCUBES = 10; public static final int SPAWNVALUE = (int) (Tokyo.BOARD_SIZE * 0.45); private Queue<Entity> particles = new ArrayDeque<Entity>(); private ParticleEmitter[] emitters; Engine engine; public static final Vec3[] BOT_COLOURS = { new Vec3(1, 0, 0), new Vec3(0, 0, 1), new Vec3(0, 1, 0), new Vec3(1, 1, 0), new Vec3(1, 0, 1), new Vec3(0, 1, 1), new Vec3(0.95f, 0.95f, 0.95f), new Vec3(0.2f, 0.2f, 0.2f) }; public static final Vec3[] SPAWN_POINTS = { new Vec3(-SPAWNVALUE, 0, -SPAWNVALUE), new Vec3(SPAWNVALUE, 0, SPAWNVALUE), new Vec3(-SPAWNVALUE, 0, SPAWNVALUE), new Vec3(SPAWNVALUE, 0, -SPAWNVALUE), new Vec3(0, 0, -SPAWNVALUE), new Vec3(0, 0, SPAWNVALUE), new Vec3(-SPAWNVALUE, 0, 0), new Vec3(SPAWNVALUE, 0, 0) }; public EntityManager(Engine engine) { this.engine = engine; emitters = new ParticleEmitter[2]; try { emitters[0] = loadParticleParameters("explosionProjectile"); emitters[1] = loadParticleParameters("explosionTank"); } catch (IOException ex) { System.err.println("Error loading particle config: " + ex.getMessage()); } } public void spawnStuff() { createFloor(); engine.addEntity(createGraphicWall(new Vec3(0, 0, -Tokyo.BOARD_SIZE / 2), new Vec3(Tokyo.BOARD_SIZE, 5, 0.5f))); engine.addEntity(createGraphicWall(new Vec3(0, 0, Tokyo.BOARD_SIZE / 2), new Vec3(Tokyo.BOARD_SIZE, 5, 0.5f))); engine.addEntity(createGraphicWall(new Vec3(Tokyo.BOARD_SIZE / 2, 0, 0), new Vec3(0.5f, 5, Tokyo.BOARD_SIZE))); engine.addEntity(createGraphicWall(new Vec3(-Tokyo.BOARD_SIZE / 2, 0, 0), new Vec3(0.5f, 5, Tokyo.BOARD_SIZE))); } public void createFloor() { Entity floor = new Entity(); floor.add(new State(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO, new Vec3(Tokyo.BOARD_SIZE))); floor.add(new Renderable("floor", new Vec3(1.0f, 1.0f, 1.0f))); try { floor.add(new HeightmapLoader().load("hm2", Tokyo.BOARD_SIZE, Tokyo.BOARD_SIZE, Tokyo.BOARD_SIZE)); } catch (IOException ex) { System.err.println("Error loading up heightmap: " + ex.getMessage()); } engine.addEntity(floor); } public Entity createGraphicWall(Vec3 pos, Vec3 scale) { Entity wall = new Entity(); wall.add(new State(pos, Vec4.VEC4_ZERO, scale)); wall.add(new BBoxComponent(scale.scale(0.5f),new Vec3(0,scale.getY()*0.5f,0))); wall.add(new Renderable("wall", new Vec3(0.75f, 0.75f, 0.75f))); return wall; } public void createObstacles(Vec3 scale) { int min = -18; int max = 18; for (int i = 0; i < NUMCUBES; i++) { Vec3 pos = new Vec3(min + (int) (Math.random() * ((max - min) + 1)), 0, min + (int) (Math.random() * ((max - min) + 1))); createGraphicWall(pos, scale); } } public Entity createTankEntityNEU(UUID id, Vec3 spawnPoint, Vec3 colour) { Vec3 scale = new Vec3(LARGE_TANK_SCALE); Entity tank = new Entity(); Controller controller = new Controller(id); tank.add(controller); tank.add(new State(spawnPoint, Vec4.VEC4_ZERO, scale)); // tank.add(new BBoxComponent(new Vec3(1.0f,0.127f,0.622f).multiply(scale))); tank.add(new BBoxComponent(LARGE_TANK_EXTENTS.multiply(scale), LARGE_TANK_BBOX_OFFSET.multiply(scale))); tank.add(new Velocity(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO)); tank.add(new Motor(2f, 20f)); tank.add(new Life(SMALL_TANK_HP)); tank.add(new Renderable(LARGE_TANK_TYPE, colour)); tank.add(new RobotToken()); tank.add(new Targetable()); tank.add(new TankTracks()); tank.add(new SnapToTerrain()); Entity turret = createLargeTankTurret(colour); turret.add(new Parent(tank)); turret.add(controller); tank.addDependent(turret); Entity barrel = createLargeTankBarrel(colour); barrel.add(new Parent(turret)); barrel.add(controller); turret.addDependent(barrel); return tank; } public Entity createLargeTankTurret(Vec3 colour) { Entity entity = new Entity(); entity.add(new State(new Vec3(0.0f, 0.17623f, -0.15976f), Vec4.VEC4_ZERO, new Vec3(1))); entity.add(new Velocity(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO)); entity.add(new Renderable(LARGE_TANK_TURRET_TYPE, colour)); entity.add(new Vision(TANK_VDIST, TANK_FOVY, TANK_FOVX)); entity.add(new TankTurret()); return entity; } public Entity createLargeTankBarrel(Vec3 colour) { Entity entity = new Entity(); entity.add(new State(new Vec3(0.0f, 0.03200f, 0.22199f), Vec4.VEC4_ZERO, new Vec3(1))); entity.add(new Weapon(WEAPON_RANGE, WEAPON_DAMAGE, BULLET_SPEED, 1.0f / FIRE_RATE, WEAPON_AMMO)); entity.add(new Velocity(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO)); entity.add(new Renderable(LARGE_TANK_BARREL_TYPE, colour)); entity.add(new AngleConstraint(new Vec4(0,0,0,-45),new Vec4(0,0,0,10))); entity.add(new TankBarrel(0.545f)); return entity; } // public TankEntity createSmallTank(Robot botController, Vec3 spawnPoint, Vec3 colour) // { // float TOTAL_LIFE = 8; // float SCALE = 2.0f; // // GfxEntity oBBEntity = gfxEngine.createEntity(GfxEntity.NORMAL); // GfxEntity visionEntity = gfxEngine.createEntity(GfxEntity.NORMAL); // // //OBB // oBBEntity.attachResource(cubeMesh); // oBBEntity.attachResource(primativeShader); // oBBEntity.yScale = 0.55f; // oBBEntity.xScale = 0.80f; // oBBEntity.colour = colour; // oBBEntity.opacity = 0.2f; // // //vision sphere // visionEntity.attachResource(ringMesh); // visionEntity.attachResource(primativeShader); // visionEntity.setScale(5, 5, 5); // visionEntity.colour = colour; //// visionEntity.opacity = 0.1f; // // tankGfxEntity.addChild(visionEntity); // tankGfxEntity.addChild(oBBEntity); // // gfxEngine.getRootEntity().addChild(tankGfxEntity); // // tank.name = "tank" + (entities.size() - 1); // tank.setScaleForOBB(oBBEntity.getScale().scale(SCALE)); // } public void createProjectileNEU(UUID parent, Weapon weapon, State current, Vec3 forward) { Entity projectile = new Entity(); State state = new State(current.pos, current.rot, new Vec3(0.3f, 0.3f, -0.3f)); projectile.add(state); projectile.add(new Velocity(forward.multiply(weapon.speed), Vec4.VEC4_ZERO)); projectile.add(new Renderable("projectile", new Vec3(0.5f, 0.5f, 0.5f))); projectile.add(new Bullet(weapon.range, weapon.damage, parent)); engine.addEntity(projectile); } public Entity makeExplosion(Vec3 where, UUID parent, int type) { Entity entity = new Entity(); entity.add(new State(where, Vec4.VEC4_ZERO, new Vec3(1, 1, 1))); ParticleEmitter emitter = new ParticleEmitter(emitters[type]); // this is a nice colour, I picked it from a photo of a bomb going off emitter.colour = new Vec3(1,0.734375f,0); // TODO: get colour from config entity.add(emitter); return entity; } /** * A Pie is a flat plane that always faces your face. */ public void makePie(State emitterState, ParticleEmitter emitter) { Entity pie = particles.poll(); if (pie == null) { pie = new Entity(); pie.add(new State(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO, Vec3.VEC3_ZERO)); pie.add(new Lifetime(0)); pie.add(new Velocity(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO)); pie.add(new Renderable("particle", Vec3.VEC3_ZERO)); } State state = pie.get(State.class); Velocity velocity = pie.get(Velocity.class); Lifetime lifetime = pie.get(Lifetime.class); Renderable renderable = pie.get(Renderable.class); Vec3 pos = emitterState.pos; Vec4 rot = emitterState.rot; Vec3 scale = emitterState.scale; state.reset(new Vec3( jitter(pos.getX(), scale.getX()), jitter(pos.getY(), scale.getY()), jitter(pos.getZ(), scale.getZ())), Vec4.VEC4_ZERO, new Vec3(jitter(emitter.scale, emitter.scaleJitter))); Vec3 dir; if (emitter.noDirection) { // uniform sphere distribution dir = new Vec3( (float) random.nextGaussian(), (float) random.nextGaussian(), (float) random.nextGaussian()) .getUnitVector(); } else { // uniform cone distribution (I think) Mat4 rotation = Matrices.rotate(new Mat4(1.0f), jitter(rot.getX(), emitter.angleJitter.getX()), X_AXIS); rotation = Matrices.rotate(rotation, jitter(rot.getY(), emitter.angleJitter.getY()), Y_AXIS); rotation = Matrices.rotate(rotation, jitter(rot.getZ(), emitter.angleJitter.getZ()), Z_AXIS); Vec4 newRotation = rotation.multiply(ANCHOR); dir = new Vec3(newRotation.getX(), newRotation.getY(), newRotation.getZ()); } float speed = jitter(emitter.speed, emitter.speedJitter); velocity.v = dir.scale(speed); velocity.a = emitter.acceleration; lifetime.life = jitter(emitter.maxLife, emitter.lifeJitter); lifetime.maxLife = lifetime.life; renderable.colour = emitter.colour; engine.addEntity(pie); } public void recyclePie(Entity entity) { // TODO: consider making queue bounded so as to limit lots of particles particles.offer(entity); } public static ParticleEmitter loadParticleParameters(String name) throws IOException { ParticleEmitter emitter = new ParticleEmitter(); loadParticleParameters(emitter, name); return emitter; } public static void loadParticleParameters(ParticleEmitter emitter, String name) throws IOException { BufferedReader br = new BufferedReader(new FileReader("particles/" + name + ".px")); try { String line; for (int lineNumber = 1; (line = br.readLine()) != null; lineNumber++) { line = line.replaceFirst(";.*$", "").trim(); if (line.isEmpty()) { continue; } String[] split1 = line.split("\\s*=\\s*"); String param = split1[0]; String value = split1[1]; Field field; try { field = ParticleEmitter.class.getField(param); } catch (NoSuchFieldException ex) { throw new IOException("Invalid parameter name [" + param + "] on line " + lineNumber); } catch (SecurityException ex) { throw new IOException("Parameter error [" + param + "] on line " + lineNumber + ": " + ex.getMessage()); } Class fieldClass = field.getType(); try { if (fieldClass == Vec3.class) { field.set(emitter, parseVec3(value)); } else if (fieldClass == AABBox.class) { field.set(emitter, parseAABBox(value)); } else { field.set(emitter, getWrapperClass(fieldClass).getMethod("valueOf", String.class).invoke(null, value)); } } catch (NumberFormatException nfe) { throw new IOException("Invalid value on line " + lineNumber + ": " + nfe.getMessage()); } catch (ReflectiveOperationException ex) { throw new IOException("Fatal error on line " + lineNumber + ": " + ex.getMessage()); } } } finally { br.close(); } } private static Class getWrapperClass(Class clazz) { if (clazz == int.class) { return Integer.class; } if (clazz == short.class) { return Short.class; } if (clazz == byte.class) { return Byte.class; } if (clazz == long.class) { return Long.class; } if (clazz == float.class) { return Float.class; } if (clazz == double.class) { return Double.class; } if (clazz == boolean.class) { return Boolean.class; } if (clazz == char.class) { return Character.class; } return Object.class; } private static Vec3 parseVec3(String values) { String[] split = values.split("\\s+"); if (split.length != 3) { throw new NumberFormatException("Invalid number of parameters: " + "need 3, found " + split.length); } return new Vec3( Float.parseFloat(split[0]), Float.parseFloat(split[1]), Float.parseFloat(split[2])); } private static AABBox parseAABBox(String values) { String[] split = values.split("\\s+"); if (split.length != 6) { throw new NumberFormatException("Invalid number of parameters: " + "need 6, found " + split.length); } return new AABBox( Float.parseFloat(split[0]), Float.parseFloat(split[1]), Float.parseFloat(split[2]), Float.parseFloat(split[3]), Float.parseFloat(split[4]), Float.parseFloat(split[5])); } }
src/afk/ge/tokyo/EntityManager.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package afk.ge.tokyo; import afk.ge.tokyo.ems.Engine; import afk.ge.tokyo.ems.Entity; import afk.ge.tokyo.ems.components.*; import static afk.gfx.GfxUtils.*; import com.hackoeur.jglm.Mat4; import com.hackoeur.jglm.Matrices; import com.hackoeur.jglm.Vec3; import com.hackoeur.jglm.Vec4; import com.jogamp.graph.geom.AABBox; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayDeque; import java.util.Queue; import java.util.UUID; /** * * @author Jw */ public class EntityManager { public static final float WEAPON_RANGE = 50; public static final float WEAPON_DAMAGE = 20; public static final float BULLET_SPEED = 10; public static final float FIRE_RATE = 1f; public static final int WEAPON_AMMO = 0; public static final float SMALL_TANK_HP = 80; public static final float LARGE_TANK_HP = 100; public static final String SMALL_TANK_TYPE = "smallTank"; public static final String LARGE_TANK_TYPE = "largeTankBase"; public static final String LARGE_TANK_TURRET_TYPE = "largeTankTurret"; public static final String LARGE_TANK_BARREL_TYPE = "largeTankBarrel"; public static final Vec3 SMALL_TANK_EXTENTS = new Vec3(0.4385f, 0.2505f, 0.5f); public static final Vec3 SMALL_TANK_BBOX_OFFSET = new Vec3(0, SMALL_TANK_EXTENTS.getY(), 0); public static final Vec3 LARGE_TANK_EXTENTS = new Vec3(0.311f, 0.1355f, 0.5f); public static final Vec3 LARGE_TANK_BBOX_OFFSET = new Vec3(0, LARGE_TANK_EXTENTS.getY(), 0); public static final float SMALL_TANK_SCALE = 2; public static final float LARGE_TANK_SCALE = 3.5f; public static final int TANK_VDIST = 15; public static final int TANK_FOVY = 70; public static final int TANK_FOVX = 170; public static final Vec3 MAGENTA = new Vec3(1, 0, 1); int NUMCUBES = 10; public static final int SPAWNVALUE = (int) (Tokyo.BOARD_SIZE * 0.45); private Queue<Entity> particles = new ArrayDeque<Entity>(); private ParticleEmitter[] emitters; Engine engine; public static final Vec3[] BOT_COLOURS = { new Vec3(1, 0, 0), new Vec3(0, 0, 1), new Vec3(0, 1, 0), new Vec3(1, 1, 0), new Vec3(1, 0, 1), new Vec3(0, 1, 1), new Vec3(0.95f, 0.95f, 0.95f), new Vec3(0.2f, 0.2f, 0.2f) }; public static final Vec3[] SPAWN_POINTS = { new Vec3(-SPAWNVALUE, 0, -SPAWNVALUE), new Vec3(SPAWNVALUE, 0, SPAWNVALUE), new Vec3(-SPAWNVALUE, 0, SPAWNVALUE), new Vec3(SPAWNVALUE, 0, -SPAWNVALUE), new Vec3(0, 0, -SPAWNVALUE), new Vec3(0, 0, SPAWNVALUE), new Vec3(-SPAWNVALUE, 0, 0), new Vec3(SPAWNVALUE, 0, 0) }; public EntityManager(Engine engine) { this.engine = engine; emitters = new ParticleEmitter[2]; try { emitters[0] = loadParticleParameters("explosionProjectile"); emitters[1] = loadParticleParameters("explosionTank"); } catch (IOException ex) { System.err.println("Error loading particle config: " + ex.getMessage()); } } public void spawnStuff() { createFloor(); engine.addEntity(createGraphicWall(new Vec3(0, 0, -Tokyo.BOARD_SIZE / 2), new Vec3(Tokyo.BOARD_SIZE, 5, 0.5f))); engine.addEntity(createGraphicWall(new Vec3(0, 0, Tokyo.BOARD_SIZE / 2), new Vec3(Tokyo.BOARD_SIZE, 5, 0.5f))); engine.addEntity(createGraphicWall(new Vec3(Tokyo.BOARD_SIZE / 2, 0, 0), new Vec3(0.5f, 5, Tokyo.BOARD_SIZE))); engine.addEntity(createGraphicWall(new Vec3(-Tokyo.BOARD_SIZE / 2, 0, 0), new Vec3(0.5f, 5, Tokyo.BOARD_SIZE))); } public void createFloor() { Entity floor = new Entity(); floor.add(new State(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO, new Vec3(Tokyo.BOARD_SIZE))); floor.add(new Renderable("floor", new Vec3(1.0f, 1.0f, 1.0f))); try { floor.add(new HeightmapLoader().load("hm2", Tokyo.BOARD_SIZE, Tokyo.BOARD_SIZE, Tokyo.BOARD_SIZE)); } catch (IOException ex) { System.err.println("Error loading up heightmap: " + ex.getMessage()); } engine.addEntity(floor); } public Entity createGraphicWall(Vec3 pos, Vec3 scale) { Entity wall = new Entity(); wall.add(new State(pos, Vec4.VEC4_ZERO, scale)); wall.add(new BBoxComponent(scale.scale(0.5f),new Vec3(0,scale.getY()*0.5f,0))); wall.add(new Renderable("wall", new Vec3(0.75f, 0.75f, 0.75f))); return wall; } public void createObstacles(Vec3 scale) { int min = -18; int max = 18; for (int i = 0; i < NUMCUBES; i++) { Vec3 pos = new Vec3(min + (int) (Math.random() * ((max - min) + 1)), 0, min + (int) (Math.random() * ((max - min) + 1))); createGraphicWall(pos, scale); } } public Entity createTankEntityNEU(UUID id, Vec3 spawnPoint, Vec3 colour) { Vec3 scale = new Vec3(LARGE_TANK_SCALE); Entity tank = new Entity(); Controller controller = new Controller(id); tank.add(controller); tank.add(new State(spawnPoint, Vec4.VEC4_ZERO, scale)); // tank.add(new BBoxComponent(new Vec3(1.0f,0.127f,0.622f).multiply(scale))); tank.add(new BBoxComponent(LARGE_TANK_EXTENTS.multiply(scale), LARGE_TANK_BBOX_OFFSET.multiply(scale))); tank.add(new Velocity(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO)); tank.add(new Motor(2f, 20f)); tank.add(new Life(SMALL_TANK_HP)); tank.add(new Renderable(LARGE_TANK_TYPE, colour)); tank.add(new RobotToken()); tank.add(new Targetable()); tank.add(new TankTracks()); tank.add(new SnapToTerrain()); Entity turret = createLargeTankTurret(colour); turret.add(new Parent(tank)); turret.add(controller); tank.addDependent(turret); Entity barrel = createLargeTankBarrel(colour); barrel.add(new Parent(turret)); barrel.add(controller); turret.addDependent(barrel); return tank; } public Entity createLargeTankTurret(Vec3 colour) { Entity entity = new Entity(); entity.add(new State(new Vec3(0.0f, 0.17623f, -0.15976f), Vec4.VEC4_ZERO, new Vec3(1))); entity.add(new Velocity(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO)); entity.add(new Renderable(LARGE_TANK_TURRET_TYPE, colour)); entity.add(new Vision(TANK_VDIST, TANK_FOVY, TANK_FOVX)); entity.add(new TankTurret()); return entity; } public Entity createLargeTankBarrel(Vec3 colour) { Entity entity = new Entity(); entity.add(new State(new Vec3(0.0f, 0.03200f, 0.22199f), Vec4.VEC4_ZERO, new Vec3(1))); entity.add(new Weapon(WEAPON_RANGE, WEAPON_DAMAGE, BULLET_SPEED, 1.0f / FIRE_RATE, WEAPON_AMMO)); entity.add(new Velocity(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO)); entity.add(new Renderable(LARGE_TANK_BARREL_TYPE, colour)); entity.add(new AngleConstraint(new Vec4(0,0,0,-45),new Vec4(0,0,0,10))); entity.add(new TankBarrel(0.545f)); return entity; } // public TankEntity createSmallTank(Robot botController, Vec3 spawnPoint, Vec3 colour) // { // float TOTAL_LIFE = 8; // float SCALE = 2.0f; // // GfxEntity oBBEntity = gfxEngine.createEntity(GfxEntity.NORMAL); // GfxEntity visionEntity = gfxEngine.createEntity(GfxEntity.NORMAL); // // //OBB // oBBEntity.attachResource(cubeMesh); // oBBEntity.attachResource(primativeShader); // oBBEntity.yScale = 0.55f; // oBBEntity.xScale = 0.80f; // oBBEntity.colour = colour; // oBBEntity.opacity = 0.2f; // // //vision sphere // visionEntity.attachResource(ringMesh); // visionEntity.attachResource(primativeShader); // visionEntity.setScale(5, 5, 5); // visionEntity.colour = colour; //// visionEntity.opacity = 0.1f; // // tankGfxEntity.addChild(visionEntity); // tankGfxEntity.addChild(oBBEntity); // // gfxEngine.getRootEntity().addChild(tankGfxEntity); // // tank.name = "tank" + (entities.size() - 1); // tank.setScaleForOBB(oBBEntity.getScale().scale(SCALE)); // } public void createProjectileNEU(UUID parent, Weapon weapon, State current, Vec3 forward) { Entity projectile = new Entity(); State state = new State(current.pos, current.rot, new Vec3(0.3f, 0.3f, -0.3f)); projectile.add(state); projectile.add(new Velocity(forward.multiply(weapon.speed), Vec4.VEC4_ZERO)); projectile.add(new Renderable("projectile", new Vec3(0.5f, 0.5f, 0.5f))); projectile.add(new Bullet(weapon.range, weapon.damage, parent)); engine.addEntity(projectile); } public Entity makeExplosion(Vec3 where, UUID parent, int type) { Entity entity = new Entity(); entity.add(new State(where, Vec4.VEC4_ZERO, new Vec3(1, 1, 1))); ParticleEmitter emitter = new ParticleEmitter(emitters[type]); // this is a nice colour, I picked it from a photo of a bomb going off emitter.colour = new Vec3(1,0.734375f,0); // TODO: get colour from config entity.add(emitter); return entity; } /** * A Pie is a flat plane that always faces your face. */ public void makePie(State emitterState, ParticleEmitter emitter) { Entity pie = particles.poll(); if (pie == null) { pie = new Entity(); pie.add(new State(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO, Vec3.VEC3_ZERO)); pie.add(new Lifetime(0)); pie.add(new Velocity(Vec3.VEC3_ZERO, Vec4.VEC4_ZERO)); pie.add(new Renderable("particle", Vec3.VEC3_ZERO)); } State state = pie.get(State.class); Velocity velocity = pie.get(Velocity.class); Lifetime lifetime = pie.get(Lifetime.class); Renderable renderable = pie.get(Renderable.class); Vec3 pos = emitterState.pos; Vec4 rot = emitterState.rot; Vec3 scale = emitterState.scale; state.reset(new Vec3( jitter(pos.getX(), scale.getX()), jitter(pos.getY(), scale.getY()), jitter(pos.getZ(), scale.getZ())), Vec4.VEC4_ZERO, new Vec3(jitter(emitter.scale, emitter.scaleJitter))); Vec3 dir; if (emitter.noDirection) { // uniform sphere distribution dir = new Vec3( (float) random.nextGaussian(), (float) random.nextGaussian(), (float) random.nextGaussian()) .getUnitVector(); } else { // uniform cone distribution (I think) Mat4 rotation = Matrices.rotate(new Mat4(1.0f), jitter(rot.getX(), emitter.angleJitter.getX()), X_AXIS); rotation = Matrices.rotate(rotation, jitter(rot.getY(), emitter.angleJitter.getY()), Y_AXIS); rotation = Matrices.rotate(rotation, jitter(rot.getZ(), emitter.angleJitter.getZ()), Z_AXIS); Vec4 newRotation = rotation.multiply(ANCHOR); dir = new Vec3(newRotation.getX(), newRotation.getY(), newRotation.getZ()); } float speed = jitter(emitter.speed, emitter.speedJitter); velocity.v = dir.scale(speed); lifetime.life = jitter(emitter.maxLife, emitter.lifeJitter); lifetime.maxLife = lifetime.life; renderable.colour = emitter.colour; engine.addEntity(pie); } public void recyclePie(Entity entity) { // TODO: consider making queue bounded so as to limit lots of particles particles.offer(entity); } public static ParticleEmitter loadParticleParameters(String name) throws IOException { ParticleEmitter emitter = new ParticleEmitter(); loadParticleParameters(emitter, name); return emitter; } public static void loadParticleParameters(ParticleEmitter emitter, String name) throws IOException { BufferedReader br = new BufferedReader(new FileReader("particles/" + name + ".px")); try { String line; for (int lineNumber = 1; (line = br.readLine()) != null; lineNumber++) { line = line.replaceFirst(";.*$", "").trim(); if (line.isEmpty()) { continue; } String[] split1 = line.split("\\s*=\\s*"); String param = split1[0]; String value = split1[1]; Field field; try { field = ParticleEmitter.class.getField(param); } catch (NoSuchFieldException ex) { throw new IOException("Invalid parameter name [" + param + "] on line " + lineNumber); } catch (SecurityException ex) { throw new IOException("Parameter error [" + param + "] on line " + lineNumber + ": " + ex.getMessage()); } Class fieldClass = field.getType(); try { if (fieldClass == Vec3.class) { field.set(emitter, parseVec3(value)); } else if (fieldClass == AABBox.class) { field.set(emitter, parseAABBox(value)); } else { field.set(emitter, getWrapperClass(fieldClass).getMethod("valueOf", String.class).invoke(null, value)); } } catch (NumberFormatException nfe) { throw new IOException("Invalid value on line " + lineNumber + ": " + nfe.getMessage()); } catch (ReflectiveOperationException ex) { throw new IOException("Fatal error on line " + lineNumber + ": " + ex.getMessage()); } } } finally { br.close(); } } private static Class getWrapperClass(Class clazz) { if (clazz == int.class) { return Integer.class; } if (clazz == short.class) { return Short.class; } if (clazz == byte.class) { return Byte.class; } if (clazz == long.class) { return Long.class; } if (clazz == float.class) { return Float.class; } if (clazz == double.class) { return Double.class; } if (clazz == boolean.class) { return Boolean.class; } if (clazz == char.class) { return Character.class; } return Object.class; } private static Vec3 parseVec3(String values) { String[] split = values.split("\\s+"); if (split.length != 3) { throw new NumberFormatException("Invalid number of parameters: " + "need 3, found " + split.length); } return new Vec3( Float.parseFloat(split[0]), Float.parseFloat(split[1]), Float.parseFloat(split[2])); } private static AABBox parseAABBox(String values) { String[] split = values.split("\\s+"); if (split.length != 6) { throw new NumberFormatException("Invalid number of parameters: " + "need 6, found " + split.length); } return new AABBox( Float.parseFloat(split[0]), Float.parseFloat(split[1]), Float.parseFloat(split[2]), Float.parseFloat(split[3]), Float.parseFloat(split[4]), Float.parseFloat(split[5])); } }
Added acceleration to particles.
src/afk/ge/tokyo/EntityManager.java
Added acceleration to particles.
<ide><path>rc/afk/ge/tokyo/EntityManager.java <ide> float speed = jitter(emitter.speed, emitter.speedJitter); <ide> <ide> velocity.v = dir.scale(speed); <add> velocity.a = emitter.acceleration; <ide> <ide> lifetime.life = jitter(emitter.maxLife, emitter.lifeJitter); <ide> lifetime.maxLife = lifetime.life;
Java
lgpl-2.1
264383f0ffd65ab992ef89641f67c7dd033e9afa
0
champtar/fmj-sourceforge-mirror,champtar/fmj-sourceforge-mirror,champtar/fmj-sourceforge-mirror,champtar/fmj-sourceforge-mirror,champtar/fmj-sourceforge-mirror
package net.sf.fmj.media.rtp; import javax.media.*; import javax.media.control.*; import net.sf.fmj.media.*; /** * Implements a basic <tt>JitterBufferBehaviour</tt> which is not adaptive, does * not perform buffering beyond the one performed by the associated * <tt>JitterBuffer</tt> and is agnostic of the <tt>Format</tt> of the received * media data. The implementation may be used by extenders to facilitate the * implementation of the <tt>JitterBufferBehaviour</tt> interface. * * @author Lyubomir Marinov */ class BasicJitterBufferBehaviour implements JitterBufferBehaviour { /** * The RTP packet queue/jitter buffer which implements the storage of the * RTP packets added to and read from {@link #stream}. */ protected final JitterBuffer q; /** * The value which has been applied by this instance with an invocation of * {@link RTPRawReceiver#setRecvBufSize(int)}. */ private int recvBufSize; /** * The statistics related to the RTP packet queue/jitter buffer associated * with {@link #stream}. */ protected final JitterBufferStats stats; /** * The <tt>RTPSourceStream</tt> which has initialized this instance. */ protected final RTPSourceStream stream; /** * Initializes a new <tt>BasicJitterBufferBehaviour</tt> instance for the * purposes of a specific <tt>RTPSourceStream</tt>. * * @param stream the <tt>RTPSourceStream</tt> which has requested the * initialization of the new instance */ protected BasicJitterBufferBehaviour(RTPSourceStream stream) { this.stream = stream; this.q = this.stream.q; this.stats = this.stream.stats; } /** * Removes the first element (the one with the least sequence number) * from <tt>fill</tt> and releases it to be reused (adds it to * <tt>free</tt>) */ protected void dropFirstPkt() { q.dropFirstFill(); } /** * Removes an element from the queue and releases it to be reused. */ public void dropPkt() { dropFirstPkt(); } /** * Gets the <tt>BufferControl</tt> implementation set on the associated * <tt>RTPSourceStream</tt>. Provided as a convenience which delegates to * {@link RTPSourceStream#getBufferControl()}. * * @return the <tt>BufferControl</tt> implementation set on the associated * <tt>RTPSourceStream</tt> */ protected BufferControl getBufferControl() { return stream.getBufferControl(); } /** * Grows {@link #q} to a specific <tt>capacity</tt>. * * @param capacity the capacity to set on <tt>q</tt> * @throws IllegalArgumentException if the specified <tt>capacity</tt> is * less than the capacity of <tt>q</tt> */ protected void grow(int capacity) { if (capacity < 1) throw new IllegalArgumentException("capacity"); int qCapacity = q.getCapacity(); if (capacity == qCapacity) return; if (capacity < qCapacity) throw new IllegalArgumentException("capacity"); Log.info("Growing packet queue to " + capacity); stats.incrementNbGrow(); q.setCapacity(capacity); } /** * {@inheritDoc} * * <tt>BasicJitterBufferBehaviour</tt> always returns <tt>false</tt> to * indicate that it implements a fixed jitter buffer/RTP packet queue. */ public boolean isAdaptive() { return false; } /** * Allows extenders to adapt the size/capacity of the associated RTP packet * queue/<tt>JitterBuffer</tt> after a specific <tt>Buffer</tt> is received * and before it is added to the <tt>JitterBuffer</tt>. * * @param buffer the <tt>Buffer</tt> which has been received and is to be * added (after the method returns) * @return the approximate length in packets of the buffering performed by * this <tt>JitterBufferBehaviour</tt> and the associated * <tt>JitterBuffer</tt>. <tt>BasicJitterBufferBehaviour</tt> always returns * <tt>0</tt>. */ protected int monitorQSize(Buffer buffer) { return 0; } /** * {@inheritDoc} * * Maintains an average approximation of the size in bytes of an RTP packet * in the <tt>JitterBufferStats</tt> of the associated * <tt>RTPSourceStream</tt> and updates the <tt>recvBufSize</tt> of the * specified <tt>rtprawreceiver</tt>. */ public boolean preAdd(Buffer buffer, RTPRawReceiver rtprawreceiver) { stats.updateSizePerPacket(buffer); int aprxBufferLengthInPkts = monitorQSize(buffer); if (aprxBufferLengthInPkts > 0) setRecvBufSize(rtprawreceiver, aprxBufferLengthInPkts); return true; } /** * {@inheritDoc} */ public void read(Buffer buffer) { if (q.getFillCount() == 0) buffer.setDiscard(true); else { Buffer bufferFromQueue = q.getFill(); /* * Whatever follows, it sounds safer to return the * bufferFromQueue into the free pool eventually. */ try { /* * Copy the bufferFromQueue into the specified (output) * buffer. */ Object bufferData = buffer.getData(); Object bufferHeader = buffer.getHeader(); buffer.copy(bufferFromQueue); bufferFromQueue.setData(bufferData); bufferFromQueue.setHeader(bufferHeader); } finally { q.returnFree(bufferFromQueue); } } } /** * {@inheritDoc} */ public void reset() { } protected void setRecvBufSize( RTPRawReceiver rtprawreceiver, int aprxBufferLengthInPkts) { int sizePerPkt = stats.getSizePerPacket(); /* * There was no comment and the variables did not use meaningful names * at the time the following code was initially written. Consequently, * it is not immediately obvious why it is necessary at all and it may * be hard to understand. A possible explanation may be that, since the * threshold value will force a delay with a specific duration/byte * size, we should better be able to hold on to that much in the socket * so that it does not throw the delayed data away. */ int aprxThresholdInBytes = (aprxBufferLengthInPkts * sizePerPkt) / 2; if ((rtprawreceiver != null) && (aprxThresholdInBytes > this.recvBufSize)) { rtprawreceiver.setRecvBufSize(aprxThresholdInBytes); int recvBufSize = rtprawreceiver.getRecvBufSize(); this.recvBufSize = (recvBufSize < aprxThresholdInBytes) ? 0x7fffffff /* BufferControlImpl.NOT_SPECIFIED? */ : aprxThresholdInBytes; Log.comment( "RTP socket receive buffer size: " + recvBufSize + " bytes.\n"); } } /** * {@inheritDoc} * * <tt>BasicJitterBufferBehaviour</tt> returns <tt>true</tt> if the * associated RTP packet queue/jitter buffer is empty; otherwise, * <tt>false</tt> */ public boolean willReadBlock() { return q.noMoreFill(); } }
src.rtp/net/sf/fmj/media/rtp/BasicJitterBufferBehaviour.java
package net.sf.fmj.media.rtp; import javax.media.*; import javax.media.control.*; import net.sf.fmj.media.*; /** * Implements a basic <tt>JitterBufferBehaviour</tt> which is not adaptive, does * not perform buffering beyond the one performed by the associated * <tt>JitterBuffer</tt> and is agnostic of the <tt>Format</tt> of the received * media data. The implementation may be used by extenders to facilitate the * implementation of the <tt>JitterBufferBehaviour</tt> interface. * * @author Lyubomir Marinov */ class BasicJitterBufferBehaviour implements JitterBufferBehaviour { /** * The RTP packet queue/jitter buffer which implements the storage of the * RTP packets added to and read from {@link #stream}. */ protected final JitterBuffer q; private int sockBufSize; /** * The statistics related to the RTP packet queue/jitter buffer associated * with {@link #stream}. */ protected final JitterBufferStats stats; /** * The <tt>RTPSourceStream</tt> which has initialized this instance. */ protected final RTPSourceStream stream; /** * Initializes a new <tt>BasicJitterBufferBehaviour</tt> instance for the * purposes of a specific <tt>RTPSourceStream</tt>. * * @param stream the <tt>RTPSourceStream</tt> which has requested the * initialization of the new instance */ protected BasicJitterBufferBehaviour(RTPSourceStream stream) { this.stream = stream; this.q = this.stream.q; this.stats = this.stream.stats; } /** * Removes the first element (the one with the least sequence number) * from <tt>fill</tt> and releases it to be reused (adds it to * <tt>free</tt>) */ protected void dropFirstPkt() { q.dropFirstFill(); } /** * Removes an element from the queue and releases it to be reused. * <p> * <b>Note</b>: Blocks until the queue is non-empty. * </p> */ public void dropPkt() { dropFirstPkt(); } /** * Gets the <tt>BufferControl</tt> implementation set on the associated * <tt>RTPSourceStream</tt>. Provided as a convenience which delegates to * {@link RTPSourceStream#getBufferControl()}. * * @return the <tt>BufferControl</tt> implementation set on the associated * <tt>RTPSourceStream</tt> */ protected BufferControl getBufferControl() { return stream.getBufferControl(); } /** * Grows {@link #q} to a specific <tt>capacity</tt>. * * @param capacity the capacity to set on <tt>q</tt> * @throws IllegalArgumentException if the specified <tt>capacity</tt> is * less than the capacity of <tt>q</tt> */ protected void grow(int capacity) { if (capacity < 1) throw new IllegalArgumentException("capacity"); int qCapacity = q.getCapacity(); if (capacity == qCapacity) return; if (capacity < qCapacity) throw new IllegalArgumentException("capacity"); Log.info("Growing packet queue to " + capacity); stats.incrementNbGrow(); q.setCapacity(capacity); } /** * {@inheritDoc} * * <tt>BasicJitterBufferBehaviour</tt> always returns <tt>false</tt> to * indicate that it implements a fixed jitter buffer/RTP packet queue. */ public boolean isAdaptive() { return false; } /** * Allows extenders to adapt the size/capacity of the associated RTP packet * queue/<tt>JitterBuffer</tt> after a specific <tt>Buffer</tt> is received * and before it is added to the <tt>JitterBuffer</tt>. * * @param buffer the <tt>Buffer</tt> which has been received and is to be * added (after the method returns) * @return the approximate length in packets of the buffering performed by * this <tt>JitterBufferBehaviour</tt> and the associated * <tt>JitterBuffer</tt>. <tt>BasicJitterBufferBehaviour</tt> always returns * <tt>0</tt>. */ protected int monitorQSize(Buffer buffer) { return 0; } /** * {@inheritDoc} * * Maintains an average approximation of the size in bytes of an RTP packet * in the <tt>JitterBufferStats</tt> of the associated * <tt>RTPSourceStream</tt> and updates the <tt>recvBufSize</tt> of the * specified <tt>rtprawreceiver</tt>. */ public boolean preAdd(Buffer buffer, RTPRawReceiver rtprawreceiver) { stats.updateSizePerPacket(buffer); int aprxBufferLengthInPkts = monitorQSize(buffer); if (aprxBufferLengthInPkts > 0) setRecvBufSize(rtprawreceiver, aprxBufferLengthInPkts); return true; } /** * {@inheritDoc} */ public void read(Buffer buffer) { if (q.getFillCount() == 0) buffer.setDiscard(true); else { Buffer bufferFromQueue = q.getFill(); /* * Whatever follows, it sounds safer to return the * bufferFromQueue into the free pool eventually. */ try { /* * Copy the bufferFromQueue into the specified (output) * buffer. */ Object bufferData = buffer.getData(); Object bufferHeader = buffer.getHeader(); buffer.copy(bufferFromQueue); bufferFromQueue.setData(bufferData); bufferFromQueue.setHeader(bufferHeader); } finally { q.returnFree(bufferFromQueue); } } } /** * {@inheritDoc} */ public void reset() { // TODO Auto-generated method stub } protected void setRecvBufSize( RTPRawReceiver rtprawreceiver, int aprxBufferLengthInPkts) { int sizePerPkt = stats.getSizePerPacket(); /* * There was no comment and the variables did not use meaningful names * at the time the following code was initially written. Consequently, * it is not immediately obvious why it is necessary at all and it may * be hard to understand. A possible explanation may be that, since the * threshold value will force a delay with a specific duration/byte * size, we should better be able to hold on to that much in the socket * so that it does not throw the delayed data away. */ int aprxThresholdInBytes = (aprxBufferLengthInPkts * sizePerPkt) / 2; if (rtprawreceiver != null && aprxThresholdInBytes > sockBufSize) { rtprawreceiver.setRecvBufSize(aprxThresholdInBytes); if (rtprawreceiver.getRecvBufSize() < aprxThresholdInBytes) sockBufSize = 0x7fffffff /* BufferControlImpl.NOT_SPECIFIED? */; else sockBufSize = aprxThresholdInBytes; Log.comment( "RTP socket receive buffer size: " + rtprawreceiver.getRecvBufSize() + " bytes.\n"); } } /** * {@inheritDoc} * * <tt>BasicJitterBufferBehaviour</tt> returns <tt>true</tt> if the * associated RTP packet queue/jitter buffer is empty; otherwise, * <tt>false</tt> */ public boolean willReadBlock() { return q.noMoreFill(); } }
Deletes an incorrect Javadoc comment. Reported by Tom Denham. git-svn-id: 0e2048bb602cf70225a2d2227aa1aa58d82524a7@29 799b4810-d841-4bb4-a54b-9156a0c3e4cd
src.rtp/net/sf/fmj/media/rtp/BasicJitterBufferBehaviour.java
Deletes an incorrect Javadoc comment. Reported by Tom Denham.
<ide><path>rc.rtp/net/sf/fmj/media/rtp/BasicJitterBufferBehaviour.java <ide> */ <ide> protected final JitterBuffer q; <ide> <del> private int sockBufSize; <add> /** <add> * The value which has been applied by this instance with an invocation of <add> * {@link RTPRawReceiver#setRecvBufSize(int)}. <add> */ <add> private int recvBufSize; <ide> <ide> /** <ide> * The statistics related to the RTP packet queue/jitter buffer associated <ide> <ide> /** <ide> * Removes an element from the queue and releases it to be reused. <del> * <p> <del> * <b>Note</b>: Blocks until the queue is non-empty. <del> * </p> <ide> */ <ide> public void dropPkt() <ide> { <ide> */ <ide> public void reset() <ide> { <del> // TODO Auto-generated method stub <ide> } <ide> <ide> protected void setRecvBufSize( <ide> int aprxThresholdInBytes <ide> = (aprxBufferLengthInPkts * sizePerPkt) / 2; <ide> <del> if (rtprawreceiver != null <del> && aprxThresholdInBytes > sockBufSize) <add> if ((rtprawreceiver != null) <add> && (aprxThresholdInBytes > this.recvBufSize)) <ide> { <ide> rtprawreceiver.setRecvBufSize(aprxThresholdInBytes); <del> if (rtprawreceiver.getRecvBufSize() < aprxThresholdInBytes) <del> sockBufSize = 0x7fffffff /* BufferControlImpl.NOT_SPECIFIED? */; <del> else <del> sockBufSize = aprxThresholdInBytes; <add> <add> int recvBufSize = rtprawreceiver.getRecvBufSize(); <add> <add> this.recvBufSize <add> = (recvBufSize < aprxThresholdInBytes) <add> ? 0x7fffffff /* BufferControlImpl.NOT_SPECIFIED? */ <add> : aprxThresholdInBytes; <ide> Log.comment( <del> "RTP socket receive buffer size: " <del> + rtprawreceiver.getRecvBufSize() <add> "RTP socket receive buffer size: " + recvBufSize <ide> + " bytes.\n"); <ide> } <ide> }
Java
apache-2.0
cb7ca694595d86843a4cf7db60a7aea11346832e
0
reactor/reactor-incubator,jbrisbin/reactor-extensions
package reactor.pipe; import org.junit.Test; import org.pcollections.TreePVector; import reactor.core.processor.RingBufferWorkProcessor; import reactor.fn.Consumer; import reactor.pipe.concurrent.AVar; import reactor.pipe.concurrent.Atom; import reactor.pipe.key.Key; import reactor.pipe.registry.ConcurrentRegistry; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class AnonymousPipeTest extends AbstractFirehoseTest { @Test public void testMap() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> res = new AVar<>(); pipe.anonymous(Key.wrap("source")) .map((i) -> i + 1) .map(i -> i * 2) .consume(res::set); pipe.notify(Key.wrap("source"), 1); assertThat(res.get(1, TimeUnit.SECONDS), is(4)); } @Test public void statefulMapTest() throws InterruptedException { AVar<Integer> res = new AVar<>(3); NamedPipe<Integer> intPipe = new NamedPipe<>(firehose); intPipe.anonymous(Key.wrap("key1")) .map((i) -> i + 1) .map((Atom<Integer> state, Integer i) -> { return state.update(old -> old + i); }, 0) .consume(res::set); intPipe.notify(Key.wrap("key1"), 1); intPipe.notify(Key.wrap("key1"), 2); intPipe.notify(Key.wrap("key1"), 3); assertThat(res.get(LATCH_TIMEOUT, LATCH_TIME_UNIT), is(9)); } @Test public void testFilter() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> res = new AVar<>(); pipe.anonymous(Key.wrap("source")) .map(i -> i + 1) .filter(i -> i % 2 != 0) .map(i -> i * 2) .consume(res::set); pipe.notify(Key.wrap("source"), 1); pipe.notify(Key.wrap("source"), 2); assertThat(res.get(1, TimeUnit.SECONDS), is(6)); } @Test public void testPartition() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<List<Integer>> res = new AVar<>(); pipe.anonymous(Key.wrap("source")) .partition((i) -> { return i.size() == 5; }) .consume(res::set); pipe.notify(Key.wrap("source"), 1); pipe.notify(Key.wrap("source"), 2); pipe.notify(Key.wrap("source"), 3); pipe.notify(Key.wrap("source"), 4); pipe.notify(Key.wrap("source"), 5); pipe.notify(Key.wrap("source"), 6); pipe.notify(Key.wrap("source"), 7); assertThat(res.get(1, TimeUnit.SECONDS), is(TreePVector.from(Arrays.asList(1, 2, 3, 4, 5)))); } @Test public void testSlide() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<List<Integer>> res = new AVar<>(6); pipe.anonymous(Key.wrap("source")) .slide(i -> { return i.subList(i.size() > 5 ? i.size() - 5 : 0, i.size()); }) .consume(res::set); pipe.notify(Key.wrap("source"), 1); pipe.notify(Key.wrap("source"), 2); pipe.notify(Key.wrap("source"), 3); pipe.notify(Key.wrap("source"), 4); pipe.notify(Key.wrap("source"), 5); pipe.notify(Key.wrap("source"), 6); assertThat(res.get(1, TimeUnit.SECONDS), is(TreePVector.from(Arrays.asList(2,3,4,5,6)))); } @Test public void testNotify() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> res = new AVar<>(); AnonymousPipe<Integer> s = pipe.anonymous(Key.wrap("source")); s.map((i) -> i + 1) .map(i -> i * 2) .consume(res::set); pipe.notify(Key.wrap("source"), 1); assertThat(res.get(10, TimeUnit.SECONDS), is(4)); } @Test public void testUnregister() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); CountDownLatch latch = new CountDownLatch(1); AnonymousPipe<Integer> s = pipe.anonymous(Key.wrap("source")); s.map((i) -> i + 1) .map(i -> i * 2) .consume(i -> latch.countDown()); pipe.notify(Key.wrap("source"), 1); s.unregister(); latch.await(10, TimeUnit.SECONDS); assertThat(pipe.firehose().getConsumerRegistry().stream().count(), is(0L)); } @Test public void testRedirect() throws InterruptedException { Key destination = Key.wrap("destination"); NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> res = new AVar<>(); AnonymousPipe<Integer> s = pipe.anonymous(Key.wrap("source")); s.map((i) -> i + 1) .map(i -> i * 2) .redirect(destination); pipe.consume(destination, (Integer i) -> res.set(i)); pipe.notify(Key.wrap("source"), 1); assertThat(res.get(1, TimeUnit.SECONDS), is(4)); } @Test public void testConsume() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> resValue = new AVar<>(); AVar<Key> resKey = new AVar<>(); AnonymousPipe<Integer> s = pipe.anonymous(Key.wrap("source")); s.map((i) -> i + 1) .map(i -> i * 2) .consume((k, v) -> { resKey.set(k); resValue.set(v); }); pipe.notify(Key.wrap("source"), 1); assertThat(resKey.get(1, TimeUnit.SECONDS).getPart(0), is("source")); assertThat(resValue.get(1, TimeUnit.SECONDS), is(4)); } @Test public void testSmoke() throws InterruptedException { // Tests backpressure and in-thread dispatches Firehose<Key> concurrentFirehose = new Firehose<>(new ConcurrentRegistry<>(), RingBufferWorkProcessor.create(Executors.newFixedThreadPool(4), 256), 4, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { System.out.printf("Exception caught while dispatching: %s\n", throwable.getMessage()); throwable.printStackTrace(); } }); int iterations = 2000; CountDownLatch latch = new CountDownLatch(iterations); NamedPipe<Integer> pipe = new NamedPipe<>(firehose); pipe.anonymous(Key.wrap("key1")) .map((i) -> i + 1) .map(i -> { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } return i * 2; }) .consume((i_) -> latch.countDown()); for (int i = 0; i < iterations; i++) { firehose.notify(Key.wrap("key1"), i); if (i % 500 == 0) { System.out.println("Processed " + i + " keys"); } } latch.await(30, TimeUnit.SECONDS); assertThat(latch.getCount(), is(0L)); concurrentFirehose.shutdown(); } }
reactor-pipe/src/test/java/reactor/pipe/AnonymousPipeTest.java
package reactor.pipe; import org.junit.Test; import org.pcollections.TreePVector; import reactor.core.processor.RingBufferWorkProcessor; import reactor.fn.Consumer; import reactor.pipe.concurrent.AVar; import reactor.pipe.concurrent.Atom; import reactor.pipe.key.Key; import reactor.pipe.registry.ConcurrentRegistry; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class AnonymousPipeTest extends AbstractFirehoseTest { @Test public void testMap() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> res = new AVar<>(); pipe.anonymous(Key.wrap("source")) .map((i) -> i + 1) .map(i -> i * 2) .consume(res::set); pipe.notify(Key.wrap("source"), 1); assertThat(res.get(1, TimeUnit.SECONDS), is(4)); } @Test public void statefulMapTest() throws InterruptedException { AVar<Integer> res = new AVar<>(3); NamedPipe<Integer> intPipe = new NamedPipe<>(firehose); intPipe.anonymous(Key.wrap("key1")) .map((i) -> i + 1) .map((Atom<Integer> state, Integer i) -> { return state.update(old -> old + i); }, 0) .consume(res::set); intPipe.notify(Key.wrap("key1"), 1); intPipe.notify(Key.wrap("key1"), 2); intPipe.notify(Key.wrap("key1"), 3); assertThat(res.get(LATCH_TIMEOUT, LATCH_TIME_UNIT), is(9)); } @Test public void testFilter() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> res = new AVar<>(); pipe.anonymous(Key.wrap("source")) .map(i -> i + 1) .filter(i -> i % 2 != 0) .map(i -> i * 2) .consume(res::set); pipe.notify(Key.wrap("source"), 1); pipe.notify(Key.wrap("source"), 2); assertThat(res.get(1, TimeUnit.SECONDS), is(6)); } @Test public void testPartition() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<List<Integer>> res = new AVar<>(); pipe.anonymous(Key.wrap("source")) .partition((i) -> { return i.size() == 5; }) .consume(res::set); pipe.notify(Key.wrap("source"), 1); pipe.notify(Key.wrap("source"), 2); pipe.notify(Key.wrap("source"), 3); pipe.notify(Key.wrap("source"), 4); pipe.notify(Key.wrap("source"), 5); pipe.notify(Key.wrap("source"), 6); pipe.notify(Key.wrap("source"), 7); assertThat(res.get(1, TimeUnit.SECONDS), is(TreePVector.from(Arrays.asList(1, 2, 3, 4, 5)))); } @Test public void testSlide() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<List<Integer>> res = new AVar<>(6); pipe.anonymous(Key.wrap("source")) .slide(i -> { return i.subList(i.size() > 5 ? i.size() - 5 : 0, i.size()); }) .consume(res::set); pipe.notify(Key.wrap("source"), 1); pipe.notify(Key.wrap("source"), 2); pipe.notify(Key.wrap("source"), 3); pipe.notify(Key.wrap("source"), 4); pipe.notify(Key.wrap("source"), 5); pipe.notify(Key.wrap("source"), 6); assertThat(res.get(1, TimeUnit.SECONDS), is(TreePVector.from(Arrays.asList(2,3,4,5,6)))); } @Test public void testNotify() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> res = new AVar<>(); AnonymousPipe<Integer> s = pipe.anonymous(Key.wrap("source")); s.map((i) -> i + 1) .map(i -> i * 2) .consume(res::set); pipe.notify(Key.wrap("source"), 1); assertThat(res.get(10, TimeUnit.SECONDS), is(4)); } @Test public void testUnregister() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); CountDownLatch latch = new CountDownLatch(2); AnonymousPipe<Integer> s = pipe.anonymous(Key.wrap("source")); s.map((i) -> i + 1) .map(i -> i * 2) .consume(i -> latch.countDown()); pipe.notify(Key.wrap("source"), 1); s.unregister(); pipe.notify(Key.wrap("source"), 1); latch.await(10, TimeUnit.SECONDS); assertThat(latch.getCount(), is(1L)); assertThat(pipe.firehose().getConsumerRegistry().stream().count(), is(0L)); } @Test public void testRedirect() throws InterruptedException { Key destination = Key.wrap("destination"); NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> res = new AVar<>(); AnonymousPipe<Integer> s = pipe.anonymous(Key.wrap("source")); s.map((i) -> i + 1) .map(i -> i * 2) .redirect(destination); pipe.consume(destination, (Integer i) -> res.set(i)); pipe.notify(Key.wrap("source"), 1); assertThat(res.get(1, TimeUnit.SECONDS), is(4)); } @Test public void testConsume() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(firehose); AVar<Integer> resValue = new AVar<>(); AVar<Key> resKey = new AVar<>(); AnonymousPipe<Integer> s = pipe.anonymous(Key.wrap("source")); s.map((i) -> i + 1) .map(i -> i * 2) .consume((k, v) -> { resKey.set(k); resValue.set(v); }); pipe.notify(Key.wrap("source"), 1); assertThat(resKey.get(1, TimeUnit.SECONDS).getPart(0), is("source")); assertThat(resValue.get(1, TimeUnit.SECONDS), is(4)); } @Test public void testSmoke() throws InterruptedException { // Tests backpressure and in-thread dispatches Firehose<Key> concurrentFirehose = new Firehose<>(new ConcurrentRegistry<>(), RingBufferWorkProcessor.create(Executors.newFixedThreadPool(4), 256), 4, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { System.out.printf("Exception caught while dispatching: %s\n", throwable.getMessage()); throwable.printStackTrace(); } }); int iterations = 2000; CountDownLatch latch = new CountDownLatch(iterations); NamedPipe<Integer> pipe = new NamedPipe<>(firehose); pipe.anonymous(Key.wrap("key1")) .map((i) -> i + 1) .map(i -> { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } return i * 2; }) .consume((i_) -> latch.countDown()); for (int i = 0; i < iterations; i++) { firehose.notify(Key.wrap("key1"), i); if (i % 500 == 0) { System.out.println("Processed " + i + " keys"); } } latch.await(30, TimeUnit.SECONDS); assertThat(latch.getCount(), is(0L)); concurrentFirehose.shutdown(); } }
This test was stupid anyways
reactor-pipe/src/test/java/reactor/pipe/AnonymousPipeTest.java
This test was stupid anyways
<ide><path>eactor-pipe/src/test/java/reactor/pipe/AnonymousPipeTest.java <ide> @Test <ide> public void testUnregister() throws InterruptedException { <ide> NamedPipe<Integer> pipe = new NamedPipe<>(firehose); <del> CountDownLatch latch = new CountDownLatch(2); <add> CountDownLatch latch = new CountDownLatch(1); <ide> <ide> AnonymousPipe<Integer> s = pipe.anonymous(Key.wrap("source")); <ide> <ide> <ide> pipe.notify(Key.wrap("source"), 1); <ide> s.unregister(); <del> pipe.notify(Key.wrap("source"), 1); <ide> <ide> latch.await(10, TimeUnit.SECONDS); <del> assertThat(latch.getCount(), is(1L)); <ide> assertThat(pipe.firehose().getConsumerRegistry().stream().count(), is(0L)); <ide> } <ide>
Java
apache-2.0
e497500463e0f70acd15ba694376b8b0566c8e6e
0
DevopsJK/SuitAgent,DevopsJK/SuitAgent,DevopsJK/SuitAgent,DevopsJK/SuitAgent
/* * www.msxf.com Inc. * Copyright (c) 2017 All Rights Reserved */ package com.falcon.suitagent.util; // ,%%%%%%%%, // ,%%/\%%%%/\%% // ,%%%\c "" J/%%% // %. %%%%/ o o \%%% // `%%. %%%% _ |%%% // `%% `%%%%(__Y__)%%' // // ;%%%%`\-/%%%' // (( / `%%%%%%%' // \\ .' | // \\ / \ | | // \\/攻城狮保佑) | | // \ /_ | |__ // (___________))))))) `\/' /* * 修订记录: * [email protected] 2017-08-04 16:53 创建 */ import com.falcon.suitagent.config.AgentConfiguration; import com.falcon.suitagent.vo.docker.ContainerProcInfoToHost; import com.google.common.collect.ImmutableMap; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.messages.AttachedNetwork; import com.spotify.docker.client.messages.Container; import com.spotify.docker.client.messages.ContainerInfo; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import static com.falcon.suitagent.util.CacheByTimeUtil.getCache; import static com.falcon.suitagent.util.CacheByTimeUtil.setCache; /** * @author [email protected] */ @Slf4j public class DockerUtil { private static final Byte[] LockForGetAllHostContainerId = new Byte[0]; private static final Byte[] LockForGetAllHostContainerProcInfos = new Byte[0]; private static final String PROC_HOST_VOLUME = "/proc_host"; private static DockerClient docker = null; static { if (AgentConfiguration.INSTANCE.isDockerRuntime()){ try { docker = new DefaultDockerClient("unix:///var/run/docker.sock"); } catch (Exception e) { log.error("docker client初始化失败,可能未挂在/var/run目录或无文件/var/run/docker.sock的访问权限",e); throw e; } } } public static void closeDockerClient(){ if (docker != null){ docker.close(); } } /** * 获取容器信息 * @param containerId * @return */ public static ContainerInfo getContainerInfo(String containerId){ String cacheKey = "containerInfoCacheKey" + containerId; final ContainerInfo[] containerInfo = {(ContainerInfo) getCache(cacheKey)}; if (containerInfo[0] != null){ return containerInfo[0]; }else { synchronized (containerId.intern()) { try { int timeOut = 45; final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1); //阻塞队列异步执行 ExecuteThreadUtil.execute(() -> { try { containerInfo[0] = docker.inspectContainer(containerId); setCache(cacheKey, containerInfo[0]); blockingQueue.offer(containerInfo[0]); } catch (Throwable t) { blockingQueue.offer(t); } }); //超时45秒 Object result = BlockingQueueUtil.getResult(blockingQueue, timeOut, TimeUnit.SECONDS); blockingQueue.clear(); if (result instanceof ContainerInfo) { return (ContainerInfo) result; }else if (result == null) { log.error("docker 容器Info获取{}秒超时:{}",timeOut,containerId); return null; }else if (result instanceof Throwable) { log.error("docker 容器Info获取异常",result); return null; }else { log.error("未知结果类型:{}",result); return null; } } catch (Exception e) { log.error("",e); return null; } } } } /** * 获取容器列表 * @param containersParam * @return */ public static List<Container> getContainers(DockerClient.ListContainersParam containersParam) { String cacheKey = "getContainer" + containersParam.value(); final List<Container> containers = (List<Container>) CacheByTimeUtil.getCache(cacheKey); if (containers != null) { return containers; } try { int timeOut = 45; final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1); //阻塞队列异步执行 ExecuteThreadUtil.execute(() -> { try { List<Container> containerList = docker.listContainers(containersParam); setCache(cacheKey, containerList); blockingQueue.offer(containerList); } catch (Throwable t) { blockingQueue.offer(t); } }); //超时 Object result = BlockingQueueUtil.getResult(blockingQueue, timeOut, TimeUnit.SECONDS); blockingQueue.clear(); if (result instanceof List) { return (List<Container>) result; }else if (result == null) { log.error("docker 容器 List 获取{}秒超",timeOut); return new ArrayList<>(); }else if (result instanceof Throwable) { log.error("docker 容器 List 获取异常",result); return new ArrayList<>(); }else { log.error("未知结果类型:{}",result); return new ArrayList<>(); } } catch (Exception e) { log.error("",e); return new ArrayList<>(); } } /** * 获取主机上所有运行容器的proc信息 * @return */ public static List<ContainerProcInfoToHost> getAllHostContainerProcInfos(){ String cacheKey = "ALL_HOST_CONTAINER_PROC_INFOS"; List<ContainerProcInfoToHost> procInfoToHosts = (List<ContainerProcInfoToHost>) getCache(cacheKey); if (procInfoToHosts != null){ //返回缓存数据 return procInfoToHosts; }else { procInfoToHosts = new ArrayList<>(); } synchronized (LockForGetAllHostContainerProcInfos){ try { List<Container> containers = getContainers(DockerClient.ListContainersParam.withStatusRunning()); for (Container container : containers) { ContainerInfo info = getContainerInfo(container.id()); if (info != null) { String pid = String.valueOf(info.state().pid()); procInfoToHosts.add(new ContainerProcInfoToHost(container.id(),PROC_HOST_VOLUME + "/" + pid + "/root",pid)); } } } catch (Exception e) { log.error("",e); } } if (!procInfoToHosts.isEmpty()) { //设置缓存 setCache(cacheKey,procInfoToHosts); } return procInfoToHosts; } /** * 获取Java应用容器的应用名称 * 注: * 必须通过docker run命令的-e参数执行应用名,例如 docker run -e "appName=suitAgent" * @param containerId * 容器id * @return * 若未指定应用名称或获取失败返回null */ public static String getJavaContainerAppName(String containerId) throws InterruptedException { String cacheKey = "appName" + containerId; String v = (String) getCache(cacheKey); if (StringUtils.isNotEmpty(v)) { return v; } try { ContainerInfo containerInfo = getContainerInfo(containerId); if (containerInfo != null){ List<String> env = containerInfo.config().env(); if (env != null){ for (String s : env) { String[] split = s.split(s.contains("=") ? "=" : ":"); if (split.length == 2){ String key = split[0]; String value = split[1]; if ("appName".equals(key)){ setCache(cacheKey,value); return value; } } } } } } catch (Exception e) { log.error("",e); } return null; } /** * 容器网络模式是否为host模式 * @param containerId * @return */ public static boolean isHostNet(String containerId){ String cacheKey = "isHostNet" + containerId; Boolean v = (Boolean) getCache(cacheKey); if (v != null){ return v; } Boolean value = false; try { ContainerInfo containerInfo = getContainerInfo(containerId); if (containerInfo != null) { ImmutableMap<String, AttachedNetwork> networks = containerInfo.networkSettings().networks(); if (networks != null && !networks.isEmpty()){ value = networks.get("host") != null && StringUtils.isNotEmpty(networks.get("host").ipAddress()); setCache(cacheKey,value); }else { log.warn("容器{}无Networks配置",containerInfo.name()); } } } catch (Exception e) { log.error("",e); } return value; } /** * 获取容器主机名 * @param containerId * @return */ public static String getHostName(String containerId){ try { ContainerInfo containerInfo = getContainerInfo(containerId); if (containerInfo != null) { return containerInfo.config().hostname(); } } catch (Exception e) { log.error("",e); } return ""; } /** * 获取容器IP地址 * @param containerId * 容器ID * @return * 1、获取失败返回null * 2、host网络模式直接返回宿主机IP */ public static String getContainerIp(String containerId){ String cacheKey = "containerIp" + containerId; String v = (String) getCache(cacheKey); if (StringUtils.isNotEmpty(v)) { return v; } try { if (isHostNet(containerId)){ return HostUtil.getHostIp(); } ContainerInfo containerInfo = getContainerInfo(containerId); if (containerInfo != null) { ImmutableMap<String, AttachedNetwork> networks = containerInfo.networkSettings().networks(); if (networks != null && !networks.isEmpty()){ String ip = networks.get(networks.keySet().asList().get(0)).ipAddress(); setCache(cacheKey,ip); return ip; }else { log.warn("容器{}无Networks配置",containerInfo.name()); } } } catch (Exception e) { log.error("",e); } return null; } /** * 判断本地所有容器(所有状态)中,是否存在容器id前12位字符串包含在指定的名称中 * @param name * @return */ public static boolean has12ContainerIdInName(String name) { if (StringUtils.isEmpty(name)){ return false; } try { for (String id : getAllHostContainerId()) { if (name.contains(id.substring(0,12))){ return true; } } } catch (Exception e) { log.error("",e); return false; } return false; } private static List<String> getAllHostContainerId(){ String cacheKey = "allHostContainerIds"; int cacheTime = 28;//28秒缓存周期,保证一次采集job只需要访问一次docker即可 List<String> ids = (List<String>) getCache(cacheKey); if (ids != null){ return ids; }else { ids = new ArrayList<>(); } synchronized (LockForGetAllHostContainerId){ try { List<Container> containerList = getContainers(DockerClient.ListContainersParam.allContainers()); for (Container container : containerList) { ids.add(container.id()); } } catch (Exception e) { log.error("",e); } } setCache(cacheKey,ids,cacheTime); return ids; } }
src/main/java/com/falcon/suitagent/util/DockerUtil.java
/* * www.msxf.com Inc. * Copyright (c) 2017 All Rights Reserved */ package com.falcon.suitagent.util; // ,%%%%%%%%, // ,%%/\%%%%/\%% // ,%%%\c "" J/%%% // %. %%%%/ o o \%%% // `%%. %%%% _ |%%% // `%% `%%%%(__Y__)%%' // // ;%%%%`\-/%%%' // (( / `%%%%%%%' // \\ .' | // \\ / \ | | // \\/攻城狮保佑) | | // \ /_ | |__ // (___________))))))) `\/' /* * 修订记录: * [email protected] 2017-08-04 16:53 创建 */ import com.falcon.suitagent.config.AgentConfiguration; import com.falcon.suitagent.vo.docker.ContainerProcInfoToHost; import com.google.common.collect.ImmutableMap; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.messages.AttachedNetwork; import com.spotify.docker.client.messages.Container; import com.spotify.docker.client.messages.ContainerInfo; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import static com.falcon.suitagent.util.CacheByTimeUtil.getCache; import static com.falcon.suitagent.util.CacheByTimeUtil.setCache; /** * @author [email protected] */ @Slf4j public class DockerUtil { private static final Byte[] LockForGetAllHostContainerId = new Byte[0]; private static final Byte[] LockForGetAllHostContainerProcInfos = new Byte[0]; private static final String PROC_HOST_VOLUME = "/proc_host"; private static DockerClient docker = null; static { if (AgentConfiguration.INSTANCE.isDockerRuntime()){ try { docker = new DefaultDockerClient("unix:///var/run/docker.sock"); } catch (Exception e) { log.error("docker client初始化失败,可能未挂在/var/run目录或无文件/var/run/docker.sock的访问权限",e); throw e; } } } public static void closeDockerClient(){ if (docker != null){ docker.close(); } } /** * 获取容器信息 * @param containerId * @return */ public static ContainerInfo getContainerInfo(String containerId){ String cacheKey = "containerInfoCacheKey" + containerId; final ContainerInfo[] containerInfo = {(ContainerInfo) getCache(cacheKey)}; if (containerInfo[0] != null){ return containerInfo[0]; }else { synchronized (containerId.intern()) { try { int timeOut = 45; final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1); //阻塞队列异步执行 ExecuteThreadUtil.execute(() -> { try { containerInfo[0] = docker.inspectContainer(containerId); setCache(cacheKey, containerInfo[0]); blockingQueue.offer(containerInfo[0]); } catch (Throwable t) { blockingQueue.offer(t); } }); //超时45秒 Object result = BlockingQueueUtil.getResult(blockingQueue, timeOut, TimeUnit.SECONDS); blockingQueue.clear(); if (result instanceof ContainerInfo) { return (ContainerInfo) result; }else if (result == null) { log.error("docker 容器Info获取{}秒超时:{}",timeOut,containerId); return null; }else if (result instanceof Throwable) { log.error("docker 容器Info获取异常",result); return null; }else { log.error("未知结果类型:{}",result); return null; } } catch (Exception e) { log.error("",e); return null; } } } } /** * 获取主机上所有运行容器的proc信息 * @return */ public static List<ContainerProcInfoToHost> getAllHostContainerProcInfos(){ String cacheKey = "ALL_HOST_CONTAINER_PROC_INFOS"; List<ContainerProcInfoToHost> procInfoToHosts = (List<ContainerProcInfoToHost>) getCache(cacheKey); if (procInfoToHosts != null){ //返回缓存数据 return procInfoToHosts; }else { procInfoToHosts = new ArrayList<>(); } if (docker != null){ synchronized (LockForGetAllHostContainerProcInfos){ try { List<Container> containers = docker.listContainers(DockerClient.ListContainersParam.withStatusRunning()); for (Container container : containers) { ContainerInfo info = getContainerInfo(container.id()); if (info != null) { String pid = String.valueOf(info.state().pid()); procInfoToHosts.add(new ContainerProcInfoToHost(container.id(),PROC_HOST_VOLUME + "/" + pid + "/root",pid)); } } } catch (Exception e) { log.error("",e); } } } if (!procInfoToHosts.isEmpty()) { //设置缓存 setCache(cacheKey,procInfoToHosts); } return procInfoToHosts; } /** * 获取Java应用容器的应用名称 * 注: * 必须通过docker run命令的-e参数执行应用名,例如 docker run -e "appName=suitAgent" * @param containerId * 容器id * @return * 若未指定应用名称或获取失败返回null */ public static String getJavaContainerAppName(String containerId) throws InterruptedException { String cacheKey = "appName" + containerId; String v = (String) getCache(cacheKey); if (StringUtils.isNotEmpty(v)) { return v; } try { ContainerInfo containerInfo = getContainerInfo(containerId); if (containerInfo != null){ List<String> env = containerInfo.config().env(); if (env != null){ for (String s : env) { String[] split = s.split(s.contains("=") ? "=" : ":"); if (split.length == 2){ String key = split[0]; String value = split[1]; if ("appName".equals(key)){ setCache(cacheKey,value); return value; } } } } } } catch (Exception e) { log.error("",e); } return null; } /** * 容器网络模式是否为host模式 * @param containerId * @return */ public static boolean isHostNet(String containerId){ String cacheKey = "isHostNet" + containerId; Boolean v = (Boolean) getCache(cacheKey); if (v != null){ return v; } Boolean value = false; try { ContainerInfo containerInfo = getContainerInfo(containerId); if (containerInfo != null) { ImmutableMap<String, AttachedNetwork> networks = containerInfo.networkSettings().networks(); if (networks != null && !networks.isEmpty()){ value = networks.get("host") != null && StringUtils.isNotEmpty(networks.get("host").ipAddress()); setCache(cacheKey,value); }else { log.warn("容器{}无Networks配置",containerInfo.name()); } } } catch (Exception e) { log.error("",e); } return value; } /** * 获取容器主机名 * @param containerId * @return */ public static String getHostName(String containerId){ try { ContainerInfo containerInfo = getContainerInfo(containerId); if (containerInfo != null) { return containerInfo.config().hostname(); } } catch (Exception e) { log.error("",e); } return ""; } /** * 获取容器IP地址 * @param containerId * 容器ID * @return * 1、获取失败返回null * 2、host网络模式直接返回宿主机IP */ public static String getContainerIp(String containerId){ String cacheKey = "containerIp" + containerId; String v = (String) getCache(cacheKey); if (StringUtils.isNotEmpty(v)) { return v; } try { if (isHostNet(containerId)){ return HostUtil.getHostIp(); } ContainerInfo containerInfo = getContainerInfo(containerId); if (containerInfo != null) { ImmutableMap<String, AttachedNetwork> networks = containerInfo.networkSettings().networks(); if (networks != null && !networks.isEmpty()){ String ip = networks.get(networks.keySet().asList().get(0)).ipAddress(); setCache(cacheKey,ip); return ip; }else { log.warn("容器{}无Networks配置",containerInfo.name()); } } } catch (Exception e) { log.error("",e); } return null; } /** * 判断本地所有容器(所有状态)中,是否存在容器id前12位字符串包含在指定的名称中 * @param name * @return */ public static boolean has12ContainerIdInName(String name) { if (StringUtils.isEmpty(name)){ return false; } try { for (String id : getAllHostContainerId()) { if (name.contains(id.substring(0,12))){ return true; } } } catch (Exception e) { log.error("",e); return false; } return false; } private static List<String> getAllHostContainerId(){ String cacheKey = "allHostContainerIds"; int cacheTime = 28;//28秒缓存周期,保证一次采集job只需要访问一次docker即可 List<String> ids = (List<String>) getCache(cacheKey); if (ids != null){ return ids; }else { ids = new ArrayList<>(); } synchronized (LockForGetAllHostContainerId){ try { List<Container> containerList = docker.listContainers(DockerClient.ListContainersParam.allContainers()); for (Container container : containerList) { ids.add(container.id()); } } catch (Exception e) { log.error("",e); } } setCache(cacheKey,ids,cacheTime); return ids; } }
容器信息获取添加超时和同步处理 Signed-off-by: QianLong <[email protected]>
src/main/java/com/falcon/suitagent/util/DockerUtil.java
容器信息获取添加超时和同步处理
<ide><path>rc/main/java/com/falcon/suitagent/util/DockerUtil.java <ide> } <ide> <ide> /** <add> * 获取容器列表 <add> * @param containersParam <add> * @return <add> */ <add> public static List<Container> getContainers(DockerClient.ListContainersParam containersParam) { <add> String cacheKey = "getContainer" + containersParam.value(); <add> final List<Container> containers = (List<Container>) CacheByTimeUtil.getCache(cacheKey); <add> if (containers != null) { <add> return containers; <add> } <add> <add> try { <add> int timeOut = 45; <add> final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1); <add> //阻塞队列异步执行 <add> ExecuteThreadUtil.execute(() -> { <add> try { <add> List<Container> containerList = docker.listContainers(containersParam); <add> setCache(cacheKey, containerList); <add> blockingQueue.offer(containerList); <add> } catch (Throwable t) { <add> blockingQueue.offer(t); <add> } <add> }); <add> <add> //超时 <add> Object result = BlockingQueueUtil.getResult(blockingQueue, timeOut, TimeUnit.SECONDS); <add> blockingQueue.clear(); <add> <add> if (result instanceof List) { <add> return (List<Container>) result; <add> }else if (result == null) { <add> log.error("docker 容器 List 获取{}秒超",timeOut); <add> return new ArrayList<>(); <add> }else if (result instanceof Throwable) { <add> log.error("docker 容器 List 获取异常",result); <add> return new ArrayList<>(); <add> }else { <add> log.error("未知结果类型:{}",result); <add> return new ArrayList<>(); <add> } <add> } catch (Exception e) { <add> log.error("",e); <add> return new ArrayList<>(); <add> } <add> <add> } <add> <add> /** <ide> * 获取主机上所有运行容器的proc信息 <ide> * @return <ide> */ <ide> }else { <ide> procInfoToHosts = new ArrayList<>(); <ide> } <del> if (docker != null){ <del> synchronized (LockForGetAllHostContainerProcInfos){ <del> try { <del> List<Container> containers = docker.listContainers(DockerClient.ListContainersParam.withStatusRunning()); <del> for (Container container : containers) { <del> ContainerInfo info = getContainerInfo(container.id()); <del> if (info != null) { <del> String pid = String.valueOf(info.state().pid()); <del> procInfoToHosts.add(new ContainerProcInfoToHost(container.id(),PROC_HOST_VOLUME + "/" + pid + "/root",pid)); <del> } <add> synchronized (LockForGetAllHostContainerProcInfos){ <add> try { <add> List<Container> containers = getContainers(DockerClient.ListContainersParam.withStatusRunning()); <add> for (Container container : containers) { <add> ContainerInfo info = getContainerInfo(container.id()); <add> if (info != null) { <add> String pid = String.valueOf(info.state().pid()); <add> procInfoToHosts.add(new ContainerProcInfoToHost(container.id(),PROC_HOST_VOLUME + "/" + pid + "/root",pid)); <ide> } <del> } catch (Exception e) { <del> log.error("",e); <del> } <add> } <add> } catch (Exception e) { <add> log.error("",e); <ide> } <ide> } <ide> if (!procInfoToHosts.isEmpty()) { <ide> } <ide> synchronized (LockForGetAllHostContainerId){ <ide> try { <del> List<Container> containerList = docker.listContainers(DockerClient.ListContainersParam.allContainers()); <add> List<Container> containerList = getContainers(DockerClient.ListContainersParam.allContainers()); <ide> for (Container container : containerList) { <ide> ids.add(container.id()); <ide> }
Java
mit
edd97b4374ad9969bc4a0526a6692c93a2893839
0
openfact/openfact-temp,openfact/openfact-temp,openfact/openfact,openfact/openfact-pe,openfact/openfact,openfact/openfact-temp,openfact/openfact-pe,openfact/openfact,openfact/openfact-temp,openfact/openfact-pe
package org.openfact.models.jpa.entities.ubl; import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import org.openfact.models.ubl.type.CodeType; import org.openfact.models.ubl.type.IdentifierType; import org.openfact.models.ubl.type.QuantityType; import org.openfact.models.ubl.type.TextType; /** * A class to define a line in an Invoice. * * @author Erik * @version 2.0 * @created 07-Set.-2016 9:15:37 a. m. */ @Entity @Table(name = "INVOICE_LINE") public class InvoiceLineEntity { @Id @Column(name = "ID_OP", length = 36) @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") @Access(AccessType.PROPERTY) private String id; /** * The buyer's accounting cost centre for this invoice line, expressed as * text. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "ACCOUNTINGCOST_VALUE")), @AttributeOverride(name = "languageID", column = @Column(name = "ACCOUNTINGCOST_LANGUAGEID")) }) private TextType accountingCost; /** * The buyer's accounting cost centre for this invoice line, expressed as a * code. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "ACCOUNTINGCOSTCODE_VALUE")), @AttributeOverride(name = "listID", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTID")), @AttributeOverride(name = "listAgencyID", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTAGENCYID")), @AttributeOverride(name = "listAgencyName", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTAGENCYNAME")), @AttributeOverride(name = "listName", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTNAME")), @AttributeOverride(name = "listVersionID", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTVERSIONID")), @AttributeOverride(name = "name", column = @Column(name = "ACCOUNTINGCOSTCODE_NAME")), @AttributeOverride(name = "languageID", column = @Column(name = "ACCOUNTINGCOSTCODE_LANGUAGEID")), @AttributeOverride(name = "listURI", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTURI")), @AttributeOverride(name = "listSchemeURI", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTSCHEMEURI")) }) private CodeType accountingCostCode; /** * An indicator that this invoice line is free of charge (true) or not * (false). The default is false. */ @Type(type = "org.hibernate.type.NumericBooleanType") @Column(name = "FREE_OF_CHARGE_INDICATOR") private boolean freeOfChargeIndicator; /** * An identifier for this invoice line. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "ID_VALUE")), @AttributeOverride(name = "schemeID", column = @Column(name = "ID_SCHEMEID")), @AttributeOverride(name = "schemeName", column = @Column(name = "ID_SCHEMENAME")), @AttributeOverride(name = "schemeAgencyID", column = @Column(name = "ID_SCHEMEAGENCYID")), @AttributeOverride(name = "schemeAgencyName", column = @Column(name = "ID_SCHEMEAGENCYNAME")), @AttributeOverride(name = "schemeVersionID", column = @Column(name = "ID_SCHEMEVERSIONID")), @AttributeOverride(name = "schemeDataURI", column = @Column(name = "ID_SCHEMEDATAURI")), @AttributeOverride(name = "schemeURI", column = @Column(name = "ID_SCHEMEURI")) }) private IdentifierType ID; /** * The quantity (of items) on this invoice line. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "INVOICEQUANTITY_VALUE")), @AttributeOverride(name = "unitCode", column = @Column(name = "INVOICEQUANTITY_UNITCODE")) }) private QuantityType invoicedQuantity; /** * The total amount for this invoice line, including allowance charges but * net of taxes. */ @Column(name = "LINE_EXTENSION_AMOUNT") private BigDecimal lineExtensionAmount; /** * Free-form text conveying information that is not contained explicitly in * other structures. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "NOTE_VALUE")), @AttributeOverride(name = "languageID", column = @Column(name = "NOTE_LANGUAGEID")) }) private TextType note; /** * A code signifying the business purpose for this payment. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "PAYMENTPURPOSECODE_VALUE")), @AttributeOverride(name = "listID", column = @Column(name = "PAYMENTPURPOSECODE_LISTID")), @AttributeOverride(name = "listAgencyID", column = @Column(name = "PAYMENTPURPOSECODE_LISTAGENCYID")), @AttributeOverride(name = "listAgencyName", column = @Column(name = "PAYMENTPURPOSECODE_LISTAGENCYNAME")), @AttributeOverride(name = "listName", column = @Column(name = "PAYMENTPURPOSECODE_LISTNAME")), @AttributeOverride(name = "listVersionID", column = @Column(name = "PAYMENTPURPOSECODE_LISTVERSIONID")), @AttributeOverride(name = "name", column = @Column(name = "PAYMENTPURPOSECODE_NAME")), @AttributeOverride(name = "languageID", column = @Column(name = "PAYMENTPURPOSECODE_LANGUAGEID")), @AttributeOverride(name = "listURI", column = @Column(name = "PAYMENTPURPOSECODE_LISTURI")), @AttributeOverride(name = "listSchemeURI", column = @Column(name = "PAYMENTPURPOSECODE_LISTSCHEMEURI")) }) private CodeType paymentPurposeCode; /** * The date of this invoice line, used to indicate the point at which tax * becomes applicable. */ @Type(type = "org.hibernate.type.LocalDateType") @Column(name = "TAX_POINT_DATE") private LocalDate taxPointDate; /** * A universally unique identifier for this invoice line. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "UUID_VALUE")), @AttributeOverride(name = "schemeID", column = @Column(name = "UUID_SCHEMEID")), @AttributeOverride(name = "schemeName", column = @Column(name = "UUID_SCHEMENAME")), @AttributeOverride(name = "schemeAgencyID", column = @Column(name = "UUID_SCHEMEAGENCYID")), @AttributeOverride(name = "schemeAgencyName", column = @Column(name = "UUID_SCHEMEAGENCYNAME")), @AttributeOverride(name = "schemeVersionID", column = @Column(name = "UUID_SCHEMEVERSIONID")), @AttributeOverride(name = "schemeDataURI", column = @Column(name = "UUID_SCHEMEDATAURI")), @AttributeOverride(name = "schemeURI", column = @Column(name = "UUID_SCHEMEURI")) }) private IdentifierType UUID; @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<AllowanceChargeEntity> allowanceCharges = new ArrayList<>(); @Transient private List<BillingReferenceEntity> billingReferences = new ArrayList<>(); @Transient private List<DeliveryEntity> deliveries = new ArrayList<>(); @Transient private List<DeliveryTermsEntity> deliveriesTerms = new ArrayList<>(); @Transient private List<DocumentReferenceEntity> documentReferences = new ArrayList<>(); @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<ItemEntity> items = new ArrayList<>(); @Transient private LineReferenceEntity despatchLineReference; @Transient private LineReferenceEntity receiptLineReference; @Transient private List<OrderLineReferenceEntity> orderLineReferences = new ArrayList<>(); @Transient private PartyEntity originatorParty; @Transient private List<PaymentTermsEntity> paymentTermses = new ArrayList<>(); @Transient private PeriodEntity invoicePeriod; @Transient private InvoiceLineEntity subInvoiceLine; @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<InvoiceLinePriceMappingEntity> prices = new ArrayList<>(); @Transient private PriceExtensionEntity itemPriceExtension; @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<PricingReferenceEntity> pricingReferences = new ArrayList<>(); @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<InvoiceLineTaxTotalMappingEntity> withholdingTaxTotal = new ArrayList<>(); @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<InvoiceLineTaxTotalMappingEntity> taxTotals = new ArrayList<>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public TextType getAccountingCost() { return accountingCost; } public void setAccountingCost(TextType accountingCost) { this.accountingCost = accountingCost; } public CodeType getAccountingCostCode() { return accountingCostCode; } public void setAccountingCostCode(CodeType accountingCostCode) { this.accountingCostCode = accountingCostCode; } public boolean isFreeOfChargeIndicator() { return freeOfChargeIndicator; } public void setFreeOfChargeIndicator(boolean freeOfChargeIndicator) { this.freeOfChargeIndicator = freeOfChargeIndicator; } public IdentifierType getID() { return ID; } public void setID(IdentifierType iD) { ID = iD; } public QuantityType getInvoicedQuantity() { return invoicedQuantity; } public void setInvoicedQuantity(QuantityType invoicedQuantity) { this.invoicedQuantity = invoicedQuantity; } public BigDecimal getLineExtensionAmount() { return lineExtensionAmount; } public void setLineExtensionAmount(BigDecimal lineExtensionAmount) { this.lineExtensionAmount = lineExtensionAmount; } public TextType getNote() { return note; } public void setNote(TextType note) { this.note = note; } public CodeType getPaymentPurposeCode() { return paymentPurposeCode; } public void setPaymentPurposeCode(CodeType paymentPurposeCode) { this.paymentPurposeCode = paymentPurposeCode; } public LocalDate getTaxPointDate() { return taxPointDate; } public void setTaxPointDate(LocalDate taxPointDate) { this.taxPointDate = taxPointDate; } public IdentifierType getUUID() { return UUID; } public void setUUID(IdentifierType uUID) { UUID = uUID; } public List<AllowanceChargeEntity> getAllowanceCharges() { return allowanceCharges; } public void setAllowanceCharges(List<AllowanceChargeEntity> allowanceCharges) { this.allowanceCharges = allowanceCharges; } public List<BillingReferenceEntity> getBillingReferences() { return billingReferences; } public void setBillingReferences(List<BillingReferenceEntity> billingReferences) { this.billingReferences = billingReferences; } public List<DeliveryEntity> getDeliveries() { return deliveries; } public void setDeliveries(List<DeliveryEntity> deliveries) { this.deliveries = deliveries; } public List<DeliveryTermsEntity> getDeliveriesTerms() { return deliveriesTerms; } public void setDeliveriesTerms(List<DeliveryTermsEntity> deliveriesTerms) { this.deliveriesTerms = deliveriesTerms; } public List<DocumentReferenceEntity> getDocumentReferences() { return documentReferences; } public void setDocumentReferences(List<DocumentReferenceEntity> documentReferences) { this.documentReferences = documentReferences; } public List<ItemEntity> getItems() { return items; } public void setItems(List<ItemEntity> items) { this.items = items; } public LineReferenceEntity getDespatchLineReference() { return despatchLineReference; } public void setDespatchLineReference(LineReferenceEntity despatchLineReference) { this.despatchLineReference = despatchLineReference; } public LineReferenceEntity getReceiptLineReference() { return receiptLineReference; } public void setReceiptLineReference(LineReferenceEntity receiptLineReference) { this.receiptLineReference = receiptLineReference; } public List<OrderLineReferenceEntity> getOrderLineReferences() { return orderLineReferences; } public void setOrderLineReferences(List<OrderLineReferenceEntity> orderLineReferences) { this.orderLineReferences = orderLineReferences; } public PartyEntity getOriginatorParty() { return originatorParty; } public void setOriginatorParty(PartyEntity originatorParty) { this.originatorParty = originatorParty; } public List<PaymentTermsEntity> getPaymentTermses() { return paymentTermses; } public void setPaymentTermses(List<PaymentTermsEntity> paymentTermses) { this.paymentTermses = paymentTermses; } public PeriodEntity getInvoicePeriod() { return invoicePeriod; } public void setInvoicePeriod(PeriodEntity invoicePeriod) { this.invoicePeriod = invoicePeriod; } public InvoiceLineEntity getSubInvoiceLine() { return subInvoiceLine; } public void setSubInvoiceLine(InvoiceLineEntity subInvoiceLine) { this.subInvoiceLine = subInvoiceLine; } public List<InvoiceLinePriceMappingEntity> getPrices() { return prices; } public void setPrices(List<InvoiceLinePriceMappingEntity> prices) { this.prices = prices; } public PriceExtensionEntity getItemPriceExtension() { return itemPriceExtension; } public void setItemPriceExtension(PriceExtensionEntity itemPriceExtension) { this.itemPriceExtension = itemPriceExtension; } public List<PricingReferenceEntity> getPricingReferences() { return pricingReferences; } public void setPricingReferences(List<PricingReferenceEntity> pricingReferences) { this.pricingReferences = pricingReferences; } public List<InvoiceLineTaxTotalMappingEntity> getWithholdingTaxTotal() { return withholdingTaxTotal; } public void setWithholdingTaxTotal(List<InvoiceLineTaxTotalMappingEntity> withholdingTaxTotal) { this.withholdingTaxTotal = withholdingTaxTotal; } public List<InvoiceLineTaxTotalMappingEntity> getTaxTotals() { return taxTotals; } public void setTaxTotals(List<InvoiceLineTaxTotalMappingEntity> taxTotals) { this.taxTotals = taxTotals; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; InvoiceLineEntity other = (InvoiceLineEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
model/jpa/src/main/java/org/openfact/models/jpa/entities/ubl/InvoiceLineEntity.java
package org.openfact.models.jpa.entities.ubl; import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import org.openfact.models.ubl.type.CodeType; import org.openfact.models.ubl.type.IdentifierType; import org.openfact.models.ubl.type.QuantityType; import org.openfact.models.ubl.type.TextType; /** * A class to define a line in an Invoice. * * @author Erik * @version 2.0 * @created 07-Set.-2016 9:15:37 a. m. */ @Entity @Table(name = "INVOICE_LINE") public class InvoiceLineEntity { @Id @Column(name = "ID_OP", length = 36) @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") @Access(AccessType.PROPERTY) private String id; /** * The buyer's accounting cost centre for this invoice line, expressed as * text. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "ACCOUNTINGCOST_VALUE")), @AttributeOverride(name = "languageID", column = @Column(name = "ACCOUNTINGCOST_LANGUAGEID")) }) private TextType accountingCost; /** * The buyer's accounting cost centre for this invoice line, expressed as a * code. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "ACCOUNTINGCOSTCODE_VALUE")), @AttributeOverride(name = "listID", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTID")), @AttributeOverride(name = "listAgencyID", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTAGENCYID")), @AttributeOverride(name = "listAgencyName", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTAGENCYNAME")), @AttributeOverride(name = "listName", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTNAME")), @AttributeOverride(name = "listVersionID", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTVERSIONID")), @AttributeOverride(name = "name", column = @Column(name = "ACCOUNTINGCOSTCODE_NAME")), @AttributeOverride(name = "languageID", column = @Column(name = "ACCOUNTINGCOSTCODE_LANGUAGEID")), @AttributeOverride(name = "listURI", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTURI")), @AttributeOverride(name = "listSchemeURI", column = @Column(name = "ACCOUNTINGCOSTCODE_LISTSCHEMEURI")) }) private CodeType accountingCostCode; /** * An indicator that this invoice line is free of charge (true) or not * (false). The default is false. */ @Type(type = "org.hibernate.type.NumericBooleanType") @Column(name = "FREE_OF_CHARGE_INDICATOR") private boolean freeOfChargeIndicator; /** * An identifier for this invoice line. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "ID_VALUE")), @AttributeOverride(name = "schemeID", column = @Column(name = "ID_SCHEMEID")), @AttributeOverride(name = "schemeName", column = @Column(name = "ID_SCHEMENAME")), @AttributeOverride(name = "schemeAgencyID", column = @Column(name = "ID_SCHEMEAGENCYID")), @AttributeOverride(name = "schemeAgencyName", column = @Column(name = "ID_SCHEMEAGENCYNAME")), @AttributeOverride(name = "schemeVersionID", column = @Column(name = "ID_SCHEMEVERSIONID")), @AttributeOverride(name = "schemeDataURI", column = @Column(name = "ID_SCHEMEDATAURI")), @AttributeOverride(name = "schemeURI", column = @Column(name = "ID_SCHEMEURI")) }) private IdentifierType ID; /** * The quantity (of items) on this invoice line. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "INVOICEQUANTITY_VALUE")), @AttributeOverride(name = "unitCode", column = @Column(name = "INVOICEQUANTITY_UNITCODE")) }) private QuantityType invoicedQuantity; /** * The total amount for this invoice line, including allowance charges but * net of taxes. */ @Column(name = "LINE_EXTENSION_AMOUNT") private BigDecimal lineExtensionAmount; /** * Free-form text conveying information that is not contained explicitly in * other structures. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "NOTE_VALUE")), @AttributeOverride(name = "languageID", column = @Column(name = "NOTE_LANGUAGEID")) }) private TextType note; /** * A code signifying the business purpose for this payment. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "PAYMENTPURPOSECODE_VALUE")), @AttributeOverride(name = "listID", column = @Column(name = "PAYMENTPURPOSECODE_LISTID")), @AttributeOverride(name = "listAgencyID", column = @Column(name = "PAYMENTPURPOSECODE_LISTAGENCYID")), @AttributeOverride(name = "listAgencyName", column = @Column(name = "PAYMENTPURPOSECODE_LISTAGENCYNAME")), @AttributeOverride(name = "listName", column = @Column(name = "PAYMENTPURPOSECODE_LISTNAME")), @AttributeOverride(name = "listVersionID", column = @Column(name = "PAYMENTPURPOSECODE_LISTVERSIONID")), @AttributeOverride(name = "name", column = @Column(name = "PAYMENTPURPOSECODE_NAME")), @AttributeOverride(name = "languageID", column = @Column(name = "PAYMENTPURPOSECODE_LANGUAGEID")), @AttributeOverride(name = "listURI", column = @Column(name = "PAYMENTPURPOSECODE_LISTURI")), @AttributeOverride(name = "listSchemeURI", column = @Column(name = "PAYMENTPURPOSECODE_LISTSCHEMEURI")) }) private CodeType paymentPurposeCode; /** * The date of this invoice line, used to indicate the point at which tax * becomes applicable. */ @Type(type = "org.hibernate.type.LocalDateType") @Column(name = "TAX_POINT_DATE") private LocalDate taxPointDate; /** * A universally unique identifier for this invoice line. */ @Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "UUID_VALUE")), @AttributeOverride(name = "schemeID", column = @Column(name = "UUID_SCHEMEID")), @AttributeOverride(name = "schemeName", column = @Column(name = "UUID_SCHEMENAME")), @AttributeOverride(name = "schemeAgencyID", column = @Column(name = "UUID_SCHEMEAGENCYID")), @AttributeOverride(name = "schemeAgencyName", column = @Column(name = "UUID_SCHEMEAGENCYNAME")), @AttributeOverride(name = "schemeVersionID", column = @Column(name = "UUID_SCHEMEVERSIONID")), @AttributeOverride(name = "schemeDataURI", column = @Column(name = "UUID_SCHEMEDATAURI")), @AttributeOverride(name = "schemeURI", column = @Column(name = "UUID_SCHEMEURI")) }) private IdentifierType UUID; @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<AllowanceChargeEntity> allowanceCharges = new ArrayList<>(); @Transient private List<BillingReferenceEntity> billingReferences = new ArrayList<>(); @Transient private List<DeliveryEntity> deliveries = new ArrayList<>(); @Transient private List<DeliveryTermsEntity> deliveriesTerms = new ArrayList<>(); @Transient private List<DocumentReferenceEntity> documentReferences = new ArrayList<>(); @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<ItemEntity> items = new ArrayList<>(); @Transient private LineReferenceEntity despatchLineReference; @Transient private LineReferenceEntity receiptLineReference; @Transient private List<OrderLineReferenceEntity> orderLineReferences = new ArrayList<>(); @Transient private PartyEntity originatorParty; @Transient private List<PaymentTermsEntity> paymentTermses = new ArrayList<>(); @Transient private PeriodEntity invoicePeriod; @Transient private InvoiceLineEntity subInvoiceLine; @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<InvoiceLinePriceMappingEntity> prices = new ArrayList<>(); @Transient private PriceExtensionEntity itemPriceExtension; @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<PricingReferenceEntity> pricingReferences = new ArrayList<>(); @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<InvoiceLineTaxTotalMappingEntity> withholdingTaxTotal = new ArrayList<>(); @OneToMany(mappedBy = "invoiceLine", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) private List<InvoiceLineTaxTotalMappingEntity> taxTotals = new ArrayList<>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public TextType getAccountingCost() { return accountingCost; } public void setAccountingCost(TextType accountingCost) { this.accountingCost = accountingCost; } public CodeType getAccountingCostCode() { return accountingCostCode; } public void setAccountingCostCode(CodeType accountingCostCode) { this.accountingCostCode = accountingCostCode; } public boolean isFreeOfChargeIndicator() { return freeOfChargeIndicator; } public void setFreeOfChargeIndicator(boolean freeOfChargeIndicator) { this.freeOfChargeIndicator = freeOfChargeIndicator; } public IdentifierType getID() { return ID; } public void setID(IdentifierType iD) { ID = iD; } public QuantityType getInvoicedQuantity() { return invoicedQuantity; } public void setInvoicedQuantity(QuantityType invoicedQuantity) { this.invoicedQuantity = invoicedQuantity; } public BigDecimal getLineExtensionAmount() { return lineExtensionAmount; } public void setLineExtensionAmount(BigDecimal lineExtensionAmount) { this.lineExtensionAmount = lineExtensionAmount; } public TextType getNote() { return note; } public void setNote(TextType note) { this.note = note; } public CodeType getPaymentPurposeCode() { return paymentPurposeCode; } public void setPaymentPurposeCode(CodeType paymentPurposeCode) { this.paymentPurposeCode = paymentPurposeCode; } public LocalDate getTaxPointDate() { return taxPointDate; } public void setTaxPointDate(LocalDate taxPointDate) { this.taxPointDate = taxPointDate; } public IdentifierType getUUID() { return UUID; } public void setUUID(IdentifierType uUID) { UUID = uUID; } public List<AllowanceChargeEntity> getAllowanceCharges() { return allowanceCharges; } public void setAllowanceCharges(List<AllowanceChargeEntity> allowanceCharges) { this.allowanceCharges = allowanceCharges; } public List<BillingReferenceEntity> getBillingReferences() { return billingReferences; } public void setBillingReferences(List<BillingReferenceEntity> billingReferences) { this.billingReferences = billingReferences; } public List<DeliveryEntity> getDeliveries() { return deliveries; } public void setDeliveries(List<DeliveryEntity> deliveries) { this.deliveries = deliveries; } public List<DeliveryTermsEntity> getDeliveriesTerms() { return deliveriesTerms; } public void setDeliveriesTerms(List<DeliveryTermsEntity> deliveriesTerms) { this.deliveriesTerms = deliveriesTerms; } public List<DocumentReferenceEntity> getDocumentReferences() { return documentReferences; } public void setDocumentReferences(List<DocumentReferenceEntity> documentReferences) { this.documentReferences = documentReferences; } public List<ItemEntity> getItems() { return items; } public void setItems(List<ItemEntity> items) { this.items = items; } public LineReferenceEntity getDespatchLineReference() { return despatchLineReference; } public void setDespatchLineReference(LineReferenceEntity despatchLineReference) { this.despatchLineReference = despatchLineReference; } public LineReferenceEntity getReceiptLineReference() { return receiptLineReference; } public void setReceiptLineReference(LineReferenceEntity receiptLineReference) { this.receiptLineReference = receiptLineReference; } public List<OrderLineReferenceEntity> getOrderLineReferences() { return orderLineReferences; } public void setOrderLineReferences(List<OrderLineReferenceEntity> orderLineReferences) { this.orderLineReferences = orderLineReferences; } public PartyEntity getOriginatorParty() { return originatorParty; } public void setOriginatorParty(PartyEntity originatorParty) { this.originatorParty = originatorParty; } public List<PaymentTermsEntity> getPaymentTermses() { return paymentTermses; } public void setPaymentTermses(List<PaymentTermsEntity> paymentTermses) { this.paymentTermses = paymentTermses; } public PeriodEntity getInvoicePeriod() { return invoicePeriod; } public void setInvoicePeriod(PeriodEntity invoicePeriod) { this.invoicePeriod = invoicePeriod; } public InvoiceLineEntity getSubInvoiceLine() { return subInvoiceLine; } public void setSubInvoiceLine(InvoiceLineEntity subInvoiceLine) { this.subInvoiceLine = subInvoiceLine; } public List<InvoiceLinePriceMappingEntity> getPrices() { return prices; } public void setPrices(List<InvoiceLinePriceMappingEntity> prices) { this.prices = prices; } public PriceExtensionEntity getItemPriceExtension() { return itemPriceExtension; } public void setItemPriceExtension(PriceExtensionEntity itemPriceExtension) { this.itemPriceExtension = itemPriceExtension; } public List<PricingReferenceEntity> getPricingReferences() { return pricingReferences; } public void setPricingReferences(List<PricingReferenceEntity> pricingReferences) { this.pricingReferences = pricingReferences; } public List<TaxTotalEntity> getWithholdingTaxTotal() { return withholdingTaxTotal; } public void setWithholdingTaxTotal(List<TaxTotalEntity> withholdingTaxTotal) { this.withholdingTaxTotal = withholdingTaxTotal; } public List<TaxTotalEntity> getTaxTotals() { return taxTotals; } public void setTaxTotals(List<TaxTotalEntity> taxTotals) { this.taxTotals = taxTotals; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; InvoiceLineEntity other = (InvoiceLineEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
update invoice line
model/jpa/src/main/java/org/openfact/models/jpa/entities/ubl/InvoiceLineEntity.java
update invoice line
<ide><path>odel/jpa/src/main/java/org/openfact/models/jpa/entities/ubl/InvoiceLineEntity.java <ide> this.pricingReferences = pricingReferences; <ide> } <ide> <del> public List<TaxTotalEntity> getWithholdingTaxTotal() { <add> <add> <add> public List<InvoiceLineTaxTotalMappingEntity> getWithholdingTaxTotal() { <ide> return withholdingTaxTotal; <ide> } <ide> <del> public void setWithholdingTaxTotal(List<TaxTotalEntity> withholdingTaxTotal) { <add> public void setWithholdingTaxTotal(List<InvoiceLineTaxTotalMappingEntity> withholdingTaxTotal) { <ide> this.withholdingTaxTotal = withholdingTaxTotal; <ide> } <ide> <del> public List<TaxTotalEntity> getTaxTotals() { <add> public List<InvoiceLineTaxTotalMappingEntity> getTaxTotals() { <ide> return taxTotals; <ide> } <ide> <del> public void setTaxTotals(List<TaxTotalEntity> taxTotals) { <add> public void setTaxTotals(List<InvoiceLineTaxTotalMappingEntity> taxTotals) { <ide> this.taxTotals = taxTotals; <ide> } <ide>
Java
mit
e3779af5b0897cc7c730cd5a61c52aea276339df
0
openregister/openregister-java,openregister/openregister-java,openregister/openregister-java,openregister/openregister-java,openregister/openregister-java
package uk.gov.register.views.representations.turtle; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.junit.Test; import uk.gov.register.core.*; import uk.gov.register.util.HashValue; import uk.gov.register.views.ItemView; import java.io.ByteArrayOutputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Map; import java.util.Set; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; public class TurtleRepresentationWriterTest { private final RegisterResolver registerResolver = register -> URI.create("http://" + register + ".test.register.gov.uk"); private final Set<String> fields = ImmutableSet.of("address", "location", "link-values", "string-values"); @Test public void rendersFieldPrefixFromConfiguration() throws Exception { Map<String, FieldValue> map = ImmutableMap.of( "key1", new StringValue("value1"), "key2", new StringValue("value2"), "key3", new StringValue("val\"ue3"), "key4", new StringValue("value4") ); ItemView itemView = new ItemView(new HashValue(HashingAlgorithm.SHA256, "hash"), map, fields); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ItemTurtleWriter writer = new ItemTurtleWriter(() -> "address", registerResolver); writer.writeTo(itemView, itemView.getClass(), null, null, null, null, outputStream); byte[] bytes = outputStream.toByteArray(); String generatedTtl = new String(bytes, StandardCharsets.UTF_8); assertThat(generatedTtl, containsString("@prefix field: <http://field.test.register.gov.uk/record/> .")); } @Test public void rendersEntryIdentifierFromRequestContext() throws Exception { Entry entry = new Entry(52, new HashValue(HashingAlgorithm.SHA256, "hash"), Instant.now(), "key"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); EntryTurtleWriter writer = new EntryTurtleWriter(() -> "address", registerResolver); writer.writeTo(entry, entry.getClass(), null, null, null, null, outputStream); byte[] bytes = outputStream.toByteArray(); String generatedTtl = new String(bytes, StandardCharsets.UTF_8); assertThat(generatedTtl, containsString("<http://address.test.register.gov.uk/entry/52>")); } @Test public void rendersLinksCorrectlyAsUrls() throws Exception { Map<String, FieldValue> map = ImmutableMap.of( "address", new LinkValue("address", "1111111"), "location", new LinkValue("address", "location-value"), "name", new StringValue("foo") ); ItemView itemView = new ItemView(new HashValue(HashingAlgorithm.SHA256, "itemhash"), map, fields); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ItemTurtleWriter writer = new ItemTurtleWriter(() -> "address", registerResolver); writer.writeTo(itemView, itemView.getClass(), null, null, null, null, outputStream); byte[] bytes = outputStream.toByteArray(); String generatedTtl = new String(bytes, StandardCharsets.UTF_8); assertThat(generatedTtl, containsString("field:address <http://address.test.register.gov.uk/record/1111111>")); assertThat(generatedTtl, containsString("field:location <http://address.test.register.gov.uk/record/location-value>")); assertThat(generatedTtl, containsString("field:name \"foo\"")); assertThat(generatedTtl, containsString("<http://address.test.register.gov.uk/item/sha-256:itemhash>")); } @Test public void rendersLists() throws Exception { Map<String, FieldValue> map = ImmutableMap.of( "link-values", new ListValue(asList(new LinkValue("address", "1111111"), new LinkValue("address", "2222222"))), "string-values", new ListValue(asList(new StringValue("value1"), new StringValue("value2"))), "name", new StringValue("foo") ); ItemView itemView = new ItemView(new HashValue(HashingAlgorithm.SHA256, "hash"), map, fields); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ItemTurtleWriter writer = new ItemTurtleWriter(() -> "address", registerResolver); writer.writeTo(itemView, itemView.getClass(), null, null, null, null, outputStream); byte[] bytes = outputStream.toByteArray(); String generatedTtl = new String(bytes, StandardCharsets.UTF_8); assertThat(generatedTtl, containsString("field:link-values <http://address.test.register.gov.uk/record/1111111> , <http://address.test.register.gov.uk/record/2222222>")); assertThat(generatedTtl, containsString("field:string-values \"value2\" , \"value1\"")); assertThat(generatedTtl, containsString("field:name \"foo\"")); } }
src/test/java/uk/gov/register/views/representations/turtle/TurtleRepresentationWriterTest.java
package uk.gov.register.views.representations.turtle; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.junit.Before; import org.junit.Test; import uk.gov.register.core.*; import uk.gov.register.resources.RequestContext; import uk.gov.register.util.HashValue; import uk.gov.register.views.ItemView; import java.io.ByteArrayOutputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Map; import java.util.Set; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; public class TurtleRepresentationWriterTest { private final RegisterResolver registerResolver = register -> URI.create("http://" + register + ".test.register.gov.uk"); private RequestContext requestContext; private final Set<String> fields = ImmutableSet.of("address", "location", "link-values", "string-values"); @Before public void setUp() throws Exception { requestContext = new RequestContext() { @Override public String getScheme() { return "http"; } }; } @Test public void rendersFieldPrefixFromConfiguration() throws Exception { Map<String, FieldValue> map = ImmutableMap.of( "key1", new StringValue("value1"), "key2", new StringValue("value2"), "key3", new StringValue("val\"ue3"), "key4", new StringValue("value4") ); ItemView itemView = new ItemView(new HashValue(HashingAlgorithm.SHA256, "hash"), map, fields); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ItemTurtleWriter writer = new ItemTurtleWriter(() -> "address", registerResolver); writer.writeTo(itemView, itemView.getClass(), null, null, null, null, outputStream); byte[] bytes = outputStream.toByteArray(); String generatedTtl = new String(bytes, StandardCharsets.UTF_8); assertThat(generatedTtl, containsString("@prefix field: <http://field.test.register.gov.uk/record/> .")); } @Test public void rendersEntryIdentifierFromRequestContext() throws Exception { Entry entry = new Entry(52, new HashValue(HashingAlgorithm.SHA256, "hash"), Instant.now(), "key"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); EntryTurtleWriter writer = new EntryTurtleWriter(() -> "address", registerResolver); writer.writeTo(entry, entry.getClass(), null, null, null, null, outputStream); byte[] bytes = outputStream.toByteArray(); String generatedTtl = new String(bytes, StandardCharsets.UTF_8); assertThat(generatedTtl, containsString("<http://address.test.register.gov.uk/entry/52>")); } @Test public void rendersLinksCorrectlyAsUrls() throws Exception { Map<String, FieldValue> map = ImmutableMap.of( "address", new LinkValue("address", "1111111"), "location", new LinkValue("address", "location-value"), "name", new StringValue("foo") ); ItemView itemView = new ItemView(new HashValue(HashingAlgorithm.SHA256, "itemhash"), map, fields); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ItemTurtleWriter writer = new ItemTurtleWriter(() -> "address", registerResolver); writer.writeTo(itemView, itemView.getClass(), null, null, null, null, outputStream); byte[] bytes = outputStream.toByteArray(); String generatedTtl = new String(bytes, StandardCharsets.UTF_8); assertThat(generatedTtl, containsString("field:address <http://address.test.register.gov.uk/record/1111111>")); assertThat(generatedTtl, containsString("field:location <http://address.test.register.gov.uk/record/location-value>")); assertThat(generatedTtl, containsString("field:name \"foo\"")); assertThat(generatedTtl, containsString("<http://address.test.register.gov.uk/item/sha-256:itemhash>")); } @Test public void rendersLists() throws Exception { Map<String, FieldValue> map = ImmutableMap.of( "link-values", new ListValue(asList(new LinkValue("address", "1111111"), new LinkValue("address", "2222222"))), "string-values", new ListValue(asList(new StringValue("value1"), new StringValue("value2"))), "name", new StringValue("foo") ); ItemView itemView = new ItemView(new HashValue(HashingAlgorithm.SHA256, "hash"), map, fields); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ItemTurtleWriter writer = new ItemTurtleWriter(() -> "address", registerResolver); writer.writeTo(itemView, itemView.getClass(), null, null, null, null, outputStream); byte[] bytes = outputStream.toByteArray(); String generatedTtl = new String(bytes, StandardCharsets.UTF_8); assertThat(generatedTtl, containsString("field:link-values <http://address.test.register.gov.uk/record/1111111> , <http://address.test.register.gov.uk/record/2222222>")); assertThat(generatedTtl, containsString("field:string-values \"value2\" , \"value1\"")); assertThat(generatedTtl, containsString("field:name \"foo\"")); } }
remove dead code (paired with @karlbaker02)
src/test/java/uk/gov/register/views/representations/turtle/TurtleRepresentationWriterTest.java
remove dead code
<ide><path>rc/test/java/uk/gov/register/views/representations/turtle/TurtleRepresentationWriterTest.java <ide> <ide> import com.google.common.collect.ImmutableMap; <ide> import com.google.common.collect.ImmutableSet; <del>import org.junit.Before; <ide> import org.junit.Test; <ide> import uk.gov.register.core.*; <del>import uk.gov.register.resources.RequestContext; <ide> import uk.gov.register.util.HashValue; <ide> import uk.gov.register.views.ItemView; <ide> <ide> <ide> public class TurtleRepresentationWriterTest { <ide> private final RegisterResolver registerResolver = register -> URI.create("http://" + register + ".test.register.gov.uk"); <del> private RequestContext requestContext; <ide> <ide> private final Set<String> fields = ImmutableSet.of("address", "location", "link-values", "string-values"); <del> <del> @Before <del> public void setUp() throws Exception { <del> requestContext = new RequestContext() { <del> @Override <del> public String getScheme() { return "http"; } <del> }; <del> } <ide> <ide> @Test <ide> public void rendersFieldPrefixFromConfiguration() throws Exception {
Java
apache-2.0
78c380ec18f64e21600395b0ecfb13c02b6ffaad
0
cscorley/solr-only-mirror,cscorley/solr-only-mirror,cscorley/solr-only-mirror
package org.apache.solr.cloud; /** * 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. */ import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.CloudSolrServer; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.cloud.CloudState; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.ZkCoreNodeProps; import org.apache.solr.common.cloud.ZkNodeProps; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.zookeeper.KeeperException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; /** * * TODO: we should still test this works as a custom update chain as well as * what we test now - the default update chain * */ public class FullSolrCloudTest extends AbstractDistributedZkTestCase { private static final String SHARD2 = "shard2"; protected static final String DEFAULT_COLLECTION = "collection1"; String t1 = "a_t"; String i1 = "a_si"; String nint = "n_i"; String tint = "n_ti"; String nfloat = "n_f"; String tfloat = "n_tf"; String ndouble = "n_d"; String tdouble = "n_td"; String nlong = "n_l"; String tlong = "other_tl1"; String ndate = "n_dt"; String tdate = "n_tdt"; String oddField = "oddField_s"; String missingField = "ignore_exception__missing_but_valid_field_t"; String invalidField = "ignore_exception__invalid_field_not_in_schema"; protected int sliceCount; protected volatile CloudSolrServer cloudClient; protected Map<JettySolrRunner,ZkNodeProps> jettyToInfo = new HashMap<JettySolrRunner,ZkNodeProps>(); protected Map<CloudSolrServerClient,ZkNodeProps> clientToInfo = new HashMap<CloudSolrServerClient,ZkNodeProps>(); protected Map<String,List<SolrServer>> shardToClient = new HashMap<String,List<SolrServer>>(); protected Map<String,List<CloudJettyRunner>> shardToJetty = new HashMap<String,List<CloudJettyRunner>>(); private AtomicInteger jettyIntCntr = new AtomicInteger(0); protected ChaosMonkey chaosMonkey; protected volatile ZkStateReader zkStateReader; private Map<String,SolrServer> shardToLeaderClient = new HashMap<String,SolrServer>(); private Map<String,CloudJettyRunner> shardToLeaderJetty = new HashMap<String,CloudJettyRunner>(); class CloudJettyRunner { JettySolrRunner jetty; String nodeName; String coreNodeName; } static class CloudSolrServerClient { SolrServer client; String shardName; public CloudSolrServerClient() {} public CloudSolrServerClient(SolrServer client) { this.client = client; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((client == null) ? 0 : client.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CloudSolrServerClient other = (CloudSolrServerClient) obj; if (client == null) { if (other.client != null) return false; } else if (!client.equals(other.client)) return false; return true; } } @Before @Override public void setUp() throws Exception { super.setUp(); ignoreException(".*"); System.setProperty("numShards", Integer.toString(sliceCount)); } @BeforeClass public static void beforeClass() throws Exception { System .setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory"); System.setProperty("solrcloud.update.delay", "0"); System.setProperty("enable.update.log", "true"); System.setProperty("remove.version.field", "true"); } @AfterClass public static void afterClass() { System.clearProperty("solr.directoryFactory"); System.clearProperty("solrcloud.update.delay"); System.clearProperty("enable.update.log"); System.clearProperty("remove.version.field"); } public FullSolrCloudTest() { fixShardCount = true; shardCount = 4; sliceCount = 2; // TODO: for now, turn off stress because it uses regular clients, and we // need the cloud client because we kill servers stress = 0; } protected void initCloud() throws Exception { if (zkStateReader == null) { synchronized (this) { if (zkStateReader != null) { return; } zkStateReader = new ZkStateReader(zkServer.getZkAddress(), 10000, AbstractZkTestCase.TIMEOUT); zkStateReader.createClusterStateWatchersAndUpdate(); } chaosMonkey = new ChaosMonkey(zkServer, zkStateReader, DEFAULT_COLLECTION, shardToJetty, shardToClient, shardToLeaderClient, shardToLeaderJetty, random); } // wait until shards have started registering... while (!zkStateReader.getCloudState().getCollections() .contains(DEFAULT_COLLECTION)) { Thread.sleep(500); } while (zkStateReader.getCloudState().getSlices(DEFAULT_COLLECTION).size() != sliceCount) { Thread.sleep(500); } // use the distributed solrj client if (cloudClient == null) { synchronized (this) { if (cloudClient != null) { return; } try { CloudSolrServer server = new CloudSolrServer(zkServer.getZkAddress()); server.setDefaultCollection(DEFAULT_COLLECTION); server.getLbServer().getHttpClient().getParams() .setConnectionManagerTimeout(5000); server.getLbServer().getHttpClient().getParams().setSoTimeout(15000); cloudClient = server; } catch (MalformedURLException e) { throw new RuntimeException(e); } } } } @Override protected void createServers(int numServers) throws Exception { System.setProperty("collection", "control_collection"); controlJetty = createJetty(testDir, testDir + "/control/data", "control_shard"); System.clearProperty("collection"); controlClient = createNewSolrServer(controlJetty.getLocalPort()); createJettys(numServers); } private List<JettySolrRunner> createJettys(int numJettys) throws Exception, InterruptedException, TimeoutException, IOException, KeeperException, URISyntaxException { List<JettySolrRunner> jettys = new ArrayList<JettySolrRunner>(); List<SolrServer> clients = new ArrayList<SolrServer>(); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= numJettys; i++) { if (sb.length() > 0) sb.append(','); JettySolrRunner j = createJetty(testDir, testDir + "/jetty" + this.jettyIntCntr.incrementAndGet(), null, "solrconfig.xml", null); jettys.add(j); SolrServer client = createNewSolrServer(j.getLocalPort()); clients.add(client); } initCloud(); this.jettys.addAll(jettys); this.clients.addAll(clients); updateMappingsFromZk(this.jettys, this.clients); // build the shard string for (int i = 1; i <= numJettys / 2; i++) { JettySolrRunner j = this.jettys.get(i); JettySolrRunner j2 = this.jettys.get(i + (numJettys / 2 - 1)); if (sb.length() > 0) sb.append(','); sb.append("localhost:").append(j.getLocalPort()).append(context); sb.append("|localhost:").append(j2.getLocalPort()).append(context); } shards = sb.toString(); return jettys; } public JettySolrRunner createJetty(String dataDir, String shardList, String solrConfigOverride) throws Exception { JettySolrRunner jetty = new JettySolrRunner(getSolrHome(), "/solr", 0, solrConfigOverride, null, false); jetty.setShards(shardList); jetty.setDataDir(dataDir); jetty.start(); return jetty; } protected void updateMappingsFromZk(List<JettySolrRunner> jettys, List<SolrServer> clients) throws Exception, IOException, KeeperException, URISyntaxException { zkStateReader.updateCloudState(true); shardToClient.clear(); shardToJetty.clear(); jettyToInfo.clear(); CloudState cloudState = zkStateReader.getCloudState(); Map<String,Slice> slices = cloudState.getSlices(DEFAULT_COLLECTION); if (slices == null) { throw new RuntimeException("No slices found for collection " + DEFAULT_COLLECTION + " in " + cloudState.getCollections()); } for (SolrServer client : clients) { // find info for this client in zk nextClient: // we find ou state by simply matching ports... for (Map.Entry<String,Slice> slice : slices.entrySet()) { Map<String,ZkNodeProps> theShards = slice.getValue().getShards(); for (Map.Entry<String,ZkNodeProps> shard : theShards.entrySet()) { int port = new URI(((CommonsHttpSolrServer) client).getBaseURL()) .getPort(); if (shard.getKey().contains(":" + port + "_")) { CloudSolrServerClient csc = new CloudSolrServerClient(); csc.client = client; csc.shardName = shard.getValue().get(ZkStateReader.NODE_NAME_PROP); boolean isLeader = shard.getValue().containsKey( ZkStateReader.LEADER_PROP); clientToInfo.put(csc, shard.getValue()); List<SolrServer> list = shardToClient.get(slice.getKey()); if (list == null) { list = new ArrayList<SolrServer>(); shardToClient.put(slice.getKey(), list); } list.add(client); if (isLeader) { shardToLeaderClient.put(slice.getKey(), client); } break nextClient; } } } } for (Map.Entry<String,Slice> slice : slices.entrySet()) { // check that things look right assertEquals(slice.getValue().getShards().size(), shardToClient.get(slice.getKey()).size()); } for (JettySolrRunner jetty : jettys) { int port = jetty.getLocalPort(); if (port == -1) { continue; // If we cannot get the port, this jetty is down } nextJetty: for (Map.Entry<String,Slice> slice : slices.entrySet()) { Map<String,ZkNodeProps> theShards = slice.getValue().getShards(); for (Map.Entry<String,ZkNodeProps> shard : theShards.entrySet()) { if (shard.getKey().contains(":" + port + "_")) { jettyToInfo.put(jetty, shard.getValue()); List<CloudJettyRunner> list = shardToJetty.get(slice.getKey()); if (list == null) { list = new ArrayList<CloudJettyRunner>(); shardToJetty.put(slice.getKey(), list); } boolean isLeader = shard.getValue().containsKey( ZkStateReader.LEADER_PROP); CloudJettyRunner cjr = new CloudJettyRunner(); cjr.jetty = jetty; cjr.nodeName = shard.getValue().get(ZkStateReader.NODE_NAME_PROP); cjr.coreNodeName = shard.getKey(); list.add(cjr); if (isLeader) { shardToLeaderJetty.put(slice.getKey(), cjr); } break nextJetty; } } } } // # of jetties may not match replicas in shard here, because we don't map // jetties that are not running - every shard should have at least one // running jetty though for (Map.Entry<String,Slice> slice : slices.entrySet()) { // check that things look right List<CloudJettyRunner> jetties = shardToJetty.get(slice.getKey()); assertNotNull("Test setup problem: We found no jetties for shard: " + slice.getKey() + " just:" + shardToJetty.keySet(), jetties); assertTrue(jetties.size() > 0); } } @Override protected void setDistributedParams(ModifiableSolrParams params) { if (r.nextBoolean()) { // don't set shards, let that be figured out from the cloud state } else { // use shard ids rather than physical locations StringBuilder sb = new StringBuilder(); for (int i = 0; i < sliceCount; i++) { if (i > 0) sb.append(','); sb.append("shard" + (i + 1)); } params.set("shards", sb.toString()); } } @Override protected void indexDoc(SolrInputDocument doc) throws IOException, SolrServerException { controlClient.add(doc); // if we wanted to randomly pick a client - but sometimes they may be // down... // boolean pick = random.nextBoolean(); // // int which = (doc.getField(id).toString().hashCode() & 0x7fffffff) % // sliceCount; // // if (pick && sliceCount > 1) { // which = which + ((shardCount / sliceCount) * // random.nextInt(sliceCount-1)); // } // // CommonsHttpSolrServer client = (CommonsHttpSolrServer) // clients.get(which); UpdateRequest ureq = new UpdateRequest(); ureq.add(doc); // ureq.setParam(UpdateParams.UPDATE_CHAIN, DISTRIB_UPDATE_CHAIN); ureq.process(cloudClient); } protected void index_specific(int serverNumber, Object... fields) throws Exception { SolrInputDocument doc = new SolrInputDocument(); for (int i = 0; i < fields.length; i += 2) { doc.addField((String) (fields[i]), fields[i + 1]); } controlClient.add(doc); CommonsHttpSolrServer client = (CommonsHttpSolrServer) clients .get(serverNumber); UpdateRequest ureq = new UpdateRequest(); ureq.add(doc); // ureq.setParam("update.chain", DISTRIB_UPDATE_CHAIN); ureq.process(client); } protected void index_specific(SolrServer client, Object... fields) throws Exception { SolrInputDocument doc = new SolrInputDocument(); for (int i = 0; i < fields.length; i += 2) { doc.addField((String) (fields[i]), fields[i + 1]); } UpdateRequest ureq = new UpdateRequest(); ureq.add(doc); // ureq.setParam("update.chain", DISTRIB_UPDATE_CHAIN); ureq.process(client); // add to control second in case adding to shards fails controlClient.add(doc); } protected void del(String q) throws Exception { controlClient.deleteByQuery(q); for (SolrServer client : clients) { UpdateRequest ureq = new UpdateRequest(); // ureq.setParam("update.chain", DISTRIB_UPDATE_CHAIN); ureq.deleteByQuery(q).process(client); } }// serial commit... /* * (non-Javadoc) * * @see org.apache.solr.BaseDistributedSearchTestCase#doTest() * * Create 3 shards, each with one replica */ @Override public void doTest() throws Exception { boolean testFinished = false; try { handle.clear(); handle.put("QTime", SKIPVAL); handle.put("timestamp", SKIPVAL); indexr(id, 1, i1, 100, tlong, 100, t1, "now is the time for all good men", "foo_f", 1.414f, "foo_b", "true", "foo_d", 1.414d); // make sure we are in a steady state... waitForRecoveriesToFinish(false); commit(); assertDocCounts(false); indexAbunchOfDocs(); commit(); assertDocCounts(VERBOSE); checkQueries(); assertDocCounts(VERBOSE); query("q", "*:*", "sort", "n_tl1 desc"); brindDownShardIndexSomeDocsAndRecover(); query("q", "*:*", "sort", "n_tl1 desc"); // test adding another replica to a shard - it should do a // recovery/replication to pick up the index from the leader addNewReplica(); long docId = testUpdateAndDelete(); // index a bad doc... try { indexr(t1, "a doc with no id"); fail("this should fail"); } catch (SolrException e) { // expected } // TODO: bring this to it's own method? // try indexing to a leader that has no replicas up ZkNodeProps leaderProps = zkStateReader.getLeaderProps( DEFAULT_COLLECTION, SHARD2); String nodeName = leaderProps.get(ZkStateReader.NODE_NAME_PROP); chaosMonkey.stopShardExcept(SHARD2, nodeName); SolrServer client = getClient(nodeName); index_specific(client, "id", docId + 1, t1, "what happens here?"); // expire a session... CloudJettyRunner cloudJetty = shardToJetty.get("shard1").get(0); chaosMonkey.expireSession(cloudJetty.jetty); indexr("id", docId + 1, t1, "slip this doc in"); waitForRecoveriesToFinish(false); checkShardConsistency("shard1"); testFinished = true; } finally { if (!testFinished) { printLayout(); } } } private long testUpdateAndDelete() throws Exception, SolrServerException, IOException { long docId = 99999999L; indexr("id", docId, t1, "originalcontent"); commit(); ModifiableSolrParams params = new ModifiableSolrParams(); params.add("q", t1 + ":originalcontent"); QueryResponse results = clients.get(0).query(params); assertEquals(1, results.getResults().getNumFound()); // update doc indexr("id", docId, t1, "updatedcontent"); commit(); results = clients.get(0).query(params); assertEquals(0, results.getResults().getNumFound()); params.set("q", t1 + ":updatedcontent"); results = clients.get(0).query(params); assertEquals(1, results.getResults().getNumFound()); UpdateRequest uReq = new UpdateRequest(); // uReq.setParam(UpdateParams.UPDATE_CHAIN, DISTRIB_UPDATE_CHAIN); uReq.deleteById(Long.toString(docId)).process(clients.get(0)); commit(); results = clients.get(0).query(params); assertEquals(0, results.getResults().getNumFound()); return docId; } private void addNewReplica() throws Exception, InterruptedException, TimeoutException, IOException, KeeperException, URISyntaxException, SolrServerException { JettySolrRunner newReplica = createJettys(1).get(0); waitForRecoveriesToFinish(false); // new server should be part of first shard // how many docs are on the new shard? for (SolrServer client : shardToClient.get("shard1")) { if (VERBOSE) System.out.println("total:" + client.query(new SolrQuery("*:*")).getResults().getNumFound()); } checkShardConsistency("shard1"); assertDocCounts(VERBOSE); } protected void waitForRecoveriesToFinish(boolean verbose) throws KeeperException, InterruptedException { boolean cont = true; int cnt = 0; while (cont) { if (verbose) System.out.println("-"); boolean sawLiveRecovering = false; zkStateReader.updateCloudState(true); CloudState cloudState = zkStateReader.getCloudState(); Map<String,Slice> slices = cloudState.getSlices(DEFAULT_COLLECTION); for (Map.Entry<String,Slice> entry : slices.entrySet()) { Map<String,ZkNodeProps> shards = entry.getValue().getShards(); for (Map.Entry<String,ZkNodeProps> shard : shards.entrySet()) { if (verbose) System.out.println("rstate:" + shard.getValue().get(ZkStateReader.STATE_PROP) + " live:" + cloudState.liveNodesContain(shard.getValue().get( ZkStateReader.NODE_NAME_PROP))); String state = shard.getValue().get(ZkStateReader.STATE_PROP); if ((state.equals(ZkStateReader.RECOVERING) || state.equals(ZkStateReader.SYNC)) && cloudState.liveNodesContain(shard.getValue().get( ZkStateReader.NODE_NAME_PROP))) { sawLiveRecovering = true; } } } if (!sawLiveRecovering || cnt == 10) { if (!sawLiveRecovering) { if (verbose) System.out.println("no one is recoverying"); } else { if (verbose) System.out .println("gave up waiting for recovery to finish.."); } cont = false; } else { Thread.sleep(2000); } cnt++; } } private void brindDownShardIndexSomeDocsAndRecover() throws Exception, SolrServerException, IOException, InterruptedException { commit(); query("q", "*:*", "sort", "n_tl1 desc"); // kill a shard JettySolrRunner deadShard = chaosMonkey.stopShard(SHARD2, 0); // ensure shard is dead try { // TODO: ignore fail index_specific(shardToClient.get(SHARD2).get(0), id, 999, i1, 107, t1, "specific doc!"); fail("This server should be down and this update should have failed"); } catch (SolrServerException e) { // expected.. } commit(); query("q", "*:*", "sort", "n_tl1 desc"); // long cloudClientDocs = cloudClient.query(new // SolrQuery("*:*")).getResults().getNumFound(); // System.out.println("clouddocs:" + cloudClientDocs); // try to index to a living shard at shard2 // TODO: this can fail with connection refused !???? index_specific(shardToClient.get(SHARD2).get(1), id, 1000, i1, 108, t1, "specific doc!"); commit(); checkShardConsistency(true, false); query("q", "*:*", "sort", "n_tl1 desc"); // try adding a doc with CloudSolrServer cloudClient.setDefaultCollection(DEFAULT_COLLECTION); SolrQuery query = new SolrQuery("*:*"); long numFound1 = cloudClient.query(query).getResults().getNumFound(); SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", 1001); controlClient.add(doc); UpdateRequest ureq = new UpdateRequest(); ureq.add(doc); // ureq.setParam("update.chain", DISTRIB_UPDATE_CHAIN); ureq.process(cloudClient); commit(); query("q", "*:*", "sort", "n_tl1 desc"); long numFound2 = cloudClient.query(query).getResults().getNumFound(); // lets just check that the one doc since last commit made it in... assertEquals(numFound1 + 1, numFound2); // test debugging testDebugQueries(); if (VERBOSE) { System.out.println(controlClient.query(new SolrQuery("*:*")).getResults() .getNumFound()); for (SolrServer client : clients) { try { System.out.println(client.query(new SolrQuery("*:*")).getResults() .getNumFound()); } catch (Exception e) { } } } // TODO: This test currently fails because debug info is obtained only // on shards with matches. // query("q","matchesnothing","fl","*,score", "debugQuery", "true"); // this should trigger a recovery phase on deadShard deadShard.start(true); // make sure we have published we are recoverying Thread.sleep(1500); waitForRecoveriesToFinish(false); List<SolrServer> s2c = shardToClient.get(SHARD2); // if we properly recovered, we should now have the couple missing docs that // came in while shard was down assertEquals(s2c.get(0).query(new SolrQuery("*:*")).getResults() .getNumFound(), s2c.get(1).query(new SolrQuery("*:*")).getResults() .getNumFound()); } private void testDebugQueries() throws Exception { handle.put("explain", UNORDERED); handle.put("debug", UNORDERED); handle.put("time", SKIPVAL); query("q", "now their fox sat had put", "fl", "*,score", CommonParams.DEBUG_QUERY, "true"); query("q", "id:[1 TO 5]", CommonParams.DEBUG_QUERY, "true"); query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.TIMING); query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.RESULTS); query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.QUERY); } private void checkQueries() throws Exception { query("q", "*:*", "sort", "n_tl1 desc"); // random value sort for (String f : fieldNames) { query("q", "*:*", "sort", f + " desc"); query("q", "*:*", "sort", f + " asc"); } // these queries should be exactly ordered and scores should exactly match query("q", "*:*", "sort", i1 + " desc"); query("q", "*:*", "sort", i1 + " asc"); query("q", "*:*", "sort", i1 + " desc", "fl", "*,score"); query("q", "*:*", "sort", "n_tl1 asc", "fl", "score"); // test legacy // behavior - // "score"=="*,score" query("q", "*:*", "sort", "n_tl1 desc"); handle.put("maxScore", SKIPVAL); query("q", "{!func}" + i1);// does not expect maxScore. So if it comes // ,ignore it. // JavaBinCodec.writeSolrDocumentList() // is agnostic of request params. handle.remove("maxScore"); query("q", "{!func}" + i1, "fl", "*,score"); // even scores should match // exactly here handle.put("highlighting", UNORDERED); handle.put("response", UNORDERED); handle.put("maxScore", SKIPVAL); query("q", "quick"); query("q", "all", "fl", "id", "start", "0"); query("q", "all", "fl", "foofoofoo", "start", "0"); // no fields in returned // docs query("q", "all", "fl", "id", "start", "100"); handle.put("score", SKIPVAL); query("q", "quick", "fl", "*,score"); query("q", "all", "fl", "*,score", "start", "1"); query("q", "all", "fl", "*,score", "start", "100"); query("q", "now their fox sat had put", "fl", "*,score", "hl", "true", "hl.fl", t1); query("q", "now their fox sat had put", "fl", "foofoofoo", "hl", "true", "hl.fl", t1); query("q", "matchesnothing", "fl", "*,score"); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", -1, "facet.sort", "count"); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", -1, "facet.sort", "count", "facet.mincount", 2); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", -1, "facet.sort", "index"); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", -1, "facet.sort", "index", "facet.mincount", 2); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", 1); query("q", "*:*", "rows", 100, "facet", "true", "facet.query", "quick", "facet.query", "all", "facet.query", "*:*"); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.offset", 1); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.mincount", 2); // test faceting multiple things at once query("q", "*:*", "rows", 100, "facet", "true", "facet.query", "quick", "facet.query", "all", "facet.query", "*:*", "facet.field", t1); // test filter tagging, facet exclusion, and naming (multi-select facet // support) query("q", "*:*", "rows", 100, "facet", "true", "facet.query", "{!key=myquick}quick", "facet.query", "{!key=myall ex=a}all", "facet.query", "*:*", "facet.field", "{!key=mykey ex=a}" + t1, "facet.field", "{!key=other ex=b}" + t1, "facet.field", "{!key=again ex=a,b}" + t1, "facet.field", t1, "fq", "{!tag=a}id:[1 TO 7]", "fq", "{!tag=b}id:[3 TO 9]"); query("q", "*:*", "facet", "true", "facet.field", "{!ex=t1}SubjectTerms_mfacet", "fq", "{!tag=t1}SubjectTerms_mfacet:(test 1)", "facet.limit", "10", "facet.mincount", "1"); // test field that is valid in schema but missing in all shards query("q", "*:*", "rows", 100, "facet", "true", "facet.field", missingField, "facet.mincount", 2); // test field that is valid in schema and missing in some shards query("q", "*:*", "rows", 100, "facet", "true", "facet.field", oddField, "facet.mincount", 2); query("q", "*:*", "sort", i1 + " desc", "stats", "true", "stats.field", i1); // Try to get better coverage for refinement queries by turning off over // requesting. // This makes it much more likely that we may not get the top facet values // and hence // we turn of that checking. handle.put("facet_fields", SKIPVAL); query("q", "*:*", "rows", 0, "facet", "true", "facet.field", t1, "facet.limit", 5, "facet.shard.limit", 5); // check a complex key name query("q", "*:*", "rows", 0, "facet", "true", "facet.field", "{!key='a b/c \\' \\} foo'}" + t1, "facet.limit", 5, "facet.shard.limit", 5); handle.remove("facet_fields"); query("q", "*:*", "sort", "n_tl1 desc"); // index the same document to two shards and make sure things // don't blow up. // assumes first n clients are first n shards if (clients.size() >= 2) { index(id, 100, i1, 107, t1, "oh no, a duplicate!"); for (int i = 0; i < shardCount; i++) { index_specific(i, id, 100, i1, 107, t1, "oh no, a duplicate!"); } commit(); query("q", "duplicate", "hl", "true", "hl.fl", t1); query("q", "fox duplicate horses", "hl", "true", "hl.fl", t1); query("q", "*:*", "rows", 100); } } private void indexAbunchOfDocs() throws Exception { indexr(id, 2, i1, 50, tlong, 50, t1, "to come to the aid of their country."); indexr(id, 3, i1, 2, tlong, 2, t1, "how now brown cow"); indexr(id, 4, i1, -100, tlong, 101, t1, "the quick fox jumped over the lazy dog"); indexr(id, 5, i1, 500, tlong, 500, t1, "the quick fox jumped way over the lazy dog"); indexr(id, 6, i1, -600, tlong, 600, t1, "humpty dumpy sat on a wall"); indexr(id, 7, i1, 123, tlong, 123, t1, "humpty dumpy had a great fall"); indexr(id, 8, i1, 876, tlong, 876, t1, "all the kings horses and all the kings men"); indexr(id, 9, i1, 7, tlong, 7, t1, "couldn't put humpty together again"); indexr(id, 10, i1, 4321, tlong, 4321, t1, "this too shall pass"); indexr(id, 11, i1, -987, tlong, 987, t1, "An eye for eye only ends up making the whole world blind."); indexr(id, 12, i1, 379, tlong, 379, t1, "Great works are performed, not by strength, but by perseverance."); indexr(id, 13, i1, 232, tlong, 232, t1, "no eggs on wall, lesson learned", oddField, "odd man out"); indexr(id, 14, "SubjectTerms_mfacet", new String[] {"mathematical models", "mathematical analysis"}); indexr(id, 15, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"}); indexr(id, 16, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"}); String[] vals = new String[100]; for (int i = 0; i < 100; i++) { vals[i] = "test " + i; } indexr(id, 17, "SubjectTerms_mfacet", vals); for (int i = 100; i < 150; i++) { indexr(id, i); } } protected void checkShardConsistency(String shard) throws Exception { checkShardConsistency(shard, false); } protected String checkShardConsistency(String shard, boolean verbose) throws Exception { List<SolrServer> solrClients = shardToClient.get(shard); if (solrClients == null) { throw new RuntimeException("shard not found:" + shard + " keys:" + shardToClient.keySet()); } long num = -1; long lastNum = -1; String failMessage = null; if (verbose) System.out.println("check const of " + shard); int cnt = 0; assertEquals( "The client count does not match up with the shard count for slice:" + shard, zkStateReader.getCloudState().getSlice(DEFAULT_COLLECTION, shard) .getShards().size(), solrClients.size()); for (SolrServer client : solrClients) { ZkNodeProps props = clientToInfo.get(new CloudSolrServerClient(client)); if (verbose) System.out.println("client" + cnt++); if (verbose) System.out.println("PROPS:" + props); try { SolrQuery query = new SolrQuery("*:*"); query.set("distrib", false); num = client.query(query).getResults().getNumFound(); } catch (SolrServerException e) { if (verbose) System.out.println("error contacting client: " + e.getMessage() + "\n"); continue; } boolean live = false; String nodeName = props.get(ZkStateReader.NODE_NAME_PROP); if (zkStateReader.getCloudState().liveNodesContain(nodeName)) { live = true; } if (verbose) System.out.println(" live:" + live); if (verbose) System.out.println(" num:" + num + "\n"); boolean active = props.get(ZkStateReader.STATE_PROP).equals( ZkStateReader.ACTIVE); if (active && live) { if (lastNum > -1 && lastNum != num && failMessage == null) { failMessage = shard + " is not consistent, expected:" + lastNum + " and got:" + num; } lastNum = num; } } return failMessage; } protected void checkShardConsistency() throws Exception { checkShardConsistency(true, false); } protected void checkShardConsistency(boolean checkVsControl, boolean verbose) throws Exception { long docs = controlClient.query(new SolrQuery("*:*")).getResults() .getNumFound(); if (verbose) System.out.println("Control Docs:" + docs); updateMappingsFromZk(jettys, clients); Set<String> theShards = shardToClient.keySet(); String failMessage = null; for (String shard : theShards) { String shardFailMessage = checkShardConsistency(shard, verbose); if (shardFailMessage != null && failMessage == null) { failMessage = shardFailMessage; } } if (failMessage != null) { fail(failMessage); } if (checkVsControl) { // now check that the right # are on each shard theShards = shardToClient.keySet(); int cnt = 0; for (String s : theShards) { int times = shardToClient.get(s).size(); for (int i = 0; i < times; i++) { try { SolrServer client = shardToClient.get(s).get(i); ZkNodeProps props = clientToInfo.get(new CloudSolrServerClient( client)); boolean active = props.get(ZkStateReader.STATE_PROP).equals( ZkStateReader.ACTIVE); if (active) { SolrQuery query = new SolrQuery("*:*"); query.set("distrib", false); long results = client.query(query).getResults().getNumFound(); if (verbose) System.out.println(new ZkCoreNodeProps(props) .getCoreUrl() + " : " + results); if (verbose) System.out.println("shard:" + props.get(ZkStateReader.SHARD_ID_PROP)); cnt += results; break; } } catch (SolrServerException e) { // if we have a problem, try the next one if (i == times - 1) { throw e; } } } } SolrQuery q = new SolrQuery("*:*"); long cloudClientDocs = cloudClient.query(q).getResults().getNumFound(); assertEquals( "adding up the # of docs on each shard does not match the control - cloud client returns:" + cloudClientDocs, docs, cnt); } } private SolrServer getClient(String nodeName) { for (CloudSolrServerClient client : clientToInfo.keySet()) { if (client.shardName.equals(nodeName)) { return client.client; } } return null; } protected void assertDocCounts(boolean verbose) throws Exception { // TODO: as we create the clients, we should build a map from shard to // node/client // and node/client to shard? if (verbose) System.out.println("control docs:" + controlClient.query(new SolrQuery("*:*")).getResults().getNumFound() + "\n\n"); long controlCount = controlClient.query(new SolrQuery("*:*")).getResults() .getNumFound(); // do some really inefficient mapping... ZkStateReader zk = new ZkStateReader(zkServer.getZkAddress(), 10000, AbstractZkTestCase.TIMEOUT); Map<String,Slice> slices = null; CloudState cloudState; try { zk.createClusterStateWatchersAndUpdate(); cloudState = zk.getCloudState(); slices = cloudState.getSlices(DEFAULT_COLLECTION); } finally { zk.close(); } if (slices == null) { throw new RuntimeException("Could not find collection " + DEFAULT_COLLECTION + " in " + cloudState.getCollections()); } for (SolrServer client : clients) { for (Map.Entry<String,Slice> slice : slices.entrySet()) { Map<String,ZkNodeProps> theShards = slice.getValue().getShards(); for (Map.Entry<String,ZkNodeProps> shard : theShards.entrySet()) { String shardName = new URI( ((CommonsHttpSolrServer) client).getBaseURL()).getPort() + "_solr_"; if (verbose && shard.getKey().endsWith(shardName)) { System.out.println("shard:" + slice.getKey()); System.out.println(shard.getValue()); } } } long count = 0; String currentState = clientToInfo.get(new CloudSolrServerClient(client)) .get(ZkStateReader.STATE_PROP); if (currentState != null && currentState.equals(ZkStateReader.ACTIVE)) { SolrQuery query = new SolrQuery("*:*"); query.set("distrib", false); count = client.query(query).getResults().getNumFound(); } if (verbose) System.out.println("client docs:" + count + "\n\n"); } if (verbose) System.out.println("control docs:" + controlClient.query(new SolrQuery("*:*")).getResults().getNumFound() + "\n\n"); SolrQuery query = new SolrQuery("*:*"); assertEquals("Doc Counts do not add up", controlCount, cloudClient.query(query).getResults().getNumFound()); } @Override protected QueryResponse queryServer(ModifiableSolrParams params) throws SolrServerException { if (r.nextBoolean()) params.set("collection", DEFAULT_COLLECTION); QueryResponse rsp = cloudClient.query(params); return rsp; } class StopableIndexingThread extends Thread { private volatile boolean stop = false; protected final int startI; protected final List<Integer> deletes = new ArrayList<Integer>(); protected final AtomicInteger fails = new AtomicInteger(); protected boolean doDeletes; public StopableIndexingThread(int startI, boolean doDeletes) { super("StopableIndexingThread"); this.startI = startI; this.doDeletes = doDeletes; setDaemon(true); } @Override public void run() { int i = startI; int numDeletes = 0; int numAdds = 0; while (true && !stop) { ++i; if (doDeletes && random.nextBoolean() && deletes.size() > 0) { Integer delete = deletes.remove(0); try { numDeletes++; controlClient.deleteById(Integer.toString(delete)); cloudClient.deleteById(Integer.toString(delete)); } catch (Exception e) { System.err.println("REQUEST FAILED:"); e.printStackTrace(); fails.incrementAndGet(); } } try { numAdds++; indexr(id, i, i1, 50, tlong, 50, t1, "to come to the aid of their country."); } catch (Exception e) { System.err.println("REQUEST FAILED:"); e.printStackTrace(); fails.incrementAndGet(); } if (doDeletes && random.nextBoolean()) { deletes.add(i); } } System.err.println("added docs:" + numAdds + " with " + fails + " fails" + " deletes:" + numDeletes); } public void safeStop() { stop = true; } public int getFails() { return fails.get(); } }; @Override @After public void tearDown() throws Exception { if (VERBOSE) { super.printLayout(); } ((CommonsHttpSolrServer) controlClient).shutdown(); if (cloudClient != null) { cloudClient.close(); } if (zkStateReader != null) { zkStateReader.close(); } super.tearDown(); System.clearProperty("zkHost"); } protected void commit() throws Exception { controlClient.commit(); cloudClient.commit(); } protected void destroyServers() throws Exception { ChaosMonkey.stop(controlJetty); for (JettySolrRunner jetty : jettys) { try { ChaosMonkey.stop(jetty); } catch (Exception e) { log.error("", e); } } clients.clear(); jettys.clear(); } protected SolrServer createNewSolrServer(int port) { try { // setup the server... String url = "http://localhost:" + port + context + "/" + DEFAULT_COLLECTION; CommonsHttpSolrServer s = new CommonsHttpSolrServer(url); s.setConnectionTimeout(100); // 1/10th sec s.setSoTimeout(30000); s.setDefaultMaxConnectionsPerHost(100); s.setMaxTotalConnections(100); return s; } catch (Exception ex) { throw new RuntimeException(ex); } } }
core/src/test/org/apache/solr/cloud/FullSolrCloudTest.java
package org.apache.solr.cloud; /** * 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. */ import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.CloudSolrServer; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.cloud.CloudState; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.ZkCoreNodeProps; import org.apache.solr.common.cloud.ZkNodeProps; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.zookeeper.KeeperException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; /** * * TODO: we should still test this works as a custom update chain as well as * what we test now - the default update chain * */ public class FullSolrCloudTest extends AbstractDistributedZkTestCase { private static final String SHARD2 = "shard2"; protected static final String DEFAULT_COLLECTION = "collection1"; String t1 = "a_t"; String i1 = "a_si"; String nint = "n_i"; String tint = "n_ti"; String nfloat = "n_f"; String tfloat = "n_tf"; String ndouble = "n_d"; String tdouble = "n_td"; String nlong = "n_l"; String tlong = "other_tl1"; String ndate = "n_dt"; String tdate = "n_tdt"; String oddField = "oddField_s"; String missingField = "ignore_exception__missing_but_valid_field_t"; String invalidField = "ignore_exception__invalid_field_not_in_schema"; protected int sliceCount; protected volatile CloudSolrServer cloudClient; protected Map<JettySolrRunner,ZkNodeProps> jettyToInfo = new HashMap<JettySolrRunner,ZkNodeProps>(); protected Map<CloudSolrServerClient,ZkNodeProps> clientToInfo = new HashMap<CloudSolrServerClient,ZkNodeProps>(); protected Map<String,List<SolrServer>> shardToClient = new HashMap<String,List<SolrServer>>(); protected Map<String,List<CloudJettyRunner>> shardToJetty = new HashMap<String,List<CloudJettyRunner>>(); private AtomicInteger jettyIntCntr = new AtomicInteger(0); protected ChaosMonkey chaosMonkey; protected volatile ZkStateReader zkStateReader; private Map<String,SolrServer> shardToLeaderClient = new HashMap<String,SolrServer>(); private Map<String,CloudJettyRunner> shardToLeaderJetty = new HashMap<String,CloudJettyRunner>(); class CloudJettyRunner { JettySolrRunner jetty; String nodeName; String coreNodeName; } static class CloudSolrServerClient { SolrServer client; String shardName; public CloudSolrServerClient() {} public CloudSolrServerClient(SolrServer client) { this.client = client; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((client == null) ? 0 : client.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CloudSolrServerClient other = (CloudSolrServerClient) obj; if (client == null) { if (other.client != null) return false; } else if (!client.equals(other.client)) return false; return true; } } @Before @Override public void setUp() throws Exception { super.setUp(); ignoreException(".*"); System.setProperty("numShards", Integer.toString(sliceCount)); } @BeforeClass public static void beforeClass() throws Exception { System .setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory"); System.setProperty("solrcloud.update.delay", "0"); System.setProperty("enable.update.log", "true"); System.setProperty("remove.version.field", "true"); } @AfterClass public static void afterClass() { System.clearProperty("solr.directoryFactory"); System.clearProperty("solrcloud.update.delay"); System.clearProperty("enable.update.log"); System.clearProperty("remove.version.field"); } public FullSolrCloudTest() { fixShardCount = true; shardCount = 4; sliceCount = 2; // TODO: for now, turn off stress because it uses regular clients, and we // need the cloud client because we kill servers stress = 0; } protected void initCloud() throws Exception { if (zkStateReader == null) { synchronized (this) { if (zkStateReader != null) { return; } zkStateReader = new ZkStateReader(zkServer.getZkAddress(), 10000, AbstractZkTestCase.TIMEOUT); zkStateReader.createClusterStateWatchersAndUpdate(); } chaosMonkey = new ChaosMonkey(zkServer, zkStateReader, DEFAULT_COLLECTION, shardToJetty, shardToClient, shardToLeaderClient, shardToLeaderJetty, random); } // wait until shards have started registering... while (!zkStateReader.getCloudState().getCollections() .contains(DEFAULT_COLLECTION)) { Thread.sleep(500); } while (zkStateReader.getCloudState().getSlices(DEFAULT_COLLECTION).size() != sliceCount) { Thread.sleep(500); } // use the distributed solrj client if (cloudClient == null) { synchronized (this) { if (cloudClient != null) { return; } try { CloudSolrServer server = new CloudSolrServer(zkServer.getZkAddress()); server.setDefaultCollection(DEFAULT_COLLECTION); server.getLbServer().getHttpClient().getParams() .setConnectionManagerTimeout(5000); server.getLbServer().getHttpClient().getParams().setSoTimeout(15000); cloudClient = server; } catch (MalformedURLException e) { throw new RuntimeException(e); } } } } @Override protected void createServers(int numServers) throws Exception { System.setProperty("collection", "control_collection"); controlJetty = createJetty(testDir, testDir + "/control/data", "control_shard"); System.clearProperty("collection"); controlClient = createNewSolrServer(controlJetty.getLocalPort()); createJettys(numServers); } private List<JettySolrRunner> createJettys(int numJettys) throws Exception, InterruptedException, TimeoutException, IOException, KeeperException, URISyntaxException { List<JettySolrRunner> jettys = new ArrayList<JettySolrRunner>(); List<SolrServer> clients = new ArrayList<SolrServer>(); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= numJettys; i++) { if (sb.length() > 0) sb.append(','); JettySolrRunner j = createJetty(testDir, testDir + "/jetty" + this.jettyIntCntr.incrementAndGet(), null, "solrconfig.xml", null); jettys.add(j); SolrServer client = createNewSolrServer(j.getLocalPort()); clients.add(client); } initCloud(); this.jettys.addAll(jettys); this.clients.addAll(clients); updateMappingsFromZk(this.jettys, this.clients); // build the shard string for (int i = 1; i <= numJettys / 2; i++) { JettySolrRunner j = this.jettys.get(i); JettySolrRunner j2 = this.jettys.get(i + (numJettys / 2 - 1)); if (sb.length() > 0) sb.append(','); sb.append("localhost:").append(j.getLocalPort()).append(context); sb.append("|localhost:").append(j2.getLocalPort()).append(context); } shards = sb.toString(); return jettys; } public JettySolrRunner createJetty(String dataDir, String shardList, String solrConfigOverride) throws Exception { JettySolrRunner jetty = new JettySolrRunner(getSolrHome(), "/solr", 0, solrConfigOverride, null, false); jetty.setShards(shardList); jetty.setDataDir(dataDir); jetty.start(); return jetty; } protected void updateMappingsFromZk(List<JettySolrRunner> jettys, List<SolrServer> clients) throws Exception, IOException, KeeperException, URISyntaxException { zkStateReader.updateCloudState(true); shardToClient.clear(); shardToJetty.clear(); jettyToInfo.clear(); CloudState cloudState = zkStateReader.getCloudState(); Map<String,Slice> slices = cloudState.getSlices(DEFAULT_COLLECTION); if (slices == null) { throw new RuntimeException("No slices found for collection " + DEFAULT_COLLECTION + " in " + cloudState.getCollections()); } for (SolrServer client : clients) { // find info for this client in zk nextClient: // we find ou state by simply matching ports... for (Map.Entry<String,Slice> slice : slices.entrySet()) { Map<String,ZkNodeProps> theShards = slice.getValue().getShards(); for (Map.Entry<String,ZkNodeProps> shard : theShards.entrySet()) { int port = new URI(((CommonsHttpSolrServer) client).getBaseURL()) .getPort(); if (shard.getKey().contains(":" + port + "_")) { CloudSolrServerClient csc = new CloudSolrServerClient(); csc.client = client; csc.shardName = shard.getValue().get(ZkStateReader.NODE_NAME_PROP); boolean isLeader = shard.getValue().containsKey( ZkStateReader.LEADER_PROP); clientToInfo.put(csc, shard.getValue()); List<SolrServer> list = shardToClient.get(slice.getKey()); if (list == null) { list = new ArrayList<SolrServer>(); shardToClient.put(slice.getKey(), list); } list.add(client); if (isLeader) { shardToLeaderClient.put(slice.getKey(), client); } break nextClient; } } } } for (Map.Entry<String,Slice> slice : slices.entrySet()) { // check that things look right assertEquals(slice.getValue().getShards().size(), shardToClient.get(slice.getKey()).size()); } for (JettySolrRunner jetty : jettys) { int port = jetty.getLocalPort(); if (port == -1) { continue; // If we cannot get the port, this jetty is down } nextJetty: for (Map.Entry<String,Slice> slice : slices.entrySet()) { Map<String,ZkNodeProps> theShards = slice.getValue().getShards(); for (Map.Entry<String,ZkNodeProps> shard : theShards.entrySet()) { if (shard.getKey().contains(":" + port + "_")) { jettyToInfo.put(jetty, shard.getValue()); List<CloudJettyRunner> list = shardToJetty.get(slice.getKey()); if (list == null) { list = new ArrayList<CloudJettyRunner>(); shardToJetty.put(slice.getKey(), list); } boolean isLeader = shard.getValue().containsKey( ZkStateReader.LEADER_PROP); CloudJettyRunner cjr = new CloudJettyRunner(); cjr.jetty = jetty; cjr.nodeName = shard.getValue().get(ZkStateReader.NODE_NAME_PROP); cjr.coreNodeName = shard.getKey(); list.add(cjr); if (isLeader) { shardToLeaderJetty.put(slice.getKey(), cjr); } break nextJetty; } } } } // # of jetties may not match replicas in shard here, because we don't map // jetties that are not running - every shard should have at least one // running jetty though for (Map.Entry<String,Slice> slice : slices.entrySet()) { // check that things look right List<CloudJettyRunner> jetties = shardToJetty.get(slice.getKey()); assertNotNull("Test setup problem: We found no jetties for shard: " + slice.getKey() + " just:" + shardToJetty.keySet(), jetties); assertTrue(jetties.size() > 0); } } @Override protected void setDistributedParams(ModifiableSolrParams params) { if (r.nextBoolean()) { // don't set shards, let that be figured out from the cloud state } else { // use shard ids rather than physical locations StringBuilder sb = new StringBuilder(); for (int i = 0; i < sliceCount; i++) { if (i > 0) sb.append(','); sb.append("shard" + (i + 1)); } params.set("shards", sb.toString()); } } @Override protected void indexDoc(SolrInputDocument doc) throws IOException, SolrServerException { controlClient.add(doc); // if we wanted to randomly pick a client - but sometimes they may be // down... // boolean pick = random.nextBoolean(); // // int which = (doc.getField(id).toString().hashCode() & 0x7fffffff) % // sliceCount; // // if (pick && sliceCount > 1) { // which = which + ((shardCount / sliceCount) * // random.nextInt(sliceCount-1)); // } // // CommonsHttpSolrServer client = (CommonsHttpSolrServer) // clients.get(which); UpdateRequest ureq = new UpdateRequest(); ureq.add(doc); // ureq.setParam(UpdateParams.UPDATE_CHAIN, DISTRIB_UPDATE_CHAIN); ureq.process(cloudClient); } protected void index_specific(int serverNumber, Object... fields) throws Exception { SolrInputDocument doc = new SolrInputDocument(); for (int i = 0; i < fields.length; i += 2) { doc.addField((String) (fields[i]), fields[i + 1]); } controlClient.add(doc); CommonsHttpSolrServer client = (CommonsHttpSolrServer) clients .get(serverNumber); UpdateRequest ureq = new UpdateRequest(); ureq.add(doc); // ureq.setParam("update.chain", DISTRIB_UPDATE_CHAIN); ureq.process(client); } protected void index_specific(SolrServer client, Object... fields) throws Exception { SolrInputDocument doc = new SolrInputDocument(); for (int i = 0; i < fields.length; i += 2) { doc.addField((String) (fields[i]), fields[i + 1]); } UpdateRequest ureq = new UpdateRequest(); ureq.add(doc); // ureq.setParam("update.chain", DISTRIB_UPDATE_CHAIN); ureq.process(client); // add to control second in case adding to shards fails controlClient.add(doc); } protected void del(String q) throws Exception { controlClient.deleteByQuery(q); for (SolrServer client : clients) { UpdateRequest ureq = new UpdateRequest(); // ureq.setParam("update.chain", DISTRIB_UPDATE_CHAIN); ureq.deleteByQuery(q).process(client); } }// serial commit... /* * (non-Javadoc) * * @see org.apache.solr.BaseDistributedSearchTestCase#doTest() * * Create 3 shards, each with one replica */ @Override public void doTest() throws Exception { handle.clear(); handle.put("QTime", SKIPVAL); handle.put("timestamp", SKIPVAL); indexr(id, 1, i1, 100, tlong, 100, t1, "now is the time for all good men", "foo_f", 1.414f, "foo_b", "true", "foo_d", 1.414d); // make sure we are in a steady state... waitForRecoveriesToFinish(false); commit(); assertDocCounts(false); indexAbunchOfDocs(); commit(); assertDocCounts(VERBOSE); checkQueries(); assertDocCounts(VERBOSE); query("q", "*:*", "sort", "n_tl1 desc"); brindDownShardIndexSomeDocsAndRecover(); query("q", "*:*", "sort", "n_tl1 desc"); // test adding another replica to a shard - it should do a // recovery/replication to pick up the index from the leader addNewReplica(); long docId = testUpdateAndDelete(); // index a bad doc... try { indexr(t1, "a doc with no id"); fail("this should fail"); } catch (SolrException e) { // expected } // TODO: bring this to it's own method? // try indexing to a leader that has no replicas up ZkNodeProps leaderProps = zkStateReader.getLeaderProps(DEFAULT_COLLECTION, SHARD2); String nodeName = leaderProps.get(ZkStateReader.NODE_NAME_PROP); chaosMonkey.stopShardExcept(SHARD2, nodeName); SolrServer client = getClient(nodeName); index_specific(client, "id", docId + 1, t1, "what happens here?"); // expire a session... CloudJettyRunner cloudJetty = shardToJetty.get("shard1").get(0); chaosMonkey.expireSession(cloudJetty.jetty); indexr("id", docId + 1, t1, "slip this doc in"); waitForRecoveriesToFinish(false); checkShardConsistency("shard1"); } private long testUpdateAndDelete() throws Exception, SolrServerException, IOException { long docId = 99999999L; indexr("id", docId, t1, "originalcontent"); commit(); ModifiableSolrParams params = new ModifiableSolrParams(); params.add("q", t1 + ":originalcontent"); QueryResponse results = clients.get(0).query(params); assertEquals(1, results.getResults().getNumFound()); // update doc indexr("id", docId, t1, "updatedcontent"); commit(); results = clients.get(0).query(params); assertEquals(0, results.getResults().getNumFound()); params.set("q", t1 + ":updatedcontent"); results = clients.get(0).query(params); assertEquals(1, results.getResults().getNumFound()); UpdateRequest uReq = new UpdateRequest(); // uReq.setParam(UpdateParams.UPDATE_CHAIN, DISTRIB_UPDATE_CHAIN); uReq.deleteById(Long.toString(docId)).process(clients.get(0)); commit(); results = clients.get(0).query(params); assertEquals(0, results.getResults().getNumFound()); return docId; } private void addNewReplica() throws Exception, InterruptedException, TimeoutException, IOException, KeeperException, URISyntaxException, SolrServerException { JettySolrRunner newReplica = createJettys(1).get(0); waitForRecoveriesToFinish(false); // new server should be part of first shard // how many docs are on the new shard? for (SolrServer client : shardToClient.get("shard1")) { if (VERBOSE) System.out.println("total:" + client.query(new SolrQuery("*:*")).getResults().getNumFound()); } checkShardConsistency("shard1"); assertDocCounts(VERBOSE); } protected void waitForRecoveriesToFinish(boolean verbose) throws KeeperException, InterruptedException { boolean cont = true; int cnt = 0; while (cont) { if (verbose) System.out.println("-"); boolean sawLiveRecovering = false; zkStateReader.updateCloudState(true); CloudState cloudState = zkStateReader.getCloudState(); Map<String,Slice> slices = cloudState.getSlices(DEFAULT_COLLECTION); for (Map.Entry<String,Slice> entry : slices.entrySet()) { Map<String,ZkNodeProps> shards = entry.getValue().getShards(); for (Map.Entry<String,ZkNodeProps> shard : shards.entrySet()) { if (verbose) System.out.println("rstate:" + shard.getValue().get(ZkStateReader.STATE_PROP) + " live:" + cloudState.liveNodesContain(shard.getValue().get( ZkStateReader.NODE_NAME_PROP))); String state = shard.getValue().get(ZkStateReader.STATE_PROP); if ((state.equals(ZkStateReader.RECOVERING) || state.equals(ZkStateReader.SYNC)) && cloudState.liveNodesContain(shard.getValue().get( ZkStateReader.NODE_NAME_PROP))) { sawLiveRecovering = true; } } } if (!sawLiveRecovering || cnt == 10) { if (!sawLiveRecovering) { if (verbose) System.out.println("no one is recoverying"); } else { if (verbose) System.out .println("gave up waiting for recovery to finish.."); } cont = false; } else { Thread.sleep(2000); } cnt++; } } private void brindDownShardIndexSomeDocsAndRecover() throws Exception, SolrServerException, IOException, InterruptedException { commit(); query("q", "*:*", "sort", "n_tl1 desc"); // kill a shard JettySolrRunner deadShard = chaosMonkey.stopShard(SHARD2, 0); // ensure shard is dead try { // TODO: ignore fail index_specific(shardToClient.get(SHARD2).get(0), id, 999, i1, 107, t1, "specific doc!"); fail("This server should be down and this update should have failed"); } catch (SolrServerException e) { // expected.. } commit(); query("q", "*:*", "sort", "n_tl1 desc"); // long cloudClientDocs = cloudClient.query(new // SolrQuery("*:*")).getResults().getNumFound(); // System.out.println("clouddocs:" + cloudClientDocs); // try to index to a living shard at shard2 // TODO: this can fail with connection refused !???? index_specific(shardToClient.get(SHARD2).get(1), id, 1000, i1, 108, t1, "specific doc!"); commit(); checkShardConsistency(true, false); query("q", "*:*", "sort", "n_tl1 desc"); // try adding a doc with CloudSolrServer cloudClient.setDefaultCollection(DEFAULT_COLLECTION); SolrQuery query = new SolrQuery("*:*"); long numFound1 = cloudClient.query(query).getResults().getNumFound(); SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", 1001); controlClient.add(doc); UpdateRequest ureq = new UpdateRequest(); ureq.add(doc); // ureq.setParam("update.chain", DISTRIB_UPDATE_CHAIN); ureq.process(cloudClient); commit(); query("q", "*:*", "sort", "n_tl1 desc"); long numFound2 = cloudClient.query(query).getResults().getNumFound(); // lets just check that the one doc since last commit made it in... assertEquals(numFound1 + 1, numFound2); // test debugging testDebugQueries(); if (VERBOSE) { System.out.println(controlClient.query(new SolrQuery("*:*")).getResults() .getNumFound()); for (SolrServer client : clients) { try { System.out.println(client.query(new SolrQuery("*:*")).getResults() .getNumFound()); } catch (Exception e) { } } } // TODO: This test currently fails because debug info is obtained only // on shards with matches. // query("q","matchesnothing","fl","*,score", "debugQuery", "true"); // this should trigger a recovery phase on deadShard deadShard.start(true); // make sure we have published we are recoverying Thread.sleep(1500); waitForRecoveriesToFinish(false); List<SolrServer> s2c = shardToClient.get(SHARD2); // if we properly recovered, we should now have the couple missing docs that // came in while shard was down assertEquals(s2c.get(0).query(new SolrQuery("*:*")).getResults() .getNumFound(), s2c.get(1).query(new SolrQuery("*:*")).getResults() .getNumFound()); } private void testDebugQueries() throws Exception { handle.put("explain", UNORDERED); handle.put("debug", UNORDERED); handle.put("time", SKIPVAL); query("q", "now their fox sat had put", "fl", "*,score", CommonParams.DEBUG_QUERY, "true"); query("q", "id:[1 TO 5]", CommonParams.DEBUG_QUERY, "true"); query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.TIMING); query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.RESULTS); query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.QUERY); } private void checkQueries() throws Exception { query("q", "*:*", "sort", "n_tl1 desc"); // random value sort for (String f : fieldNames) { query("q", "*:*", "sort", f + " desc"); query("q", "*:*", "sort", f + " asc"); } // these queries should be exactly ordered and scores should exactly match query("q", "*:*", "sort", i1 + " desc"); query("q", "*:*", "sort", i1 + " asc"); query("q", "*:*", "sort", i1 + " desc", "fl", "*,score"); query("q", "*:*", "sort", "n_tl1 asc", "fl", "score"); // test legacy // behavior - // "score"=="*,score" query("q", "*:*", "sort", "n_tl1 desc"); handle.put("maxScore", SKIPVAL); query("q", "{!func}" + i1);// does not expect maxScore. So if it comes // ,ignore it. // JavaBinCodec.writeSolrDocumentList() // is agnostic of request params. handle.remove("maxScore"); query("q", "{!func}" + i1, "fl", "*,score"); // even scores should match // exactly here handle.put("highlighting", UNORDERED); handle.put("response", UNORDERED); handle.put("maxScore", SKIPVAL); query("q", "quick"); query("q", "all", "fl", "id", "start", "0"); query("q", "all", "fl", "foofoofoo", "start", "0"); // no fields in returned // docs query("q", "all", "fl", "id", "start", "100"); handle.put("score", SKIPVAL); query("q", "quick", "fl", "*,score"); query("q", "all", "fl", "*,score", "start", "1"); query("q", "all", "fl", "*,score", "start", "100"); query("q", "now their fox sat had put", "fl", "*,score", "hl", "true", "hl.fl", t1); query("q", "now their fox sat had put", "fl", "foofoofoo", "hl", "true", "hl.fl", t1); query("q", "matchesnothing", "fl", "*,score"); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", -1, "facet.sort", "count"); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", -1, "facet.sort", "count", "facet.mincount", 2); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", -1, "facet.sort", "index"); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", -1, "facet.sort", "index", "facet.mincount", 2); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.limit", 1); query("q", "*:*", "rows", 100, "facet", "true", "facet.query", "quick", "facet.query", "all", "facet.query", "*:*"); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.offset", 1); query("q", "*:*", "rows", 100, "facet", "true", "facet.field", t1, "facet.mincount", 2); // test faceting multiple things at once query("q", "*:*", "rows", 100, "facet", "true", "facet.query", "quick", "facet.query", "all", "facet.query", "*:*", "facet.field", t1); // test filter tagging, facet exclusion, and naming (multi-select facet // support) query("q", "*:*", "rows", 100, "facet", "true", "facet.query", "{!key=myquick}quick", "facet.query", "{!key=myall ex=a}all", "facet.query", "*:*", "facet.field", "{!key=mykey ex=a}" + t1, "facet.field", "{!key=other ex=b}" + t1, "facet.field", "{!key=again ex=a,b}" + t1, "facet.field", t1, "fq", "{!tag=a}id:[1 TO 7]", "fq", "{!tag=b}id:[3 TO 9]"); query("q", "*:*", "facet", "true", "facet.field", "{!ex=t1}SubjectTerms_mfacet", "fq", "{!tag=t1}SubjectTerms_mfacet:(test 1)", "facet.limit", "10", "facet.mincount", "1"); // test field that is valid in schema but missing in all shards query("q", "*:*", "rows", 100, "facet", "true", "facet.field", missingField, "facet.mincount", 2); // test field that is valid in schema and missing in some shards query("q", "*:*", "rows", 100, "facet", "true", "facet.field", oddField, "facet.mincount", 2); query("q", "*:*", "sort", i1 + " desc", "stats", "true", "stats.field", i1); // Try to get better coverage for refinement queries by turning off over // requesting. // This makes it much more likely that we may not get the top facet values // and hence // we turn of that checking. handle.put("facet_fields", SKIPVAL); query("q", "*:*", "rows", 0, "facet", "true", "facet.field", t1, "facet.limit", 5, "facet.shard.limit", 5); // check a complex key name query("q", "*:*", "rows", 0, "facet", "true", "facet.field", "{!key='a b/c \\' \\} foo'}" + t1, "facet.limit", 5, "facet.shard.limit", 5); handle.remove("facet_fields"); query("q", "*:*", "sort", "n_tl1 desc"); // index the same document to two shards and make sure things // don't blow up. // assumes first n clients are first n shards if (clients.size() >= 2) { index(id, 100, i1, 107, t1, "oh no, a duplicate!"); for (int i = 0; i < shardCount; i++) { index_specific(i, id, 100, i1, 107, t1, "oh no, a duplicate!"); } commit(); query("q", "duplicate", "hl", "true", "hl.fl", t1); query("q", "fox duplicate horses", "hl", "true", "hl.fl", t1); query("q", "*:*", "rows", 100); } } private void indexAbunchOfDocs() throws Exception { indexr(id, 2, i1, 50, tlong, 50, t1, "to come to the aid of their country."); indexr(id, 3, i1, 2, tlong, 2, t1, "how now brown cow"); indexr(id, 4, i1, -100, tlong, 101, t1, "the quick fox jumped over the lazy dog"); indexr(id, 5, i1, 500, tlong, 500, t1, "the quick fox jumped way over the lazy dog"); indexr(id, 6, i1, -600, tlong, 600, t1, "humpty dumpy sat on a wall"); indexr(id, 7, i1, 123, tlong, 123, t1, "humpty dumpy had a great fall"); indexr(id, 8, i1, 876, tlong, 876, t1, "all the kings horses and all the kings men"); indexr(id, 9, i1, 7, tlong, 7, t1, "couldn't put humpty together again"); indexr(id, 10, i1, 4321, tlong, 4321, t1, "this too shall pass"); indexr(id, 11, i1, -987, tlong, 987, t1, "An eye for eye only ends up making the whole world blind."); indexr(id, 12, i1, 379, tlong, 379, t1, "Great works are performed, not by strength, but by perseverance."); indexr(id, 13, i1, 232, tlong, 232, t1, "no eggs on wall, lesson learned", oddField, "odd man out"); indexr(id, 14, "SubjectTerms_mfacet", new String[] {"mathematical models", "mathematical analysis"}); indexr(id, 15, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"}); indexr(id, 16, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"}); String[] vals = new String[100]; for (int i = 0; i < 100; i++) { vals[i] = "test " + i; } indexr(id, 17, "SubjectTerms_mfacet", vals); for (int i = 100; i < 150; i++) { indexr(id, i); } } protected void checkShardConsistency(String shard) throws Exception { checkShardConsistency(shard, false); } protected String checkShardConsistency(String shard, boolean verbose) throws Exception { List<SolrServer> solrClients = shardToClient.get(shard); if (solrClients == null) { throw new RuntimeException("shard not found:" + shard + " keys:" + shardToClient.keySet()); } long num = -1; long lastNum = -1; String failMessage = null; if (verbose) System.out.println("check const of " + shard); int cnt = 0; assertEquals( "The client count does not match up with the shard count for slice:" + shard, zkStateReader.getCloudState().getSlice(DEFAULT_COLLECTION, shard) .getShards().size(), solrClients.size()); for (SolrServer client : solrClients) { ZkNodeProps props = clientToInfo.get(new CloudSolrServerClient(client)); if (verbose) System.out.println("client" + cnt++); if (verbose) System.out.println("PROPS:" + props); try { SolrQuery query = new SolrQuery("*:*"); query.set("distrib", false); num = client.query(query).getResults().getNumFound(); } catch (SolrServerException e) { if (verbose) System.out.println("error contacting client: " + e.getMessage() + "\n"); continue; } boolean live = false; String nodeName = props.get(ZkStateReader.NODE_NAME_PROP); if (zkStateReader.getCloudState().liveNodesContain(nodeName)) { live = true; } if (verbose) System.out.println(" live:" + live); if (verbose) System.out.println(" num:" + num + "\n"); boolean active = props.get(ZkStateReader.STATE_PROP).equals( ZkStateReader.ACTIVE); if (active && live) { if (lastNum > -1 && lastNum != num && failMessage == null) { failMessage = shard + " is not consistent, expected:" + lastNum + " and got:" + num; } lastNum = num; } } return failMessage; } protected void checkShardConsistency() throws Exception { checkShardConsistency(true, false); } protected void checkShardConsistency(boolean checkVsControl, boolean verbose) throws Exception { long docs = controlClient.query(new SolrQuery("*:*")).getResults() .getNumFound(); if (verbose) System.out.println("Control Docs:" + docs); updateMappingsFromZk(jettys, clients); Set<String> theShards = shardToClient.keySet(); String failMessage = null; for (String shard : theShards) { String shardFailMessage = checkShardConsistency(shard, verbose); if (shardFailMessage != null && failMessage == null) { failMessage = shardFailMessage; } } if (failMessage != null) { fail(failMessage); } if (checkVsControl) { // now check that the right # are on each shard theShards = shardToClient.keySet(); int cnt = 0; for (String s : theShards) { int times = shardToClient.get(s).size(); for (int i = 0; i < times; i++) { try { SolrServer client = shardToClient.get(s).get(i); ZkNodeProps props = clientToInfo.get(new CloudSolrServerClient( client)); boolean active = props.get(ZkStateReader.STATE_PROP).equals( ZkStateReader.ACTIVE); if (active) { SolrQuery query = new SolrQuery("*:*"); query.set("distrib", false); long results = client.query(query).getResults().getNumFound(); if (verbose) System.out.println(new ZkCoreNodeProps(props) .getCoreUrl() + " : " + results); if (verbose) System.out.println("shard:" + props.get(ZkStateReader.SHARD_ID_PROP)); cnt += results; break; } } catch (SolrServerException e) { // if we have a problem, try the next one if (i == times - 1) { throw e; } } } } SolrQuery q = new SolrQuery("*:*"); long cloudClientDocs = cloudClient.query(q).getResults().getNumFound(); assertEquals( "adding up the # of docs on each shard does not match the control - cloud client returns:" + cloudClientDocs, docs, cnt); } } private SolrServer getClient(String nodeName) { for (CloudSolrServerClient client : clientToInfo.keySet()) { if (client.shardName.equals(nodeName)) { return client.client; } } return null; } protected void assertDocCounts(boolean verbose) throws Exception { // TODO: as we create the clients, we should build a map from shard to // node/client // and node/client to shard? if (verbose) System.out.println("control docs:" + controlClient.query(new SolrQuery("*:*")).getResults().getNumFound() + "\n\n"); long controlCount = controlClient.query(new SolrQuery("*:*")).getResults() .getNumFound(); // do some really inefficient mapping... ZkStateReader zk = new ZkStateReader(zkServer.getZkAddress(), 10000, AbstractZkTestCase.TIMEOUT); Map<String,Slice> slices = null; CloudState cloudState; try { zk.createClusterStateWatchersAndUpdate(); cloudState = zk.getCloudState(); slices = cloudState.getSlices(DEFAULT_COLLECTION); } finally { zk.close(); } if (slices == null) { throw new RuntimeException("Could not find collection " + DEFAULT_COLLECTION + " in " + cloudState.getCollections()); } for (SolrServer client : clients) { for (Map.Entry<String,Slice> slice : slices.entrySet()) { Map<String,ZkNodeProps> theShards = slice.getValue().getShards(); for (Map.Entry<String,ZkNodeProps> shard : theShards.entrySet()) { String shardName = new URI( ((CommonsHttpSolrServer) client).getBaseURL()).getPort() + "_solr_"; if (verbose && shard.getKey().endsWith(shardName)) { System.out.println("shard:" + slice.getKey()); System.out.println(shard.getValue()); } } } long count = 0; String currentState = clientToInfo.get(new CloudSolrServerClient(client)) .get(ZkStateReader.STATE_PROP); if (currentState != null && currentState.equals(ZkStateReader.ACTIVE)) { SolrQuery query = new SolrQuery("*:*"); query.set("distrib", false); count = client.query(query).getResults().getNumFound(); } if (verbose) System.out.println("client docs:" + count + "\n\n"); } if (verbose) System.out.println("control docs:" + controlClient.query(new SolrQuery("*:*")).getResults().getNumFound() + "\n\n"); SolrQuery query = new SolrQuery("*:*"); assertEquals("Doc Counts do not add up", controlCount, cloudClient.query(query).getResults().getNumFound()); } @Override protected QueryResponse queryServer(ModifiableSolrParams params) throws SolrServerException { if (r.nextBoolean()) params.set("collection", DEFAULT_COLLECTION); QueryResponse rsp = cloudClient.query(params); return rsp; } class StopableIndexingThread extends Thread { private volatile boolean stop = false; protected final int startI; protected final List<Integer> deletes = new ArrayList<Integer>(); protected final AtomicInteger fails = new AtomicInteger(); protected boolean doDeletes; public StopableIndexingThread(int startI, boolean doDeletes) { super("StopableIndexingThread"); this.startI = startI; this.doDeletes = doDeletes; setDaemon(true); } @Override public void run() { int i = startI; int numDeletes = 0; int numAdds = 0; while (true && !stop) { ++i; if (doDeletes && random.nextBoolean() && deletes.size() > 0) { Integer delete = deletes.remove(0); try { numDeletes++; controlClient.deleteById(Integer.toString(delete)); cloudClient.deleteById(Integer.toString(delete)); } catch (Exception e) { System.err.println("REQUEST FAILED:"); e.printStackTrace(); fails.incrementAndGet(); } } try { numAdds++; indexr(id, i, i1, 50, tlong, 50, t1, "to come to the aid of their country."); } catch (Exception e) { System.err.println("REQUEST FAILED:"); e.printStackTrace(); fails.incrementAndGet(); } if (doDeletes && random.nextBoolean()) { deletes.add(i); } } System.err.println("added docs:" + numAdds + " with " + fails + " fails" + " deletes:" + numDeletes); } public void safeStop() { stop = true; } public int getFails() { return fails.get(); } }; @Override @After public void tearDown() throws Exception { if (VERBOSE) { super.printLayout(); } ((CommonsHttpSolrServer) controlClient).shutdown(); if (cloudClient != null) { cloudClient.close(); } if (zkStateReader != null) { zkStateReader.close(); } super.tearDown(); System.clearProperty("zkHost"); } protected void commit() throws Exception { controlClient.commit(); cloudClient.commit(); } protected void destroyServers() throws Exception { ChaosMonkey.stop(controlJetty); for (JettySolrRunner jetty : jettys) { try { ChaosMonkey.stop(jetty); } catch (Exception e) { log.error("", e); } } clients.clear(); jettys.clear(); } protected SolrServer createNewSolrServer(int port) { try { // setup the server... String url = "http://localhost:" + port + context + "/" + DEFAULT_COLLECTION; CommonsHttpSolrServer s = new CommonsHttpSolrServer(url); s.setConnectionTimeout(100); // 1/10th sec s.setSoTimeout(30000); s.setDefaultMaxConnectionsPerHost(100); s.setMaxTotalConnections(100); return s; } catch (Exception ex) { throw new RuntimeException(ex); } } }
if the test fails, print out the zk state git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1235995 13f79535-47bb-0310-9956-ffa450edef68
core/src/test/org/apache/solr/cloud/FullSolrCloudTest.java
if the test fails, print out the zk state
<ide><path>ore/src/test/org/apache/solr/cloud/FullSolrCloudTest.java <ide> */ <ide> @Override <ide> public void doTest() throws Exception { <del> handle.clear(); <del> handle.put("QTime", SKIPVAL); <del> handle.put("timestamp", SKIPVAL); <del> <del> indexr(id, 1, i1, 100, tlong, 100, t1, "now is the time for all good men", <del> "foo_f", 1.414f, "foo_b", "true", "foo_d", 1.414d); <del> <del> // make sure we are in a steady state... <del> waitForRecoveriesToFinish(false); <del> <del> commit(); <del> <del> assertDocCounts(false); <del> <del> indexAbunchOfDocs(); <del> <del> commit(); <del> <del> assertDocCounts(VERBOSE); <del> checkQueries(); <del> <del> assertDocCounts(VERBOSE); <del> <del> query("q", "*:*", "sort", "n_tl1 desc"); <del> <del> brindDownShardIndexSomeDocsAndRecover(); <del> <del> query("q", "*:*", "sort", "n_tl1 desc"); <del> <del> // test adding another replica to a shard - it should do a <del> // recovery/replication to pick up the index from the leader <del> addNewReplica(); <del> <del> long docId = testUpdateAndDelete(); <del> <del> // index a bad doc... <add> boolean testFinished = false; <ide> try { <del> indexr(t1, "a doc with no id"); <del> fail("this should fail"); <del> } catch (SolrException e) { <del> // expected <del> } <del> <del> // TODO: bring this to it's own method? <del> // try indexing to a leader that has no replicas up <del> ZkNodeProps leaderProps = zkStateReader.getLeaderProps(DEFAULT_COLLECTION, <del> SHARD2); <del> <del> String nodeName = leaderProps.get(ZkStateReader.NODE_NAME_PROP); <del> chaosMonkey.stopShardExcept(SHARD2, nodeName); <del> <del> SolrServer client = getClient(nodeName); <del> <del> index_specific(client, "id", docId + 1, t1, "what happens here?"); <del> <del> // expire a session... <del> CloudJettyRunner cloudJetty = shardToJetty.get("shard1").get(0); <del> chaosMonkey.expireSession(cloudJetty.jetty); <del> <del> indexr("id", docId + 1, t1, "slip this doc in"); <del> <del> waitForRecoveriesToFinish(false); <del> <del> checkShardConsistency("shard1"); <add> handle.clear(); <add> handle.put("QTime", SKIPVAL); <add> handle.put("timestamp", SKIPVAL); <add> <add> indexr(id, 1, i1, 100, tlong, 100, t1, <add> "now is the time for all good men", "foo_f", 1.414f, "foo_b", "true", <add> "foo_d", 1.414d); <add> <add> // make sure we are in a steady state... <add> waitForRecoveriesToFinish(false); <add> <add> commit(); <add> <add> assertDocCounts(false); <add> <add> indexAbunchOfDocs(); <add> <add> commit(); <add> <add> assertDocCounts(VERBOSE); <add> checkQueries(); <add> <add> assertDocCounts(VERBOSE); <add> <add> query("q", "*:*", "sort", "n_tl1 desc"); <add> <add> brindDownShardIndexSomeDocsAndRecover(); <add> <add> query("q", "*:*", "sort", "n_tl1 desc"); <add> <add> // test adding another replica to a shard - it should do a <add> // recovery/replication to pick up the index from the leader <add> addNewReplica(); <add> <add> long docId = testUpdateAndDelete(); <add> <add> // index a bad doc... <add> try { <add> indexr(t1, "a doc with no id"); <add> fail("this should fail"); <add> } catch (SolrException e) { <add> // expected <add> } <add> <add> // TODO: bring this to it's own method? <add> // try indexing to a leader that has no replicas up <add> ZkNodeProps leaderProps = zkStateReader.getLeaderProps( <add> DEFAULT_COLLECTION, SHARD2); <add> <add> String nodeName = leaderProps.get(ZkStateReader.NODE_NAME_PROP); <add> chaosMonkey.stopShardExcept(SHARD2, nodeName); <add> <add> SolrServer client = getClient(nodeName); <add> <add> index_specific(client, "id", docId + 1, t1, "what happens here?"); <add> <add> // expire a session... <add> CloudJettyRunner cloudJetty = shardToJetty.get("shard1").get(0); <add> chaosMonkey.expireSession(cloudJetty.jetty); <add> <add> indexr("id", docId + 1, t1, "slip this doc in"); <add> <add> waitForRecoveriesToFinish(false); <add> <add> checkShardConsistency("shard1"); <add> <add> testFinished = true; <add> } finally { <add> if (!testFinished) { <add> printLayout(); <add> } <add> } <ide> <ide> } <ide>
Java
apache-2.0
cd4f3001ede95e3439a5c6164bb515f8a83eabe3
0
lime-company/powerauth-webflow,lime-company/powerauth-webflow,lime-company/powerauth-webflow
/* * Copyright 2021 Wultra s.r.o. * * 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 io.getlime.security.powerauth.lib.nextstep.model.response; import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.OtpStatus; import lombok.Data; import javax.validation.constraints.NotNull; /** * Response object used for creating an OTP. * * @author Roman Strobl, [email protected] */ @Data public class CreateOtpResponse { @NotNull private String otpName; private String userId; @NotNull private String otpId; @NotNull private String otpValue; @NotNull private OtpStatus otpStatus; }
powerauth-nextstep-model/src/main/java/io/getlime/security/powerauth/lib/nextstep/model/response/CreateOtpResponse.java
/* * Copyright 2021 Wultra s.r.o. * * 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 io.getlime.security.powerauth.lib.nextstep.model.response; import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.OtpStatus; import lombok.Data; import javax.validation.constraints.NotNull; /** * Response object used for creating an OTP. * * @author Roman Strobl, [email protected] */ @Data public class CreateOtpResponse { @NotNull private String otpName; @NotNull private String userId; @NotNull private String otpId; @NotNull private String otpValue; @NotNull private OtpStatus otpStatus; }
Allow OTP creation without user ID
powerauth-nextstep-model/src/main/java/io/getlime/security/powerauth/lib/nextstep/model/response/CreateOtpResponse.java
Allow OTP creation without user ID
<ide><path>owerauth-nextstep-model/src/main/java/io/getlime/security/powerauth/lib/nextstep/model/response/CreateOtpResponse.java <ide> <ide> @NotNull <ide> private String otpName; <del> @NotNull <ide> private String userId; <ide> @NotNull <ide> private String otpId;
Java
apache-2.0
61798faf627e6fd97a909fd6115c1722b5d0ab59
0
jedouard98/codeu_summer_2017,jedouard98/codeu_summer_2017
// Copyright 2017 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 codeu.chat.server; import java.util.Comparator; import java.util.HashMap; import codeu.chat.common.ConversationHeader; import codeu.chat.common.ConversationPayload; import codeu.chat.common.LinearUuidGenerator; import codeu.chat.common.Message; import codeu.chat.common.User; import codeu.chat.util.Time; import codeu.chat.util.Uuid; import codeu.chat.util.store.Store; import codeu.chat.util.store.StoreAccessor; public final class Model { private static final Comparator<Uuid> UUID_COMPARE = new Comparator<Uuid>() { @Override public int compare(Uuid a, Uuid b) { if (a == b) { return 0; } if (a == null && b != null) { return -1; } if (a != null && b == null) { return 1; } final int order = Integer.compare(a.id(), b.id()); return order == 0 ? compare(a.root(), b.root()) : order; } }; private static final Comparator<Time> TIME_COMPARE = new Comparator<Time>() { @Override public int compare(Time a, Time b) { return a.compareTo(b); } }; private static final Comparator<String> STRING_COMPARE = String.CASE_INSENSITIVE_ORDER; private final Store<Uuid, User> userById = new Store<>(UUID_COMPARE); private final Store<Time, User> userByTime = new Store<>(TIME_COMPARE); private final Store<String, User> userByText = new Store<>(STRING_COMPARE); private final Store<Uuid, ConversationHeader> conversationById = new Store<>(UUID_COMPARE); private final Store<Time, ConversationHeader> conversationByTime = new Store<>(TIME_COMPARE); private final Store<String, ConversationHeader> conversationByText = new Store<>(STRING_COMPARE); private final Store<Uuid, ConversationPayload> conversationPayloadById = new Store<>(UUID_COMPARE); private final Store<Uuid, Message> messageById = new Store<>(UUID_COMPARE); private final Store<Time, Message> messageByTime = new Store<>(TIME_COMPARE); private final Store<String, Message> messageByText = new Store<>(STRING_COMPARE); // TODO: remove stucture all together to mimick UserFollowing Class implementation for users private final HashMap<Uuid, HashMap<Uuid, Integer>> userConversationTracking = new HashMap<Uuid, HashMap<Uuid, Integer>>(); private final String version = "1.1"; private final Time serverStartTime = Time.now(); public int togglePermission(Uuid user, Uuid targetUser, int permission, Uuid conversation) { ConversationHeader foundConversation = conversationById().first(conversation); int sourcePerm = foundConversation.getPermission(user); int targetPerm = foundConversation.getPermission(targetUser); targetPerm = (targetPerm == -1) ? 0 : targetPerm; int permissionDiff = permission ^ targetPerm & 0b0111; if (((permissionDiff & ConversationHeader.ADMIN_PERM) >= 1) && !ConversationHeader.isOwner(sourcePerm)) { return -1; } if (((permissionDiff & ConversationHeader.MEMBER_PERM) >= 1) && !(ConversationHeader.isOwner(sourcePerm) || ConversationHeader.isAdmin(sourcePerm))) { return -1; } foundConversation.togglePermission(targetUser, (byte) permission); return foundConversation.getPermission(targetUser); } public void add(User user) { userConversationTracking.put(user.id, new HashMap<Uuid, Integer>()); userById.insert(user.id, user); userByTime.insert(user.creation, user); userByText.insert(user.name, user); } public String statusUpdate(Uuid user) { StringBuilder status = new StringBuilder(); HashMap<Uuid, Integer> userConversationSize = userConversationTracking.get(user); for (Uuid conversation : userConversationSize.keySet()) { ConversationHeader convo = conversationById().first(conversation); String title = convo.title; int newMessages = convo.size - userConversationSize.get(conversation); String line = String.format("CONVERSATION %s: You have %d new messages!\n", title, newMessages); status.append(line); userConversationTracking.get(user).put(conversation, convo.size); } User userA = userById().first(user); status.append(userA.statusUpdate()); return status.toString(); } public void unfollowUser(User userA, User userB) { User user1 = userById().first(userA.id); User user2 = userById().first(userB.id); User.unfollow(user1, user2); } public void followUser(User userA, User userB) { User user1 = userById().first(userA.id); User user2 = userById().first(userB.id); User.follow(user1, user2); } public void unfollowConversation(Uuid user, Uuid conversation) { userConversationTracking.get(user).remove(conversation); } public void followConversation(Uuid user, Uuid conversation) { // Put into hashmap the conversation and what the size of the conversation // is for the user at the time of following ConversationHeader convo = conversationById().first(conversation); userConversationTracking.get(user).put(conversation, convo.size); } public long uptime() { return Time.now().inMs() - serverStartTime.inMs(); } public String version() { return version; } public StoreAccessor<Uuid, User> userById() { return userById; } public StoreAccessor<Time, User> userByTime() { return userByTime; } public StoreAccessor<String, User> userByText() { return userByText; } public void add(User user, ConversationHeader conversation) { user.addCreatedConversation(conversation); conversationById.insert(conversation.id, conversation); conversationByTime.insert(conversation.creation, conversation); conversationByText.insert(conversation.title, conversation); conversationPayloadById.insert(conversation.id, new ConversationPayload(conversation.id)); } public StoreAccessor<Uuid, ConversationHeader> conversationById() { return conversationById; } public StoreAccessor<Time, ConversationHeader> conversationByTime() { return conversationByTime; } public StoreAccessor<String, ConversationHeader> conversationByText() { return conversationByText; } public StoreAccessor<Uuid, ConversationPayload> conversationPayloadById() { return conversationPayloadById; } public void add(Message message) { messageById.insert(message.id, message); messageByTime.insert(message.creation, message); messageByText.insert(message.content, message); } public StoreAccessor<Uuid, Message> messageById() { return messageById; } public StoreAccessor<Time, Message> messageByTime() { return messageByTime; } public StoreAccessor<String, Message> messageByText() { return messageByText; } }
src/codeu/chat/server/Model.java
// Copyright 2017 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 codeu.chat.server; import java.util.Comparator; import java.util.HashMap; import codeu.chat.common.ConversationHeader; import codeu.chat.common.ConversationPayload; import codeu.chat.common.LinearUuidGenerator; import codeu.chat.common.Message; import codeu.chat.common.User; import codeu.chat.util.Time; import codeu.chat.util.Uuid; import codeu.chat.util.store.Store; import codeu.chat.util.store.StoreAccessor; public final class Model { private static final Comparator<Uuid> UUID_COMPARE = new Comparator<Uuid>() { @Override public int compare(Uuid a, Uuid b) { if (a == b) { return 0; } if (a == null && b != null) { return -1; } if (a != null && b == null) { return 1; } final int order = Integer.compare(a.id(), b.id()); return order == 0 ? compare(a.root(), b.root()) : order; } }; private static final Comparator<Time> TIME_COMPARE = new Comparator<Time>() { @Override public int compare(Time a, Time b) { return a.compareTo(b); } }; private static final Comparator<String> STRING_COMPARE = String.CASE_INSENSITIVE_ORDER; private final Store<Uuid, User> userById = new Store<>(UUID_COMPARE); private final Store<Time, User> userByTime = new Store<>(TIME_COMPARE); private final Store<String, User> userByText = new Store<>(STRING_COMPARE); private final Store<Uuid, ConversationHeader> conversationById = new Store<>(UUID_COMPARE); private final Store<Time, ConversationHeader> conversationByTime = new Store<>(TIME_COMPARE); private final Store<String, ConversationHeader> conversationByText = new Store<>(STRING_COMPARE); private final Store<Uuid, ConversationPayload> conversationPayloadById = new Store<>(UUID_COMPARE); private final Store<Uuid, Message> messageById = new Store<>(UUID_COMPARE); private final Store<Time, Message> messageByTime = new Store<>(TIME_COMPARE); private final Store<String, Message> messageByText = new Store<>(STRING_COMPARE); // TODO: remove stucture all together to mimick UserFollowing Class implementation for users private final HashMap<Uuid, HashMap<Uuid, Integer>> userConversationTracking = new HashMap<Uuid, HashMap<Uuid, Integer>>(); private final String version = "1.1"; private final Time serverStartTime = Time.now(); public void togglePermission(Uuid user, Uuid userToBeChanged, int permission, Uuid conversation) { ConversationHeader foundConversation = conversationById().first(conversation); if (foundConversation.getPermission(user) > 1) { System.out.println("The user's permission before " + foundConversation.getPermission(userToBeChanged)); foundConversation.togglePermission(userToBeChanged, (byte) permission); System.out.println("This is the user's permission after" + foundConversation.getPermission(userToBeChanged)); } } public void add(User user) { userConversationTracking.put(user.id, new HashMap<Uuid, Integer>()); userById.insert(user.id, user); userByTime.insert(user.creation, user); userByText.insert(user.name, user); } public String statusUpdate(Uuid user) { StringBuilder status = new StringBuilder(); HashMap<Uuid, Integer> userConversationSize = userConversationTracking.get(user); for (Uuid conversation : userConversationSize.keySet()) { ConversationHeader convo = conversationById().first(conversation); String title = convo.title; int newMessages = convo.size - userConversationSize.get(conversation); String line = String.format("CONVERSATION %s: You have %d new messages!\n", title, newMessages); status.append(line); userConversationTracking.get(user).put(conversation, convo.size); } User userA = userById().first(user); status.append(userA.statusUpdate()); return status.toString(); } public void unfollowUser(User userA, User userB) { User user1 = userById().first(userA.id); User user2 = userById().first(userB.id); User.unfollow(user1, user2); } public void followUser(User userA, User userB) { User user1 = userById().first(userA.id); User user2 = userById().first(userB.id); User.follow(user1, user2); } public void unfollowConversation(Uuid user, Uuid conversation) { userConversationTracking.get(user).remove(conversation); } public void followConversation(Uuid user, Uuid conversation) { // Put into hashmap the conversation and what the size of the conversation // is for the user at the time of following ConversationHeader convo = conversationById().first(conversation); userConversationTracking.get(user).put(conversation, convo.size); } public long uptime() { return Time.now().inMs() - serverStartTime.inMs(); } public String version() { return version; } public StoreAccessor<Uuid, User> userById() { return userById; } public StoreAccessor<Time, User> userByTime() { return userByTime; } public StoreAccessor<String, User> userByText() { return userByText; } public void add(User user, ConversationHeader conversation) { user.addCreatedConversation(conversation); conversationById.insert(conversation.id, conversation); conversationByTime.insert(conversation.creation, conversation); conversationByText.insert(conversation.title, conversation); conversationPayloadById.insert(conversation.id, new ConversationPayload(conversation.id)); } public StoreAccessor<Uuid, ConversationHeader> conversationById() { return conversationById; } public StoreAccessor<Time, ConversationHeader> conversationByTime() { return conversationByTime; } public StoreAccessor<String, ConversationHeader> conversationByText() { return conversationByText; } public StoreAccessor<Uuid, ConversationPayload> conversationPayloadById(Uuid user, Uuid conversation) throws Exception { ConversationHeader conversationServer = conversationById.first(conversation); System.out.println("This is the user's permission: " + conversationServer.getPermission(user)); if (conversationServer.getPermission(user) == -1) { throw new Exception("You do not have access to this conversation."); } return conversationPayloadById; } public void add(Message message) { messageById.insert(message.id, message); messageByTime.insert(message.creation, message); messageByText.insert(message.content, message); } public StoreAccessor<Uuid, Message> messageById() { return messageById; } public StoreAccessor<Time, Message> messageByTime() { return messageByTime; } public StoreAccessor<String, Message> messageByText() { return messageByText; } }
Updated Model with last feature
src/codeu/chat/server/Model.java
Updated Model with last feature
<ide><path>rc/codeu/chat/server/Model.java <ide> private final String version = "1.1"; <ide> private final Time serverStartTime = Time.now(); <ide> <del> public void togglePermission(Uuid user, Uuid userToBeChanged, int permission, Uuid conversation) { <add> public int togglePermission(Uuid user, Uuid targetUser, int permission, Uuid conversation) { <ide> ConversationHeader foundConversation = conversationById().first(conversation); <del> if (foundConversation.getPermission(user) > 1) { <del> System.out.println("The user's permission before " + foundConversation.getPermission(userToBeChanged)); <del> foundConversation.togglePermission(userToBeChanged, (byte) permission); <del> System.out.println("This is the user's permission after" + foundConversation.getPermission(userToBeChanged)); <del> } <del> } <add> int sourcePerm = foundConversation.getPermission(user); <add> <add> int targetPerm = foundConversation.getPermission(targetUser); <add> targetPerm = (targetPerm == -1) ? 0 : targetPerm; <add> int permissionDiff = permission ^ targetPerm & 0b0111; <add> <add> if (((permissionDiff & ConversationHeader.ADMIN_PERM) >= 1) && !ConversationHeader.isOwner(sourcePerm)) { <add> return -1; <add> } <add> if (((permissionDiff & ConversationHeader.MEMBER_PERM) >= 1) && !(ConversationHeader.isOwner(sourcePerm) || ConversationHeader.isAdmin(sourcePerm))) { <add> return -1; <add> } <add> foundConversation.togglePermission(targetUser, (byte) permission); <add> return foundConversation.getPermission(targetUser); <add> } <add> <ide> public void add(User user) { <ide> userConversationTracking.put(user.id, new HashMap<Uuid, Integer>()); <ide> userById.insert(user.id, user); <ide> return conversationByText; <ide> } <ide> <del> public StoreAccessor<Uuid, ConversationPayload> conversationPayloadById(Uuid user, Uuid conversation) throws Exception { <del> ConversationHeader conversationServer = conversationById.first(conversation); <del> System.out.println("This is the user's permission: " + conversationServer.getPermission(user)); <del> if (conversationServer.getPermission(user) == -1) { <del> throw new Exception("You do not have access to this conversation."); <del> } <add> public StoreAccessor<Uuid, ConversationPayload> conversationPayloadById() { <ide> return conversationPayloadById; <ide> } <ide>
Java
apache-2.0
4062da14e866fde402b2f31116c58ba9710164ae
0
AndreasAbdi/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,mduerig/jackrabbit-oak,francescomari/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,chetanmeh/jackrabbit-oak,code-distillery/jackrabbit-oak,rombert/jackrabbit-oak,kwin/jackrabbit-oak,alexkli/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,meggermo/jackrabbit-oak,afilimonov/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexkli/jackrabbit-oak,joansmith/jackrabbit-oak,stillalex/jackrabbit-oak,meggermo/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexparvulescu/jackrabbit-oak,kwin/jackrabbit-oak,francescomari/jackrabbit-oak,davidegiannella/jackrabbit-oak,yesil/jackrabbit-oak,meggermo/jackrabbit-oak,ieb/jackrabbit-oak,francescomari/jackrabbit-oak,alexkli/jackrabbit-oak,mduerig/jackrabbit-oak,alexkli/jackrabbit-oak,ieb/jackrabbit-oak,joansmith/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,yesil/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,catholicon/jackrabbit-oak,ieb/jackrabbit-oak,catholicon/jackrabbit-oak,anchela/jackrabbit-oak,rombert/jackrabbit-oak,tripodsan/jackrabbit-oak,alexkli/jackrabbit-oak,mduerig/jackrabbit-oak,tripodsan/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,ieb/jackrabbit-oak,stillalex/jackrabbit-oak,chetanmeh/jackrabbit-oak,catholicon/jackrabbit-oak,code-distillery/jackrabbit-oak,kwin/jackrabbit-oak,anchela/jackrabbit-oak,catholicon/jackrabbit-oak,kwin/jackrabbit-oak,tripodsan/jackrabbit-oak,alexparvulescu/jackrabbit-oak,yesil/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,chetanmeh/jackrabbit-oak,tripodsan/jackrabbit-oak,bdelacretaz/jackrabbit-oak,meggermo/jackrabbit-oak,catholicon/jackrabbit-oak,joansmith/jackrabbit-oak,stillalex/jackrabbit-oak,leftouterjoin/jackrabbit-oak,bdelacretaz/jackrabbit-oak,davidegiannella/jackrabbit-oak,joansmith/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexparvulescu/jackrabbit-oak,leftouterjoin/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,bdelacretaz/jackrabbit-oak,afilimonov/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,francescomari/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,bdelacretaz/jackrabbit-oak,alexparvulescu/jackrabbit-oak,rombert/jackrabbit-oak,davidegiannella/jackrabbit-oak,joansmith/jackrabbit-oak,yesil/jackrabbit-oak,afilimonov/jackrabbit-oak,kwin/jackrabbit-oak,code-distillery/jackrabbit-oak,mduerig/jackrabbit-oak,davidegiannella/jackrabbit-oak,francescomari/jackrabbit-oak,davidegiannella/jackrabbit-oak,stillalex/jackrabbit-oak,chetanmeh/jackrabbit-oak,meggermo/jackrabbit-oak,leftouterjoin/jackrabbit-oak,mduerig/jackrabbit-oak,afilimonov/jackrabbit-oak,code-distillery/jackrabbit-oak,leftouterjoin/jackrabbit-oak,stillalex/jackrabbit-oak,anchela/jackrabbit-oak,chetanmeh/jackrabbit-oak,rombert/jackrabbit-oak,AndreasAbdi/jackrabbit-oak
/* * 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 org.apache.jackrabbit.oak.plugins.nodetype.constraint; import javax.jcr.PropertyType; import javax.jcr.Value; import com.google.common.base.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class Constraints { private static final Logger log = LoggerFactory.getLogger(Constraints.class); private Constraints() { } public static Predicate<Value> valueConstraint(int type, String constraint) { switch (type) { case PropertyType.STRING: return new StringConstraint(constraint); case PropertyType.BINARY: return new BinaryConstraint(constraint); case PropertyType.LONG: return new LongConstraint(constraint); case PropertyType.DOUBLE: return new DoubleConstraint(constraint); case PropertyType.DATE: return new DateConstraint(constraint); case PropertyType.BOOLEAN: return new BooleanConstraint(constraint); case PropertyType.NAME: return new NameConstraint(constraint); case PropertyType.PATH: return new PathConstraint(constraint); case PropertyType.REFERENCE: return new ReferenceConstraint(constraint); case PropertyType.WEAKREFERENCE: return new ReferenceConstraint(constraint); case PropertyType.URI: return new StringConstraint(constraint); case PropertyType.DECIMAL: return new DecimalConstraint(constraint); default: String msg = "Invalid property type: " + type; log.warn(msg); throw new IllegalArgumentException(msg); } } }
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/nodetype/constraint/Constraints.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 org.apache.jackrabbit.oak.plugins.nodetype.constraint; import javax.jcr.PropertyType; import javax.jcr.Value; import com.google.common.base.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Constraints { private static final Logger log = LoggerFactory.getLogger(Constraints.class); private Constraints() { } public static Predicate<Value> valueConstraint(int type, String constraint) { switch (type) { case PropertyType.STRING: return new StringConstraint(constraint); case PropertyType.BINARY: return new BinaryConstraint(constraint); case PropertyType.LONG: return new LongConstraint(constraint); case PropertyType.DOUBLE: return new DoubleConstraint(constraint); case PropertyType.DATE: return new DateConstraint(constraint); case PropertyType.BOOLEAN: return new BooleanConstraint(constraint); case PropertyType.NAME: return new NameConstraint(constraint); case PropertyType.PATH: return new PathConstraint(constraint); case PropertyType.REFERENCE: return new ReferenceConstraint(constraint); case PropertyType.WEAKREFERENCE: return new ReferenceConstraint(constraint); case PropertyType.URI: return new StringConstraint(constraint); case PropertyType.DECIMAL: return new DecimalConstraint(constraint); default: String msg = "Invalid property type: " + type; log.warn(msg); throw new IllegalArgumentException(msg); } } }
make utility class final git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1459804 13f79535-47bb-0310-9956-ffa450edef68
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/nodetype/constraint/Constraints.java
make utility class final
<ide><path>ak-core/src/main/java/org/apache/jackrabbit/oak/plugins/nodetype/constraint/Constraints.java <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <del>public class Constraints { <add>public final class Constraints { <ide> private static final Logger log = LoggerFactory.getLogger(Constraints.class); <ide> <ide> private Constraints() {
Java
bsd-2-clause
254dd4eb5a7e2580370c6cb3f8ecedbc70ee9191
0
joshhartigan/hex-picker
import javax.swing.*; import java.awt.*; class HpComponent extends JComponent { private Color color; HpComponent() { color = new Color(0, 0, 0); } public void setColor(Color color) { this.color = color; } public void paint(Graphics g) { g.setColor(color); int width = 200; int height = 200; g.fillRect(0, 0, width / 2, height); } } public class HexPicker { public static void main(String[] args) { JFrame window = new JFrame("Hex Picker 3000"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setLayout(new GridLayout()); HpComponent hp = new HpComponent(); window.getContentPane().add(hp); TextField tf = new TextField(); window.getContentPane().add(tf); int width = 200; int height = 200; window.setSize(width, height); window.setVisible(true); } }
java/src/HexPicker.java
import javax.swing.*; import java.awt.*; class HpWindow extends JComponent { public void paint(Graphics g) { // testing code { g.setColor(new Color(34, 209, 24)); g.fillRect(10, 10, 200, 200); // } } } public class HexPicker { public static void main(String[] args) { JFrame window = new JFrame("Hex Picker 3000"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setBounds(30, 30, 300, 300); window.getContentPane().add(new HpWindow()); window.setVisible(true); } }
finalise layout
java/src/HexPicker.java
finalise layout
<ide><path>ava/src/HexPicker.java <ide> import javax.swing.*; <ide> import java.awt.*; <ide> <del>class HpWindow extends JComponent { <add>class HpComponent extends JComponent { <add> private Color color; <add> <add> HpComponent() { <add> color = new Color(0, 0, 0); <add> } <add> <add> public void setColor(Color color) { <add> this.color = color; <add> } <add> <ide> public void paint(Graphics g) { <del> // testing code { <del> g.setColor(new Color(34, 209, 24)); <del> g.fillRect(10, 10, 200, 200); <del> // } <add> g.setColor(color); <add> <add> int width = 200; <add> int height = 200; <add> <add> g.fillRect(0, 0, width / 2, height); <ide> } <ide> } <ide> <ide> <ide> JFrame window = new JFrame("Hex Picker 3000"); <ide> window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); <del> window.setBounds(30, 30, 300, 300); <del> window.getContentPane().add(new HpWindow()); <add> window.setLayout(new GridLayout()); <add> <add> HpComponent hp = new HpComponent(); <add> window.getContentPane().add(hp); <add> <add> TextField tf = new TextField(); <add> window.getContentPane().add(tf); <add> <add> int width = 200; <add> int height = 200; <add> <add> window.setSize(width, height); <ide> window.setVisible(true); <ide> <ide> }
Java
artistic-2.0
5c27d01c9d1f02121ce38865488c2a0279a32f14
0
Liahim85/SaltyMod_1.7.10
package ru.liahim.saltmod; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ru.liahim.saltmod.common.CommonProxy; import ru.liahim.saltmod.init.ModBlocks; import ru.liahim.saltmod.init.ModItems; import ru.liahim.saltmod.init.SaltConfig; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @Mod(modid=SaltMod.MODID, name=SaltMod.NAME, version=SaltMod.VERSION) public class SaltMod { public static final String MODID = "SaltMod"; public static final String NAME = "Salty Mod"; public static final String VERSION = "1.8.a"; public static final Logger logger = LogManager.getLogger(NAME); public static SaltConfig config; @Mod.Instance(MODID) public static SaltMod instance; @SidedProxy(clientSide = "ru.liahim.saltmod.common.ClientProxy", serverSide = "ru.liahim.saltmod.common.CommonProxy") public static CommonProxy proxy; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { logger.info("Starting SaltMod PreInitialization"); config = new SaltConfig(event.getSuggestedConfigurationFile()); config.preInit(); ModItems.init(); ModBlocks.init(); proxy.preInit(event); } @Mod.EventHandler public void init(FMLInitializationEvent event) { config.init(); proxy.init(event); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { config.postInit(); proxy.postInit(event); } }
java/ru/liahim/saltmod/SaltMod.java
package ru.liahim.saltmod; import ru.liahim.saltmod.common.CommonProxy; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; @Mod(modid=SaltMod.MODID, name=SaltMod.NAME, version=SaltMod.VERSION) public class SaltMod { public static final String MODID = "SaltMod"; public static final String NAME = "Salty Mod"; public static final String VERSION = "1.7.d"; @Instance(MODID) public static SaltMod instance; @SidedProxy(clientSide="ru.liahim.saltmod.client.ClientProxy", serverSide="ru.liahim.saltmod.common.CommonProxy") public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent event) { this.proxy.preInit(event); } @EventHandler public void init(FMLInitializationEvent event) { this.proxy.init(event); } @EventHandler public void postInit(FMLPostInitializationEvent event) { this.proxy.postInit(event); } @EventHandler public void serverStarting(FMLServerStartingEvent event){} }
Added files via upload
java/ru/liahim/saltmod/SaltMod.java
Added files via upload
<ide><path>ava/ru/liahim/saltmod/SaltMod.java <ide> package ru.liahim.saltmod; <ide> <add>import org.apache.logging.log4j.LogManager; <add>import org.apache.logging.log4j.Logger; <add> <ide> import ru.liahim.saltmod.common.CommonProxy; <add>import ru.liahim.saltmod.init.ModBlocks; <add>import ru.liahim.saltmod.init.ModItems; <add>import ru.liahim.saltmod.init.SaltConfig; <ide> import cpw.mods.fml.common.Mod; <del>import cpw.mods.fml.common.Mod.EventHandler; <del>import cpw.mods.fml.common.Mod.Instance; <ide> import cpw.mods.fml.common.SidedProxy; <ide> import cpw.mods.fml.common.event.FMLInitializationEvent; <ide> import cpw.mods.fml.common.event.FMLPostInitializationEvent; <ide> import cpw.mods.fml.common.event.FMLPreInitializationEvent; <del>import cpw.mods.fml.common.event.FMLServerStartingEvent; <ide> <ide> @Mod(modid=SaltMod.MODID, name=SaltMod.NAME, version=SaltMod.VERSION) <ide> <ide> public class SaltMod { <del> <add> <ide> public static final String MODID = "SaltMod"; <ide> public static final String NAME = "Salty Mod"; <del> public static final String VERSION = "1.7.d"; <del> <del> @Instance(MODID) <add> public static final String VERSION = "1.8.a"; <add> public static final Logger logger = LogManager.getLogger(NAME); <add> <add> public static SaltConfig config; <add> <add> @Mod.Instance(MODID) <ide> public static SaltMod instance; <ide> <del> @SidedProxy(clientSide="ru.liahim.saltmod.client.ClientProxy", serverSide="ru.liahim.saltmod.common.CommonProxy") <add> @SidedProxy(clientSide = "ru.liahim.saltmod.common.ClientProxy", serverSide = "ru.liahim.saltmod.common.CommonProxy") <ide> public static CommonProxy proxy; <ide> <del> @EventHandler <del> public void preInit(FMLPreInitializationEvent event) <del> { <del> this.proxy.preInit(event); <del> } <del> <del> @EventHandler <del> public void init(FMLInitializationEvent event) <del> { <del> this.proxy.init(event); <add> @Mod.EventHandler <add> public void preInit(FMLPreInitializationEvent event) { <add> logger.info("Starting SaltMod PreInitialization"); <add> config = new SaltConfig(event.getSuggestedConfigurationFile()); <add> config.preInit(); <add> ModItems.init(); <add> ModBlocks.init(); <add> proxy.preInit(event); <ide> } <ide> <del> @EventHandler <del> public void postInit(FMLPostInitializationEvent event) <del> { <del> this.proxy.postInit(event); <add> @Mod.EventHandler <add> public void init(FMLInitializationEvent event) { <add> config.init(); <add> proxy.init(event); <ide> } <del> <del> @EventHandler <del> public void serverStarting(FMLServerStartingEvent event){} <add> <add> @Mod.EventHandler <add> public void postInit(FMLPostInitializationEvent event) { <add> config.postInit(); <add> proxy.postInit(event); <add> } <ide> }
Java
agpl-3.0
52c8137d0c7def10598a9572f6a8bc22fe7969c1
0
imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms
import java.io.*; import java.util.*; import java.text.*; import javax.servlet.*; import javax.servlet.http.*; import imcode.external.diverse.*; import imcode.external.chat.*; import imcode.util.* ; /** * @author Monika Hurtig * @version 1.0 * Date : 2001-09-05 */ public class QuotPicEngine extends HttpServlet { String inFile = ""; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; //get parameters String type = req.getParameter("type"); inFile = req.getParameter("file"); BufferedReader readFile = new BufferedReader( new StringReader( IMCServiceRMI.getFortune(imcServer,inFile + ".txt") ) ); SimpleDateFormat dateF = new SimpleDateFormat("yyMMdd"); //collect the correct questions/citat/pictures HashMap row_texts = new HashMap(50); //rownr int row = 0; String line = readFile.readLine(); //get questions while (line.length() != 0) //&& !( ( date1.before(date)||date1.equals(date) ) && ( date2.after(date)||date2.equals(date) ) ) ) { StringTokenizer tokens = new StringTokenizer(line,"#"); try { //the dates Date date1 = dateF.parse(tokens.nextToken()); Date date2 = dateF.parse(tokens.nextToken()); Date date = new Date(); String tempQ = tokens.nextToken(); if ( ( ( date1.before(date) ) || ( (dateF.format(date1)).equals(dateF.format(date)) ) ) && ( ( date2.after(date) ) || ( (dateF.format(date2)).equals(dateF.format(date)) ) ) ) { row_texts.put( new Integer(row),tempQ ); } } catch(ParseException e) { log("ParseException in QuotPicEngine"); } row++; line = readFile.readLine(); } int max_row = row; Collection texts = row_texts.values(); int nr = texts.size(); //get the text and row to return String theText; int the_row; //format the dates if (!(nr>0)) { //no question was found theText = "Ingen text kan visas" ; the_row = -1; } else { //get one randomised item Set rows = row_texts.keySet(); do { Random random = new Random(); the_row = random.nextInt(max_row); } while(!rows.contains(new Integer(the_row))); theText = (String)row_texts.get(new Integer(the_row)); } // res.setContentType("text/html"); // PrintWriter out = res.getWriter(); if( type.equals("pic")) { out.println( "<img src=\" " + theText + "\"> "); } else if(type.equals("quot")) { out.println(theText ); //raden i filen out.println("<input type=\"hidden\" name=\"quotrow\" value=\"" + the_row + "\">"); out.println("<input type=\"hidden\" name=\"quot\" value=\"" + theText + "\">"); } else { out.println( theText ); } return ; } // End doGet public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.doGet(req,res); return ; } /** Log function, will work for both servletexec and Apache **/ public void log( String str) { super.log(str) ; } } // End class
servlets/QuotPicEngine.java
import java.io.*; import java.util.*; import java.text.*; import javax.servlet.*; import javax.servlet.http.*; import imcode.external.diverse.*; import imcode.external.chat.*; import imcode.util.* ; /** * @author Monika Hurtig * @version 1.0 * Date : 2001-09-05 */ public class QuotPicEngine extends HttpServlet { String inFile = ""; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String host = req.getHeader("Host") ; String imcServer = Utility.getDomainPref("userserver",host) ; //get parameters String type = req.getParameter("type"); inFile = req.getParameter("file"); BufferedReader readFile = new BufferedReader( new StringReader( IMCServiceRMI.getFortune(imcServer,inFile + ".txt") ) ); SimpleDateFormat dateF = new SimpleDateFormat("yyMMdd"); //collect the correct questions/citat/pictures HashMap row_texts = new HashMap(50); //rownr int row = 0; String line = readFile.readLine(); //get questions while (line.length() != 0) //&& !( ( date1.before(date)||date1.equals(date) ) && ( date2.after(date)||date2.equals(date) ) ) ) { StringTokenizer tokens = new StringTokenizer(line,"#"); try { //the dates Date date1 = dateF.parse(tokens.nextToken()); Date date2 = dateF.parse(tokens.nextToken()); Date date = new Date(); String tempQ = tokens.nextToken(); if ( ( date1.before(date)||date1.equals(date) ) && ( date2.after(date)||date2.equals(date) ) ) { row_texts.put( new Integer(row),tempQ ); } } catch(ParseException e) { log("ParseException in QuotPicEngine"); } row++; line = readFile.readLine(); } int max_row = row; Collection texts = row_texts.values(); int nr = texts.size(); //get the text and row to return String theText; int the_row; //format the dates if (!(nr>0)) { //no question was found theText = "Ingen text kan visas" ; the_row = -1; } else { //get one randomised item Set rows = row_texts.keySet(); do { Random random = new Random(); the_row = random.nextInt(max_row); } while(!rows.contains(new Integer(the_row))); theText = (String)row_texts.get(new Integer(the_row)); } res.setContentType("text/html"); PrintWriter out = res.getWriter(); if( type.equals("pic")) { out.println( "<img src=\" " + theText + "\"> "); } else if(type.equals("quot")) { out.println(theText ); //raden i filen out.println("<input type=\"hidden\" name=\"quotrow\" value=\"" + the_row + "\">"); out.println("<input type=\"hidden\" name=\"quot\" value=\"" + theText + "\">"); } else { out.println( theText ); } return ; } // End doGet public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.doGet(req,res); return ; } /** Log function, will work for both servletexec and Apache **/ public void log( String str) { super.log(str) ; } } // End class
bug 122 Finel version of quotEngine git-svn-id: b7e9aa1d6cd963481915708f70423d437278b157@1041 bd66a97b-2aff-0310-9095-89ca5cabf5a6
servlets/QuotPicEngine.java
bug 122 Finel version of quotEngine
<ide><path>ervlets/QuotPicEngine.java <ide> <ide> public void doGet(HttpServletRequest req, HttpServletResponse res) <ide> throws ServletException, IOException <del> { <add> { <add> <add> res.setContentType("text/html"); <add> PrintWriter out = res.getWriter(); <add> <ide> <ide> String host = req.getHeader("Host") ; <ide> String imcServer = Utility.getDomainPref("userserver",host) ; <ide> inFile = req.getParameter("file"); <ide> <ide> BufferedReader readFile = new BufferedReader( new StringReader( IMCServiceRMI.getFortune(imcServer,inFile + ".txt") ) ); <del> <ide> SimpleDateFormat dateF = new SimpleDateFormat("yyMMdd"); <ide> <ide> //collect the correct questions/citat/pictures <ide> HashMap row_texts = new HashMap(50); <ide> <ide> //rownr <del> int row = 0; <add> int row = 0; <add> <ide> String line = readFile.readLine(); <ide> <ide> //get questions <ide> //the dates <ide> Date date1 = dateF.parse(tokens.nextToken()); <ide> Date date2 = dateF.parse(tokens.nextToken()); <del> <ide> Date date = new Date(); <del> <add> <ide> String tempQ = tokens.nextToken(); <del> <del> if ( ( date1.before(date)||date1.equals(date) ) && ( date2.after(date)||date2.equals(date) ) ) <add> <add> if ( ( ( date1.before(date) ) || ( (dateF.format(date1)).equals(dateF.format(date)) ) ) && ( ( date2.after(date) ) || ( (dateF.format(date2)).equals(dateF.format(date)) ) ) ) <ide> { <ide> row_texts.put( new Integer(row),tempQ ); <ide> } <del> <add> <ide> } <ide> catch(ParseException e) <ide> { <ide> log("ParseException in QuotPicEngine"); <ide> } <del> <add> <ide> row++; <ide> line = readFile.readLine(); <ide> } <ide> theText = (String)row_texts.get(new Integer(the_row)); <ide> } <ide> <del> res.setContentType("text/html"); <del> PrintWriter out = res.getWriter(); <add>// res.setContentType("text/html"); <add>// PrintWriter out = res.getWriter(); <ide> <ide> if( type.equals("pic")) <ide> {
Java
apache-2.0
c64c04be1df3d6224f6262720921a6a0f7417068
0
apache/directory-project
/* * @(#) $Id$ * * Copyright 2004 The Apache Software Foundation * * 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 org.apache.mina.common; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import org.apache.mina.util.ExpiringStack; /** * A {@link ByteBufferAllocator} which pools allocated buffers. * <p> * All buffers are allocated with the size of power of 2 (e.g. 16, 32, 64, ...) * This means that you cannot simply assume that the actual capacity of the * buffer and the capacity you requested are same. * </p> * <p> * This allocator releases the buffers which have not been in use for a certain * period. You can adjust the period by calling {@link #setTimeout(int)}. * The default timeout is 1 minute (60 seconds). To release these buffers * periodically, a daemon thread is started when a new instance of the allocator * is created. You can stop the thread by calling {@link #dispose()}. * </p> * * @author The Apache Directory Project ([email protected]) * @version $Rev$, $Date$ */ public class PooledByteBufferAllocator implements ByteBufferAllocator { private static final int MINIMUM_CAPACITY = 1; private static int threadId = 0; private final Expirer expirer; private final ExpiringStack containerStack = new ExpiringStack(); private final ExpiringStack[] heapBufferStacks = new ExpiringStack[] { new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), }; private final ExpiringStack[] directBufferStacks = new ExpiringStack[] { new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), }; private int timeout; private boolean disposed; /** * Creates a new instance with the default timeout. */ public PooledByteBufferAllocator() { this( 60 ); } /** * Creates a new instance with the specified <tt>timeout</tt>. */ public PooledByteBufferAllocator( int timeout ) { setTimeout( timeout ); expirer = new Expirer(); expirer.start(); } /** * Stops the thread which releases unused buffers and make this allocator * unusable from now on. */ public void dispose() { if( this == ByteBuffer.getAllocator() ) { throw new IllegalStateException( "This allocator is in use." ); } expirer.shutdown(); synchronized( containerStack ) { containerStack.clear(); } for( int i = directBufferStacks.length - 1; i >= 0; i -- ) { ExpiringStack stack = directBufferStacks[i]; synchronized( stack ) { stack.clear(); } } for( int i = heapBufferStacks.length - 1; i >= 0; i -- ) { ExpiringStack stack = heapBufferStacks[i]; synchronized( stack ) { stack.clear(); } } disposed = true; } /** * Returns the timeout value of this allocator in seconds. */ public int getTimeout() { return timeout; } /** * Returns the timeout value of this allocator in milliseconds. */ public long getTimeoutMillis() { return timeout * 1000L; } /** * Sets the timeout value of this allocator in seconds. * * @param timeout <tt>0</tt> or negative value to disable timeout. */ public void setTimeout( int timeout ) { if( timeout < 0 ) { timeout = 0; } this.timeout = timeout; if( timeout > 0 ) { } } public ByteBuffer allocate( int capacity, boolean direct ) { ensureNotDisposed(); UnexpandableByteBuffer ubb = allocate0( capacity, direct ); PooledByteBuffer buf = allocateContainer(); buf.init( ubb, true ); return buf; } private PooledByteBuffer allocateContainer() { PooledByteBuffer buf; synchronized( containerStack ) { buf = ( PooledByteBuffer ) containerStack.pop(); } if( buf == null ) { buf = new PooledByteBuffer(); } return buf; } private UnexpandableByteBuffer allocate0( int capacity, boolean direct ) { ExpiringStack[] bufferStacks = direct? directBufferStacks : heapBufferStacks; int idx = getBufferStackIndex( bufferStacks, capacity ); ExpiringStack stack = bufferStacks[ idx ]; UnexpandableByteBuffer buf; synchronized( stack ) { buf = ( UnexpandableByteBuffer ) stack.pop(); } if( buf == null ) { java.nio.ByteBuffer nioBuf = direct ? java.nio.ByteBuffer.allocateDirect( MINIMUM_CAPACITY << idx ) : java.nio.ByteBuffer.allocate( MINIMUM_CAPACITY << idx ); buf = new UnexpandableByteBuffer( nioBuf ); } buf.init(); return buf; } private void release0( UnexpandableByteBuffer buf ) { ExpiringStack[] bufferStacks = buf.buf().isDirect()? directBufferStacks : heapBufferStacks; ExpiringStack stack = bufferStacks[ getBufferStackIndex( bufferStacks, buf.buf().capacity() ) ]; synchronized( stack ) { // push back stack.push( buf ); } } public ByteBuffer wrap( java.nio.ByteBuffer nioBuffer ) { ensureNotDisposed(); PooledByteBuffer buf = allocateContainer(); buf.init( new UnexpandableByteBuffer( nioBuffer ), false ); buf.buf.init(); buf.setPooled( false ); return buf; } private int getBufferStackIndex( ExpiringStack[] bufferStacks, int size ) { int targetSize = MINIMUM_CAPACITY; int stackIdx = 0; while( size > targetSize ) { targetSize <<= 1; stackIdx ++ ; if( stackIdx >= bufferStacks.length ) { throw new IllegalArgumentException( "Buffer size is too big: " + size ); } } return stackIdx; } private void ensureNotDisposed() { if( disposed ) { throw new IllegalStateException( "This allocator is disposed already." ); } } private class Expirer extends Thread { private boolean timeToStop; public Expirer() { super( "PooledByteBufferExpirer-" + threadId++ ); setDaemon( true ); } public void shutdown() { timeToStop = true; interrupt(); while( isAlive() ) { try { join(); } catch ( InterruptedException e ) { } } } public void run() { // Expire unused buffers every seconds while( !timeToStop ) { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { } // Check if expiration is disabled. long timeout = getTimeoutMillis(); if( timeout <= 0L ) { continue; } // Expire old buffers long expirationTime = System.currentTimeMillis() - timeout; synchronized( containerStack ) { containerStack.expireBefore( expirationTime ); } for( int i = directBufferStacks.length - 1; i >= 0; i -- ) { ExpiringStack stack = directBufferStacks[ i ]; synchronized( stack ) { stack.expireBefore( expirationTime ); } } for( int i = heapBufferStacks.length - 1; i >= 0; i -- ) { ExpiringStack stack = heapBufferStacks[ i ]; synchronized( stack ) { stack.expireBefore( expirationTime ); } } } } } private class PooledByteBuffer extends ByteBuffer { private UnexpandableByteBuffer buf; private int refCount = 1; private boolean autoExpand; protected PooledByteBuffer() { } public synchronized void init( UnexpandableByteBuffer buf, boolean clear ) { this.buf = buf; if( clear ) { buf.buf().clear(); } buf.buf().order( ByteOrder.BIG_ENDIAN ); autoExpand = false; refCount = 1; } public synchronized void acquire() { if( refCount <= 0 ) { throw new IllegalStateException( "Already released buffer." ); } refCount ++; } public void release() { synchronized( this ) { if( refCount <= 0 ) { refCount = 0; throw new IllegalStateException( "Already released buffer. You released the buffer too many times." ); } refCount --; if( refCount > 0) { return; } } // No need to return buffers to the pool if it is disposed already. if( disposed ) { return; } buf.release(); synchronized( containerStack ) { containerStack.push( this ); } } public java.nio.ByteBuffer buf() { return buf.buf(); } public boolean isDirect() { return buf.buf().isDirect(); } public boolean isReadOnly() { return buf.buf().isReadOnly(); } public boolean isAutoExpand() { return autoExpand; } public ByteBuffer setAutoExpand( boolean autoExpand ) { this.autoExpand = autoExpand; return this; } public boolean isPooled() { return buf.isPooled(); } public void setPooled( boolean pooled ) { buf.setPooled(pooled); } public int capacity() { return buf.buf().capacity(); } public int position() { return buf.buf().position(); } public ByteBuffer position( int newPosition ) { autoExpand( newPosition, 0 ); buf.buf().position( newPosition ); return this; } public int limit() { return buf.buf().limit(); } public ByteBuffer limit( int newLimit ) { autoExpand( newLimit, 0 ); buf.buf().limit( newLimit ); return this; } public ByteBuffer mark() { buf.buf().mark(); return this; } public ByteBuffer reset() { buf.buf().reset(); return this; } public ByteBuffer clear() { buf.buf().clear(); return this; } public ByteBuffer flip() { buf.buf().flip(); return this; } public ByteBuffer rewind() { buf.buf().rewind(); return this; } public int remaining() { return buf.buf().remaining(); } public ByteBuffer duplicate() { PooledByteBuffer newBuf = allocateContainer(); newBuf.init( new UnexpandableByteBuffer( buf.buf().duplicate(), buf ), false ); return newBuf; } public ByteBuffer slice() { PooledByteBuffer newBuf = allocateContainer(); newBuf.init( new UnexpandableByteBuffer( buf.buf().slice(), buf ), false ); return newBuf; } public ByteBuffer asReadOnlyBuffer() { PooledByteBuffer newBuf = allocateContainer(); newBuf.init( new UnexpandableByteBuffer( buf.buf().asReadOnlyBuffer(), buf ), false ); return newBuf; } public byte get() { return buf.buf().get(); } public ByteBuffer put( byte b ) { autoExpand( 1 ); buf.buf().put( b ); return this; } public byte get( int index ) { return buf.buf().get( index ); } public ByteBuffer put( int index, byte b ) { autoExpand( index, 1 ); buf.buf().put( index, b ); return this; } public ByteBuffer get( byte[] dst, int offset, int length ) { buf.buf().get( dst, offset, length ); return this; } public ByteBuffer put( java.nio.ByteBuffer src ) { autoExpand( src.remaining() ); buf.buf().put( src ); return this; } public ByteBuffer put( byte[] src, int offset, int length ) { autoExpand( length ); buf.buf().put( src, offset, length ); return this; } public ByteBuffer compact() { buf.buf().compact(); return this; } public int compareTo( ByteBuffer that ) { return this.buf.buf().compareTo( that.buf() ); } public ByteOrder order() { return buf.buf().order(); } public ByteBuffer order( ByteOrder bo ) { buf.buf().order( bo ); return this; } public char getChar() { return buf.buf().getChar(); } public ByteBuffer putChar( char value ) { autoExpand( 2 ); buf.buf().putChar( value ); return this; } public char getChar( int index ) { return buf.buf().getChar( index ); } public ByteBuffer putChar( int index, char value ) { autoExpand( index, 2 ); buf.buf().putChar( index, value ); return this; } public CharBuffer asCharBuffer() { return buf.buf().asCharBuffer(); } public short getShort() { return buf.buf().getShort(); } public ByteBuffer putShort( short value ) { autoExpand( 2 ); buf.buf().putShort( value ); return this; } public short getShort( int index ) { return buf.buf().getShort( index ); } public ByteBuffer putShort( int index, short value ) { autoExpand( index, 2 ); buf.buf().putShort( index, value ); return this; } public ShortBuffer asShortBuffer() { return buf.buf().asShortBuffer(); } public int getInt() { return buf.buf().getInt(); } public ByteBuffer putInt( int value ) { autoExpand( 4 ); buf.buf().putInt( value ); return this; } public int getInt( int index ) { return buf.buf().getInt( index ); } public ByteBuffer putInt( int index, int value ) { autoExpand( index, 4 ); buf.buf().putInt( index, value ); return this; } public IntBuffer asIntBuffer() { return buf.buf().asIntBuffer(); } public long getLong() { return buf.buf().getLong(); } public ByteBuffer putLong( long value ) { autoExpand( 8 ); buf.buf().putLong( value ); return this; } public long getLong( int index ) { return buf.buf().getLong( index ); } public ByteBuffer putLong( int index, long value ) { autoExpand( index, 8 ); buf.buf().putLong( index, value ); return this; } public LongBuffer asLongBuffer() { return buf.buf().asLongBuffer(); } public float getFloat() { return buf.buf().getFloat(); } public ByteBuffer putFloat( float value ) { autoExpand( 4 ); buf.buf().putFloat( value ); return this; } public float getFloat( int index ) { return buf.buf().getFloat( index ); } public ByteBuffer putFloat( int index, float value ) { autoExpand( index, 4 ); buf.buf().putFloat( index, value ); return this; } public FloatBuffer asFloatBuffer() { return buf.buf().asFloatBuffer(); } public double getDouble() { return buf.buf().getDouble(); } public ByteBuffer putDouble( double value ) { autoExpand( 8 ); buf.buf().putDouble( value ); return this; } public double getDouble( int index ) { return buf.buf().getDouble( index ); } public ByteBuffer putDouble( int index, double value ) { autoExpand( index, 8 ); buf.buf().putDouble( index, value ); return this; } public DoubleBuffer asDoubleBuffer() { return buf.buf().asDoubleBuffer(); } public ByteBuffer expand( int expectedRemaining ) { if( autoExpand ) { int pos = buf.buf().position(); int limit = buf.buf().limit(); int end = pos + expectedRemaining; if( end > limit ) { ensureCapacity( end ); buf.buf().limit( end ); } } return this; } public ByteBuffer expand( int pos, int expectedRemaining ) { if( autoExpand ) { int limit = buf.buf().limit(); int end = pos + expectedRemaining; if( end > limit ) { ensureCapacity( end ); buf.buf().limit( end ); } } return this; } private void ensureCapacity( int requestedCapacity ) { if( requestedCapacity <= buf.buf().capacity() ) { return; } if( buf.isDerived() ) { throw new IllegalStateException( "Derived buffers cannot be expanded." ); } int newCapacity = MINIMUM_CAPACITY; while( newCapacity < requestedCapacity ) { newCapacity <<= 1; } UnexpandableByteBuffer oldBuf = this.buf; UnexpandableByteBuffer newBuf = allocate0( newCapacity, isDirect() ); newBuf.buf().clear(); newBuf.buf().order( oldBuf.buf().order() ); int pos = oldBuf.buf().position(); int limit = oldBuf.buf().limit(); oldBuf.buf().clear(); newBuf.buf().put( oldBuf.buf() ); newBuf.buf().position( 0 ); newBuf.buf().limit( limit ); newBuf.buf().position( pos ); this.buf = newBuf; oldBuf.release(); } } private class UnexpandableByteBuffer { private final java.nio.ByteBuffer buf; private final UnexpandableByteBuffer parentBuf; private int refCount; private boolean pooled; protected UnexpandableByteBuffer( java.nio.ByteBuffer buf ) { this.buf = buf; this.parentBuf = null; } protected UnexpandableByteBuffer( java.nio.ByteBuffer buf, UnexpandableByteBuffer parentBuf ) { parentBuf.acquire(); this.buf = buf; this.parentBuf = parentBuf; } public void init() { refCount = 1; pooled = true; } public synchronized void acquire() { if( isDerived() ) { parentBuf.acquire(); return; } if( refCount <= 0 ) { throw new IllegalStateException( "Already released buffer." ); } refCount ++; } public void release() { if( isDerived() ) { parentBuf.release(); return; } synchronized( this ) { if( refCount <= 0 ) { refCount = 0; throw new IllegalStateException( "Already released buffer. You released the buffer too many times." ); } refCount --; if( refCount > 0) { return; } } // No need to return buffers to the pool if it is disposed already. if( disposed ) { return; } if( pooled ) { if( parentBuf != null ) { release0( parentBuf ); } else { release0( this ); } } } public java.nio.ByteBuffer buf() { return buf; } public boolean isPooled() { return pooled; } public void setPooled( boolean pooled ) { this.pooled = pooled; } public boolean isDerived() { return parentBuf != null; } } }
mina/core/src/main/java/org/apache/mina/common/PooledByteBufferAllocator.java
/* * @(#) $Id$ * * Copyright 2004 The Apache Software Foundation * * 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 org.apache.mina.common; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import org.apache.mina.util.ExpiringStack; /** * A {@link ByteBufferAllocator} which pools allocated buffers. * <p> * All buffers are allocated with the size of power of 2 (e.g. 16, 32, 64, ...) * This means that you cannot simply assume that the actual capacity of the * buffer and the capacity you requested are same. * </p> * <p> * This allocator releases the buffers which have not been in use for a certain * period. You can adjust the period by calling {@link #setTimeout(int)}. * The default timeout is 1 minute (60 seconds). To release these buffers * periodically, a daemon thread is started when a new instance of the allocator * is created. You can stop the thread by calling {@link #dispose()}. * </p> * * @author The Apache Directory Project ([email protected]) * @version $Rev$, $Date$ */ public class PooledByteBufferAllocator implements ByteBufferAllocator { private static final int MINIMUM_CAPACITY = 1; private static int threadId = 0; private final Expirer expirer; private final ExpiringStack containerStack = new ExpiringStack(); private final ExpiringStack[] heapBufferStacks = new ExpiringStack[] { new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), }; private final ExpiringStack[] directBufferStacks = new ExpiringStack[] { new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), new ExpiringStack(), }; private int timeout; private boolean disposed; /** * Creates a new instance with the default timeout. */ public PooledByteBufferAllocator() { this( 60 ); } /** * Creates a new instance with the specified <tt>timeout</tt>. */ public PooledByteBufferAllocator( int timeout ) { setTimeout( timeout ); expirer = new Expirer(); expirer.start(); } /** * Stops the thread which releases unused buffers and make this allocator * unusable from now on. */ public void dispose() { if( this == ByteBuffer.getAllocator() ) { throw new IllegalStateException( "This allocator is in use." ); } expirer.shutdown(); synchronized( containerStack ) { containerStack.clear(); } for( int i = directBufferStacks.length - 1; i >= 0; i -- ) { ExpiringStack stack = directBufferStacks[i]; synchronized( stack ) { stack.clear(); } } for( int i = heapBufferStacks.length - 1; i >= 0; i -- ) { ExpiringStack stack = heapBufferStacks[i]; synchronized( stack ) { stack.clear(); } } disposed = true; } /** * Returns the timeout value of this allocator in seconds. */ public int getTimeout() { return timeout; } /** * Returns the timeout value of this allocator in milliseconds. */ public long getTimeoutMillis() { return timeout * 1000L; } /** * Sets the timeout value of this allocator in seconds. * * @param timeout <tt>0</tt> or negative value to disable timeout. */ public void setTimeout( int timeout ) { if( timeout < 0 ) { timeout = 0; } this.timeout = timeout; if( timeout > 0 ) { } } public ByteBuffer allocate( int capacity, boolean direct ) { ensureNotDisposed(); UnexpandableByteBuffer ubb = allocate0( capacity, direct ); PooledByteBuffer buf = allocateContainer(); buf.init( ubb, true ); return buf; } private PooledByteBuffer allocateContainer() { PooledByteBuffer buf; synchronized( containerStack ) { buf = ( PooledByteBuffer ) containerStack.pop(); } if( buf == null ) { buf = new PooledByteBuffer(); } return buf; } private UnexpandableByteBuffer allocate0( int capacity, boolean direct ) { ExpiringStack[] bufferStacks = direct? directBufferStacks : heapBufferStacks; int idx = getBufferStackIndex( bufferStacks, capacity ); ExpiringStack stack = bufferStacks[ idx ]; UnexpandableByteBuffer buf; synchronized( stack ) { buf = ( UnexpandableByteBuffer ) stack.pop(); } if( buf == null ) { java.nio.ByteBuffer nioBuf = direct ? java.nio.ByteBuffer.allocateDirect( MINIMUM_CAPACITY << idx ) : java.nio.ByteBuffer.allocate( MINIMUM_CAPACITY << idx ); buf = new UnexpandableByteBuffer( nioBuf ); } buf.init(); return buf; } private void release0( UnexpandableByteBuffer buf ) { ExpiringStack[] bufferStacks = buf.buf().isDirect()? directBufferStacks : heapBufferStacks; ExpiringStack stack = bufferStacks[ getBufferStackIndex( bufferStacks, buf.buf().capacity() ) ]; synchronized( stack ) { // push back stack.push( buf ); } } public ByteBuffer wrap( java.nio.ByteBuffer nioBuffer ) { ensureNotDisposed(); PooledByteBuffer buf = allocateContainer(); buf.init( new UnexpandableByteBuffer( nioBuffer ), false ); buf.setPooled( false ); return buf; } private int getBufferStackIndex( ExpiringStack[] bufferStacks, int size ) { int targetSize = MINIMUM_CAPACITY; int stackIdx = 0; while( size > targetSize ) { targetSize <<= 1; stackIdx ++ ; if( stackIdx >= bufferStacks.length ) { throw new IllegalArgumentException( "Buffer size is too big: " + size ); } } return stackIdx; } private void ensureNotDisposed() { if( disposed ) { throw new IllegalStateException( "This allocator is disposed already." ); } } private class Expirer extends Thread { private boolean timeToStop; public Expirer() { super( "PooledByteBufferExpirer-" + threadId++ ); setDaemon( true ); } public void shutdown() { timeToStop = true; interrupt(); while( isAlive() ) { try { join(); } catch ( InterruptedException e ) { } } } public void run() { // Expire unused buffers every seconds while( !timeToStop ) { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { } // Check if expiration is disabled. long timeout = getTimeoutMillis(); if( timeout <= 0L ) { continue; } // Expire old buffers long expirationTime = System.currentTimeMillis() - timeout; synchronized( containerStack ) { containerStack.expireBefore( expirationTime ); } for( int i = directBufferStacks.length - 1; i >= 0; i -- ) { ExpiringStack stack = directBufferStacks[ i ]; synchronized( stack ) { stack.expireBefore( expirationTime ); } } for( int i = heapBufferStacks.length - 1; i >= 0; i -- ) { ExpiringStack stack = heapBufferStacks[ i ]; synchronized( stack ) { stack.expireBefore( expirationTime ); } } } } } private class PooledByteBuffer extends ByteBuffer { private UnexpandableByteBuffer buf; private int refCount = 1; private boolean autoExpand; protected PooledByteBuffer() { } public synchronized void init( UnexpandableByteBuffer buf, boolean clear ) { this.buf = buf; if( clear ) { buf.buf().clear(); } buf.buf().order( ByteOrder.BIG_ENDIAN ); autoExpand = false; refCount = 1; } public synchronized void acquire() { if( refCount <= 0 ) { throw new IllegalStateException( "Already released buffer." ); } refCount ++; } public void release() { synchronized( this ) { if( refCount <= 0 ) { refCount = 0; throw new IllegalStateException( "Already released buffer. You released the buffer too many times." ); } refCount --; if( refCount > 0) { return; } } // No need to return buffers to the pool if it is disposed already. if( disposed ) { return; } buf.release(); synchronized( containerStack ) { containerStack.push( this ); } } public java.nio.ByteBuffer buf() { return buf.buf(); } public boolean isDirect() { return buf.buf().isDirect(); } public boolean isReadOnly() { return buf.buf().isReadOnly(); } public boolean isAutoExpand() { return autoExpand; } public ByteBuffer setAutoExpand( boolean autoExpand ) { this.autoExpand = autoExpand; return this; } public boolean isPooled() { return buf.isPooled(); } public void setPooled( boolean pooled ) { buf.setPooled(pooled); } public int capacity() { return buf.buf().capacity(); } public int position() { return buf.buf().position(); } public ByteBuffer position( int newPosition ) { autoExpand( newPosition, 0 ); buf.buf().position( newPosition ); return this; } public int limit() { return buf.buf().limit(); } public ByteBuffer limit( int newLimit ) { autoExpand( newLimit, 0 ); buf.buf().limit( newLimit ); return this; } public ByteBuffer mark() { buf.buf().mark(); return this; } public ByteBuffer reset() { buf.buf().reset(); return this; } public ByteBuffer clear() { buf.buf().clear(); return this; } public ByteBuffer flip() { buf.buf().flip(); return this; } public ByteBuffer rewind() { buf.buf().rewind(); return this; } public int remaining() { return buf.buf().remaining(); } public ByteBuffer duplicate() { PooledByteBuffer newBuf = allocateContainer(); newBuf.init( new UnexpandableByteBuffer( buf.buf().duplicate(), buf ), false ); return newBuf; } public ByteBuffer slice() { PooledByteBuffer newBuf = allocateContainer(); newBuf.init( new UnexpandableByteBuffer( buf.buf().slice(), buf ), false ); return newBuf; } public ByteBuffer asReadOnlyBuffer() { PooledByteBuffer newBuf = allocateContainer(); newBuf.init( new UnexpandableByteBuffer( buf.buf().asReadOnlyBuffer(), buf ), false ); return newBuf; } public byte get() { return buf.buf().get(); } public ByteBuffer put( byte b ) { autoExpand( 1 ); buf.buf().put( b ); return this; } public byte get( int index ) { return buf.buf().get( index ); } public ByteBuffer put( int index, byte b ) { autoExpand( index, 1 ); buf.buf().put( index, b ); return this; } public ByteBuffer get( byte[] dst, int offset, int length ) { buf.buf().get( dst, offset, length ); return this; } public ByteBuffer put( java.nio.ByteBuffer src ) { autoExpand( src.remaining() ); buf.buf().put( src ); return this; } public ByteBuffer put( byte[] src, int offset, int length ) { autoExpand( length ); buf.buf().put( src, offset, length ); return this; } public ByteBuffer compact() { buf.buf().compact(); return this; } public int compareTo( ByteBuffer that ) { return this.buf.buf().compareTo( that.buf() ); } public ByteOrder order() { return buf.buf().order(); } public ByteBuffer order( ByteOrder bo ) { buf.buf().order( bo ); return this; } public char getChar() { return buf.buf().getChar(); } public ByteBuffer putChar( char value ) { autoExpand( 2 ); buf.buf().putChar( value ); return this; } public char getChar( int index ) { return buf.buf().getChar( index ); } public ByteBuffer putChar( int index, char value ) { autoExpand( index, 2 ); buf.buf().putChar( index, value ); return this; } public CharBuffer asCharBuffer() { return buf.buf().asCharBuffer(); } public short getShort() { return buf.buf().getShort(); } public ByteBuffer putShort( short value ) { autoExpand( 2 ); buf.buf().putShort( value ); return this; } public short getShort( int index ) { return buf.buf().getShort( index ); } public ByteBuffer putShort( int index, short value ) { autoExpand( index, 2 ); buf.buf().putShort( index, value ); return this; } public ShortBuffer asShortBuffer() { return buf.buf().asShortBuffer(); } public int getInt() { return buf.buf().getInt(); } public ByteBuffer putInt( int value ) { autoExpand( 4 ); buf.buf().putInt( value ); return this; } public int getInt( int index ) { return buf.buf().getInt( index ); } public ByteBuffer putInt( int index, int value ) { autoExpand( index, 4 ); buf.buf().putInt( index, value ); return this; } public IntBuffer asIntBuffer() { return buf.buf().asIntBuffer(); } public long getLong() { return buf.buf().getLong(); } public ByteBuffer putLong( long value ) { autoExpand( 8 ); buf.buf().putLong( value ); return this; } public long getLong( int index ) { return buf.buf().getLong( index ); } public ByteBuffer putLong( int index, long value ) { autoExpand( index, 8 ); buf.buf().putLong( index, value ); return this; } public LongBuffer asLongBuffer() { return buf.buf().asLongBuffer(); } public float getFloat() { return buf.buf().getFloat(); } public ByteBuffer putFloat( float value ) { autoExpand( 4 ); buf.buf().putFloat( value ); return this; } public float getFloat( int index ) { return buf.buf().getFloat( index ); } public ByteBuffer putFloat( int index, float value ) { autoExpand( index, 4 ); buf.buf().putFloat( index, value ); return this; } public FloatBuffer asFloatBuffer() { return buf.buf().asFloatBuffer(); } public double getDouble() { return buf.buf().getDouble(); } public ByteBuffer putDouble( double value ) { autoExpand( 8 ); buf.buf().putDouble( value ); return this; } public double getDouble( int index ) { return buf.buf().getDouble( index ); } public ByteBuffer putDouble( int index, double value ) { autoExpand( index, 8 ); buf.buf().putDouble( index, value ); return this; } public DoubleBuffer asDoubleBuffer() { return buf.buf().asDoubleBuffer(); } public ByteBuffer expand( int expectedRemaining ) { if( autoExpand ) { int pos = buf.buf().position(); int limit = buf.buf().limit(); int end = pos + expectedRemaining; if( end > limit ) { ensureCapacity( end ); buf.buf().limit( end ); } } return this; } public ByteBuffer expand( int pos, int expectedRemaining ) { if( autoExpand ) { int limit = buf.buf().limit(); int end = pos + expectedRemaining; if( end > limit ) { ensureCapacity( end ); buf.buf().limit( end ); } } return this; } private void ensureCapacity( int requestedCapacity ) { if( requestedCapacity <= buf.buf().capacity() ) { return; } if( buf.isDerived() ) { throw new IllegalStateException( "Derived buffers cannot be expanded." ); } int newCapacity = MINIMUM_CAPACITY; while( newCapacity < requestedCapacity ) { newCapacity <<= 1; } UnexpandableByteBuffer oldBuf = this.buf; UnexpandableByteBuffer newBuf = allocate0( newCapacity, isDirect() ); newBuf.buf().clear(); newBuf.buf().order( oldBuf.buf().order() ); int pos = oldBuf.buf().position(); int limit = oldBuf.buf().limit(); oldBuf.buf().clear(); newBuf.buf().put( oldBuf.buf() ); newBuf.buf().position( 0 ); newBuf.buf().limit( limit ); newBuf.buf().position( pos ); this.buf = newBuf; oldBuf.release(); } } private class UnexpandableByteBuffer { private final java.nio.ByteBuffer buf; private final UnexpandableByteBuffer parentBuf; private int refCount; private boolean pooled; protected UnexpandableByteBuffer( java.nio.ByteBuffer buf ) { this.buf = buf; this.parentBuf = null; } protected UnexpandableByteBuffer( java.nio.ByteBuffer buf, UnexpandableByteBuffer parentBuf ) { parentBuf.acquire(); this.buf = buf; this.parentBuf = parentBuf; } public void init() { refCount = 1; pooled = true; } public synchronized void acquire() { if( isDerived() ) { parentBuf.acquire(); return; } if( refCount <= 0 ) { throw new IllegalStateException( "Already released buffer." ); } refCount ++; } public void release() { if( isDerived() ) { parentBuf.release(); return; } synchronized( this ) { if( refCount <= 0 ) { refCount = 0; throw new IllegalStateException( "Already released buffer. You released the buffer too many times." ); } refCount --; if( refCount > 0) { return; } } // No need to return buffers to the pool if it is disposed already. if( disposed ) { return; } if( pooled ) { if( parentBuf != null ) { release0( parentBuf ); } else { release0( this ); } } } public java.nio.ByteBuffer buf() { return buf; } public boolean isPooled() { return pooled; } public void setPooled( boolean pooled ) { this.pooled = pooled; } public boolean isDerived() { return parentBuf != null; } } }
Added a call to init() on the created UnexpandableByteBuffer so that its refCount is set to 1 when wrapping an NIO ByteBuffer. git-svn-id: 5c3b06693d750a6aefbf1081b6b7d57c0165fdb2@387902 13f79535-47bb-0310-9956-ffa450edef68
mina/core/src/main/java/org/apache/mina/common/PooledByteBufferAllocator.java
Added a call to init() on the created UnexpandableByteBuffer so that its refCount is set to 1 when wrapping an NIO ByteBuffer.
<ide><path>ina/core/src/main/java/org/apache/mina/common/PooledByteBufferAllocator.java <ide> ensureNotDisposed(); <ide> PooledByteBuffer buf = allocateContainer(); <ide> buf.init( new UnexpandableByteBuffer( nioBuffer ), false ); <add> buf.buf.init(); <ide> buf.setPooled( false ); <ide> return buf; <ide> }
Java
apache-2.0
18a9b5562c81c2f181295b6f7d55f899610f1a04
0
BenDol/gwt-lightslider,BenDol/gwt-lightslider
/* * Copyright 2015 Doltech Systems Ltd. * * 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 nz.co.doltech.gwtls.client.ui; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.event.shared.HandlerRegistration; import nz.co.doltech.gwtls.client.base.ComplexWidget; import nz.co.doltech.gwtls.client.events.AfterSlideEvent; import nz.co.doltech.gwtls.client.events.AfterSlideHandler; import nz.co.doltech.gwtls.client.events.BeforeNextSlideEvent; import nz.co.doltech.gwtls.client.events.BeforeNextSlideHandler; import nz.co.doltech.gwtls.client.events.BeforePrevSlideEvent; import nz.co.doltech.gwtls.client.events.BeforePrevSlideHandler; import nz.co.doltech.gwtls.client.events.BeforeSlideEvent; import nz.co.doltech.gwtls.client.events.BeforeSlideHandler; import nz.co.doltech.gwtls.client.events.BeforeStartEvent; import nz.co.doltech.gwtls.client.events.BeforeStartHandler; import nz.co.doltech.gwtls.client.events.SliderLoadEvent; import nz.co.doltech.gwtls.client.events.SliderLoadHandler; import nz.co.doltech.gwtls.client.options.Responsive; public class LightSlider extends ComplexWidget { private JsLightSlider impl; // Options private int item = 1; private boolean autoWidth; private int slideMove = 1; private int slideMargin = 10; private String addClass = ""; private String mode = "slide"; private boolean useCss = true; private String cssEasing = "ease"; private String easing = "linear"; private int speed = 400; private boolean auto; private boolean pauseOnHover; private boolean loop; private boolean slideEndAnimation = true; private int pause = 2000; private boolean keyPress; private boolean controls = true; private String prevHtml = ""; private String nextHtml = ""; private boolean rtl; private boolean adaptiveHeight; private boolean vertical; private int verticalHeight = 500; private int vThumbWidth = 100; private int thumbItem = 10; private boolean pager = true; private boolean gallery = false; private int galleryMargin = 5; private int thumbMargin = 5; private String currentPagerPosition = "middle"; private boolean enableTouch = true; private boolean enableDrag = true; private boolean freeMove = true; private int swipeThreshold = 40; private Responsive responsive = Responsive.create(); public LightSlider() { setElement(Document.get().createULElement()); getElement().setId("lightSlider"); } @Override protected void onLoad() { if(impl == null) { initialize(); } } // Setters/Getters public int getItem() { return item; } /** * number of slides to show at a time. */ public void setItem(int item) { this.item = item; } public boolean isAutoWidth() { return autoWidth; } /** * Custom width for each slide. */ public void setAutoWidth(boolean autoWidth) { this.autoWidth = autoWidth; } public int getSlideMove() { return slideMove; } /** * Number of slides to be moved at a time. */ public void setSlideMove(int slideMove) { this.slideMove = slideMove; } public int getSlideMargin() { return slideMargin; } /** * Spacing between each slide. */ public void setSlideMargin(int slideMargin) { this.slideMargin = slideMargin; } public String getAddClass() { return addClass; } /** * Add custom class for slider, can be used to set different * style for different sliders. */ public void setAddClass(String addClass) { this.addClass = addClass; } public String getMode() { return mode; } /** * Type of transition 'slide' and 'fade'. */ public void setMode(String mode) { this.mode = mode; } public boolean isUseCss() { return useCss; } /** * If true LightSlider will use CSS transitions. if falls jquery * animation will be used. */ public void setUseCss(boolean useCss) { this.useCss = useCss; } public String getCssEasing() { return cssEasing; } /** * Type of easing to be used for css animations. */ public void setCssEasing(String cssEasing) { this.cssEasing = cssEasing; } public String getEasing() { return easing; } /** * Type of easing to be used for jquery animations. */ public void setEasing(String easing) { this.easing = easing; } public int getSpeed() { return speed; } /** * Transition duration (in ms), e.g. speed:400. */ public void setSpeed(int speed) { this.speed = speed; } public boolean isAuto() { return auto; } /** * If true, the Slider will automatically start to play. */ public void setAuto(boolean auto) { this.auto = auto; } public boolean isPauseOnHover() { return pauseOnHover; } /** * Pause autoplay on hover. */ public void setPauseOnHover(boolean pauseOnHover) { this.pauseOnHover = pauseOnHover; } public boolean isLoop() { return loop; } /** * If false, will disable the ability to loop back to the * beginning of the slide when on the last element. */ public void setLoop(boolean loop) { this.loop = loop; } public boolean isSlideEndAnimation() { return slideEndAnimation; } /** * Enable slideEnd animation. */ public void setSlideEndAnimation(boolean slideEndAnimation) { this.slideEndAnimation = slideEndAnimation; } public int getPause() { return pause; } /** * The time (in ms) between each auto transition. */ public void setPause(int pause) { this.pause = pause; } public boolean isKeyPress() { return keyPress; } /** * Enable keyboard navigation. */ public void setKeyPress(boolean keyPress) { this.keyPress = keyPress; } public boolean isControls() { return controls; } /** * If false, prev/next buttons will not be displayed. */ public void setControls(boolean controls) { this.controls = controls; } public String getPrevHtml() { return prevHtml; } /** * Custom html for prev control. */ public void setPrevHtml(String prevHtml) { this.prevHtml = prevHtml; } public String getNextHtml() { return nextHtml; } /** * Custom html for next control. */ public void setNextHtml(String nextHtml) { this.nextHtml = nextHtml; } public boolean isRtl() { return rtl; } /** * Change direction to right-to-left. */ public void setRtl(boolean rtl) { this.rtl = rtl; } public boolean isAdaptiveHeight() { return adaptiveHeight; } /** * Dynamically adjust slider height based on each slide's height. */ public void setAdaptiveHeight(boolean adaptiveHeight) { this.adaptiveHeight = adaptiveHeight; } public boolean isVertical() { return vertical; } /** * change slide's direction from horizontal to Vertical. */ public void setVertical(boolean vertical) { this.vertical = vertical; } public int getVerticalHeight() { return verticalHeight; } /** * Set height of slider if vertical mode is active and item more than 1. */ public void setVerticalHeight(int verticalHeight) { this.verticalHeight = verticalHeight; } public int getVThumbWidth() { return vThumbWidth; } /** * Width of gallery thumbnail while vertical mode active */ public void setVThumbWidth(int vThumbWidth) { this.vThumbWidth = vThumbWidth; } public int getThumbItem() { return thumbItem; } /** * Number of gallery thumbnail to show at a time. */ public void setThumbItem(int thumbItem) { this.thumbItem = thumbItem; } public boolean isPager() { return pager; } /** * Enable pager option. */ public void setPager(boolean pager) { this.pager = pager; } public boolean isGallery() { return gallery; } /** * Enable thumbnails gallery. */ public void setGallery(boolean gallery) { this.gallery = gallery; } public int getGalleryMargin() { return galleryMargin; } /** * Spacing between gallery and slide. */ public void setGalleryMargin(int galleryMargin) { this.galleryMargin = galleryMargin; } public int getThumbMargin() { return thumbMargin; } /** * Spacing between each thumbnails. */ public void setThumbMargin(int thumbMargin) { this.thumbMargin = thumbMargin; } public String getCurrentPagerPosition() { return currentPagerPosition; } /** * Position of thumbnails . 'left', 'middle', 'right'. */ public void setCurrentPagerPosition(String currentPagerPosition) { this.currentPagerPosition = currentPagerPosition; } public boolean isEnableTouch() { return enableTouch; } /** * Enables touch support. */ public void setEnableTouch(boolean enableTouch) { this.enableTouch = enableTouch; } public boolean isEnableDrag() { return enableDrag; } /** * Enables desktop mouse drag support. */ public void setEnableDrag(boolean enableDrag) { this.enableDrag = enableDrag; } public boolean isFreeMove() { return freeMove; } /** * Enable free move(no limit) while swipe or drag. */ public void setFreeMove(boolean freeMove) { this.freeMove = freeMove; } public int getSwipeThreshold() { return swipeThreshold; } /** * Threshold for swipe actions to move left or right. */ public void setSwipeThreshold(int swipeThreshold) { this.swipeThreshold = swipeThreshold; } public Responsive getResponsive() { return responsive; } /** * Separate settings per breakpoint. */ public void setResponsive(Responsive responsive) { this.responsive = responsive; } // Methods public final void goToSlide(int slide) { impl.goToSlide(slide); } public final void goToPrevSlide() { impl.goToPrevSlide(); } public final void goToNextSlide() { impl.goToNextSlide(); } public final void getCurrentSlideCount() { impl.getCurrentSlideCount(); } public final void refresh() { impl.refresh(); } public final void play() { impl.play(); } public final void pause() { impl.pause(); } public final void destroy() { impl.destroy(); } protected final JsLightSlider getImpl() { return impl; } // Events /** * Executes before slider start loading. */ public HandlerRegistration addBeforeStartHandler(BeforeStartHandler handler) { return addHandler(handler, BeforeStartEvent.getType()); } private void onBeforeStart(JsLightSlider impl) { BeforeStartEvent.fire(this, impl); } /** * Executes immediately after the slider is fully loaded. */ public HandlerRegistration addSliderLoadHandler(SliderLoadHandler handler) { return addHandler(handler, SliderLoadEvent.getType()); } private void onSliderLoad(JsLightSlider impl) { SliderLoadEvent.fire(this, impl); } /** * Executes immediately before each slide transition. */ public HandlerRegistration addBeforeSlideHandler(BeforeSlideHandler handler) { return addHandler(handler, BeforeSlideEvent.getType()); } private void onBeforeSlide(JsLightSlider impl) { BeforeSlideEvent.fire(this, impl); } /** * Executes immediately after each slide transition. */ public HandlerRegistration addAfterSlideHandler(AfterSlideHandler handler) { return addHandler(handler, AfterSlideEvent.getType()); } private void onAfterSlide(JsLightSlider impl) { AfterSlideEvent.fire(this, impl); } /** * Executes immediately before each "Next" slide transition. */ public HandlerRegistration addBeforeNextSlideHandler(BeforeNextSlideHandler handler) { return addHandler(handler, BeforeNextSlideEvent.getType()); } private void onBeforeNextSlide(JsLightSlider impl) { BeforeNextSlideEvent.fire(this, impl); } /** * Executes immediately before each "Prev" slide transition. */ public HandlerRegistration addBeforePrevSlideHandler(BeforePrevSlideHandler handler) { return addHandler(handler, BeforePrevSlideEvent.getType()); } private void onBeforePrevSlide(JsLightSlider impl) { BeforePrevSlideEvent.fire(this, impl); } /** * Destroys the existing slider implementation * and initializes. */ public void reinitialize() { if(impl != null) { impl.destroy(); impl = null; } initialize(); } /** * Initialize the Light Slider widget. */ public void initialize() { initialize(getElement()); } private native void initialize(Element e) /*-{ var that = this; [email protected]::impl = $wnd.jQuery(e).lightSlider({ // Options item: [email protected]::item, autoWidth: [email protected]::autoWidth, slideMove: [email protected]::slideMove, slideMargin: [email protected]::slideMargin, addClass: [email protected]::addClass, mode: [email protected]::mode, useCSS: [email protected]::useCss, cssEasing: [email protected]::cssEasing, easing: [email protected]::easing, speed: [email protected]::speed, auto: [email protected]::auto, pauseOnHover: [email protected]::pauseOnHover, loop: [email protected]::loop, slideEndAnimation: [email protected]::slideEndAnimation, pause: [email protected]::pause, keyPress: [email protected]::keyPress, controls: [email protected]::controls, prevHtml: [email protected]::prevHtml, nextHtml: [email protected]::nextHtml, rtl: [email protected]::rtl, adaptiveHeight: [email protected]::adaptiveHeight, vertical: [email protected]::vertical, verticalHeight: [email protected]::verticalHeight, vThumbWidth: [email protected]::vThumbWidth, thumbItem: [email protected]::thumbItem, pager: [email protected]::pager, gallery: [email protected]::gallery, galleryMargin: [email protected]::galleryMargin, thumbMargin: [email protected]::thumbMargin, currentPagerPosition: [email protected]::currentPagerPosition, enableTouch: [email protected]::enableTouch, enableDrag: [email protected]::enableDrag, freeMove: [email protected]::freeMove, swipeThreshold: [email protected]::swipeThreshold, responsive: [email protected]::responsive, // Events onBeforeStart: function ($el) { [email protected]::onBeforeStart(*)($el); }, onSliderLoad: function ($el) { [email protected]::onSliderLoad(*)($el); }, onBeforeSlide: function ($el, scene) { [email protected]::onBeforeSlide(*)($el); }, onAfterSlide: function ($el, scene) { [email protected]::onAfterSlide(*)($el); }, onBeforeNextSlide: function ($el, scene) { [email protected]::onBeforeNextSlide(*)($el); }, onBeforePrevSlide: function ($el, scene) { [email protected]::onBeforePrevSlide(*)($el); } }); }-*/; }
src/main/java/nz/co/doltech/gwtls/client/ui/LightSlider.java
/* * Copyright 2015 Doltech Systems Ltd. * * 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 nz.co.doltech.gwtls.client.ui; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.event.shared.HandlerRegistration; import nz.co.doltech.gwtls.client.base.ComplexWidget; import nz.co.doltech.gwtls.client.events.AfterSlideEvent; import nz.co.doltech.gwtls.client.events.AfterSlideHandler; import nz.co.doltech.gwtls.client.events.BeforeNextSlideEvent; import nz.co.doltech.gwtls.client.events.BeforeNextSlideHandler; import nz.co.doltech.gwtls.client.events.BeforePrevSlideEvent; import nz.co.doltech.gwtls.client.events.BeforePrevSlideHandler; import nz.co.doltech.gwtls.client.events.BeforeSlideEvent; import nz.co.doltech.gwtls.client.events.BeforeSlideHandler; import nz.co.doltech.gwtls.client.events.BeforeStartEvent; import nz.co.doltech.gwtls.client.events.BeforeStartHandler; import nz.co.doltech.gwtls.client.events.SliderLoadEvent; import nz.co.doltech.gwtls.client.events.SliderLoadHandler; import nz.co.doltech.gwtls.client.options.Responsive; public class LightSlider extends ComplexWidget { private JsLightSlider impl; // Options private int item = 1; private boolean autoWidth; private int slideMove = 1; private int slideMargin = 10; private String addClass = ""; private String mode = "slide"; private boolean useCss = true; private String cssEasing = "ease"; private String easing = "linear"; private int speed = 400; private boolean auto; private boolean pauseOnHover; private boolean loop; private boolean slideEndAnimation = true; private int pause = 2000; private boolean keyPress; private boolean controls = true; private String prevHtml = ""; private String nextHtml = ""; private boolean rtl; private boolean adaptiveHeight; private boolean vertical; private int verticalHeight = 500; private int vThumbWidth = 100; private int thumbItem = 10; private boolean pager = true; private boolean gallery = false; private int galleryMargin = 5; private int thumbMargin = 5; private String currentPagerPosition = "middle"; private boolean enableTouch = true; private boolean enableDrag = true; private boolean freeMove = true; private int swipeThreshold = 40; private Responsive responsive = Responsive.create(); public LightSlider() { setElement(Document.get().createULElement()); getElement().setId("lightSlider"); } @Override protected void onLoad() { if(impl == null) { initialize(); } } // Setters/Getters public int getItem() { return item; } /** * number of slides to show at a time. */ public void setItem(int item) { this.item = item; } public boolean isAutoWidth() { return autoWidth; } /** * Custom width for each slide. */ public void setAutoWidth(boolean autoWidth) { this.autoWidth = autoWidth; } public int getSlideMove() { return slideMove; } /** * Number of slides to be moved at a time. */ public void setSlideMove(int slideMove) { this.slideMove = slideMove; } public int getSlideMargin() { return slideMargin; } /** * Spacing between each slide. */ public void setSlideMargin(int slideMargin) { this.slideMargin = slideMargin; } public String getAddClass() { return addClass; } /** * Add custom class for slider, can be used to set different * style for different sliders. */ public void setAddClass(String addClass) { this.addClass = addClass; } public String getMode() { return mode; } /** * Type of transition 'slide' and 'fade'. */ public void setMode(String mode) { this.mode = mode; } public boolean isUseCss() { return useCss; } /** * If true LightSlider will use CSS transitions. if falls jquery * animation will be used. */ public void setUseCss(boolean useCss) { this.useCss = useCss; } public String getCssEasing() { return cssEasing; } /** * Type of easing to be used for css animations. */ public void setCssEasing(String cssEasing) { this.cssEasing = cssEasing; } public String getEasing() { return easing; } /** * Type of easing to be used for jquery animations. */ public void setEasing(String easing) { this.easing = easing; } public int getSpeed() { return speed; } /** * Transition duration (in ms), e.g. speed:400. */ public void setSpeed(int speed) { this.speed = speed; } public boolean isAuto() { return auto; } /** * If true, the Slider will automatically start to play. */ public void setAuto(boolean auto) { this.auto = auto; } public boolean isPauseOnHover() { return pauseOnHover; } /** * Pause autoplay on hover. */ public void setPauseOnHover(boolean pauseOnHover) { this.pauseOnHover = pauseOnHover; } public boolean isLoop() { return loop; } /** * If false, will disable the ability to loop back to the * beginning of the slide when on the last element. */ public void setLoop(boolean loop) { this.loop = loop; } public boolean isSlideEndAnimation() { return slideEndAnimation; } /** * Enable slideEnd animation. */ public void setSlideEndAnimation(boolean slideEndAnimation) { this.slideEndAnimation = slideEndAnimation; } public int getPause() { return pause; } /** * The time (in ms) between each auto transition. */ public void setPause(int pause) { this.pause = pause; } public boolean isKeyPress() { return keyPress; } /** * Enable keyboard navigation. */ public void setKeyPress(boolean keyPress) { this.keyPress = keyPress; } public boolean isControls() { return controls; } /** * If false, prev/next buttons will not be displayed. */ public void setControls(boolean controls) { this.controls = controls; } public String getPrevHtml() { return prevHtml; } /** * Custom html for prev control. */ public void setPrevHtml(String prevHtml) { this.prevHtml = prevHtml; } public String getNextHtml() { return nextHtml; } /** * Custom html for next control. */ public void setNextHtml(String nextHtml) { this.nextHtml = nextHtml; } public boolean isRtl() { return rtl; } /** * Change direction to right-to-left. */ public void setRtl(boolean rtl) { this.rtl = rtl; } public boolean isAdaptiveHeight() { return adaptiveHeight; } /** * Dynamically adjust slider height based on each slide's height. */ public void setAdaptiveHeight(boolean adaptiveHeight) { this.adaptiveHeight = adaptiveHeight; } public boolean isVertical() { return vertical; } /** * change slide's direction from horizontal to Vertical. */ public void setVertical(boolean vertical) { this.vertical = vertical; } public int getVerticalHeight() { return verticalHeight; } /** * Set height of slider if vertical mode is active and item more than 1. */ public void setVerticalHeight(int verticalHeight) { this.verticalHeight = verticalHeight; } public int getVThumbWidth() { return vThumbWidth; } /** * Width of gallery thumbnail while vertical mode active */ public void setVThumbWidth(int vThumbWidth) { this.vThumbWidth = vThumbWidth; } public int getThumbItem() { return thumbItem; } /** * Number of gallery thumbnail to show at a time. */ public void setThumbItem(int thumbItem) { this.thumbItem = thumbItem; } public boolean isPager() { return pager; } /** * Enable pager option. */ public void setPager(boolean pager) { this.pager = pager; } public boolean isGallery() { return gallery; } /** * Enable thumbnails gallery. */ public void setGallery(boolean gallery) { this.gallery = gallery; } public int getGalleryMargin() { return galleryMargin; } /** * Spacing between gallery and slide. */ public void setGalleryMargin(int galleryMargin) { this.galleryMargin = galleryMargin; } public int getThumbMargin() { return thumbMargin; } /** * Spacing between each thumbnails. */ public void setThumbMargin(int thumbMargin) { this.thumbMargin = thumbMargin; } public String getCurrentPagerPosition() { return currentPagerPosition; } /** * Position of thumbnails . 'left', 'middle', 'right'. */ public void setCurrentPagerPosition(String currentPagerPosition) { this.currentPagerPosition = currentPagerPosition; } public boolean isEnableTouch() { return enableTouch; } /** * Enables touch support. */ public void setEnableTouch(boolean enableTouch) { this.enableTouch = enableTouch; } public boolean isEnableDrag() { return enableDrag; } /** * Enables desktop mouse drag support. */ public void setEnableDrag(boolean enableDrag) { this.enableDrag = enableDrag; } public boolean isFreeMove() { return freeMove; } /** * Enable free move(no limit) while swipe or drag. */ public void setFreeMove(boolean freeMove) { this.freeMove = freeMove; } public int getSwipeThreshold() { return swipeThreshold; } /** * Threshold for swipe actions to move left or right. */ public void setSwipeThreshold(int swipeThreshold) { this.swipeThreshold = swipeThreshold; } public Responsive getResponsive() { return responsive; } /** * Separate settings per breakpoint. */ public void setResponsive(Responsive responsive) { this.responsive = responsive; } // Methods public final void goToSlide(int slide) { impl.goToSlide(slide); } public final void goToPrevSlide() { impl.goToPrevSlide(); } public final void goToNextSlide() { impl.goToNextSlide(); } public final void getCurrentSlideCount() { impl.getCurrentSlideCount(); } public final void refresh() { impl.refresh(); } public final void play() { impl.play(); } public final void pause() { impl.pause(); } public final void destroy() { impl.destroy(); } protected final JsLightSlider getImpl() { return impl; } // Events /** * Executes before slider start loading. */ public HandlerRegistration addBeforeStartHandler(BeforeStartHandler handler) { return addHandler(handler, BeforeStartEvent.getType()); } private void onBeforeStart(JsLightSlider impl) { BeforeStartEvent.fire(this, impl); } /** * Executes immediately after the slider is fully loaded. */ public HandlerRegistration addSliderLoadHandler(SliderLoadHandler handler) { return addHandler(handler, SliderLoadEvent.getType()); } private void onSliderLoad(JsLightSlider impl) { SliderLoadEvent.fire(this, impl); } /** * Executes immediately before each slide transition. */ public HandlerRegistration addBeforeSlideHandler(BeforeSlideHandler handler) { return addHandler(handler, BeforeSlideEvent.getType()); } private void onBeforeSlide(JsLightSlider impl) { BeforeSlideEvent.fire(this, impl); } /** * Executes immediately after each slide transition. */ public HandlerRegistration addAfterSlideHandler(AfterSlideHandler handler) { return addHandler(handler, AfterSlideEvent.getType()); } private void onAfterSlide(JsLightSlider impl) { AfterSlideEvent.fire(this, impl); } /** * Executes immediately before each "Next" slide transition. */ public HandlerRegistration addBeforeNextSlideHandler(BeforeNextSlideHandler handler) { return addHandler(handler, BeforeNextSlideEvent.getType()); } private void onBeforeNextSlide(JsLightSlider impl) { BeforeNextSlideEvent.fire(this, impl); } /** * Executes immediately before each "Prev" slide transition. */ public HandlerRegistration addBeforePrevSlideHandler(BeforePrevSlideHandler handler) { return addHandler(handler, BeforePrevSlideEvent.getType()); } private void onBeforePrevSlide(JsLightSlider impl) { BeforePrevSlideEvent.fire(this, impl); } /** * Destroys the existing slider implementation * and initializes. */ public void reinitialize() { if(impl != null) { impl.destroy(); } impl = null; initialize(); } /** * Initialize the Light Slider widget. */ public void initialize() { initialize(getElement()); } private native void initialize(Element e) /*-{ var that = this; [email protected]::impl = $wnd.jQuery(e).lightSlider({ // Options item: [email protected]::item, autoWidth: [email protected]::autoWidth, slideMove: [email protected]::slideMove, slideMargin: [email protected]::slideMargin, addClass: [email protected]::addClass, mode: [email protected]::mode, useCSS: [email protected]::useCss, cssEasing: [email protected]::cssEasing, easing: [email protected]::easing, speed: [email protected]::speed, auto: [email protected]::auto, pauseOnHover: [email protected]::pauseOnHover, loop: [email protected]::loop, slideEndAnimation: [email protected]::slideEndAnimation, pause: [email protected]::pause, keyPress: [email protected]::keyPress, controls: [email protected]::controls, prevHtml: [email protected]::prevHtml, nextHtml: [email protected]::nextHtml, rtl: [email protected]::rtl, adaptiveHeight: [email protected]::adaptiveHeight, vertical: [email protected]::vertical, verticalHeight: [email protected]::verticalHeight, vThumbWidth: [email protected]::vThumbWidth, thumbItem: [email protected]::thumbItem, pager: [email protected]::pager, gallery: [email protected]::gallery, galleryMargin: [email protected]::galleryMargin, thumbMargin: [email protected]::thumbMargin, currentPagerPosition: [email protected]::currentPagerPosition, enableTouch: [email protected]::enableTouch, enableDrag: [email protected]::enableDrag, freeMove: [email protected]::freeMove, swipeThreshold: [email protected]::swipeThreshold, responsive: [email protected]::responsive, // Events onBeforeStart: function ($el) { [email protected]::onBeforeStart(*)($el); }, onSliderLoad: function ($el) { [email protected]::onSliderLoad(*)($el); }, onBeforeSlide: function ($el, scene) { [email protected]::onBeforeSlide(*)($el); }, onAfterSlide: function ($el, scene) { [email protected]::onAfterSlide(*)($el); }, onBeforeNextSlide: function ($el, scene) { [email protected]::onBeforeNextSlide(*)($el); }, onBeforePrevSlide: function ($el, scene) { [email protected]::onBeforePrevSlide(*)($el); } }); }-*/; }
Minor fix.
src/main/java/nz/co/doltech/gwtls/client/ui/LightSlider.java
Minor fix.
<ide><path>rc/main/java/nz/co/doltech/gwtls/client/ui/LightSlider.java <ide> public void reinitialize() { <ide> if(impl != null) { <ide> impl.destroy(); <add> impl = null; <ide> } <del> impl = null; <del> <ide> initialize(); <ide> } <ide>
Java
mit
daff8b70acc76728ddf4a5bcf172dd7c7dfdecc1
0
jharris119/klondike
package info.jayharris.klondike; import com.beust.jcommander.IStringConverter; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.googlecode.blacken.colors.ColorNames; import com.googlecode.blacken.colors.ColorPalette; import com.googlecode.blacken.swing.SwingTerminal; import com.googlecode.blacken.terminal.*; import info.jayharris.cardgames.Deck; import org.apache.commons.collections4.iterators.LoopingListIterator; import java.util.*; public class TerminalUI implements KlondikeUI, Observer { private Klondike klondike; private boolean quit; private ColorPalette palette; private CursesLikeAPI term = null; private TerminalUIComponent<?> pointingTo, movingFrom = null; private List<TerminalUIComponent<?>> components; private LoopingListIterator<TerminalUIComponent<?>> componentOrder; private boolean lastDirectionRight = true; // direction of last move -- // if componentOrder.next() => X, then an immediate call to // componentOrder.previous() will also => X. public final int START_ROW = 0, LEFT_COL = 5, SPACE_BETWEEN = 5, TABLEAU_ROW = 2, WASTE_CARDS_SHOWN = 6, WASTE_START_COL = LEFT_COL + "[24 cards]".length() + SPACE_BETWEEN, WASTE_MAX_WIDTH = "... XX XX XX XX XX XX".length(), FOUNDATION_START_COL = WASTE_START_COL + WASTE_MAX_WIDTH + SPACE_BETWEEN; public TerminalUI(Klondike klondike) { this.klondike = klondike; this.klondike.addObserver(this); } protected boolean loop() { int key; if (palette.containsKey("White")) { term.setCurBackground("White"); } if (palette.containsKey("Black")) { term.setCurForeground("Black"); } term.clear(); while (!this.quit) { for (TerminalUIComponent<?> component : components) { component.writeToTerminal(); } pointingTo.drawPointer(false); key = term.getch(); // getch automatically does a refresh onKeyPress(key); } term.refresh(); return this.quit; } public void init(TerminalInterface term, ColorPalette palette) { if (term == null) { this.term = new CursesLikeAPI(new SwingTerminal()); this.term.init("Klondike", 25, 80); } else { this.term = new CursesLikeAPI(term); } if (palette == null) { palette = new ColorPalette(); palette.addAll(ColorNames.XTERM_256_COLORS, false); palette.putMapping(ColorNames.SVG_COLORS); } this.palette = palette; this.term.setPalette(palette); // set up all of the deck, waste, foundation, tableau visual components components = new ArrayList<TerminalUIComponent<?>>() {{ int col; /****************************************************************** * Deck UI component ******************************************************************/ this.add(new TerminalUIComponent<Deck>(klondike.getDeck(), START_ROW, LEFT_COL) { @Override public void writeToTerminal() { super.writeToTerminal("[" + Strings.padStart(Integer.toString(klondike.getDeck().size()), 2, ' ') + " cards]"); } @Override public void doAction() { klondike.deal(); } }); /****************************************************************** * Waste UI component ******************************************************************/ this.add(new TerminalUIComponent<Klondike.Waste>(klondike.getWaste(), START_ROW, WASTE_START_COL) { @Override public void doAction() { // pick up the next card in the waste if (movingFrom == null && !payload.isEmpty()) { movingFrom = this; } // return the card to whence it came else { movingFrom = null; } } @Override public void writeToTerminal() { int sz = payload.size(); int index = Math.max(0, sz - WASTE_CARDS_SHOWN), strlen = 0; if (sz > WASTE_CARDS_SHOWN) { writeToTerminal("... "); strlen += "... ".length(); } while (index < sz) { if (index == sz - 1) { if (movingFrom == this) { setCurBackground("Yellow"); } writeToTerminal(0, strlen, payload.get(index).toString()); strlen += 2; } else { writeToTerminal(0, strlen, payload.get(index).toString() + " "); strlen += 3; } setCurBackground("White"); ++index; } while (strlen < WASTE_MAX_WIDTH) { writeToTerminal(0, strlen, " "); ++strlen; } } }); /****************************************************************** * Tableau UI components ******************************************************************/ col = LEFT_COL; for (int i = 0; i < 7; ++i) { this.add(new TableauUIComponent(klondike.getTableau(i), col)); col += "XX".length() + SPACE_BETWEEN; } /****************************************************************** * Foundation UI component ******************************************************************/ col = FOUNDATION_START_COL; this.add(new TerminalUIComponent<Collection<Klondike.Foundation>>( klondike.getFoundations(), START_ROW, col) { Joiner joiner = Joiner.on(Strings.repeat(" ", SPACE_BETWEEN)); @Override public void writeToTerminal() { writeToTerminal(joiner.join(payload)); } @Override public void doAction() { boolean legal = false; if (movingFrom != null) { if (movingFrom.getClass() == TableauUIComponent.class) { legal = klondike.moveFromTableauToFoundation((Klondike.Tableau) movingFrom.payload); } else { legal = klondike.moveFromWasteToFoundation(); } } if (legal) { movingFrom.writeToTerminal(); this.writeToTerminal(); movingFrom = null; } } }); }}; componentOrder = new LoopingListIterator<>(components); pointingTo = componentOrder.next(); start(); } private void onKeyPress(int codepoint) { switch (codepoint) { case ' ': pointingTo.doAction(); break; case 'a': case 'A': movePointerAndRedraw(true); break; case 'd': case 'D': movePointerAndRedraw(false); break; case 'r': case 'R': if (klondike.isGameOver()) { klondike = new Klondike(klondike.rules); } break; default: break; } pointingTo.receiveKeyPress(codepoint); } private void setCurBackground(String c) { term.setCurBackground(c); } private void movePointerAndRedraw(boolean left) { pointingTo.drawPointer(true); if (left) { movePointerLeft(); } else { movePointerRight(); } pointingTo.receiveFocus(); pointingTo.drawPointer(false); } private void movePointerRight() { pointingTo = componentOrder.next(); if (!lastDirectionRight) { pointingTo = componentOrder.next(); lastDirectionRight = true; } } private void movePointerLeft() { pointingTo = componentOrder.previous(); if (lastDirectionRight) { pointingTo = componentOrder.previous(); lastDirectionRight = false; } } private void start() { klondike.init(); } public void quit() { this.quit = true; term.quit(); } @Override public void update(Observable o, Object arg) { String msg, color; if (o == klondike && arg instanceof Klondike.GameOver) { if (klondike.won()) { msg = " YOU WIN! "; color = "Green"; } else { msg = "GAME OVER!"; color = "Magenta"; } String s = "Press 'R' to restart"; term.setCurForeground(color); term.mvputs(10, term.getWidth() / 2 - 10, Strings.repeat("#", 20)); term.mvputs(11, term.getWidth() / 2 - 10, "#" + Strings.repeat(" ", 18) + "#"); term.mvputs(12, term.getWidth() / 2 - 10, "#" + String.format(" %s ", msg) + "#"); term.mvputs(13, term.getWidth() / 2 - 10, "#" + Strings.repeat(" ", 18) + "#"); term.mvputs(14, term.getWidth() / 2 - 10, Strings.repeat("#", 20)); term.mvputs(term.getHeight() - 1, term.getWidth() - s.length() - 2, s); } term.setCurForeground("Black"); } public abstract class TerminalUIComponent<T> { T payload; int startRow, startColumn; public TerminalUIComponent(T payload, int startRow, int startColumn) { this.payload = payload; this.startRow = startRow; this.startColumn = startColumn; } public abstract void doAction(); public void receiveFocus() {} public void receiveKeyPress(int codepoint) {} public void writeToTerminal() { this.writeToTerminal(payload.toString()); } public void writeToTerminal(String str) { term.mvputs(startRow, startColumn, str); } public void writeToTerminal(int rowOffset, int columnOffset, String str) { term.mvputs(startRow + rowOffset, startColumn + columnOffset, str); } /** * Draw or undraw the pointer indicating the current element. * * @param remove if {@code true} then remove the pointer, otherwise draw it */ public void drawPointer(boolean remove) { term.mvputs(startRow, startColumn - 3, remove ? " " : "-> "); } } public class TableauUIComponent extends TerminalUIComponent<Klondike.Tableau> { int pointerIndex; int lengthToClean; public TableauUIComponent(Klondike.Tableau payload, int column) { super(payload, TABLEAU_ROW, column); pointerIndex = payload.size() - 1; lengthToClean = payload.size(); } public void writeToTerminal() { for (int i = 0; i < Math.max(payload.size(), lengthToClean); ++i) { if (movingFrom == this && pointerIndex == i) { setCurBackground("Yellow"); } if (i == payload.size()) { setCurBackground("White"); } term.mvputs(startRow + i, startColumn, i < payload.size() ? payload.get(i).toString() : " "); } setCurBackground("White"); lengthToClean = payload.size(); } public void doAction() { boolean legal = false; if (movingFrom == this) { movingFrom = null; } else if (movingFrom == null) { if (!payload.isEmpty()) { movingFrom = this; } } else if (movingFrom.getClass() == TableauUIComponent.class) { TableauUIComponent _movingFrom = (TableauUIComponent) movingFrom; int numCards = _movingFrom.payload.size() - _movingFrom.pointerIndex; legal = klondike.moveFromTableauToTableau(_movingFrom.payload, this.payload, numCards); } else { legal = klondike.moveFromWasteToTableau(this.payload); } if (legal) { movingFrom.writeToTerminal(); writeToTerminal(); drawPointer(true); this.pointerIndex = payload.size() - 1; drawPointer(false); movingFrom = null; } } public void receiveFocus() { if (movingFrom != this) { pointerIndex = Math.max(payload.size() - 1, 0); } } public void receiveKeyPress(int codepoint) { switch (codepoint) { case 'w': case 'W': movePointerUp(); break; case 's': case 'S': movePointerDown(); break; default: break; } } public void movePointerUp() { if (pointerIndex > payload.size() - payload.countFaceup()) { drawPointer(true); --pointerIndex; drawPointer(false); } } public void movePointerDown() { if (pointerIndex < payload.size() - 1) { drawPointer(true); ++pointerIndex; drawPointer(false); } } public void drawPointer(boolean remove) { term.mvputs(startRow + pointerIndex, startColumn - 3, remove ? " " : "-> "); } } static class CommandLineParams { @Parameter(names = "--deal-one", description = "Deal one card at a time (instead of three).") private boolean dealOne = false; @Parameter(names = "--passes", description = "Maximum number of times through the deck.", converter = PassesConverter.class) private Klondike.Rules.Passes passes = Klondike.Rules.Passes.INFINITY; public class PassesConverter implements IStringConverter<Klondike.Rules.Passes> { @Override public Klondike.Rules.Passes convert(String value) { switch(value) { case "1": return Klondike.Rules.Passes.SINGLE; case "3": return Klondike.Rules.Passes.THREE; default: return Klondike.Rules.Passes.INFINITY; } } } } public static void main(String[] args) { CommandLineParams params = new TerminalUI.CommandLineParams(); new JCommander(params, args); Klondike.Rules rules = new Klondike.Rules( params.dealOne ? Klondike.Rules.Deal.DEAL_SINGLE : Klondike.Rules.Deal.DEAL_THREE, params.passes); TerminalUI ui = new TerminalUI(new Klondike(rules)); ui.init(null, null); ui.loop(); ui.quit(); } }
src/main/java/info/jayharris/klondike/TerminalUI.java
package info.jayharris.klondike; import com.beust.jcommander.IStringConverter; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.googlecode.blacken.colors.ColorNames; import com.googlecode.blacken.colors.ColorPalette; import com.googlecode.blacken.swing.SwingTerminal; import com.googlecode.blacken.terminal.*; import info.jayharris.cardgames.Deck; import org.apache.commons.collections4.iterators.LoopingListIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public class TerminalUI implements KlondikeUI, Observer { private Klondike klondike; private boolean quit; private ColorPalette palette; private CursesLikeAPI term = null; private TerminalUIComponent<?> pointingTo, movingFrom = null; private List<TerminalUIComponent<?>> components; private LoopingListIterator<TerminalUIComponent<?>> componentOrder; private boolean lastDirectionRight = true; // direction of last move -- // if componentOrder.next() => X, then an immediate call to // componentOrder.previous() will also => X. public final int START_ROW = 0, LEFT_COL = 5, SPACE_BETWEEN = 5, TABLEAU_ROW = 2, WASTE_CARDS_SHOWN = 6, WASTE_START_COL = LEFT_COL + "[24 cards]".length() + SPACE_BETWEEN, WASTE_MAX_WIDTH = "... XX XX XX XX XX XX".length(), FOUNDATION_START_COL = WASTE_START_COL + WASTE_MAX_WIDTH + SPACE_BETWEEN; final Logger logger = LoggerFactory.getLogger(TerminalUI.class); public TerminalUI(Klondike klondike) { this.klondike = klondike; this.klondike.addObserver(this); } protected boolean loop() { int key = BlackenKeys.NO_KEY; if (palette.containsKey("White")) { term.setCurBackground("White"); } if (palette.containsKey("Black")) { term.setCurForeground("Black"); } term.clear(); while (!this.quit) { for (TerminalUIComponent<?> component : components) { component.writeToTerminal(); } pointingTo.drawPointer(false); key = term.getch(); // getch automatically does a refresh onKeyPress(key); } term.refresh(); return this.quit; } public void init(TerminalInterface term, ColorPalette palette) { if (term == null) { this.term = new CursesLikeAPI(new SwingTerminal()); this.term.init("Klondike", 25, 80); } else { this.term = new CursesLikeAPI(term); } if (palette == null) { palette = new ColorPalette(); palette.addAll(ColorNames.XTERM_256_COLORS, false); palette.putMapping(ColorNames.SVG_COLORS); } this.palette = palette; this.term.setPalette(palette); // set up all of the deck, waste, foundation, tableau visual components components = new ArrayList<TerminalUIComponent<?>>() {{ int col; /****************************************************************** * Deck UI component ******************************************************************/ this.add(new TerminalUIComponent<Deck>(klondike.getDeck(), START_ROW, LEFT_COL) { @Override public void writeToTerminal() { super.writeToTerminal("[" + Strings.padStart(Integer.toString(klondike.getDeck().size()), 2, ' ') + " cards]"); } @Override public void doAction() { klondike.deal(); } }); /****************************************************************** * Waste UI component ******************************************************************/ this.add(new TerminalUIComponent<Klondike.Waste>(klondike.getWaste(), START_ROW, WASTE_START_COL) { @Override public void doAction() { // pick up the next card in the waste if (movingFrom == null && !payload.isEmpty()) { movingFrom = this; } // return the card to whence it came else { movingFrom = null; } } @Override public void writeToTerminal() { int sz = payload.size(); int index = Math.max(0, sz - WASTE_CARDS_SHOWN), strlen = 0; if (sz > WASTE_CARDS_SHOWN) { writeToTerminal("... "); strlen += "... ".length(); } while (index < sz) { if (index == sz - 1) { if (movingFrom == this) { setCurBackground("Yellow"); } writeToTerminal(0, strlen, payload.get(index).toString()); strlen += 2; } else { writeToTerminal(0, strlen, payload.get(index).toString() + " "); strlen += 3; } setCurBackground("White"); ++index; } while (strlen < WASTE_MAX_WIDTH) { writeToTerminal(0, strlen, " "); ++strlen; } } }); /****************************************************************** * Tableau UI components ******************************************************************/ col = LEFT_COL; for (int i = 0; i < 7; ++i) { this.add(new TableauUIComponent(klondike.getTableau(i), col)); col += "XX".length() + SPACE_BETWEEN; } /****************************************************************** * Foundation UI component ******************************************************************/ col = FOUNDATION_START_COL; this.add(new TerminalUIComponent<Collection<Klondike.Foundation>>( klondike.getFoundations(), START_ROW, col) { Joiner joiner = Joiner.on(Strings.repeat(" ", SPACE_BETWEEN)); @Override public void writeToTerminal() { writeToTerminal(joiner.join(payload)); } @Override public void doAction() { boolean legal = false; if (movingFrom != null) { if (movingFrom.getClass() == TableauUIComponent.class) { legal = klondike.moveFromTableauToFoundation((Klondike.Tableau) movingFrom.payload); } else { legal = klondike.moveFromWasteToFoundation(); } } if (legal) { movingFrom.writeToTerminal(); this.writeToTerminal(); movingFrom = null; } } }); }}; componentOrder = new LoopingListIterator(components); pointingTo = componentOrder.next(); start(); } private void onKeyPress(int codepoint) { switch (codepoint) { case ' ': pointingTo.doAction(); break; case 'a': case 'A': movePointerAndRedraw(true); break; case 'd': case 'D': movePointerAndRedraw(false); break; case 'r': case 'R': if (klondike.isGameOver()) { klondike = new Klondike(klondike.rules); } break; default: break; } pointingTo.receiveKeyPress(codepoint); } private void setCurBackground(String c) { term.setCurBackground(c); } private void movePointerAndRedraw(boolean left) { pointingTo.drawPointer(true); if (left) { movePointerLeft(); } else { movePointerRight(); } pointingTo.receiveFocus(); pointingTo.drawPointer(false); } private void movePointerRight() { pointingTo = componentOrder.next(); if (!lastDirectionRight) { pointingTo = componentOrder.next(); lastDirectionRight = true; } } private void movePointerLeft() { pointingTo = componentOrder.previous(); if (lastDirectionRight) { pointingTo = componentOrder.previous(); lastDirectionRight = false; } } private void start() { klondike.init(); } public void quit() { this.quit = true; term.quit(); } @Override public void update(Observable o, Object arg) { String msg, color; if (o == klondike && arg instanceof Klondike.GameOver) { if (klondike.won()) { msg = " YOU WIN! "; color = "Green"; } else { msg = "GAME OVER!"; color = "Magenta"; } String s = "Press 'R' to restart"; term.setCurForeground(color); term.mvputs(10, term.getWidth() / 2 - 10, Strings.repeat("#", 20)); term.mvputs(11, term.getWidth() / 2 - 10, "#" + Strings.repeat(" ", 18) + "#"); term.mvputs(12, term.getWidth() / 2 - 10, "#" + String.format(" %s ", msg) + "#"); term.mvputs(13, term.getWidth() / 2 - 10, "#" + Strings.repeat(" ", 18) + "#"); term.mvputs(14, term.getWidth() / 2 - 10, Strings.repeat("#", 20)); term.mvputs(term.getHeight() - 1, term.getWidth() - s.length() - 2, s); } term.setCurForeground("Black"); } public abstract class TerminalUIComponent<T> { T payload; int startRow, startColumn; public TerminalUIComponent(T payload, int startRow, int startColumn) { this.payload = payload; this.startRow = startRow; this.startColumn = startColumn; } public abstract void doAction(); public void receiveFocus() {} public void receiveKeyPress(int codepoint) {} public void writeToTerminal() { this.writeToTerminal(payload.toString()); } public void writeToTerminal(String str) { term.mvputs(startRow, startColumn, str); } public void writeToTerminal(int rowOffset, int columnOffset, String str) { term.mvputs(startRow + rowOffset, startColumn + columnOffset, str); } /** * Draw or undraw the pointer indicating the current element. * * @param remove if {@code true} then remove the pointer, otherwise draw it */ public void drawPointer(boolean remove) { term.mvputs(startRow, startColumn - 3, remove ? " " : "-> "); } } public class TableauUIComponent extends TerminalUIComponent<Klondike.Tableau> { int pointerIndex; int lengthToClean; static final String blank = " "; public TableauUIComponent(Klondike.Tableau payload, int column) { super(payload, TABLEAU_ROW, column); pointerIndex = payload.size() - 1; lengthToClean = payload.size(); } public void writeToTerminal() { for (int i = 0; i < Math.max(payload.size(), lengthToClean); ++i) { if (movingFrom == this && pointerIndex == i) { setCurBackground("Yellow"); } if (i == payload.size()) { setCurBackground("White"); } term.mvputs(startRow + i, startColumn, i < payload.size() ? payload.get(i).toString() : " "); } setCurBackground("White"); lengthToClean = payload.size(); } public void doAction() { boolean legal = false; if (movingFrom == this) { movingFrom = null; } else if (movingFrom == null) { if (!payload.isEmpty()) { movingFrom = this; } } else if (movingFrom.getClass() == TableauUIComponent.class) { TableauUIComponent _movingFrom = (TableauUIComponent) movingFrom; int numCards = _movingFrom.payload.size() - _movingFrom.pointerIndex; legal = klondike.moveFromTableauToTableau(_movingFrom.payload, this.payload, numCards); } else { legal = klondike.moveFromWasteToTableau(this.payload); } if (legal) { movingFrom.writeToTerminal(); writeToTerminal(); drawPointer(true); this.pointerIndex = payload.size() - 1; drawPointer(false); movingFrom = null; } } public void receiveFocus() { if (movingFrom != this) { pointerIndex = Math.max(payload.size() - 1, 0); } } public void receiveKeyPress(int codepoint) { switch (codepoint) { case 'w': case 'W': movePointerUp(); break; case 's': case 'S': movePointerDown(); break; default: break; } } public void movePointerUp() { if (pointerIndex > payload.size() - payload.countFaceup()) { drawPointer(true); --pointerIndex; drawPointer(false); } } public void movePointerDown() { if (pointerIndex < payload.size() - 1) { drawPointer(true); ++pointerIndex; drawPointer(false); } } public void drawPointer(boolean remove) { term.mvputs(startRow + pointerIndex, startColumn - 3, remove ? " " : "-> "); } } static class CommandLineParams { @Parameter(names = "--deal-one", description = "Deal one card at a time (instead of three).") private boolean dealOne = false; @Parameter(names = "--passes", description = "Maximum number of times through the deck.", converter = PassesConverter.class) private Klondike.Rules.Passes passes = Klondike.Rules.Passes.INFINITY; public class PassesConverter implements IStringConverter<Klondike.Rules.Passes> { @Override public Klondike.Rules.Passes convert(String value) { switch(value) { case "1": return Klondike.Rules.Passes.SINGLE; case "3": return Klondike.Rules.Passes.THREE; default: return Klondike.Rules.Passes.INFINITY; } } } } public static void main(String[] args) { CommandLineParams params = new TerminalUI.CommandLineParams(); new JCommander(params, args); Klondike.Rules rules = new Klondike.Rules( params.dealOne ? Klondike.Rules.Deal.DEAL_SINGLE : Klondike.Rules.Deal.DEAL_THREE, params.passes); TerminalUI ui = new TerminalUI(new Klondike(rules)); ui.init(null, null); ui.loop(); ui.quit(); } }
cleanup
src/main/java/info/jayharris/klondike/TerminalUI.java
cleanup
<ide><path>rc/main/java/info/jayharris/klondike/TerminalUI.java <ide> import com.googlecode.blacken.terminal.*; <ide> import info.jayharris.cardgames.Deck; <ide> import org.apache.commons.collections4.iterators.LoopingListIterator; <del>import org.slf4j.Logger; <del>import org.slf4j.LoggerFactory; <ide> <ide> import java.util.*; <ide> <ide> WASTE_MAX_WIDTH = "... XX XX XX XX XX XX".length(), <ide> FOUNDATION_START_COL = WASTE_START_COL + WASTE_MAX_WIDTH + SPACE_BETWEEN; <ide> <del> final Logger logger = LoggerFactory.getLogger(TerminalUI.class); <del> <ide> public TerminalUI(Klondike klondike) { <ide> this.klondike = klondike; <ide> this.klondike.addObserver(this); <ide> } <ide> <ide> protected boolean loop() { <del> int key = BlackenKeys.NO_KEY; <add> int key; <ide> if (palette.containsKey("White")) { <ide> term.setCurBackground("White"); <ide> } <ide> } <ide> }); <ide> }}; <del> componentOrder = new LoopingListIterator(components); <add> componentOrder = new LoopingListIterator<>(components); <ide> pointingTo = componentOrder.next(); <ide> <ide> start(); <ide> int pointerIndex; <ide> int lengthToClean; <ide> <del> static final String blank = " "; <del> <ide> public TableauUIComponent(Klondike.Tableau payload, int column) { <ide> super(payload, TABLEAU_ROW, column); <ide> pointerIndex = payload.size() - 1;
Java
mit
5597fb622705bef466d7437aa155aaedc86af6ae
0
FedericoPecora/meta-csp-framework,FedericoPecora/meta-csp-framework,FedericoPecora/meta-csp-framework
package multi.activity; import java.util.Vector; import multi.allenInterval.AllenIntervalConstraint; import multi.allenInterval.AllenIntervalNetworkSolver; import symbols.SymbolicValueConstraint; import symbols.SymbolicVariableConstraintSolver; import utility.UI.PlotActivityNetworkGantt; import framework.ConstraintNetwork; import framework.ConstraintSolver; import framework.Variable; import framework.multi.MultiConstraintSolver; public class ActivityNetworkSolver extends MultiConstraintSolver { /** * */ private static final long serialVersionUID = 4961558508886363042L; protected int IDs = 0; protected long origin; /** * @return the origin */ public long getOrigin() { return origin; } /** * @return the horizon */ public long getHorizon() { return horizon; } private long horizon; public ActivityNetworkSolver(long origin, long horizon) { super(new Class[] {AllenIntervalConstraint.class, SymbolicValueConstraint.class}, new Class[]{Activity.class}, createConstraintSolvers(origin,horizon,500)); this.origin = origin; this.horizon = horizon; } public ActivityNetworkSolver(long origin, long horizon, int numActivities) { super(new Class[] {AllenIntervalConstraint.class, SymbolicValueConstraint.class}, new Class[]{Activity.class}, createConstraintSolvers(origin,horizon,numActivities)); this.origin = origin; this.horizon = horizon; } private static ConstraintSolver[] createConstraintSolvers(long origin, long horizon, int numActivities) { ConstraintSolver[] ret = new ConstraintSolver[] {new AllenIntervalNetworkSolver(origin, horizon, numActivities), new SymbolicVariableConstraintSolver()}; return ret; } /** * Get the rigidity number belonging to the underlaying AllenIntervalNetworkSolver that in turn exploits an APSP solver * @param selectedVariableNames Only variable/components in this {@link Vector} will be plotted */ public double getRigidityNumber(){ return (((AllenIntervalNetworkSolver) (this.constraintSolvers[0]))).getRigidityNumber(); } /** * Draw all activities on Gantt chart */ public void drawAsGantt() { new PlotActivityNetworkGantt(this, null, "Activity Network Gantt"); } /** * Draw selected variables on Gantt chart * @param selectedVariableNames Only variable/components in this {@link Vector} will be plotted */ public void drawAsGantt( Vector<String> selectedVariableNames ) { new PlotActivityNetworkGantt(this, selectedVariableNames, "Activity Network Gantt"); } /** * Draw variables matching this {@link String} on Gantt chart * @param varsMatchingThis {@link String} that must be contained in a variable to be plotted */ public void drawAsGantt( String varsMatchingThis ) { Vector<String> selectedVariables = new Vector<String>(); for ( Variable v : this.getVariables() ) { if ( v.getComponent().contains(varsMatchingThis)) { selectedVariables.add(v.getComponent()); } } new PlotActivityNetworkGantt(this, selectedVariables, "Activity Network Gantt"); } @Override protected ConstraintNetwork createConstraintNetwork() { return new ActivityNetwork(this); } @Override protected Variable createVariableSub() { return new Activity(this, IDs++, this.constraintSolvers); } @Override protected Variable[] createVariablesSub(int num) { Variable[] ret = new Variable[num]; for (int i = 0; i < num; i++) ret[i] = new Activity(this, IDs++, this.constraintSolvers); return ret; } @Override public boolean propagate() { // For now, does nothing... return true; } @Override protected void removeVariableSub(Variable v) { // TODO Auto-generated method stub } @Override protected void removeVariablesSub(Variable[] v) { // TODO Auto-generated method stub } }
src/main/java/multi/activity/ActivityNetworkSolver.java
package multi.activity; import java.util.Vector; import multi.allenInterval.AllenIntervalConstraint; import multi.allenInterval.AllenIntervalNetworkSolver; import symbols.SymbolicValueConstraint; import symbols.SymbolicVariableConstraintSolver; import utility.UI.PlotActivityNetworkGantt; import framework.ConstraintNetwork; import framework.ConstraintSolver; import framework.Variable; import framework.multi.MultiConstraintSolver; public class ActivityNetworkSolver extends MultiConstraintSolver { /** * */ private static final long serialVersionUID = 4961558508886363042L; protected int IDs = 0; protected long origin; /** * @return the origin */ public long getOrigin() { return origin; } /** * @return the horizon */ public long getHorizon() { return horizon; } private long horizon; public ActivityNetworkSolver(long origin, long horizon) { super(new Class[] {AllenIntervalConstraint.class, SymbolicValueConstraint.class}, new Class[]{Activity.class}, createConstraintSolvers(origin,horizon,500)); this.origin = origin; this.horizon = horizon; } public ActivityNetworkSolver(long origin, long horizon, int numActivities) { super(new Class[] {AllenIntervalConstraint.class, SymbolicValueConstraint.class}, new Class[]{Activity.class}, createConstraintSolvers(origin,horizon,numActivities)); this.origin = origin; this.horizon = horizon; } private static ConstraintSolver[] createConstraintSolvers(long origin, long horizon, int numActivities) { ConstraintSolver[] ret = new ConstraintSolver[] {new AllenIntervalNetworkSolver(origin, horizon, numActivities), new SymbolicVariableConstraintSolver()}; return ret; } /** * Draw all activities on Gantt chart */ public void drawAsGantt() { new PlotActivityNetworkGantt(this, null, "Activity Network Gantt"); } /** * Draw selected variables on Gantt chart * @param selectedVariableNames Only variable/components in this {@link Vector} will be plotted */ public void drawAsGantt( Vector<String> selectedVariableNames ) { new PlotActivityNetworkGantt(this, selectedVariableNames, "Activity Network Gantt"); } /** * Draw variables matching this {@link String} on Gantt chart * @param varsMatchingThis {@link String} that must be contained in a variable to be plotted */ public void drawAsGantt( String varsMatchingThis ) { Vector<String> selectedVariables = new Vector<String>(); for ( Variable v : this.getVariables() ) { if ( v.getComponent().contains(varsMatchingThis)) { selectedVariables.add(v.getComponent()); } } new PlotActivityNetworkGantt(this, selectedVariables, "Activity Network Gantt"); } @Override protected ConstraintNetwork createConstraintNetwork() { return new ActivityNetwork(this); } @Override protected Variable createVariableSub() { return new Activity(this, IDs++, this.constraintSolvers); } @Override protected Variable[] createVariablesSub(int num) { Variable[] ret = new Variable[num]; for (int i = 0; i < num; i++) ret[i] = new Activity(this, IDs++, this.constraintSolvers); return ret; } @Override public boolean propagate() { // For now, does nothing... return true; } @Override protected void removeVariableSub(Variable v) { // TODO Auto-generated method stub } @Override protected void removeVariablesSub(Variable[] v) { // TODO Auto-generated method stub } }
Imported in ActivityNetworkSolver the possibility to get the rigidity number relaterd to the underlaying AllenIntervalConstraintSolver --Mau
src/main/java/multi/activity/ActivityNetworkSolver.java
Imported in ActivityNetworkSolver the possibility to get the rigidity number relaterd to the underlaying AllenIntervalConstraintSolver --Mau
<ide><path>rc/main/java/multi/activity/ActivityNetworkSolver.java <ide> private static ConstraintSolver[] createConstraintSolvers(long origin, long horizon, int numActivities) { <ide> ConstraintSolver[] ret = new ConstraintSolver[] {new AllenIntervalNetworkSolver(origin, horizon, numActivities), new SymbolicVariableConstraintSolver()}; <ide> return ret; <add> } <add> <add> <add> /** <add> * Get the rigidity number belonging to the underlaying AllenIntervalNetworkSolver that in turn exploits an APSP solver <add> * @param selectedVariableNames Only variable/components in this {@link Vector} will be plotted <add> */ <add> public double getRigidityNumber(){ <add> return (((AllenIntervalNetworkSolver) (this.constraintSolvers[0]))).getRigidityNumber(); <ide> } <ide> <ide> /**
Java
apache-2.0
8f0455f7acffa591fcf1388cd21a72c6f268f947
0
hyvas/libgdx,bladecoder/libgdx,fwolff/libgdx,FredGithub/libgdx,cypherdare/libgdx,josephknight/libgdx,stinsonga/libgdx,MikkelTAndersen/libgdx,fwolff/libgdx,ttencate/libgdx,MikkelTAndersen/libgdx,MovingBlocks/libgdx,cypherdare/libgdx,MovingBlocks/libgdx,MikkelTAndersen/libgdx,tommyettinger/libgdx,hyvas/libgdx,codepoke/libgdx,sarkanyi/libgdx,hyvas/libgdx,codepoke/libgdx,tommyettinger/libgdx,sarkanyi/libgdx,alex-dorokhov/libgdx,libgdx/libgdx,MikkelTAndersen/libgdx,josephknight/libgdx,MikkelTAndersen/libgdx,FredGithub/libgdx,ttencate/libgdx,bladecoder/libgdx,tommyettinger/libgdx,sarkanyi/libgdx,alex-dorokhov/libgdx,MovingBlocks/libgdx,samskivert/libgdx,FredGithub/libgdx,NathanSweet/libgdx,FredGithub/libgdx,hyvas/libgdx,Zomby2D/libgdx,stinsonga/libgdx,MikkelTAndersen/libgdx,alex-dorokhov/libgdx,stinsonga/libgdx,samskivert/libgdx,sarkanyi/libgdx,MovingBlocks/libgdx,FredGithub/libgdx,ttencate/libgdx,fwolff/libgdx,Zomby2D/libgdx,libgdx/libgdx,alex-dorokhov/libgdx,NathanSweet/libgdx,josephknight/libgdx,tommyettinger/libgdx,libgdx/libgdx,stinsonga/libgdx,MovingBlocks/libgdx,Zomby2D/libgdx,bladecoder/libgdx,josephknight/libgdx,hyvas/libgdx,fwolff/libgdx,FredGithub/libgdx,FredGithub/libgdx,stinsonga/libgdx,MikkelTAndersen/libgdx,samskivert/libgdx,MovingBlocks/libgdx,libgdx/libgdx,cypherdare/libgdx,josephknight/libgdx,sarkanyi/libgdx,libgdx/libgdx,hyvas/libgdx,Zomby2D/libgdx,samskivert/libgdx,alex-dorokhov/libgdx,ttencate/libgdx,fwolff/libgdx,fwolff/libgdx,codepoke/libgdx,samskivert/libgdx,ttencate/libgdx,sarkanyi/libgdx,codepoke/libgdx,sarkanyi/libgdx,alex-dorokhov/libgdx,bladecoder/libgdx,FredGithub/libgdx,codepoke/libgdx,ttencate/libgdx,josephknight/libgdx,MikkelTAndersen/libgdx,NathanSweet/libgdx,samskivert/libgdx,MovingBlocks/libgdx,alex-dorokhov/libgdx,alex-dorokhov/libgdx,NathanSweet/libgdx,samskivert/libgdx,fwolff/libgdx,josephknight/libgdx,NathanSweet/libgdx,josephknight/libgdx,hyvas/libgdx,ttencate/libgdx,codepoke/libgdx,fwolff/libgdx,hyvas/libgdx,bladecoder/libgdx,codepoke/libgdx,cypherdare/libgdx,ttencate/libgdx,codepoke/libgdx,tommyettinger/libgdx,samskivert/libgdx,sarkanyi/libgdx,cypherdare/libgdx,MovingBlocks/libgdx,Zomby2D/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.utils.ArraySelection; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent; import com.badlogic.gdx.scenes.scene2d.utils.Cullable; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.scenes.scene2d.utils.UIUtils; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectSet; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pools; /** A list (aka list box) displays textual items and highlights the currently selected item. * <p> * {@link ChangeEvent} is fired when the list selection changes. * <p> * The preferred size of the list is determined by the text bounds of the items and the size of the {@link ListStyle#selection}. * @author mzechner * @author Nathan Sweet */ public class List<T> extends Widget implements Cullable { ListStyle style; final Array<T> items = new Array(); final ArraySelection<T> selection = new ArraySelection(items); private Rectangle cullingArea; private float prefWidth, prefHeight; float itemHeight; private int alignment = Align.left; int touchDown; public List (Skin skin) { this(skin.get(ListStyle.class)); } public List (Skin skin, String styleName) { this(skin.get(styleName, ListStyle.class)); } public List (ListStyle style) { selection.setActor(this); selection.setRequired(true); setStyle(style); setSize(getPrefWidth(), getPrefHeight()); addListener(new InputListener() { public boolean keyDown (InputEvent event, int keycode) { if (keycode == Keys.A && UIUtils.ctrl() && selection.getMultiple()) { selection.clear(); selection.addAll(items); return true; } return false; } public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { if (pointer != 0 || button != 0) return false; if (selection.isDisabled()) return false; if (selection.getMultiple()) getStage().setKeyboardFocus(List.this); if (items.size == 0) return false; float height = getHeight(); Drawable background = List.this.style.background; if (background != null) { height -= background.getTopHeight() + background.getBottomHeight(); y -= background.getBottomHeight(); } int index = (int)((height - y) / itemHeight); index = Math.max(0, index); index = Math.min(items.size - 1, index); selection.choose(items.get(index)); touchDown = index; return true; } public void touchUp (InputEvent event, float x, float y, int pointer, int button) { if (pointer != 0 || button != 0) return; touchDown = -1; } public void exit (InputEvent event, float x, float y, int pointer, Actor toActor) { if (pointer != 0) return; touchDown = -1; } }); } public void setStyle (ListStyle style) { if (style == null) throw new IllegalArgumentException("style cannot be null."); this.style = style; invalidateHierarchy(); } /** Returns the list's style. Modifying the returned style may not have an effect until {@link #setStyle(ListStyle)} is * called. */ public ListStyle getStyle () { return style; } public void layout () { BitmapFont font = style.font; Drawable selectedDrawable = style.selection; itemHeight = font.getCapHeight() - font.getDescent() * 2; itemHeight += selectedDrawable.getTopHeight() + selectedDrawable.getBottomHeight(); prefWidth = 0; Pool<GlyphLayout> layoutPool = Pools.get(GlyphLayout.class); GlyphLayout layout = layoutPool.obtain(); for (int i = 0; i < items.size; i++) { layout.setText(font, toString(items.get(i))); prefWidth = Math.max(layout.width, prefWidth); } layoutPool.free(layout); prefWidth += selectedDrawable.getLeftWidth() + selectedDrawable.getRightWidth(); prefHeight = items.size * itemHeight; Drawable background = style.background; if (background != null) { prefWidth += background.getLeftWidth() + background.getRightWidth(); prefHeight += background.getTopHeight() + background.getBottomHeight(); } } @Override public void draw (Batch batch, float parentAlpha) { validate(); BitmapFont font = style.font; Drawable selectedDrawable = style.selection; Color fontColorSelected = style.fontColorSelected; Color fontColorUnselected = style.fontColorUnselected; Color color = getColor(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); float x = getX(), y = getY(), width = getWidth(), height = getHeight(); float itemY = height; Drawable background = style.background; if (background != null) { background.draw(batch, x, y, width, height); float leftWidth = background.getLeftWidth(); x += leftWidth; itemY -= background.getTopHeight(); width -= leftWidth + background.getRightWidth(); } float textOffsetX = selectedDrawable.getLeftWidth(), textWidth = width - textOffsetX - selectedDrawable.getRightWidth(); float textOffsetY = selectedDrawable.getTopHeight() - font.getDescent(); font.setColor(fontColorUnselected.r, fontColorUnselected.g, fontColorUnselected.b, fontColorUnselected.a * parentAlpha); for (int i = 0; i < items.size; i++) { if (cullingArea == null || (itemY - itemHeight <= cullingArea.y + cullingArea.height && itemY >= cullingArea.y)) { T item = items.get(i); boolean selected = selection.contains(item); if (selected) { Drawable drawable = selectedDrawable; if (touchDown == i && style.down != null) drawable = style.down; drawable.draw(batch, x, y + itemY - itemHeight, width, itemHeight); font.setColor(fontColorSelected.r, fontColorSelected.g, fontColorSelected.b, fontColorSelected.a * parentAlpha); } drawItem(batch, font, i, item, x + textOffsetX, y + itemY - textOffsetY, textWidth); if (selected) { font.setColor(fontColorUnselected.r, fontColorUnselected.g, fontColorUnselected.b, fontColorUnselected.a * parentAlpha); } } else if (itemY < cullingArea.y) { break; } itemY -= itemHeight; } } protected GlyphLayout drawItem (Batch batch, BitmapFont font, int index, T item, float x, float y, float width) { String string = toString(item); return font.draw(batch, string, x, y, 0, string.length(), width, alignment, false, "..."); } public ArraySelection<T> getSelection () { return selection; } /** Returns the first selected item, or null. */ public T getSelected () { return selection.first(); } /** Sets the selection to only the passed item, if it is a possible choice. * @param item May be null. */ public void setSelected (T item) { if (items.contains(item, false)) selection.set(item); else if (selection.getRequired() && items.size > 0) selection.set(items.first()); else selection.clear(); } /** @return The index of the first selected item. The top item has an index of 0. Nothing selected has an index of -1. */ public int getSelectedIndex () { ObjectSet<T> selected = selection.items(); return selected.size == 0 ? -1 : items.indexOf(selected.first(), false); } /** Sets the selection to only the selected index. */ public void setSelectedIndex (int index) { if (index < -1 || index >= items.size) throw new IllegalArgumentException("index must be >= -1 and < " + items.size + ": " + index); if (index == -1) { selection.clear(); } else { selection.set(items.get(index)); } } public void setItems (T... newItems) { if (newItems == null) throw new IllegalArgumentException("newItems cannot be null."); float oldPrefWidth = getPrefWidth(), oldPrefHeight = getPrefHeight(); items.clear(); items.addAll(newItems); selection.validate(); invalidate(); if (oldPrefWidth != getPrefWidth() || oldPrefHeight != getPrefHeight()) invalidateHierarchy(); } /** Sets the items visible in the list, clearing the selection if it is no longer valid. If a selection is * {@link ArraySelection#getRequired()}, the first item is selected. */ public void setItems (Array newItems) { if (newItems == null) throw new IllegalArgumentException("newItems cannot be null."); float oldPrefWidth = getPrefWidth(), oldPrefHeight = getPrefHeight(); items.clear(); items.addAll(newItems); selection.validate(); invalidate(); if (oldPrefWidth != getPrefWidth() || oldPrefHeight != getPrefHeight()) invalidateHierarchy(); } public void clearItems () { if (items.size == 0) return; items.clear(); selection.clear(); invalidateHierarchy(); } /** Returns the internal items array. If modified, {@link #setItems(Array)} must be called to reflect the changes. */ public Array<T> getItems () { return items; } public float getItemHeight () { return itemHeight; } public float getPrefWidth () { validate(); return prefWidth; } public float getPrefHeight () { validate(); return prefHeight; } protected String toString (T obj) { return obj.toString(); } public void setCullingArea (Rectangle cullingArea) { this.cullingArea = cullingArea; } /** Sets the horizontal alignment of the list items. * @param alignment See {@link Align}. */ public void setAlignment (int alignment) { this.alignment = alignment; } /** The style for a list, see {@link List}. * @author mzechner * @author Nathan Sweet */ static public class ListStyle { public BitmapFont font; public Color fontColorSelected = new Color(1, 1, 1, 1); public Color fontColorUnselected = new Color(1, 1, 1, 1); public Drawable selection; /** Optional. */ public Drawable down, background; public ListStyle () { } public ListStyle (BitmapFont font, Color fontColorSelected, Color fontColorUnselected, Drawable selection) { this.font = font; this.fontColorSelected.set(fontColorSelected); this.fontColorUnselected.set(fontColorUnselected); this.selection = selection; } public ListStyle (ListStyle style) { this.font = style.font; this.fontColorSelected.set(style.fontColorSelected); this.fontColorUnselected.set(style.fontColorUnselected); this.selection = style.selection; this.down = style.down; } } }
gdx/src/com/badlogic/gdx/scenes/scene2d/ui/List.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.utils.ArraySelection; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent; import com.badlogic.gdx.scenes.scene2d.utils.Cullable; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.scenes.scene2d.utils.UIUtils; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectSet; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pools; /** A list (aka list box) displays textual items and highlights the currently selected item. * <p> * {@link ChangeEvent} is fired when the list selection changes. * <p> * The preferred size of the list is determined by the text bounds of the items and the size of the {@link ListStyle#selection}. * @author mzechner * @author Nathan Sweet */ public class List<T> extends Widget implements Cullable { private ListStyle style; final Array<T> items = new Array(); final ArraySelection<T> selection = new ArraySelection(items); private Rectangle cullingArea; private float prefWidth, prefHeight; private float itemHeight; private int alignment = Align.left; public List (Skin skin) { this(skin.get(ListStyle.class)); } public List (Skin skin, String styleName) { this(skin.get(styleName, ListStyle.class)); } public List (ListStyle style) { selection.setActor(this); selection.setRequired(true); setStyle(style); setSize(getPrefWidth(), getPrefHeight()); addListener(new InputListener() { public boolean keyDown (InputEvent event, int keycode) { if (keycode == Keys.A && UIUtils.ctrl() && selection.getMultiple()) { selection.clear(); selection.addAll(items); return true; } return false; } public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { if (pointer == 0 && button != 0) return false; if (selection.isDisabled()) return false; if (selection.getMultiple()) getStage().setKeyboardFocus(List.this); List.this.touchDown(y); return true; } }); } void touchDown (float y) { if (items.size == 0) return; float height = getHeight(); if (style.background != null) { height -= style.background.getTopHeight() + style.background.getBottomHeight(); y -= style.background.getBottomHeight(); } int index = (int)((height - y) / itemHeight); index = Math.max(0, index); index = Math.min(items.size - 1, index); selection.choose(items.get(index)); } public void setStyle (ListStyle style) { if (style == null) throw new IllegalArgumentException("style cannot be null."); this.style = style; invalidateHierarchy(); } /** Returns the list's style. Modifying the returned style may not have an effect until {@link #setStyle(ListStyle)} is * called. */ public ListStyle getStyle () { return style; } public void layout () { final BitmapFont font = style.font; final Drawable selectedDrawable = style.selection; itemHeight = font.getCapHeight() - font.getDescent() * 2; itemHeight += selectedDrawable.getTopHeight() + selectedDrawable.getBottomHeight(); prefWidth = 0; Pool<GlyphLayout> layoutPool = Pools.get(GlyphLayout.class); GlyphLayout layout = layoutPool.obtain(); for (int i = 0; i < items.size; i++) { layout.setText(font, toString(items.get(i))); prefWidth = Math.max(layout.width, prefWidth); } layoutPool.free(layout); prefWidth += selectedDrawable.getLeftWidth() + selectedDrawable.getRightWidth(); prefHeight = items.size * itemHeight; Drawable background = style.background; if (background != null) { prefWidth += background.getLeftWidth() + background.getRightWidth(); prefHeight += background.getTopHeight() + background.getBottomHeight(); } } @Override public void draw (Batch batch, float parentAlpha) { validate(); BitmapFont font = style.font; Drawable selectedDrawable = style.selection; Color fontColorSelected = style.fontColorSelected; Color fontColorUnselected = style.fontColorUnselected; Color color = getColor(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); float x = getX(), y = getY(), width = getWidth(), height = getHeight(); float itemY = height; Drawable background = style.background; if (background != null) { background.draw(batch, x, y, width, height); float leftWidth = background.getLeftWidth(); x += leftWidth; itemY -= background.getTopHeight(); width -= leftWidth + background.getRightWidth(); } float textOffsetX = selectedDrawable.getLeftWidth(), textWidth = width - textOffsetX - selectedDrawable.getRightWidth(); float textOffsetY = selectedDrawable.getTopHeight() - font.getDescent(); font.setColor(fontColorUnselected.r, fontColorUnselected.g, fontColorUnselected.b, fontColorUnselected.a * parentAlpha); for (int i = 0; i < items.size; i++) { if (cullingArea == null || (itemY - itemHeight <= cullingArea.y + cullingArea.height && itemY >= cullingArea.y)) { T item = items.get(i); boolean selected = selection.contains(item); if (selected) { selectedDrawable.draw(batch, x, y + itemY - itemHeight, width, itemHeight); font.setColor(fontColorSelected.r, fontColorSelected.g, fontColorSelected.b, fontColorSelected.a * parentAlpha); } drawItem(batch, font, i, item, x + textOffsetX, y + itemY - textOffsetY, textWidth); if (selected) { font.setColor(fontColorUnselected.r, fontColorUnselected.g, fontColorUnselected.b, fontColorUnselected.a * parentAlpha); } } else if (itemY < cullingArea.y) { break; } itemY -= itemHeight; } } protected GlyphLayout drawItem (Batch batch, BitmapFont font, int index, T item, float x, float y, float width) { String string = toString(item); return font.draw(batch, string, x, y, 0, string.length(), width, alignment, false, "..."); } public ArraySelection<T> getSelection () { return selection; } /** Returns the first selected item, or null. */ public T getSelected () { return selection.first(); } /** Sets the selection to only the passed item, if it is a possible choice. * @param item May be null. */ public void setSelected (T item) { if (items.contains(item, false)) selection.set(item); else if (selection.getRequired() && items.size > 0) selection.set(items.first()); else selection.clear(); } /** @return The index of the first selected item. The top item has an index of 0. Nothing selected has an index of -1. */ public int getSelectedIndex () { ObjectSet<T> selected = selection.items(); return selected.size == 0 ? -1 : items.indexOf(selected.first(), false); } /** Sets the selection to only the selected index. */ public void setSelectedIndex (int index) { if (index < -1 || index >= items.size) throw new IllegalArgumentException("index must be >= -1 and < " + items.size + ": " + index); if (index == -1) { selection.clear(); } else { selection.set(items.get(index)); } } public void setItems (T... newItems) { if (newItems == null) throw new IllegalArgumentException("newItems cannot be null."); float oldPrefWidth = getPrefWidth(), oldPrefHeight = getPrefHeight(); items.clear(); items.addAll(newItems); selection.validate(); invalidate(); if (oldPrefWidth != getPrefWidth() || oldPrefHeight != getPrefHeight()) invalidateHierarchy(); } /** Sets the items visible in the list, clearing the selection if it is no longer valid. If a selection is * {@link ArraySelection#getRequired()}, the first item is selected. */ public void setItems (Array newItems) { if (newItems == null) throw new IllegalArgumentException("newItems cannot be null."); float oldPrefWidth = getPrefWidth(), oldPrefHeight = getPrefHeight(); items.clear(); items.addAll(newItems); selection.validate(); invalidate(); if (oldPrefWidth != getPrefWidth() || oldPrefHeight != getPrefHeight()) invalidateHierarchy(); } public void clearItems () { if (items.size == 0) return; items.clear(); selection.clear(); invalidateHierarchy(); } /** Returns the internal items array. If modified, {@link #setItems(Array)} must be called to reflect the changes. */ public Array<T> getItems () { return items; } public float getItemHeight () { return itemHeight; } public float getPrefWidth () { validate(); return prefWidth; } public float getPrefHeight () { validate(); return prefHeight; } protected String toString (T obj) { return obj.toString(); } public void setCullingArea (Rectangle cullingArea) { this.cullingArea = cullingArea; } /** Sets the horizontal alignment of the list items. * @param alignment See {@link Align}. */ public void setAlignment (int alignment) { this.alignment = alignment; } /** The style for a list, see {@link List}. * @author mzechner * @author Nathan Sweet */ static public class ListStyle { public BitmapFont font; public Color fontColorSelected = new Color(1, 1, 1, 1); public Color fontColorUnselected = new Color(1, 1, 1, 1); public Drawable selection; /** Optional. */ public Drawable background; public ListStyle () { } public ListStyle (BitmapFont font, Color fontColorSelected, Color fontColorUnselected, Drawable selection) { this.font = font; this.fontColorSelected.set(fontColorSelected); this.fontColorUnselected.set(fontColorUnselected); this.selection = selection; } public ListStyle (ListStyle style) { this.font = style.font; this.fontColorSelected.set(style.fontColorSelected); this.fontColorUnselected.set(style.fontColorUnselected); this.selection = style.selection; } } }
[scene2d] Added down drawable for List.
gdx/src/com/badlogic/gdx/scenes/scene2d/ui/List.java
[scene2d] Added down drawable for List.
<ide><path>dx/src/com/badlogic/gdx/scenes/scene2d/ui/List.java <ide> import com.badlogic.gdx.graphics.g2d.BitmapFont; <ide> import com.badlogic.gdx.graphics.g2d.GlyphLayout; <ide> import com.badlogic.gdx.math.Rectangle; <add>import com.badlogic.gdx.scenes.scene2d.Actor; <ide> import com.badlogic.gdx.scenes.scene2d.InputEvent; <ide> import com.badlogic.gdx.scenes.scene2d.InputListener; <ide> import com.badlogic.gdx.scenes.scene2d.utils.ArraySelection; <ide> * @author mzechner <ide> * @author Nathan Sweet */ <ide> public class List<T> extends Widget implements Cullable { <del> private ListStyle style; <add> ListStyle style; <ide> final Array<T> items = new Array(); <ide> final ArraySelection<T> selection = new ArraySelection(items); <ide> private Rectangle cullingArea; <ide> private float prefWidth, prefHeight; <del> private float itemHeight; <add> float itemHeight; <ide> private int alignment = Align.left; <add> int touchDown; <ide> <ide> public List (Skin skin) { <ide> this(skin.get(ListStyle.class)); <ide> } <ide> <ide> public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { <del> if (pointer == 0 && button != 0) return false; <add> if (pointer != 0 || button != 0) return false; <ide> if (selection.isDisabled()) return false; <ide> if (selection.getMultiple()) getStage().setKeyboardFocus(List.this); <del> List.this.touchDown(y); <add> if (items.size == 0) return false; <add> float height = getHeight(); <add> Drawable background = List.this.style.background; <add> if (background != null) { <add> height -= background.getTopHeight() + background.getBottomHeight(); <add> y -= background.getBottomHeight(); <add> } <add> int index = (int)((height - y) / itemHeight); <add> index = Math.max(0, index); <add> index = Math.min(items.size - 1, index); <add> selection.choose(items.get(index)); <add> touchDown = index; <ide> return true; <ide> } <add> <add> public void touchUp (InputEvent event, float x, float y, int pointer, int button) { <add> if (pointer != 0 || button != 0) return; <add> touchDown = -1; <add> } <add> <add> public void exit (InputEvent event, float x, float y, int pointer, Actor toActor) { <add> if (pointer != 0) return; <add> touchDown = -1; <add> } <ide> }); <del> } <del> <del> void touchDown (float y) { <del> if (items.size == 0) return; <del> float height = getHeight(); <del> if (style.background != null) { <del> height -= style.background.getTopHeight() + style.background.getBottomHeight(); <del> y -= style.background.getBottomHeight(); <del> } <del> int index = (int)((height - y) / itemHeight); <del> index = Math.max(0, index); <del> index = Math.min(items.size - 1, index); <del> selection.choose(items.get(index)); <ide> } <ide> <ide> public void setStyle (ListStyle style) { <ide> } <ide> <ide> public void layout () { <del> final BitmapFont font = style.font; <del> final Drawable selectedDrawable = style.selection; <add> BitmapFont font = style.font; <add> Drawable selectedDrawable = style.selection; <ide> <ide> itemHeight = font.getCapHeight() - font.getDescent() * 2; <ide> itemHeight += selectedDrawable.getTopHeight() + selectedDrawable.getBottomHeight(); <ide> T item = items.get(i); <ide> boolean selected = selection.contains(item); <ide> if (selected) { <del> selectedDrawable.draw(batch, x, y + itemY - itemHeight, width, itemHeight); <add> Drawable drawable = selectedDrawable; <add> if (touchDown == i && style.down != null) drawable = style.down; <add> drawable.draw(batch, x, y + itemY - itemHeight, width, itemHeight); <ide> font.setColor(fontColorSelected.r, fontColorSelected.g, fontColorSelected.b, fontColorSelected.a * parentAlpha); <ide> } <ide> drawItem(batch, font, i, item, x + textOffsetX, y + itemY - textOffsetY, textWidth); <ide> public Color fontColorUnselected = new Color(1, 1, 1, 1); <ide> public Drawable selection; <ide> /** Optional. */ <del> public Drawable background; <add> public Drawable down, background; <ide> <ide> public ListStyle () { <ide> } <ide> this.fontColorSelected.set(style.fontColorSelected); <ide> this.fontColorUnselected.set(style.fontColorUnselected); <ide> this.selection = style.selection; <add> this.down = style.down; <ide> } <ide> } <ide> }
Java
mit
9072bfa4f54bee1379e28620b366bfc84bdb6063
0
Bimde/Blackjack-Server
package connection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import gameplay.Dealer; import utilities.ClientList; import utilities.Validator; public class Client implements Runnable, Comparable<Client> { private Server server; private Socket socket; private BufferedReader input; private PrintWriter output; private String name; private boolean connected; private Dealer dealer; public void setDealer(Dealer dealer) { this.dealer = dealer; } // Whether or not the player is ready to start the game private boolean isReady = false; // Potential Player or Spectator object private Player player; // 'U' for unassigned, 'P' for player and 'S' for spectator private char userType; /** * Disconnect/timeout the client. */ public void disconnect() { if (this.userType == 'P') { System.out.println(this.player.getPlayerNo() + " has disconnected"); this.server.queueMessage("! " + this.player.getPlayerNo()); } else { System.out.println("Client has disconnected"); } this.userType = 'U'; this.connected = false; try { this.input.close(); this.socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.output.close(); if (this.isPlayer()) { this.server.disconnectPlayer(this); } this.server.disconnectClient(this); } /** * Constructor for a new Client object. * * @param client * the socket of the client. * @param server * the server to put the client on. */ public Client(Socket client, Server server) { this.socket = client; this.connected = true; this.server = server; } @Override public void run() { try { this.output = new PrintWriter(this.socket.getOutputStream()); } catch (IOException e) { System.out.println("Error getting client's output stream"); e.printStackTrace(); this.connected = false; } try { this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); } catch (IOException e) { System.out.println("Error getting client's input stream"); e.printStackTrace(); this.connected = false; } try { while (this.name == null) { String newName = input.readLine(); if (Validator.isValidName(newName)) { this.name = newName; } else { this.sendMessage("% FORMATERROR"); } } System.out.println("New user registered as " + name); } catch (IOException e) { this.disconnect(); this.connected = false; } // The user is unassigned at first this.userType = 'U'; // Set the user's account type, either enter the user into the game or // assign as a spectator while (this.userType == 'U' && this.connected) { try { String message = this.input.readLine(); if (message.equalsIgnoreCase("PLAY")) { if (this.server.gameStarted()) { this.userType = 'S'; this.sendMessage("% LATE"); } else if (server.isFull()) { this.sendMessage("% FULL"); } else { this.userType = 'P'; this.sendMessage("% ACCEPTED"); this.server.newPlayer(this); player = new Player(this.server, this.server.returnAndUsePlayerNumber()); } } else if (message.equalsIgnoreCase("SPECTATE")) { this.userType = 'S'; this.sendMessage("% ACCEPTED"); } } catch (IOException e) { this.disconnect(); } } if (this.isPlayer()) { this.sendStartMessage(); // Check if the player is ready to start while (this.connected && !this.isReady) { try { String message = this.input.readLine(); if (message.equalsIgnoreCase("READY")) { this.server.ready(this.player.getPlayerNo()); this.isReady = true; System.out.println(name + " is ready"); } else { this.sendMessage("% FORMATERROR"); } } catch (IOException e) { this.disconnect(); } } } System.out.println("TEST1"); // Game while (this.isPlayer() && this.connected) { System.out.println("TEST2"); try { String message = this.input.readLine(); System.out.println(this.getPlayerNo() + " : " + this.name + "'S MESSAGGE: " + message); // If the player is betting then set the bet int betPlaced = 0; System.out.println(this.player.getCoins()); System.out.println("TEST3"); if (this.dealer.bettingIsActive() && this.player.getCurrentBet() == 0 && message.matches("[0-9]+") && (betPlaced = Integer.parseInt(message)) >= Server.MIN_BET && betPlaced <= this.player.getCoins()) { System.out.println("TEST4"); this.server.queueMessage("$ " + this.getPlayerNo() + " bets " + betPlaced); this.player.setCurrentBet(betPlaced); } else if (this.dealer.getCurrentPlayerTurn() == this.getPlayerNo() && message.equalsIgnoreCase("hit")) { this.player.setCurrentMove('H'); } else if (dealer.getCurrentPlayerTurn() == this.getPlayerNo() && message.equalsIgnoreCase("stand")) { this.player.setCurrentMove('S'); } else if (this.dealer.getCurrentPlayerTurn() == this.getPlayerNo() && message.equalsIgnoreCase("doubledown")) { this.player.setCurrentMove('D'); } else { System.out.println("???: " + betPlaced); this.sendMessage("% FORMATERROR"); } } catch (Exception e) { this.server.queueMessage("! " + this.getPlayerNo()); this.disconnect(); e.printStackTrace(); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Sends a private message to the client. * * @param message * the message to send. */ public void sendMessage(String message) { this.output.println(message); this.output.flush(); } protected Socket getSocket() { return this.socket; } public String getName() { return this.name; } public int getPlayerNo() { if (this.player == null) return -1; return this.player.getPlayerNo(); } public char getUserType() { return this.userType; } public boolean isPlayer() { return (this.userType == 'P'); } public void setUserType(char userType) { this.userType = userType; } public int getBet() { if (this.player == null) return -1; return this.player.getCurrentBet(); } public int getCoins() { if (this.player == null) return -1; return this.player.getCoins(); } public Player getPlayer() { return this.player; } public void setBet(int betAmount) { if (this.player == null) return; this.player.setCurrentBet(betAmount); } public void setCoins(int noOfCoins) { if (this.player == null) return; this.player.setCoins(noOfCoins); } public void setPlayer(Player player) { this.player = player; } private void sendStartMessage() { ClientList players = this.server.getCurrentPlayers(); String message = "@ " + this.getPlayerNo() + " " + (players.size() - 1); for (Client client : players) { String name = client.getName(); if (!name.equals(this.name)) message += " " + client.getName() + " //"; } this.sendMessage(message); } public boolean isReady() { return this.isReady; } public void setReady(boolean isReady) { this.isReady = isReady; } @Override public int compareTo(Client object) { return this.getPlayerNo() - object.getPlayerNo(); } @Override public String toString() { return this.name + " : " + this.player.getCoins(); } }
src/connection/Client.java
package connection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import gameplay.Dealer; import utilities.ClientList; import utilities.Validator; public class Client implements Runnable, Comparable<Client> { private Server server; private Socket socket; private BufferedReader input; private PrintWriter output; private String name; private boolean connected; private Dealer dealer; public void setDealer(Dealer dealer) { this.dealer = dealer; } // Whether or not the player is ready to start the game private boolean isReady = false; // Potential Player or Spectator object private Player player; // 'U' for unassigned, 'P' for player and 'S' for spectator private char userType; /** * Disconnect/timeout the client. */ public void disconnect() { if (this.userType == 'P') { System.out.println(this.player.getPlayerNo() + " has disconnected"); this.server.queueMessage("! " + this.player.getPlayerNo()); } else { System.out.println("Client has disconnected"); } this.userType = 'U'; this.connected = false; try { this.input.close(); this.socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.output.close(); if (this.isPlayer()) { this.server.disconnectPlayer(this); } this.server.disconnectClient(this); } /** * Constructor for a new Client object. * * @param client * the socket of the client. * @param server * the server to put the client on. */ public Client(Socket client, Server server) { this.socket = client; this.connected = true; this.server = server; } @Override public void run() { try { this.output = new PrintWriter(this.socket.getOutputStream()); } catch (IOException e) { System.out.println("Error getting client's output stream"); e.printStackTrace(); this.connected = false; } try { this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); } catch (IOException e) { System.out.println("Error getting client's input stream"); e.printStackTrace(); this.connected = false; } try { while (this.name == null) { String newName = input.readLine(); if (Validator.isValidName(newName)) { this.name = newName; } else { this.sendMessage("% FORMATERROR"); } } System.out.println("New user registered as " + name); } catch (IOException e) { this.disconnect(); this.connected = false; } // The user is unassigned at first this.userType = 'U'; // Set the user's account type, either enter the user into the game or // assign as a spectator while (this.userType == 'U' && this.connected) { try { String message = this.input.readLine(); if (message.equalsIgnoreCase("PLAY")) { if (this.server.gameStarted()) { this.userType = 'S'; this.sendMessage("% LATE"); } else if (server.isFull()) { this.sendMessage("% FULL"); } else { this.userType = 'P'; this.sendMessage("% ACCEPTED"); this.server.newPlayer(this); player = new Player(this.server, this.server.returnAndUsePlayerNumber()); } } else if (message.equalsIgnoreCase("SPECTATE")) { this.userType = 'S'; this.sendMessage("% ACCEPTED"); } } catch (IOException e) { this.disconnect(); } } if (this.isPlayer()) { this.sendStartMessage(); // Check if the player is ready to start while (this.connected && !this.isReady) { try { String message = this.input.readLine(); if (message.equalsIgnoreCase("READY")) { this.server.ready(this.player.getPlayerNo()); this.isReady = true; System.out.println(name + " is ready"); } else { this.sendMessage("% FORMATERROR"); } } catch (IOException e) { this.disconnect(); } } } System.out.println("TEST1"); // Game while (this.isPlayer() && this.connected) { System.out.println("TEST2"); try { String message = this.input.readLine(); System.out.println(this.getPlayerNo() + " : " + this.name + "'S MESSAGGE: " + message); // If the player is betting then set the bet int betPlaced = 0; System.out.println(this.player.getCoins()); System.out.println("TEST3"); if (this.dealer.bettingIsActive() && this.player.getCurrentBet() == 0 && message.matches("[0-9]+") && (betPlaced = Integer.parseInt(message)) >= Server.MIN_BET && betPlaced <= this.player.getCoins()) { System.out.println("TEST4"); this.server.queueMessage("$ " + this.getPlayerNo() + " bets " + betPlaced); this.player.setCurrentBet(betPlaced); } else if (this.dealer.getCurrentPlayerTurn() == this.getPlayerNo() && message.equalsIgnoreCase("hit")) { this.player.setCurrentMove('H'); } else if (dealer.getCurrentPlayerTurn() == this.getPlayerNo() && message.equalsIgnoreCase("stand")) { this.player.setCurrentMove('S'); } else if (this.dealer.getCurrentPlayerTurn() == this.getPlayerNo() && message.equalsIgnoreCase("doubledown")) { this.player.setCurrentMove('D'); } else { System.out.println("???: " + betPlaced); this.sendMessage("% FORMATERROR"); } } catch (IOException e) { this.server.queueMessage("! " + this.getPlayerNo()); this.disconnect(); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Sends a private message to the client. * * @param message * the message to send. */ public void sendMessage(String message) { this.output.println(message); this.output.flush(); } protected Socket getSocket() { return this.socket; } public String getName() { return this.name; } public int getPlayerNo() { if (this.player == null) return -1; return this.player.getPlayerNo(); } public char getUserType() { return this.userType; } public boolean isPlayer() { return (this.userType == 'P'); } public void setUserType(char userType) { this.userType = userType; } public int getBet() { if (this.player == null) return -1; return this.player.getCurrentBet(); } public int getCoins() { if (this.player == null) return -1; return this.player.getCoins(); } public Player getPlayer() { return this.player; } public void setBet(int betAmount) { if (this.player == null) return; this.player.setCurrentBet(betAmount); } public void setCoins(int noOfCoins) { if (this.player == null) return; this.player.setCoins(noOfCoins); } public void setPlayer(Player player) { this.player = player; } private void sendStartMessage() { ClientList players = this.server.getCurrentPlayers(); String message = "@ " + this.getPlayerNo() + " " + (players.size() - 1); for (Client client : players) { String name = client.getName(); if (!name.equals(this.name)) message += " " + client.getName() + " //"; } this.sendMessage(message); } public boolean isReady() { return this.isReady; } public void setReady(boolean isReady) { this.isReady = isReady; } @Override public int compareTo(Client object) { return this.getPlayerNo() - object.getPlayerNo(); } @Override public String toString() { return this.name + " : " + this.player.getCoins(); } }
Fixed error handling on disconnected client
src/connection/Client.java
Fixed error handling on disconnected client
<ide><path>rc/connection/Client.java <ide> this.sendMessage("% FORMATERROR"); <ide> } <ide> <del> } catch (IOException e) { <add> } catch (Exception e) { <ide> this.server.queueMessage("! " + this.getPlayerNo()); <ide> this.disconnect(); <add> e.printStackTrace(); <ide> } <ide> <ide> try {
Java
apache-2.0
ab65e12f3da0eb9ab12ff6a08590e4600d02815e
0
benbahrenburg/benCoding.AlarmManager,benbahrenburg/benCoding.AlarmManager,benbahrenburg/benCoding.AlarmManager
/** * benCoding.AlarmManager Project * Copyright (c) 2009-2012 by Ben Bahrenburg. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package bencoding.alarmmanager; import org.appcelerator.titanium.TiApplication; import android.R; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.net.Uri; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; public class AlarmNotificationListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NotificationManager notificationManager = null; utils.debugLog("In Alarm Notification Listener"); Bundle bundle = intent.getExtras(); if(bundle.get("notification_request_code") == null){ utils.infoLog("notification_request_code is null assume cancelled"); return; } int requestCode = bundle.getInt("notification_request_code", AlarmmanagerModule.DEFAULT_REQUEST_CODE); utils.debugLog("requestCode is " + requestCode); String contentTitle = bundle.getString("notification_title"); utils.debugLog("contentTitle is " + contentTitle); String contentText = bundle.getString("notification_msg"); utils.debugLog("contentText is " + contentText); String className = bundle.getString("notification_root_classname"); utils.debugLog("className is " + className); boolean hasIcon = bundle.getBoolean("notification_has_icon", true); int icon = R.drawable.stat_notify_more; if(hasIcon){ icon = bundle.getInt("notification_icon",R.drawable.stat_notify_more); utils.debugLog("User provided an icon of " + icon); }else{ utils.debugLog("No icon provided, default will be used"); } String soundPath = bundle.getString("notification_sound"); boolean hasCustomSound = !utils.isEmptyString(soundPath); //Add default notification flags boolean playSound = bundle.getBoolean("notification_play_sound",false); utils.debugLog("On notification play sound? " + new Boolean(playSound).toString()); boolean doVibrate = bundle.getBoolean("notification_vibrate",false); utils.debugLog("On notification vibrate? " + new Boolean(doVibrate).toString()); boolean showLights = bundle.getBoolean("notification_show_lights",false); utils.debugLog("On notification show lights? " + new Boolean(showLights).toString()); notificationManager = (NotificationManager) TiApplication.getInstance().getSystemService(TiApplication.NOTIFICATION_SERVICE); utils.debugLog("NotificationManager created"); Intent notifyIntent =createIntent(className); Notification notification = new Notification(icon, contentTitle, System.currentTimeMillis()); PendingIntent sender = PendingIntent.getActivity( TiApplication.getInstance().getApplicationContext(), requestCode, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT | Notification.FLAG_AUTO_CANCEL); utils.debugLog("setting notification flags"); notification = createNotifyFlags(notification,playSound,hasCustomSound,soundPath,doVibrate,showLights); utils.debugLog("setLatestEventInfo"); notification.setLatestEventInfo(TiApplication.getInstance().getApplicationContext(), contentTitle,contentText, sender); utils.debugLog("Notifying using requestCode =" + requestCode); notificationManager.notify(requestCode, notification); utils.infoLog("You should now see a notification"); } private Notification createNotifyFlags(Notification notification, boolean playSound, boolean hasCustomSound, String soundPath, boolean doVibrate, boolean showLights){ //Set the notifications flags if(playSound){ if(hasCustomSound){ notification.sound = Uri.parse(soundPath); }else{ notification.defaults |= Notification.DEFAULT_SOUND; } } if(doVibrate){ notification.defaults |=Notification.DEFAULT_VIBRATE; } if(showLights){ notification.defaults |=Notification.DEFAULT_LIGHTS; notification.flags |= Notification.FLAG_SHOW_LIGHTS; } if (playSound && !hasCustomSound && doVibrate && showLights){ notification.defaults = Notification.DEFAULT_ALL; } //Set alarm flags notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL; return notification; } private Intent createIntent(String className){ try { if(utils.isEmptyString(className)){ //If no activity is provided, use the App Start Activity utils.infoLog("[AlarmManager] Using application Start Activity"); Intent iStartActivity = TiApplication.getInstance().getApplicationContext().getPackageManager() .getLaunchIntentForPackage( TiApplication.getInstance().getApplicationContext().getPackageName() ); //Add the flags needed to restart iStartActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); iStartActivity.addCategory(Intent.CATEGORY_LAUNCHER); iStartActivity.setAction(Intent.ACTION_MAIN); return iStartActivity; }else{ utils.infoLog("[AlarmManager] Trying to get a class for name '" + className + "'"); @SuppressWarnings("rawtypes")Class intentClass = Class.forName(className); Intent intentFromClass = new Intent(TiApplication.getInstance().getApplicationContext(), intentClass); //Add the flags needed to restart intentFromClass.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); intentFromClass.addCategory(Intent.CATEGORY_LAUNCHER); intentFromClass.setAction(Intent.ACTION_MAIN); return intentFromClass; } } catch (ClassNotFoundException e) { utils.errorLog(e); return null; } } }
src/bencoding/alarmmanager/AlarmNotificationListener.java
/** * benCoding.AlarmManager Project * Copyright (c) 2009-2012 by Ben Bahrenburg. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package bencoding.alarmmanager; import org.appcelerator.titanium.TiApplication; import android.R; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.net.Uri; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; public class AlarmNotificationListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NotificationManager notificationManager = null; utils.debugLog("In Alarm Notification Listener"); Bundle bundle = intent.getExtras(); if(bundle.get("notification_request_code") == null){ utils.infoLog("notification_request_code is null assume cancelled"); return; } int requestCode = bundle.getInt("notification_request_code", AlarmmanagerModule.DEFAULT_REQUEST_CODE); utils.debugLog("requestCode is " + requestCode); String contentTitle = bundle.getString("notification_title"); utils.debugLog("contentTitle is " + contentTitle); String contentText = bundle.getString("notification_msg"); utils.debugLog("contentText is " + contentText); String className = bundle.getString("notification_root_classname"); utils.debugLog("className is " + className); boolean hasIcon = bundle.getBoolean("notification_has_icon", true); int icon = R.drawable.stat_notify_more; if(hasIcon){ icon = bundle.getInt("notification_icon",R.drawable.stat_notify_more); utils.debugLog("User provided an icon of " + icon); }else{ utils.debugLog("No icon provided, default will be used"); } String soundPath = bundle.getString("notification_sound"); //Add default notification flags boolean playSound = bundle.getBoolean("notification_play_sound",false); utils.debugLog("On notification play sound? " + new Boolean(playSound).toString()); boolean doVibrate = bundle.getBoolean("notification_vibrate",false); utils.debugLog("On notification vibrate? " + new Boolean(doVibrate).toString()); boolean showLights = bundle.getBoolean("notification_show_lights",false); utils.debugLog("On notification show lights? " + new Boolean(showLights).toString()); notificationManager = (NotificationManager) TiApplication.getInstance().getSystemService(TiApplication.NOTIFICATION_SERVICE); utils.debugLog("NotificationManager created"); Intent notifyIntent =createIntent(className); Notification notification = new Notification(icon, contentTitle, System.currentTimeMillis()); PendingIntent sender = PendingIntent.getActivity( TiApplication.getInstance().getApplicationContext(), requestCode, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT | Notification.FLAG_AUTO_CANCEL); utils.debugLog("setting notification flags"); notification = createNotifyFlags(notification,playSound,soundPath,doVibrate,showLights); utils.debugLog("setLatestEventInfo"); notification.setLatestEventInfo(TiApplication.getInstance().getApplicationContext(), contentTitle,contentText, sender); utils.debugLog("Notifying using requestCode =" + requestCode); notificationManager.notify(requestCode, notification); utils.infoLog("You should now see a notification"); } private Notification createNotifyFlags(Notification notification, boolean playSound, String soundPath, boolean doVibrate, boolean showLights){ //Set the notifications flags if(playSound){ if(utils.isEmptyString(soundPath)){ notification.defaults |= Notification.DEFAULT_SOUND; }else{ notification.sound = Uri.parse(soundPath); } } if(doVibrate){ notification.defaults |=Notification.DEFAULT_VIBRATE; } if(showLights){ notification.defaults |=Notification.DEFAULT_LIGHTS; notification.flags |= Notification.FLAG_SHOW_LIGHTS; } if (playSound && doVibrate && showLights){ notification.defaults = Notification.DEFAULT_ALL; } //Set alarm flags notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL; return notification; } private Intent createIntent(String className){ try { if(utils.isEmptyString(className)){ //If no activity is provided, use the App Start Activity utils.infoLog("[AlarmManager] Using application Start Activity"); Intent iStartActivity = TiApplication.getInstance().getApplicationContext().getPackageManager() .getLaunchIntentForPackage( TiApplication.getInstance().getApplicationContext().getPackageName() ); //Add the flags needed to restart iStartActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); iStartActivity.addCategory(Intent.CATEGORY_LAUNCHER); iStartActivity.setAction(Intent.ACTION_MAIN); return iStartActivity; }else{ utils.infoLog("[AlarmManager] Trying to get a class for name '" + className + "'"); @SuppressWarnings("rawtypes")Class intentClass = Class.forName(className); Intent intentFromClass = new Intent(TiApplication.getInstance().getApplicationContext(), intentClass); //Add the flags needed to restart intentFromClass.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); intentFromClass.addCategory(Intent.CATEGORY_LAUNCHER); intentFromClass.setAction(Intent.ACTION_MAIN); return intentFromClass; } } catch (ClassNotFoundException e) { utils.errorLog(e); return null; } } }
don't override custom sound with default Fixes #34
src/bencoding/alarmmanager/AlarmNotificationListener.java
don't override custom sound with default Fixes #34
<ide><path>rc/bencoding/alarmmanager/AlarmNotificationListener.java <ide> utils.debugLog("No icon provided, default will be used"); <ide> } <ide> String soundPath = bundle.getString("notification_sound"); <add> boolean hasCustomSound = !utils.isEmptyString(soundPath); <ide> //Add default notification flags <ide> boolean playSound = bundle.getBoolean("notification_play_sound",false); <ide> utils.debugLog("On notification play sound? " + new Boolean(playSound).toString()); <ide> <ide> <ide> utils.debugLog("setting notification flags"); <del> notification = createNotifyFlags(notification,playSound,soundPath,doVibrate,showLights); <add> notification = createNotifyFlags(notification,playSound,hasCustomSound,soundPath,doVibrate,showLights); <ide> utils.debugLog("setLatestEventInfo"); <ide> notification.setLatestEventInfo(TiApplication.getInstance().getApplicationContext(), contentTitle,contentText, sender); <ide> utils.debugLog("Notifying using requestCode =" + requestCode); <ide> <ide> } <ide> <del> private Notification createNotifyFlags(Notification notification, boolean playSound, String soundPath, boolean doVibrate, boolean showLights){ <add> private Notification createNotifyFlags(Notification notification, boolean playSound, boolean hasCustomSound, String soundPath, boolean doVibrate, boolean showLights){ <ide> //Set the notifications flags <ide> if(playSound){ <del> if(utils.isEmptyString(soundPath)){ <add> if(hasCustomSound){ <add> notification.sound = Uri.parse(soundPath); <add> }else{ <ide> notification.defaults |= Notification.DEFAULT_SOUND; <del> }else{ <del> notification.sound = Uri.parse(soundPath); <ide> } <ide> } <ide> <ide> notification.defaults |=Notification.DEFAULT_LIGHTS; <ide> notification.flags |= Notification.FLAG_SHOW_LIGHTS; <ide> } <del> if (playSound && doVibrate && showLights){ <add> if (playSound && !hasCustomSound && doVibrate && showLights){ <ide> notification.defaults = Notification.DEFAULT_ALL; <ide> } <ide>
Java
mit
7dda4387b94871cf93c490cd80c3e44b093613b4
0
mmaia/kafka-simple-demo,mmaia/kafka-simple-demo,mmaia/kafka-simple-demo,mmaia/kafka-simple-demo
package com.codespair.kafka.navigator.kafkanavigatorbe.kafka.jmx; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import javax.management.AttributeList; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import java.io.IOException; import java.util.*; @Slf4j @Service @Scope("prototype") @Getter public class KafkaJMX { private JMXServiceURL jmxServiceURL; private List<String> jmxDomains; private boolean connected; private MBeanServerConnection mbsc; /** * Connects with kafka jmx and return true if successful, false otherwise. * * @param jmxUrl the url of a broker to connect with using JMX. * @return a list of available JMX Bean domain names to be navigated. */ public boolean connect(String jmxUrl) { String url = "service:jmx:rmi:///jndi/rmi://" + jmxUrl + "/jmxrmi"; try { mbsc = mBeanServerConnection(url); connected = true; } catch (IOException e) { log.error("could not connect to jmx kafka server: {}", e.getMessage(), e); } return isConnected(); } /** * Recover a list of jmx domains of this kafka server * @return a List with strings each representing a jmx domain from the kafka broker */ public Optional<List<String>> getJmxDomains() { String domains[]; try { domains = mbsc.getDomains(); jmxDomains = Arrays.asList(domains); logDomains(domains); return Optional.of(jmxDomains); } catch (IOException e) { log.error("Error recovering JMX Domains: {}", e.getMessage(), e); return Optional.empty(); } } /** * Recover the Broker id * * @return an Integer representing the Broker id */ public Optional<Integer> getBrokerId() { try { ObjectName objectName = new ObjectName("kafka.server:type=app-info"); return Optional.of((Integer) (mbsc.getAttribute(objectName, "id"))); } catch (Exception e) { log.error("Error getting Broker id: {}", e.getMessage(), e); return Optional.empty(); } } /** * Get general topic metrics for broker * @return AttributeList with topic metrics from broker. */ public Optional<AttributeList> getTopicMetrics() { try { ObjectName objectName = new ObjectName("kafka.server:type=BrokerTopicMetrics"); return Optional.of(mbsc.getAttributes(objectName, topicMetricsAttributes())); } catch (Exception e) { log.error("Erorr recovering Topic Metrics for Broker: {}", getBrokerId().get()); return Optional.empty(); } } private String[] topicMetricsAttributes() { final String[] attributes = { "BytesInPerSec", "BytesOutPerSec", "BytesRejectPerSec", "FailedFetchRequestsPerSec", "FailedProduceRequestsPerSec", "MessagesInPerSec", "TotalFetchRequestsPerSec", "TotalProduceRequestsPerSec" }; return attributes; } private MBeanServerConnection mBeanServerConnection(String url) throws IOException { log.info("connecting to mbeanserver url: {}", url); jmxServiceURL = new JMXServiceURL(url); JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceURL, defaultJMXConnectorProperties()); return jmxc.getMBeanServerConnection(); } private void logDomains(String[] domains) { Arrays.sort(domains); for (String domain : domains) { log.info("\tDomain = " + domain); } } private Map<String, String> defaultJMXConnectorProperties() { Map<String, String> props = new HashMap<>(); props.put("jmx.remote.x.request.waiting.timeout", "3000"); props.put("jmx.remote.x.notification.fetch.timeout", "3000"); props.put("sun.rmi.transport.connectionTimeout", "3000"); props.put("sun.rmi.transport.tcp.handshakeTimeout", "3000"); props.put("sun.rmi.transport.tcp.responseTimeout", "3000"); return props; } }
knav-be/src/main/java/com/codespair/kafka/navigator/kafkanavigatorbe/kafka/jmx/KafkaJMX.java
package com.codespair.kafka.navigator.kafkanavigatorbe.kafka.jmx; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import javax.management.AttributeList; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import java.io.IOException; import java.util.*; @Slf4j @Service @Scope("prototype") @Getter public class KafkaJMX { private JMXServiceURL jmxServiceURL; private List<String> jmxDomains; private boolean connected; private MBeanServerConnection mbsc; /** * Connects with kafka jmx and return true if successful, false otherwise. * * @param jmxUrl the url of a broker to connect with using JMX. * @return a list of available JMX Bean domain names to be navigated. */ public boolean connect(String jmxUrl) { String url = "service:jmx:rmi:///jndi/rmi://" + jmxUrl + "/jmxrmi"; try { mbsc = mBeanServerConnection(url); connected = true; return isConnected(); } catch (IOException e) { log.error("could not connect to jmx kafka server: {}", e.getMessage(), e); } } public Optional<List<String>> getJmxDomains() { String domains[]; try { domains = mbsc.getDomains(); jmxDomains = Arrays.asList(domains); logDomains(domains); return Optional.of(jmxDomains); } catch (IOException e) { log.error("Error recovering JMX Domains: {}", e.getMessage(), e); return Optional.empty(); } } /** * Recover the Broker id * * @return an Integer representing the Broker id */ public Optional<Integer> getBrokerId() { try { ObjectName objectName = new ObjectName("kafka.server:type=app-info"); return Optional.of((Integer) (mbsc.getAttribute(objectName, "id"))); } catch (Exception e) { log.error("Error getting Broker id: {}", e.getMessage(), e); return Optional.empty(); } } public Optional<AttributeList> getTopicMetrics() { try { ObjectName objectName = new ObjectName("kafka.server:type=BrokerTopicMetrics"); Optional.of(mbsc.getAttributes(objectName, topicMetricsAttributes())); } catch (Exception e) { log.error("Erorr recovering Topic Metrics for Broker: {}", getBrokerId().get()); return Optional.empty(); } } private String[] topicMetricsAttributes() { final String[] attributes = { "BytesInPerSec", "BytesOutPerSec", "BytesRejectPerSec", "FailedFetchRequestsPerSec", "FailedProduceRequestsPerSec", "MessagesInPerSec", "TotalFetchRequestsPerSec", "TotalProduceRequestsPerSec" }; return attributes; } private MBeanServerConnection mBeanServerConnection(String url) throws IOException { log.info("connecting to mbeanserver url: {}", url); jmxServiceURL = new JMXServiceURL(url); JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceURL, defaultJMXConnectorProperties()); return jmxc.getMBeanServerConnection(); } private void logDomains(String[] domains) { Arrays.sort(domains); for (String domain : domains) { log.info("\tDomain = " + domain); } } private Map<String, String> defaultJMXConnectorProperties() { Map<String, String> props = new HashMap<>(); props.put("jmx.remote.x.request.waiting.timeout", "3000"); props.put("jmx.remote.x.notification.fetch.timeout", "3000"); props.put("sun.rmi.transport.connectionTimeout", "3000"); props.put("sun.rmi.transport.tcp.handshakeTimeout", "3000"); props.put("sun.rmi.transport.tcp.responseTimeout", "3000"); return props; } }
working on gattering jmx informationa about broker
knav-be/src/main/java/com/codespair/kafka/navigator/kafkanavigatorbe/kafka/jmx/KafkaJMX.java
working on gattering jmx informationa about broker
<ide><path>nav-be/src/main/java/com/codespair/kafka/navigator/kafkanavigatorbe/kafka/jmx/KafkaJMX.java <ide> try { <ide> mbsc = mBeanServerConnection(url); <ide> connected = true; <del> return isConnected(); <ide> } catch (IOException e) { <ide> log.error("could not connect to jmx kafka server: {}", e.getMessage(), e); <ide> } <add> return isConnected(); <ide> } <ide> <add> /** <add> * Recover a list of jmx domains of this kafka server <add> * @return a List with strings each representing a jmx domain from the kafka broker <add> */ <ide> public Optional<List<String>> getJmxDomains() { <ide> String domains[]; <ide> try { <ide> } <ide> } <ide> <add> /** <add> * Get general topic metrics for broker <add> * @return AttributeList with topic metrics from broker. <add> */ <ide> public Optional<AttributeList> getTopicMetrics() { <ide> try { <ide> ObjectName objectName = new ObjectName("kafka.server:type=BrokerTopicMetrics"); <del> Optional.of(mbsc.getAttributes(objectName, topicMetricsAttributes())); <del> <add> return Optional.of(mbsc.getAttributes(objectName, topicMetricsAttributes())); <ide> } catch (Exception e) { <ide> log.error("Erorr recovering Topic Metrics for Broker: {}", <ide> getBrokerId().get());
Java
lgpl-2.1
793d26e25c117932fda716546f70503b184f8017
0
keiono/biopax,cytoscape/biopax
// $Id: BioPaxVisualStyleUtil.java,v 1.17 2006/08/23 15:21:07 cerami Exp $ //------------------------------------------------------------------------------ /** Copyright (c) 2006 Memorial Sloan-Kettering Cancer Center. ** ** Code written by: Ethan Cerami ** Authors: Ethan Cerami, Gary Bader, Chris Sander ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of the GNU Lesser General Public License as published ** by the Free Software Foundation; either version 2.1 of the License, or ** any later version. ** ** This library is distributed in the hope that it will be useful, but ** WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF ** MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and ** documentation provided hereunder is on an "as is" basis, and ** Memorial Sloan-Kettering Cancer Center ** has no obligations to provide maintenance, support, ** updates, enhancements or modifications. In no event shall ** Memorial Sloan-Kettering Cancer Center ** be liable to any party for direct, indirect, special, ** incidental or consequential damages, including lost profits, arising ** out of the use of this software and its documentation, even if ** Memorial Sloan-Kettering Cancer Center ** has been advised of the possibility of such damage. See ** the GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this library; if not, write to the Free Software Foundation, ** Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. **/ package org.cytoscape.biopax.util; import java.awt.Color; import java.awt.Paint; import org.biopax.paxtools.model.BioPAXElement; import org.biopax.paxtools.model.level3.Complex; import org.biopax.paxtools.model.level3.Control; import org.biopax.paxtools.model.level3.Interaction; import org.biopax.paxtools.model.level3.PhysicalEntity; import static org.cytoscape.biopax.MapBioPaxToCytoscape.*; import org.cytoscape.model.CyNode; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.presentation.property.MinimalVisualLexicon; import org.cytoscape.view.presentation.property.NodeShapeVisualProperty; import org.cytoscape.view.presentation.property.RichVisualLexicon; import org.cytoscape.view.presentation.property.values.NodeShape; import org.cytoscape.view.vizmap.VisualMappingFunctionFactory; import org.cytoscape.view.vizmap.VisualMappingManager; import org.cytoscape.view.vizmap.VisualStyle; import org.cytoscape.view.vizmap.VisualStyleFactory; import org.cytoscape.view.vizmap.mappings.DiscreteMapping; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Creates an "out-of-the-box" default Visual Mapper for rendering BioPAX * networks. * * @author Ethan Cerami * @author Igor Rodchenkov (re-factoring using PaxTools API) */ public class BioPaxVisualStyleUtil { public static final Logger log = LoggerFactory .getLogger(BioPaxVisualStyleUtil.class); /** * Name of BioPax Visual Style. */ public static final String BIO_PAX_VISUAL_STYLE = "BioPAX"; /** * size of physical entity node (default node size width) */ public static final double BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH = 20; // taken from DNodeView /** * size of physical entity node (default node size height) */ public static final double BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT = 20; // taken from DNodeView /** * size of physical entity node scale - (used to scale post tranlational * modification nodes) */ public static final double BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_SIZE_SCALE = 3; /** * Size of interaction node */ private static final double BIO_PAX_VISUAL_STYLE_INTERACTION_NODE_SIZE_SCALE = 0.33; /** * Size of complex node */ private static final double BIO_PAX_VISUAL_STYLE_COMPLEX_NODE_SIZE_SCALE = 0.33; /** * Default color of nodes */ private static final Color DEFAULT_NODE_COLOR = new Color(255, 255, 255); /** * Node border color */ private static final Color DEFAULT_NODE_BORDER_COLOR = new Color(0, 102, 102); /** * Complex node color */ private static final Color COMPLEX_NODE_COLOR = new Color(0, 0, 0); /** * Complex node color */ private static final Color COMPLEX_NODE_BORDER_COLOR = COMPLEX_NODE_COLOR; VisualStyle style; private final VisualStyleFactory styleFactory; private final VisualMappingManager mappingManager; private final VisualMappingFunctionFactory discreteFactory; private final VisualMappingFunctionFactory passthroughFactory; public BioPaxVisualStyleUtil(VisualStyleFactory styleFactory, VisualMappingManager mappingManager, VisualMappingFunctionFactory discreteMappingFactory, VisualMappingFunctionFactory passthroughFactory) { this.styleFactory = styleFactory; this.mappingManager = mappingManager; this.discreteFactory = discreteMappingFactory; this.passthroughFactory = passthroughFactory; } /** * Constructor. If an existing BioPAX Viz Mapper already exists, we use it. * Otherwise, we create a new one. * * @return VisualStyle Object. */ public VisualStyle getBioPaxVisualStyle() { // If the BioPAX Visual Style already exists, use this one instead. // The user may have tweaked the out-of-the box mapping, and we don't // want to over-ride these tweaks. synchronized (this) { if (style == null) { style = styleFactory.createVisualStyle(BIO_PAX_VISUAL_STYLE); // style.getDependency().set(VisualPropertyDependency.Definition.NODE_SIZE_LOCKED,false); createNodeShape(style); createNodeSize(style); createNodeLabel(style); createNodeColor(style); createNodeBorderColor(style); createTargetArrows(style); mappingManager.addVisualStyle(style); } } return style; } private void createNodeShape(VisualStyle style) { style.setDefaultValue(RichVisualLexicon.NODE_SHAPE, NodeShapeVisualProperty.RECTANGLE); // create a discrete mapper, for mapping a biopax type to a shape DiscreteMapping<String, NodeShape> function = (DiscreteMapping<String, NodeShape>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, RichVisualLexicon.NODE_SHAPE); // map all physical entities to circles for (Class<? extends BioPAXElement> claz : BioPaxUtil.getSubclassNames(PhysicalEntity.class)) { String name = claz.getSimpleName(); function.putMapValue(name, NodeShapeVisualProperty.ELLIPSE); } // hack for phosphorylated proteins function.putMapValue(BioPaxUtil.PROTEIN_PHOSPHORYLATED, NodeShapeVisualProperty.ELLIPSE); // map all interactions // - control to triangles // - others to square for (Class<?> c : BioPaxUtil.getSubclassNames(Interaction.class)) { String entityName = c.getSimpleName(); if (Control.class.isAssignableFrom(c)) { function.putMapValue(entityName, NodeShapeVisualProperty.TRIANGLE); } else { function.putMapValue(entityName, NodeShapeVisualProperty.RECTANGLE); } } style.addVisualMappingFunction(function); } private void createNodeSize(VisualStyle style) { // create a discrete mapper, for mapping biopax node type // to a particular node size. DiscreteMapping<String, Double> width = (DiscreteMapping<String, Double>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, MinimalVisualLexicon.NODE_WIDTH); DiscreteMapping<String, Double> height = (DiscreteMapping<String, Double>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, MinimalVisualLexicon.NODE_HEIGHT); // map all interactions to required size for (Class c : BioPaxUtil.getSubclassNames(Interaction.class)) { String entityName = c.getSimpleName(); width.putMapValue(entityName, new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH * BIO_PAX_VISUAL_STYLE_INTERACTION_NODE_SIZE_SCALE)); height.putMapValue(entityName, new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT * BIO_PAX_VISUAL_STYLE_INTERACTION_NODE_SIZE_SCALE)); } // map all complex to required size // for (Class c : BioPaxUtil.getSubclassNames(Complex.class)) { String entityName = "Complex";//c.getSimpleName(); width.putMapValue(entityName, new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH * BIO_PAX_VISUAL_STYLE_COMPLEX_NODE_SIZE_SCALE)); height.putMapValue(entityName, new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT * BIO_PAX_VISUAL_STYLE_COMPLEX_NODE_SIZE_SCALE)); // } /* * // hack for phosphorylated proteins - make them large so label fits * within node // commented out by Ethan Cerami, November 15, 2006 * discreteMappingWidth.putMapValue(BioPaxUtil.PROTEIN_PHOSPHORYLATED, * new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH * BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_SIZE_SCALE)); * discreteMappingHeight.putMapValue(BioPaxUtil.PROTEIN_PHOSPHORYLATED, * new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT * BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_SIZE_SCALE)); */ // create and set node height calculator in node appearance calculator style.setDefaultValue(MinimalVisualLexicon.NODE_WIDTH, BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH); style.setDefaultValue(MinimalVisualLexicon.NODE_HEIGHT, BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT); style.addVisualMappingFunction(width); style.addVisualMappingFunction(height); } private void createNodeLabel(VisualStyle style) { // create pass through mapper for node labels style.addVisualMappingFunction(passthroughFactory .createVisualMappingFunction(CyNode.NAME, String.class, null, MinimalVisualLexicon.NODE_LABEL)); } private void createNodeColor(VisualStyle style) { style.setDefaultValue(MinimalVisualLexicon.NODE_FILL_COLOR, DEFAULT_NODE_COLOR); // create a discrete mapper, for mapping biopax node type // to a particular node color DiscreteMapping<String, Paint> function = (DiscreteMapping<String, Paint>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, MinimalVisualLexicon.NODE_FILL_COLOR); // map all complex to black function.putMapValue("Complex", COMPLEX_NODE_COLOR); style.addVisualMappingFunction(function); } private void createNodeBorderColor(VisualStyle style) { style.setDefaultValue(RichVisualLexicon.NODE_BORDER_PAINT, DEFAULT_NODE_BORDER_COLOR); // create a discrete mapper, for mapping biopax node type // to a particular node color DiscreteMapping<String, Paint> function = (DiscreteMapping<String, Paint>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, RichVisualLexicon.NODE_BORDER_PAINT); // map all complex to black function.putMapValue("Complex", COMPLEX_NODE_BORDER_COLOR); style.addVisualMappingFunction(function); } @Deprecated private void createTargetArrows(VisualStyle style) { // DiscreteMapping discreteMapping = new // DiscreteMapping(ArrowShape.NONE, // MapBioPaxToCytoscape.BIOPAX_EDGE_TYPE, // ObjectMapping.EDGE_MAPPING); // // discreteMapping.putMapValue(MapBioPaxToCytoscape.RIGHT, // ArrowShape.DELTA); // discreteMapping.putMapValue(MapBioPaxToCytoscape.CONTROLLED, // ArrowShape.DELTA); // discreteMapping.putMapValue(MapBioPaxToCytoscape.COFACTOR, // ArrowShape.DELTA); // discreteMapping.putMapValue(MapBioPaxToCytoscape.CONTAINS, // ArrowShape.CIRCLE); // // // Inhibition Edges // for (ControlType controlType : ControlType.values()) { // if(controlType.toString().startsWith("I")) { // discreteMapping.putMapValue(controlType.toString(), ArrowShape.T); // } // } // // // Activation Edges // for (ControlType controlType : ControlType.values()) { // if(controlType.toString().startsWith("A")) { // discreteMapping.putMapValue(controlType.toString(), // ArrowShape.DELTA); // } // } // // Calculator edgeTargetArrowCalculator = new // BasicCalculator("BioPAX Target Arrows" // + VERSION_POST_FIX, // discreteMapping, // VisualPropertyType.EDGE_TGTARROW_SHAPE); // eac.setCalculator(edgeTargetArrowCalculator); } @Deprecated public void setNodeToolTips(CyNetworkView networkView) { // // grab node attributes // CyAttributes nodeAttributes = Cytoscape.getNodeAttributes(); // // // iterate through the nodes // Iterator<NodeView> nodesIt = networkView.getNodeViewsIterator(); // while (nodesIt.hasNext()) { // NodeView nodeView = nodesIt.next(); // String id = nodeView.getNode().getIdentifier(); // String tip = // nodeAttributes.getStringAttribute(id, // MapBioPaxToCytoscape.BIOPAX_ENTITY_TYPE) // + "\n" + // nodeAttributes.getListAttribute(id, // MapBioPaxToCytoscape.BIOPAX_CELLULAR_LOCATIONS); // // nodeView.setToolTip(tip); // // if(log.isDebugging()) // log.debug("tooltip set "+ tip + " for node " + id); // } // networkView.updateView(); } }
src/main/java/org/cytoscape/biopax/util/BioPaxVisualStyleUtil.java
// $Id: BioPaxVisualStyleUtil.java,v 1.17 2006/08/23 15:21:07 cerami Exp $ //------------------------------------------------------------------------------ /** Copyright (c) 2006 Memorial Sloan-Kettering Cancer Center. ** ** Code written by: Ethan Cerami ** Authors: Ethan Cerami, Gary Bader, Chris Sander ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of the GNU Lesser General Public License as published ** by the Free Software Foundation; either version 2.1 of the License, or ** any later version. ** ** This library is distributed in the hope that it will be useful, but ** WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF ** MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and ** documentation provided hereunder is on an "as is" basis, and ** Memorial Sloan-Kettering Cancer Center ** has no obligations to provide maintenance, support, ** updates, enhancements or modifications. In no event shall ** Memorial Sloan-Kettering Cancer Center ** be liable to any party for direct, indirect, special, ** incidental or consequential damages, including lost profits, arising ** out of the use of this software and its documentation, even if ** Memorial Sloan-Kettering Cancer Center ** has been advised of the possibility of such damage. See ** the GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this library; if not, write to the Free Software Foundation, ** Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. **/ package org.cytoscape.biopax.util; import java.awt.Color; import java.awt.Paint; import org.biopax.paxtools.model.BioPAXElement; import org.biopax.paxtools.model.level3.Complex; import org.biopax.paxtools.model.level3.Control; import org.biopax.paxtools.model.level3.Interaction; import org.biopax.paxtools.model.level3.PhysicalEntity; import static org.cytoscape.biopax.MapBioPaxToCytoscape.*; import org.cytoscape.model.CyNode; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.presentation.property.MinimalVisualLexicon; import org.cytoscape.view.presentation.property.NodeShapeVisualProperty; import org.cytoscape.view.presentation.property.RichVisualLexicon; import org.cytoscape.view.presentation.property.values.NodeShape; import org.cytoscape.view.vizmap.VisualMappingFunctionFactory; import org.cytoscape.view.vizmap.VisualMappingManager; import org.cytoscape.view.vizmap.VisualStyle; import org.cytoscape.view.vizmap.VisualStyleFactory; import org.cytoscape.view.vizmap.mappings.DiscreteMapping; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Creates an "out-of-the-box" default Visual Mapper for rendering BioPAX * networks. * * @author Ethan Cerami * @author Igor Rodchenkov (re-factoring using PaxTools API) */ public class BioPaxVisualStyleUtil { public static final Logger log = LoggerFactory .getLogger(BioPaxVisualStyleUtil.class); /** * Name of BioPax Visual Style. */ public static final String BIO_PAX_VISUAL_STYLE = "BioPAX"; /** * size of physical entity node (default node size width) */ public static final double BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH = 20; // taken from DNodeView /** * size of physical entity node (default node size height) */ public static final double BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT = 20; // taken from DNodeView /** * size of physical entity node scale - (used to scale post tranlational * modification nodes) */ public static final double BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_SIZE_SCALE = 3; /** * Size of interaction node */ private static final double BIO_PAX_VISUAL_STYLE_INTERACTION_NODE_SIZE_SCALE = 0.33; /** * Size of complex node */ private static final double BIO_PAX_VISUAL_STYLE_COMPLEX_NODE_SIZE_SCALE = 0.33; /** * Default color of nodes */ private static final Color DEFAULT_NODE_COLOR = new Color(255, 255, 255); /** * Node border color */ private static final Color DEFAULT_NODE_BORDER_COLOR = new Color(0, 102, 102); /** * Complex node color */ private static final Color COMPLEX_NODE_COLOR = new Color(0, 0, 0); /** * Complex node color */ private static final Color COMPLEX_NODE_BORDER_COLOR = COMPLEX_NODE_COLOR; VisualStyle style; private final VisualStyleFactory styleFactory; private final VisualMappingManager mappingManager; private final VisualMappingFunctionFactory discreteFactory; private final VisualMappingFunctionFactory passthroughFactory; public BioPaxVisualStyleUtil(VisualStyleFactory styleFactory, VisualMappingManager mappingManager, VisualMappingFunctionFactory discreteMappingFactory, VisualMappingFunctionFactory passthroughFactory) { this.styleFactory = styleFactory; this.mappingManager = mappingManager; this.discreteFactory = discreteMappingFactory; this.passthroughFactory = passthroughFactory; } /** * Constructor. If an existing BioPAX Viz Mapper already exists, we use it. * Otherwise, we create a new one. * * @return VisualStyle Object. */ public VisualStyle getBioPaxVisualStyle() { // If the BioPAX Visual Style already exists, use this one instead. // The user may have tweaked the out-of-the box mapping, and we don't // want to over-ride these tweaks. synchronized (this) { if (style == null) { style = styleFactory.getInstance(BIO_PAX_VISUAL_STYLE); // style.getDependency().set(VisualPropertyDependency.Definition.NODE_SIZE_LOCKED,false); createNodeShape(style); createNodeSize(style); createNodeLabel(style); createNodeColor(style); createNodeBorderColor(style); createTargetArrows(style); mappingManager.addVisualStyle(style); } } return style; } private void createNodeShape(VisualStyle style) { style.setDefaultValue(RichVisualLexicon.NODE_SHAPE, NodeShapeVisualProperty.RECTANGLE); // create a discrete mapper, for mapping a biopax type to a shape DiscreteMapping<String, NodeShape> function = (DiscreteMapping<String, NodeShape>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, RichVisualLexicon.NODE_SHAPE); // map all physical entities to circles for (Class<? extends BioPAXElement> claz : BioPaxUtil.getSubclassNames(PhysicalEntity.class)) { String name = claz.getSimpleName(); function.putMapValue(name, NodeShapeVisualProperty.ELLIPSE); } // hack for phosphorylated proteins function.putMapValue(BioPaxUtil.PROTEIN_PHOSPHORYLATED, NodeShapeVisualProperty.ELLIPSE); // map all interactions // - control to triangles // - others to square for (Class<?> c : BioPaxUtil.getSubclassNames(Interaction.class)) { String entityName = c.getSimpleName(); if (Control.class.isAssignableFrom(c)) { function.putMapValue(entityName, NodeShapeVisualProperty.TRIANGLE); } else { function.putMapValue(entityName, NodeShapeVisualProperty.RECTANGLE); } } style.addVisualMappingFunction(function); } private void createNodeSize(VisualStyle style) { // create a discrete mapper, for mapping biopax node type // to a particular node size. DiscreteMapping<String, Double> width = (DiscreteMapping<String, Double>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, MinimalVisualLexicon.NODE_WIDTH); DiscreteMapping<String, Double> height = (DiscreteMapping<String, Double>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, MinimalVisualLexicon.NODE_HEIGHT); // map all interactions to required size for (Class c : BioPaxUtil.getSubclassNames(Interaction.class)) { String entityName = c.getSimpleName(); width.putMapValue(entityName, new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH * BIO_PAX_VISUAL_STYLE_INTERACTION_NODE_SIZE_SCALE)); height.putMapValue(entityName, new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT * BIO_PAX_VISUAL_STYLE_INTERACTION_NODE_SIZE_SCALE)); } // map all complex to required size // for (Class c : BioPaxUtil.getSubclassNames(Complex.class)) { String entityName = "Complex";//c.getSimpleName(); width.putMapValue(entityName, new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH * BIO_PAX_VISUAL_STYLE_COMPLEX_NODE_SIZE_SCALE)); height.putMapValue(entityName, new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT * BIO_PAX_VISUAL_STYLE_COMPLEX_NODE_SIZE_SCALE)); // } /* * // hack for phosphorylated proteins - make them large so label fits * within node // commented out by Ethan Cerami, November 15, 2006 * discreteMappingWidth.putMapValue(BioPaxUtil.PROTEIN_PHOSPHORYLATED, * new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH * BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_SIZE_SCALE)); * discreteMappingHeight.putMapValue(BioPaxUtil.PROTEIN_PHOSPHORYLATED, * new Double(BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT * BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_SIZE_SCALE)); */ // create and set node height calculator in node appearance calculator style.setDefaultValue(MinimalVisualLexicon.NODE_WIDTH, BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_WIDTH); style.setDefaultValue(MinimalVisualLexicon.NODE_HEIGHT, BIO_PAX_VISUAL_STYLE_PHYSICAL_ENTITY_NODE_HEIGHT); style.addVisualMappingFunction(width); style.addVisualMappingFunction(height); } private void createNodeLabel(VisualStyle style) { // create pass through mapper for node labels style.addVisualMappingFunction(passthroughFactory .createVisualMappingFunction(CyNode.NAME, String.class, null, MinimalVisualLexicon.NODE_LABEL)); } private void createNodeColor(VisualStyle style) { style.setDefaultValue(MinimalVisualLexicon.NODE_FILL_COLOR, DEFAULT_NODE_COLOR); // create a discrete mapper, for mapping biopax node type // to a particular node color DiscreteMapping<String, Paint> function = (DiscreteMapping<String, Paint>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, MinimalVisualLexicon.NODE_FILL_COLOR); // map all complex to black function.putMapValue("Complex", COMPLEX_NODE_COLOR); style.addVisualMappingFunction(function); } private void createNodeBorderColor(VisualStyle style) { style.setDefaultValue(RichVisualLexicon.NODE_BORDER_PAINT, DEFAULT_NODE_BORDER_COLOR); // create a discrete mapper, for mapping biopax node type // to a particular node color DiscreteMapping<String, Paint> function = (DiscreteMapping<String, Paint>) discreteFactory .createVisualMappingFunction( BIOPAX_ENTITY_TYPE, String.class, null, RichVisualLexicon.NODE_BORDER_PAINT); // map all complex to black function.putMapValue("Complex", COMPLEX_NODE_BORDER_COLOR); style.addVisualMappingFunction(function); } @Deprecated private void createTargetArrows(VisualStyle style) { // DiscreteMapping discreteMapping = new // DiscreteMapping(ArrowShape.NONE, // MapBioPaxToCytoscape.BIOPAX_EDGE_TYPE, // ObjectMapping.EDGE_MAPPING); // // discreteMapping.putMapValue(MapBioPaxToCytoscape.RIGHT, // ArrowShape.DELTA); // discreteMapping.putMapValue(MapBioPaxToCytoscape.CONTROLLED, // ArrowShape.DELTA); // discreteMapping.putMapValue(MapBioPaxToCytoscape.COFACTOR, // ArrowShape.DELTA); // discreteMapping.putMapValue(MapBioPaxToCytoscape.CONTAINS, // ArrowShape.CIRCLE); // // // Inhibition Edges // for (ControlType controlType : ControlType.values()) { // if(controlType.toString().startsWith("I")) { // discreteMapping.putMapValue(controlType.toString(), ArrowShape.T); // } // } // // // Activation Edges // for (ControlType controlType : ControlType.values()) { // if(controlType.toString().startsWith("A")) { // discreteMapping.putMapValue(controlType.toString(), // ArrowShape.DELTA); // } // } // // Calculator edgeTargetArrowCalculator = new // BasicCalculator("BioPAX Target Arrows" // + VERSION_POST_FIX, // discreteMapping, // VisualPropertyType.EDGE_TGTARROW_SHAPE); // eac.setCalculator(edgeTargetArrowCalculator); } @Deprecated public void setNodeToolTips(CyNetworkView networkView) { // // grab node attributes // CyAttributes nodeAttributes = Cytoscape.getNodeAttributes(); // // // iterate through the nodes // Iterator<NodeView> nodesIt = networkView.getNodeViewsIterator(); // while (nodesIt.hasNext()) { // NodeView nodeView = nodesIt.next(); // String id = nodeView.getNode().getIdentifier(); // String tip = // nodeAttributes.getStringAttribute(id, // MapBioPaxToCytoscape.BIOPAX_ENTITY_TYPE) // + "\n" + // nodeAttributes.getListAttribute(id, // MapBioPaxToCytoscape.BIOPAX_CELLULAR_LOCATIONS); // // nodeView.setToolTip(tip); // // if(log.isDebugging()) // log.debug("tooltip set "+ tip + " for node " + id); // } // networkView.updateView(); } }
Renamed factory methods to be more consistent
src/main/java/org/cytoscape/biopax/util/BioPaxVisualStyleUtil.java
Renamed factory methods to be more consistent
<ide><path>rc/main/java/org/cytoscape/biopax/util/BioPaxVisualStyleUtil.java <ide> // want to over-ride these tweaks. <ide> synchronized (this) { <ide> if (style == null) { <del> style = styleFactory.getInstance(BIO_PAX_VISUAL_STYLE); <add> style = styleFactory.createVisualStyle(BIO_PAX_VISUAL_STYLE); <ide> <ide> // style.getDependency().set(VisualPropertyDependency.Definition.NODE_SIZE_LOCKED,false); <ide>
Java
mit
0830681b2c9d72ac81d11101c70e79bb9289a175
0
mcasperson/IridiumApplicationTesting,mcasperson/IridiumApplicationTesting,mcasperson/IridiumApplicationTesting
package au.com.agic.apptesting.utils.impl; import au.com.agic.apptesting.utils.JavaScriptRunner; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import javax.validation.constraints.NotNull; /** * An implementation of the JavaScript runner service */ public class JavaScriptRunnerImpl implements JavaScriptRunner { @Override public void interactHiddenElementMouseEvent( @NotNull final WebElement element, @NotNull final String event, @NotNull final JavascriptExecutor js) { /* PhantomJS doesn't support the click method, so "element.click()" won't work here. We need to dispatch the event instead. */ js.executeScript("var ev = document.createEvent('MouseEvent');" + " ev.initMouseEvent(" + " '" + event + "'," + " true /* bubble */, true /* cancelable */," + " window, null," + " 0, 0, 0, 0, /* coordinates */" + " false, false, false, false, /* modifier keys */" + " 0 /*left*/, null" + " );" + " arguments[0].dispatchEvent(ev);", element); } @Override public void interactHiddenElementKeyEvent( @NotNull final WebElement element, @NotNull final String event, @NotNull final JavascriptExecutor js) { /* PhantomJS doesn't support the click method, so "element.click()" won't work here. We need to dispatch the event instead. */ js.executeScript("var ev = document.createEvent('KeyboardEvent');" + " (ev.initKeyEvent || ev.initKeyboardEvent).call(ev," + " '" + event + "'," + " true /* bubble */, true /* cancelable */," + " window, null," + " 0, 0, 0, 0, /* coordinates */" + " false, false, false, false, /* modifier keys */" + " 0 /*left*/, null" + " );" + " arguments[0].dispatchEvent(ev);", element); } }
src/main/java/au/com/agic/apptesting/utils/impl/JavaScriptRunnerImpl.java
package au.com.agic.apptesting.utils.impl; import au.com.agic.apptesting.utils.JavaScriptRunner; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import javax.validation.constraints.NotNull; /** * An implementation of the JavaScript runner service */ public class JavaScriptRunnerImpl implements JavaScriptRunner { @Override public void interactHiddenElementMouseEvent( @NotNull final WebElement element, @NotNull final String event, @NotNull final JavascriptExecutor js) { /* PhantomJS doesn't support the click method, so "element.click()" won't work here. We need to dispatch the event instead. */ js.executeScript("var ev = document.createEvent('MouseEvent');" + " ev.initMouseEvent(" + " '" + event + "'," + " true /* bubble */, true /* cancelable */," + " window, null," + " 0, 0, 0, 0, /* coordinates */" + " false, false, false, false, /* modifier keys */" + " 0 /*left*/, null" + " );" + " arguments[0].dispatchEvent(ev);", element); } @Override public void interactHiddenElementKeyEvent( @NotNull final WebElement element, @NotNull final String event, @NotNull final JavascriptExecutor js) { /* PhantomJS doesn't support the click method, so "element.click()" won't work here. We need to dispatch the event instead. */ js.executeScript("var ev = document.createEvent('KeyboardEvent');" + " ev.initKeyboardEvent(" + " '" + event + "'," + " true /* bubble */, true /* cancelable */," + " window, null," + " 0, 0, 0, 0, /* coordinates */" + " false, false, false, false, /* modifier keys */" + " 0 /*left*/, null" + " );" + " arguments[0].dispatchEvent(ev);", element); } }
Fixing up issues with the regression test suite in Firefox
src/main/java/au/com/agic/apptesting/utils/impl/JavaScriptRunnerImpl.java
Fixing up issues with the regression test suite in Firefox
<ide><path>rc/main/java/au/com/agic/apptesting/utils/impl/JavaScriptRunnerImpl.java <ide> here. We need to dispatch the event instead. <ide> */ <ide> js.executeScript("var ev = document.createEvent('KeyboardEvent');" <del> + " ev.initKeyboardEvent(" <add> + " (ev.initKeyEvent || ev.initKeyboardEvent).call(ev," <ide> + " '" + event + "'," <ide> + " true /* bubble */, true /* cancelable */," <ide> + " window, null,"
JavaScript
mit
73042890d2fd288747b792de541bfe97f6758a55
0
Seriesbox/seriesbox-server
var fs = require('fs'), path = require('path'), _ = require('lodash'); ptn = require('parse-torrent-name'), replaceExt = require('replace-ext'), junk = require('junk'); var SUPPORTED_FILETYPES = new RegExp("(avi|mkv|mpeg|mov|mp4|m4v|wmv)$","g"); //Pipe seperated var walk = function(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var i = 0; (function next() { var file = list[i++]; if (!file) return done(null, results); file = dir + '/' + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { walk(file, function(err, res) { results = results.concat(res); next(); }); } else { var ext = file.split("."); ext = ext[ext.length - 1]; if (ext.match(SUPPORTED_FILETYPES)) { results.push(file); } next(); } }); })(); }); }; var FileParser = function(file){ var name = replaceExt(file, ''); parsed = ptn(name); //console.log(info); return ptn(name); }; var FolderParser = function(dir){ walk(dir, function(err, files){ if(err){ throw err; } var list; files = files.filter(junk.not); list = _.each(files, function(file, index, list){ var parsedFile = FileParser(path.basename(file)); parsedFile.file = file; if(file !== parsedFile && typeof parsedFile == 'object' && parsedFile.title){ list[index] = parsedFile; }else{ list[index] = null; } return file; }); //console.log(list) var shows = []; _.each(list, function(item){ if(item && item.title && item.season){ if(!shows[item.title]){ shows[item.title] = []; } // Filter all undefined properties // http://stackoverflow.com/questions/14058193/remove-empty-properties-falsy-values-from-object-with-underscore-js var ep = _.pick(item, _.identity); shows[item.title].push(ep); } }); console.log(shows); return shows; }); }; module.exports = { FolderParser: FolderParser }; console.log(FolderParser('\/\\192.168.0.11\/htpc\/TV'));
src/parsers/tv/Parser.js
var fs = require('fs'), path = require('path'), _ = require('lodash'); ptn = require('parse-torrent-name'), replaceExt = require('replace-ext'), junk = require('junk'); var SUPPORTED_FILETYPES = new RegExp("(avi|mkv|mpeg|mov|mp4|m4v|wmv)$","g"); //Pipe seperated var walk = function(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var i = 0; (function next() { var file = list[i++]; if (!file) return done(null, results); file = dir + '/' + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { walk(file, function(err, res) { results = results.concat(res); next(); }); } else { var ext = file.split("."); ext = ext[ext.length - 1]; if (ext.match(SUPPORTED_FILETYPES)) { results.push(file); } next(); } }); })(); }); }; var FileParser = function(file){ var name = replaceExt(file, ''); //console.log(info); return ptn(name); }; var FolderParser = function(dir){ walk(dir, function(err, files){ if(err){ throw err; } var list; files = files.filter(junk.not); list = _.each(files, function(file, index, list){ file = FileParser(path.basename(file)); list[index] = file; return file; }); //console.log(list) var shows = []; _.each(list, function(item){ if(!shows[item.title]){ shows[item.title] = []; } // Filter all undefined properties // http://stackoverflow.com/questions/14058193/remove-empty-properties-falsy-values-from-object-with-underscore-js var ep = _.pick(item, _.identity); shows[item.title].push(ep); }); console.log(shows); return shows; }); }; module.exports = { FolderParser: FolderParser }; console.log(FolderParser('\/\\192.168.0.11\/htpc\/TV'));
Don't add invalid parser results to list parse-torrent-name has problems parsing certain files, so check for season and title before adding to list
src/parsers/tv/Parser.js
Don't add invalid parser results to list
<ide><path>rc/parsers/tv/Parser.js <ide> }; <ide> var FileParser = function(file){ <ide> var name = replaceExt(file, ''); <add> parsed = ptn(name); <ide> //console.log(info); <ide> return ptn(name); <ide> }; <ide> var list; <ide> files = files.filter(junk.not); <ide> list = _.each(files, function(file, index, list){ <del> file = FileParser(path.basename(file)); <del> list[index] = file; <add> var parsedFile = FileParser(path.basename(file)); <add> parsedFile.file = file; <add> if(file !== parsedFile && typeof parsedFile == 'object' && parsedFile.title){ <add> list[index] = parsedFile; <add> }else{ <add> list[index] = null; <add> } <ide> return file; <ide> }); <ide> //console.log(list) <ide> var shows = []; <ide> _.each(list, function(item){ <del> if(!shows[item.title]){ <del> shows[item.title] = []; <add> if(item && item.title && item.season){ <add> if(!shows[item.title]){ <add> shows[item.title] = []; <add> } <add> // Filter all undefined properties <add> // http://stackoverflow.com/questions/14058193/remove-empty-properties-falsy-values-from-object-with-underscore-js <add> var ep = _.pick(item, _.identity); <add> shows[item.title].push(ep); <ide> } <del> // Filter all undefined properties <del> // http://stackoverflow.com/questions/14058193/remove-empty-properties-falsy-values-from-object-with-underscore-js <del> var ep = _.pick(item, _.identity); <del> shows[item.title].push(ep); <ide> }); <ide> console.log(shows); <ide> return shows;
Java
apache-2.0
error: pathspec 'app/src/main/java/com/fkeglevich/rawdumper/camera/data/FocusArea.java' did not match any file(s) known to git
0112d1b3fc128746297ee60e0c156d1f59774db1
1
fkeglevich/Raw-Dumper,fkeglevich/Raw-Dumper,fkeglevich/Raw-Dumper
/* * Copyright 2017, Flávio Keglevich * * 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.fkeglevich.rawdumper.camera.data; import android.view.MotionEvent; import android.view.View; /** * TODO: Add class header * <p> * Created by Flávio Keglevich on 29/10/17. */ public class FocusArea { private static final int DEFAULT_TOUCH_SIZE = 100; private final int x; private final int y; private final int viewWidth; private final int viewHeight; private final int touchSize; public static FocusArea createTouchArea(View view, MotionEvent motionEvent, int touchSize) { return new FocusArea((int) motionEvent.getX(), (int) motionEvent.getY(), view.getWidth(), view.getHeight(), touchSize); } public static FocusArea createTouchArea(View view, MotionEvent motionEvent) { return createTouchArea(view, motionEvent, DEFAULT_TOUCH_SIZE); } public FocusArea(int x, int y, int viewWidth, int viewHeight, int touchSize) { this.x = x; this.y = y; this.viewWidth = viewWidth; this.viewHeight = viewHeight; this.touchSize = touchSize; } public int getX() { return x; } public int getY() { return y; } public int getViewWidth() { return viewWidth; } public int getViewHeight() { return viewHeight; } public int getTouchSize() { return touchSize; } }
app/src/main/java/com/fkeglevich/rawdumper/camera/data/FocusArea.java
Created FocusArea
app/src/main/java/com/fkeglevich/rawdumper/camera/data/FocusArea.java
Created FocusArea
<ide><path>pp/src/main/java/com/fkeglevich/rawdumper/camera/data/FocusArea.java <add>/* <add> * Copyright 2017, Flávio Keglevich <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package com.fkeglevich.rawdumper.camera.data; <add> <add>import android.view.MotionEvent; <add>import android.view.View; <add> <add>/** <add> * TODO: Add class header <add> * <p> <add> * Created by Flávio Keglevich on 29/10/17. <add> */ <add> <add>public class FocusArea <add>{ <add> private static final int DEFAULT_TOUCH_SIZE = 100; <add> <add> private final int x; <add> private final int y; <add> private final int viewWidth; <add> private final int viewHeight; <add> private final int touchSize; <add> <add> public static FocusArea createTouchArea(View view, MotionEvent motionEvent, int touchSize) <add> { <add> return new FocusArea((int) motionEvent.getX(), (int) motionEvent.getY(), view.getWidth(), view.getHeight(), touchSize); <add> } <add> <add> public static FocusArea createTouchArea(View view, MotionEvent motionEvent) <add> { <add> return createTouchArea(view, motionEvent, DEFAULT_TOUCH_SIZE); <add> } <add> <add> public FocusArea(int x, int y, int viewWidth, int viewHeight, int touchSize) <add> { <add> this.x = x; <add> this.y = y; <add> this.viewWidth = viewWidth; <add> this.viewHeight = viewHeight; <add> this.touchSize = touchSize; <add> } <add> <add> public int getX() <add> { <add> return x; <add> } <add> <add> public int getY() <add> { <add> return y; <add> } <add> <add> public int getViewWidth() <add> { <add> return viewWidth; <add> } <add> <add> public int getViewHeight() <add> { <add> return viewHeight; <add> } <add> <add> public int getTouchSize() <add> { <add> return touchSize; <add> } <add>}
Java
agpl-3.0
4af84c3b9473efd0edec8fc250a24c9a6dfd471e
0
EvilOlaf/mcMMO,virustotalop/mcMMO,isokissa3/mcMMO,Maximvdw/mcMMO,jhonMalcom79/mcMMO_pers
import java.util.logging.Level; import java.util.logging.Logger; //===================================================================== //Class: vMinecraftListener //Use: The listener to catch incoming chat and commands //Author: nossr50, TrapAlice, cerevisiae //===================================================================== public class vMinecraftListener extends PluginListener { public int damagetype; public String deadplayer; public boolean senddeath; protected static final Logger log = Logger.getLogger("Minecraft"); //===================================================================== //Function: disable //Input: None //Output: None //Use: Disables vMinecraft, but why would you want to do that? ;) //===================================================================== public void disable() { log.log(Level.INFO, "vMinecraft disabled"); } //===================================================================== //Function: onChat //Input: Player player: The player calling the command // String message: The message to color //Output: boolean: If the user has access to the command // and it is enabled //Use: Checks for quote, rage, and colors //===================================================================== public boolean onChat(Player player, String message){ //Quote (Greentext) if (message.startsWith("@") || vMinecraftSettings.getInstance().isAdminToggled(player.getName())) return vMinecraftChat.adminChat(player, message); else if (message.startsWith(">")) return vMinecraftChat.quote(player, message); //Rage (FFF) else if (message.startsWith("FFF")) return vMinecraftChat.rage(player, message); //Send through quakeColors otherwise else return vMinecraftChat.quakeColors(player, message); } //===================================================================== //Function: onCommand //Input: Player player: The player calling the command // String[] split: The arguments //Output: boolean: If the user has access to the command // and it is enabled //Use: Checks for exploits and runs the commands //===================================================================== public boolean onCommand(Player player, String[] split) { //Copy the arguments into their own array. String[] args = new String[split.length - 1]; System.arraycopy(split, 1, args, 0, args.length); //Return the results of the command int exitCode = vMinecraftCommands.cl.call(split[0], player, args); if(exitCode == 0) return false; else if(exitCode == 1) return true; else return false; } //===================================================================== //Function: onHealthChange //Input: Player player: The player calling the command // int oldValue: The old health value; // int newValue: The new health value //Output: boolean: If the user has access to the command // and it is enabled //Use: Checks for exploits and runs the commands //===================================================================== public boolean onHealthChange(Player player,int oldValue,int newValue){ if (vMinecraftSettings.getInstance().isEzModo(player.getName())) { return oldValue > newValue; } if (player.getHealth() < 1){ senddeath = true; deadplayer = player.getName(); } return true; } public void onLogin(Player player){ vMinecraftChat.sendMessage(player, player, Colors.Rose + "There are currently " + etc.getServer().getPlayerList().size() + " players online."); vMinecraftUsers.addUser(player); } public void onDisconnect(Player player){ vMinecraftUsers.removeUser(player); } public boolean onIgnite(Block block, Player player) { if(vMinecraftSettings.stopFire){ if(block.getStatus() == 3 || block.getStatus() == 1){ return true; } if(block.getStatus() == 2 && !player.isAdmin()){ return true; } } return false; } public boolean onDamage(PluginLoader.DamageType type, BaseEntity attacker, BaseEntity defender, int amount) { if (senddeath == true) { if (type == type.CREEPER_EXPLOSION) { vMinecraftChat.gmsg(deadplayer + Colors.Rose + " was blown to bits by a creeper"); } else if(type == type.FALL){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " fell to death!"); } else if(type == type.FIRE){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " was incinerated"); } else if (type == type.FIRE_TICK){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " Stop drop and roll, not scream, run, and burn "); } else if (type == type.LAVA){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " drowned in lava"); } else if (type == type.WATER){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " should've attended that swimming class"); } else { vMinecraftChat.gmsg(Colors.Gray + deadplayer + " " + vMinecraftSettings.randomDeathMsg()); } senddeath = false; } return true; } }
vMinecraftListener.java
import java.util.logging.Level; import java.util.logging.Logger; //===================================================================== //Class: vMinecraftListener //Use: The listener to catch incoming chat and commands //Author: nossr50, TrapAlice, cerevisiae //===================================================================== public class vMinecraftListener extends PluginListener { public int damagetype; public String deadplayer; public boolean senddeath; protected static final Logger log = Logger.getLogger("Minecraft"); //===================================================================== //Function: disable //Input: None //Output: None //Use: Disables vMinecraft, but why would you want to do that? ;) //===================================================================== public void disable() { log.log(Level.INFO, "vMinecraft disabled"); } //===================================================================== //Function: onChat //Input: Player player: The player calling the command // String message: The message to color //Output: boolean: If the user has access to the command // and it is enabled //Use: Checks for quote, rage, and colors //===================================================================== public boolean onChat(Player player, String message){ //Quote (Greentext) if (message.startsWith("@") || vMinecraftSettings.getInstance().isAdminToggled(player.getName())) return vMinecraftChat.adminChat(player, message); else if (message.startsWith(">")) return vMinecraftChat.quote(player, message); //Rage (FFF) else if (message.startsWith("FFF")) return vMinecraftChat.rage(player, message); //Send through quakeColors otherwise else return vMinecraftChat.quakeColors(player, message); } //===================================================================== //Function: onCommand //Input: Player player: The player calling the command // String[] split: The arguments //Output: boolean: If the user has access to the command // and it is enabled //Use: Checks for exploits and runs the commands //===================================================================== public boolean onCommand(Player player, String[] split) { //Copy the arguments into their own array. String[] args = new String[split.length - 1]; System.arraycopy(split, 1, args, 0, args.length); //Return the results of the command int exitCode = vMinecraftCommands.cl.call(split[0], player, args); if(exitCode == 0) return false; else if(exitCode == 1) return true; else return false; } //===================================================================== //Function: onHealthChange //Input: Player player: The player calling the command // int oldValue: The old health value; // int newValue: The new health value //Output: boolean: If the user has access to the command // and it is enabled //Use: Checks for exploits and runs the commands //===================================================================== public boolean onHealthChange(Player player,int oldValue,int newValue){ if (vMinecraftSettings.getInstance().isEzModo(player.getName())) { return oldValue > newValue; } if (player.getHealth() < 1){ senddeath = true; deadplayer = player.getName(); } return false; } public void onLogin(Player player){ vMinecraftChat.sendMessage(player, player, Colors.Rose + "There are currently " + etc.getServer().getPlayerList().size() + " players online."); vMinecraftUsers.addUser(player); } public void onDisconnect(Player player){ vMinecraftUsers.removeUser(player); } public boolean onIgnite(Block block, Player player) { if(vMinecraftSettings.stopFire){ if(block.getStatus() == 3 || block.getStatus() == 1){ return true; } if(block.getStatus() == 2 && !player.isAdmin()){ return true; } } return false; } public boolean onDamage(PluginLoader.DamageType type, BaseEntity attacker, BaseEntity defender, int amount) { if (senddeath == true) { if (type == type.CREEPER_EXPLOSION) { vMinecraftChat.gmsg(deadplayer + Colors.Rose + " was blown to bits by a creeper"); } else if(type == type.FALL){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " fell to death!"); } else if(type == type.FIRE){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " was incinerated"); } else if (type == type.FIRE_TICK){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " Stop drop and roll, not scream, run, and burn "); } else if (type == type.LAVA){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " drowned in lava"); } else if (type == type.WATER){ vMinecraftChat.gmsg(deadplayer + Colors.Rose + " should've attended that swimming class"); } else { vMinecraftChat.gmsg(Colors.Gray + deadplayer + " " + vMinecraftSettings.randomDeathMsg()); } senddeath = false; } return true; } }
Fixed accidentally making everyone invincible.
vMinecraftListener.java
Fixed accidentally making everyone invincible.
<ide><path>MinecraftListener.java <ide> senddeath = true; <ide> deadplayer = player.getName(); <ide> } <del> return false; <add> return true; <ide> } <ide> <ide> public void onLogin(Player player){
Java
mit
50cfbeb03b8b6c631f4dcf5bb876b033af75ef45
0
dxiao/PPBunnies,dxiao/PPBunnies,dxiao/PPBunnies
package com.gravity.map; import java.util.List; import org.newdawn.slick.Graphics; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.tiled.TiledMap; import com.google.common.collect.Lists; import com.gravity.gameplay.GravityGameController; import com.gravity.physics.Entity; import com.gravity.physics.SpikeEntity; import com.gravity.physics.TileWorldEntity; public class TileWorld implements GameWorld { public final int height; public final int width; public final int tileHeight; public final int tileWidth; private List<Entity> entityNoCalls, entityCallColls; private TiledMap map; private final int TILES_LAYER_ID; private final int SPIKES_LAYER_ID; public TileWorld(TiledMap map, GravityGameController controller) { TILES_LAYER_ID = map.getLayerIndex("collisions"); SPIKES_LAYER_ID = map.getLayerIndex("spikes"); // Get width/height this.tileWidth = map.getTileWidth(); this.tileHeight = map.getTileHeight(); this.width = map.getWidth() * tileWidth; this.height = map.getHeight() * tileHeight; this.map = map; // Iterate over and find all tiles int layerId = TILES_LAYER_ID; // Layer ID to search at entityNoCalls = Lists.newArrayList(); entityCallColls = Lists.newArrayList(); for (int i = 0; i < map.getWidth(); i++) { for (int j = 0; j < map.getHeight(); j++) { int tileId = map.getTileId(i, j, layerId); if (tileId != 0) { // Tile exists at this spot Rectangle r = new Rectangle(i * tileWidth, j * tileHeight, tileWidth, tileHeight); Entity e = new TileWorldEntity(r); entityNoCalls.add(e); } } } layerId = SPIKES_LAYER_ID; for (int i = 0; i < map.getWidth(); i++) { for (int j = 0; j < map.getHeight(); j++) { int tileId = map.getTileId(i, j, layerId); if (tileId != 0) { // Tile exists at this spot Rectangle r = new Rectangle(i * tileWidth, j * tileHeight, tileWidth, tileHeight); Entity e = new SpikeEntity(controller, r); entityCallColls.add(e); } } } } @Override public List<Entity> getCollisions(Shape shape) { List<Entity> collisions = Lists.newArrayList(); for (Entity ent : entityNoCalls) { if (shape.intersects(ent.getShape(0))) { collisions.add(ent); } } return collisions; } @Override public List<Shape> getTouching(Shape shape) { List<Shape> touches = Lists.newArrayList(); for (Entity terrain : entityNoCalls) { if (shape.intersects(terrain.getShape(0))) { touches.add(terrain.getShape(0)); } } for (Entity terrain : entityCallColls) { if (shape.intersects(terrain.getShape(0))) { touches.add(terrain.getShape(0)); } } return touches; } @Override public int getHeight() { return height; } @Override public int getWidth() { return width; } @Override public List<Entity> getTerrainEntitiesNoCalls() { return entityNoCalls; } @Override public void render(Graphics g, int offsetX, int offsetY) { /* * // if we need to draw hitboxes again: g.pushTransform(); g.translate(offsetX, offsetY); g.setColor(Color.red); for (Entity e : * entityNoCalls) { g.draw(e.getShape(0)); } g.setColor(Color.white); g.resetTransform(); g.popTransform(); */ map.render(offsetX, offsetY); } @Override public List<Entity> getTerrainEntitiesCallColls() { return entityCallColls; } }
Platformer/src/com/gravity/map/TileWorld.java
package com.gravity.map; import java.util.List; import org.newdawn.slick.Graphics; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.tiled.TiledMap; import com.google.common.collect.Lists; import com.gravity.gameplay.GravityGameController; import com.gravity.physics.Entity; import com.gravity.physics.SpikeEntity; import com.gravity.physics.TileWorldEntity; public class TileWorld implements GameWorld { public final int height; public final int width; public final int tileHeight; public final int tileWidth; private List<Entity> entityNoCalls, entityCallColls; private TiledMap map; private final int TILES_LAYER_ID; private final int SPIKES_LAYER_ID; public TileWorld(TiledMap map, GravityGameController controller) { TILES_LAYER_ID = map.getLayerIndex("collisions"); SPIKES_LAYER_ID = map.getLayerIndex("spikes"); // Get width/height this.tileWidth = map.getTileWidth(); this.tileHeight = map.getTileHeight(); this.width = map.getWidth() * tileWidth; this.height = map.getHeight() * tileHeight; this.map = map; // Iterate over and find all tiles int layerId = TILES_LAYER_ID; // Layer ID to search at entityNoCalls = Lists.newArrayList(); entityCallColls = Lists.newArrayList(); for (int i = 0; i < map.getWidth(); i++) { for (int j = 0; j < map.getHeight(); j++) { int tileId = map.getTileId(i, j, layerId); if (tileId != 0) { // Tile exists at this spot Rectangle r = new Rectangle(i * tileWidth, j * tileHeight, tileWidth, tileHeight); Entity e = new TileWorldEntity(r); entityNoCalls.add(e); } } } layerId = SPIKES_LAYER_ID; for (int i = 0; i < map.getWidth(); i++) { for (int j = 0; j < map.getHeight(); j++) { int tileId = map.getTileId(i, j, layerId); if (tileId != 0) { // Tile exists at this spot Rectangle r = new Rectangle(i * tileWidth, j * tileHeight, tileWidth, tileHeight); Entity e = new SpikeEntity(controller, r); entityCallColls.add(e); } } } } @Override public List<Entity> getCollisions(Shape shape) { List<Entity> collisions = Lists.newArrayList(); for (Entity ent : entityNoCalls) { if (shape.intersects(ent.getShape(0))) { collisions.add(ent); } } return collisions; } @Override public List<Shape> getTouching(Shape shape) { List<Shape> touches = Lists.newArrayList(); for (Entity terrain : entityNoCalls) { if (shape.intersects(terrain.getShape(0))) { touches.add(terrain.getShape(0)); } } return touches; } @Override public int getHeight() { return height; } @Override public int getWidth() { return width; } @Override public List<Entity> getTerrainEntitiesNoCalls() { return entityNoCalls; } @Override public void render(Graphics g, int offsetX, int offsetY) { /* * // if we need to draw hitboxes again: g.pushTransform(); g.translate(offsetX, offsetY); g.setColor(Color.red); for (Entity e : * entityNoCalls) { g.draw(e.getShape(0)); } g.setColor(Color.white); g.resetTransform(); g.popTransform(); */ map.render(offsetX, offsetY); } @Override public List<Entity> getTerrainEntitiesCallColls() { return entityCallColls; } }
Fixed corner spike jumps
Platformer/src/com/gravity/map/TileWorld.java
Fixed corner spike jumps
<ide><path>latformer/src/com/gravity/map/TileWorld.java <ide> touches.add(terrain.getShape(0)); <ide> } <ide> } <add> for (Entity terrain : entityCallColls) { <add> if (shape.intersects(terrain.getShape(0))) { <add> touches.add(terrain.getShape(0)); <add> } <add> } <ide> return touches; <ide> } <ide>
Java
lgpl-2.1
cbeb01764a4e528d5fbc6386b304d725272ed68c
0
levants/lightmare
package org.lightmare.utils.reflect; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Class to use reflection {@link Method} calls and {@link Field} information * sets * * @author levan * */ public class MetaUtils { // default values for primitives private static byte byteDef; private static boolean booleanDef; private static char charDef; private static short shortDef; private static int intDef; private static long longDef; private static float floatDef; private static double doubleDef; // default value for modifier private static final int DEFAULT_MODIFIER = 0; /** * Sets object accessible flag as true if it is not * * @param accessibleObject * @param accessible */ private static void setAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (ObjectUtils.notTrue(accessibleObject.isAccessible())) { accessibleObject.setAccessible(Boolean.TRUE); } } } } /** * Sets passed {@link AccessibleObject}'s accessible flag as passed * accessible boolean value if the last one is false * * @param accessibleObject * @param accessible */ private static void resetAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (accessibleObject.isAccessible()) { accessibleObject.setAccessible(accessible); } } } } /** * Makes accessible passed {@link Constructor}'s and invokes * {@link Constructor#newInstance(Object...)} method * * @param constructor * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T newInstance(Constructor<T> constructor, Object... parameters) throws IOException { T instance; boolean accessible = constructor.isAccessible(); try { setAccessible(constructor, accessible); instance = constructor.newInstance(parameters); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } finally { resetAccessible(constructor, accessible); } return instance; } /** * Gets declared constructor for given {@link Class} and given parameters * * @param type * @param parameterTypes * @return {@link Constructor} * @throws IOException */ public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes) throws IOException { Constructor<T> constructor; try { constructor = type.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return constructor; } /** * Instantiates class by {@link Constructor} (MetaUtils * {@link #newInstance(Constructor, Object...)}) after * {@link MetaUtils#getConstructor(Class, Class...)} method call * * @param type * @param parameterTypes * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T callConstructor(Class<T> type, Class<?>[] parameterTypes, Object... parameters) throws IOException { T instance; Constructor<T> constructor = getConstructor(type, parameterTypes); instance = newInstance(constructor, parameters); return instance; } /** * Loads class by name * * @param className * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className) throws IOException { Class<?> clazz = classForName(className, null); return clazz; } /** * Loads class by name with specific {@link ClassLoader} if it is not * <code>null</code> * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, ClassLoader loader) throws IOException { Class<?> clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Loads and if initialize parameter is true initializes class by name with * specific {@link ClassLoader} if it is not <code>null</code> * * @param className * @param initialize * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, boolean initialize, ClassLoader loader) throws IOException { Class<?> clazz; try { if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, initialize, loader); } } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Loads class by name with current {@link Thread}'s {@link ClassLoader} and * initializes it * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> initClassForName(String className) throws IOException { Class<?> clazz; ClassLoader loader = LibraryLoader.getContextClassLoader(); clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Creates {@link Class} instance by {@link Class#newInstance()} method call * * @param clazz * @return */ public static <T> T instantiate(Class<T> clazz) throws IOException { T instance; try { instance = clazz.newInstance(); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } return instance; } /** * Gets declared method from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws IOException { Method method; try { method = clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return method; } /** * Gets all declared methods from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method[] getDeclaredMethods(Class<?> clazz) throws IOException { Method[] methods; try { methods = clazz.getDeclaredMethods(); } catch (SecurityException ex) { throw new IOException(ex); } return methods; } /** * Gets one modifier <code>int</code> value for passed collection * * @param modifiers * @return <code>int</code> */ private static int calculateModifier(int[] modifiers) { int modifier = DEFAULT_MODIFIER; if (ObjectUtils.notNull(modifiers)) { int length = modifiers.length; int modifierValue; for (int i = 0; i < length; i++) { modifierValue = modifiers[i]; modifier = modifier | modifierValue; } } return modifier; } /** * Finds if passed {@link Class} has declared public {@link Method} with * appropriated name * * @param clazz * @param modifiers * @param methodName * @return <code>boolean</code> * @throws IOException */ private static boolean classHasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Method[] methods = getDeclaredMethods(clazz); int length = methods.length; int modifier = calculateModifier(modifiers); Method method; for (int i = 0; i < length && ObjectUtils.notTrue(found); i++) { method = methods[i]; found = method.getName().equals(methodName); if (found && ObjectUtils.notEquals(modifier, DEFAULT_MODIFIER)) { found = ((method.getModifiers() & modifier) > DEFAULT_MODIFIER); } } return found; } /** * Finds if passed {@link Class} has {@link Method} with appropriated name * and modifiers * * @param clazz * @param methodName * @param modifiers * @return <code>boolean</code> * @throws IOException */ public static boolean hasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Class<?> superClass = clazz; while (ObjectUtils.notNull(superClass) && ObjectUtils.notTrue(found)) { found = MetaUtils.classHasMethod(superClass, methodName, modifiers); if (ObjectUtils.notTrue(found)) { superClass = superClass.getSuperclass(); } } return found; } /** * Finds if passed {@link Class} has public {@link Method} with appropriated * name * * @param clazz * @param methodName * @return <code>boolean</code> * @throws IOException */ public static boolean hasPublicMethod(Class<?> clazz, String methodName) throws IOException { boolean found = MetaUtils.hasMethod(clazz, methodName, Modifier.PUBLIC); return found; } /** * Gets declared field from passed class with specified name * * @param clazz * @param name * @return {@link Field} * @throws IOException */ public static Field getDeclaredField(Class<?> clazz, String name) throws IOException { Field field; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return field; } /** * Returns passed {@link Field}'s modifier * * @param field * @return <code>int</code> */ public static int getModifiers(Field field) { return field.getModifiers(); } /** * Returns passed {@link Method}'s modifier * * @param method * @return <code>int</code> */ public static int getModifiers(Method method) { return method.getModifiers(); } /** * Returns type of passed {@link Field} invoking {@link Field#getType()} * method * * @param field * @return {@link Class}<?> */ public static Class<?> getType(Field field) { return field.getType(); } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invoke(Method method, Object data, Object... arguments) throws IOException { Object value; try { value = method.invoke(data, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invokePrivate(Method method, Object data, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invoke(method, data, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Common method to invoke static {@link Method} with reflection * * @param method * @param arguments * @return * @throws IOException */ public static Object invokeStatic(Method method, Object... arguments) throws IOException { Object value; try { value = method.invoke(null, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke private static {@link Method} * * @param method * @param arguments * @return * @throws IOException */ public static Object invokePrivateStatic(Method method, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invokeStatic(method, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Sets value to {@link Field} sets accessible Boolean.TRUE remporary if * needed * * @param field * @param value * @throws IOException */ public static void setFieldValue(Field field, Object data, Object value) throws IOException { boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); field.set(data, value); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } } /** * Gets value of specific field in specific {@link Object} * * @param field * @param data * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field, Object data) throws IOException { Object value; boolean accessible = field.isAccessible(); try { if (ObjectUtils.notTrue(accessible)) { field.setAccessible(Boolean.TRUE); } value = field.get(data); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } return value; } /** * Gets value of specific static field * * @param field * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field) throws IOException { Object value = getFieldValue(field, null); return value; } /** * Gets {@link List} of all {@link Method}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Method> * @throws IOException */ public static List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Method> methods = new ArrayList<Method>(); Method[] allMethods = getDeclaredMethods(clazz); for (Method method : allMethods) { if (method.isAnnotationPresent(annotationClass)) { methods.add(method); } } return methods; } /** * Gets {@link List} of all {@link Field}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Field> * @throws IOException */ public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Field> fields = new ArrayList<Field>(); Field[] allFields = clazz.getDeclaredFields(); for (Field field : allFields) { if (field.isAnnotationPresent(annotationClass)) { fields.add(field); } } return fields; } /** * Gets wrapper class if passed class is primitive type * * @param type * @return {@link Class}<T> */ public static <T> Class<T> getWrapper(Class<?> type) { Class<T> wrapper; if (type.isPrimitive()) { if (type.equals(byte.class)) { wrapper = ObjectUtils.cast(Byte.class); } else if (type.equals(boolean.class)) { wrapper = ObjectUtils.cast(Boolean.class); } else if (type.equals(char.class)) { wrapper = ObjectUtils.cast(Character.class); } else if (type.equals(short.class)) { wrapper = ObjectUtils.cast(Short.class); } else if (type.equals(int.class)) { wrapper = ObjectUtils.cast(Integer.class); } else if (type.equals(long.class)) { wrapper = ObjectUtils.cast(Long.class); } else if (type.equals(float.class)) { wrapper = ObjectUtils.cast(Float.class); } else if (type.equals(double.class)) { wrapper = ObjectUtils.cast(Double.class); } else { wrapper = ObjectUtils.cast(type); } } else { wrapper = ObjectUtils.cast(type); } return wrapper; } /** * Returns default values if passed class is primitive else returns null * * @param clazz * @return Object */ public static Object getDefault(Class<?> clazz) { Object value; if (clazz.isPrimitive()) { if (clazz.equals(byte.class)) { value = byteDef; } else if (clazz.equals(boolean.class)) { value = booleanDef; } else if (clazz.equals(char.class)) { value = charDef; } else if (clazz.equals(short.class)) { value = shortDef; } else if (clazz.equals(int.class)) { value = intDef; } else if (clazz.equals(long.class)) { value = longDef; } else if (clazz.equals(float.class)) { value = floatDef; } else if (clazz.equals(double.class)) { value = doubleDef; } else { value = null; } } else { value = null; } return value; } }
src/main/java/org/lightmare/utils/reflect/MetaUtils.java
package org.lightmare.utils.reflect; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Class to use reflection {@link Method} calls and {@link Field} information * sets * * @author levan * */ public class MetaUtils { // default values for primitives private static byte byteDef; private static boolean booleanDef; private static char charDef; private static short shortDef; private static int intDef; private static long longDef; private static float floatDef; private static double doubleDef; // default value for modifier private static final int DEFAULT_MODIFIER = 0; /** * Sets object accessible flag as true if it is not * * @param accessibleObject * @param accessible */ private static void setAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (ObjectUtils.notTrue(accessibleObject.isAccessible())) { accessibleObject.setAccessible(Boolean.TRUE); } } } } /** * Sets passed {@link AccessibleObject}'s accessible flag as passed * accessible boolean value if the last one is false * * @param accessibleObject * @param accessible */ private static void resetAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (accessibleObject.isAccessible()) { accessibleObject.setAccessible(accessible); } } } } /** * Makes accessible passed {@link Constructor}'s and invokes * {@link Constructor#newInstance(Object...)} method * * @param constructor * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T newInstance(Constructor<T> constructor, Object... parameters) throws IOException { T instance; boolean accessible = constructor.isAccessible(); try { setAccessible(constructor, accessible); instance = constructor.newInstance(parameters); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } finally { resetAccessible(constructor, accessible); } return instance; } /** * Gets declared constructor for given {@link Class} and given parameters * * @param type * @param parameterTypes * @return {@link Constructor} * @throws IOException */ public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes) throws IOException { Constructor<T> constructor; try { constructor = type.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return constructor; } /** * Instantiates class by {@link Constructor} (MetaUtils * {@link #newInstance(Constructor, Object...)}) after * {@link MetaUtils#getConstructor(Class, Class...)} method call * * @param type * @param parameterTypes * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T callConstructor(Class<T> type, Class<?>[] parameterTypes, Object... parameters) throws IOException { T instance; Constructor<T> constructor = getConstructor(type, parameterTypes); instance = newInstance(constructor, parameters); return instance; } /** * Loads class by name * * @param className * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className) throws IOException { Class<?> clazz = classForName(className, null); return clazz; } /** * Loads class by name with specific {@link ClassLoader} if it is not * <code>null</code> * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, ClassLoader loader) throws IOException { Class<?> clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Loads and if initialize parameter is true initializes class by name with * specific {@link ClassLoader} if it is not <code>null</code> * * @param className * @param initialize * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, boolean initialize, ClassLoader loader) throws IOException { Class<?> clazz; try { if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, initialize, loader); } } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Loads class by name with current {@link Thread}'s {@link ClassLoader} and * initializes it * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> initClassForName(String className) throws IOException { Class<?> clazz; ClassLoader loader = LibraryLoader.getContextClassLoader(); clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Creates {@link Class} instance by {@link Class#newInstance()} method call * * @param clazz * @return */ public static <T> T instantiate(Class<T> clazz) throws IOException { T instance; try { instance = clazz.newInstance(); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } return instance; } /** * Gets declared method from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws IOException { Method method; try { method = clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return method; } /** * Gets all declared methods from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method[] getDeclaredMethods(Class<?> clazz) throws IOException { Method[] methods; try { methods = clazz.getDeclaredMethods(); } catch (SecurityException ex) { throw new IOException(ex); } return methods; } /** * Gets one modifier <code>int</code> value for passed collection * * @param modifiers * @return <code>int</code> */ private static int calculateModifier(int[] modifiers) { int modifier = DEFAULT_MODIFIER; if (ObjectUtils.notNull(modifiers)) { int length = modifiers.length; int modifierValue; for (int i = 0; i < length; i++) { modifierValue = modifiers[i]; modifier = modifier | modifierValue; } } return modifier; } /** * Finds if passed {@link Class} has declared public {@link Method} with * appropriated name * * @param clazz * @param modifiers * @param methodName * @return <code>boolean</code> * @throws IOException */ private static boolean classHasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Method[] methods = getDeclaredMethods(clazz); int length = methods.length; int modifier = calculateModifier(modifiers); Method method; for (int i = 0; i < length && ObjectUtils.notTrue(found); i++) { method = methods[i]; found = method.getName().equals(methodName); if (found && ObjectUtils.notEquals(modifier, DEFAULT_MODIFIER)) { found = ((method.getModifiers() & modifier) > DEFAULT_MODIFIER); } } return found; } /** * Finds if passed {@link Class} has {@link Method} with appropriated name * and modifiers * * @param clazz * @param methodName * @param modifiers * @return <code>boolean</code> * @throws IOException */ public static boolean hasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Class<?> superClass = clazz; while (ObjectUtils.notNull(superClass) && ObjectUtils.notTrue(found)) { found = MetaUtils.classHasMethod(superClass, methodName, modifiers); if (ObjectUtils.notTrue(found)) { superClass = superClass.getSuperclass(); } } return found; } /** * Finds if passed {@link Class} has public {@link Method} with appropriated * name * * @param clazz * @param methodName * @return <code>boolean</code> * @throws IOException */ public static boolean hasPublicMethod(Class<?> clazz, String methodName) throws IOException { boolean found = MetaUtils.hasMethod(clazz, methodName, Modifier.PUBLIC); return found; } /** * Gets declared field from passed class with specified name * * @param clazz * @param name * @return {@link Field} * @throws IOException */ public static Field getDeclaredField(Class<?> clazz, String name) throws IOException { Field field; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return field; } /** * Returns passed {@link Field}'s modifier * * @param field * @return <code>int</code> */ public static int getModifiers(Field field) { return field.getModifiers(); } /** * Returns passed {@link Method}'s modifier * * @param method * @return <code>int</code> */ public static int getModifiers(Method method) { return method.getModifiers(); } /** * Returns type of passed {@link Field} invoking {@link Field#getType()} * method * * @param field * @return {@link Class}<?> */ public static Class<?> getType(Field field) { return field.getType(); } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invoke(Method method, Object data, Object... arguments) throws IOException { Object value; try { value = method.invoke(data, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invokePrivate(Method method, Object data, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invoke(method, data, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Common method to invoke static {@link Method} with reflection * * @param method * @param arguments * @return * @throws IOException */ public static Object invokeStatic(Method method, Object... arguments) throws IOException { Object value; try { value = method.invoke(null, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke private static {@link Method} * * @param method * @param arguments * @return * @throws IOException */ public static Object invokePrivateStatic(Method method, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invokeStatic(method, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Sets value to {@link Field} sets accessible Boolean.TRUE remporary if * needed * * @param field * @param value * @throws IOException */ public static void setFieldValue(Field field, Object data, Object value) throws IOException { boolean accessible = field.isAccessible(); try { if (ObjectUtils.notTrue(accessible)) { setAccessible(field, accessible); } field.set(data, value); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } } /** * Gets value of specific field in specific {@link Object} * * @param field * @param data * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field, Object data) throws IOException { Object value; boolean accessible = field.isAccessible(); try { if (ObjectUtils.notTrue(accessible)) { field.setAccessible(Boolean.TRUE); } value = field.get(data); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } return value; } /** * Gets value of specific static field * * @param field * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field) throws IOException { Object value = getFieldValue(field, null); return value; } /** * Gets {@link List} of all {@link Method}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Method> * @throws IOException */ public static List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Method> methods = new ArrayList<Method>(); Method[] allMethods = getDeclaredMethods(clazz); for (Method method : allMethods) { if (method.isAnnotationPresent(annotationClass)) { methods.add(method); } } return methods; } /** * Gets {@link List} of all {@link Field}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Field> * @throws IOException */ public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Field> fields = new ArrayList<Field>(); Field[] allFields = clazz.getDeclaredFields(); for (Field field : allFields) { if (field.isAnnotationPresent(annotationClass)) { fields.add(field); } } return fields; } /** * Gets wrapper class if passed class is primitive type * * @param type * @return {@link Class}<T> */ public static <T> Class<T> getWrapper(Class<?> type) { Class<T> wrapper; if (type.isPrimitive()) { if (type.equals(byte.class)) { wrapper = ObjectUtils.cast(Byte.class); } else if (type.equals(boolean.class)) { wrapper = ObjectUtils.cast(Boolean.class); } else if (type.equals(char.class)) { wrapper = ObjectUtils.cast(Character.class); } else if (type.equals(short.class)) { wrapper = ObjectUtils.cast(Short.class); } else if (type.equals(int.class)) { wrapper = ObjectUtils.cast(Integer.class); } else if (type.equals(long.class)) { wrapper = ObjectUtils.cast(Long.class); } else if (type.equals(float.class)) { wrapper = ObjectUtils.cast(Float.class); } else if (type.equals(double.class)) { wrapper = ObjectUtils.cast(Double.class); } else { wrapper = ObjectUtils.cast(type); } } else { wrapper = ObjectUtils.cast(type); } return wrapper; } /** * Returns default values if passed class is primitive else returns null * * @param clazz * @return Object */ public static Object getDefault(Class<?> clazz) { Object value; if (clazz.isPrimitive()) { if (clazz.equals(byte.class)) { value = byteDef; } else if (clazz.equals(boolean.class)) { value = booleanDef; } else if (clazz.equals(char.class)) { value = charDef; } else if (clazz.equals(short.class)) { value = shortDef; } else if (clazz.equals(int.class)) { value = intDef; } else if (clazz.equals(long.class)) { value = longDef; } else if (clazz.equals(float.class)) { value = floatDef; } else if (clazz.equals(double.class)) { value = doubleDef; } else { value = null; } } else { value = null; } return value; } }
improved reflection utilities
src/main/java/org/lightmare/utils/reflect/MetaUtils.java
improved reflection utilities
<ide><path>rc/main/java/org/lightmare/utils/reflect/MetaUtils.java <ide> <ide> try { <ide> <del> if (ObjectUtils.notTrue(accessible)) { <ide> setAccessible(field, accessible); <del> } <ide> <ide> field.set(data, value); <ide> } catch (IllegalArgumentException ex) {
JavaScript
mit
9f9d414afd4334c833fdc355ce220a0a63b0085c
0
sl/drawdio,sl/drawdio
'use strict'; var fs = require('fs'); var PNG = require('png-js'); var jsfeat = require('jsfeat'); /* Creates a vector representing important features of the image given an image. */ const processImage = function(path, callback) { const blurRadius = 2; const lowThreshhold = 20; const highThreshold = 50; console.log('attempting to load image at path: ' + path); const image = new PNG.load(path); const width = image.width; const height = image.height; // roughEdgeFrequency: percentage of pixels that contain a rough edge (0-1) // averageRed: average pixel red value from (0-1) // averageGreen: average pixel green value from (0-1) // averageBlue: average pixel blue value from (0-1) // hueDist: array containing hue distributions at intervals of 1/6 spectrums // cornerDensity: the number of corners detected in the image // numClusters: the average distance in pixels between corners O(n^3)? var imageData = {}; image.decode(function(pixels) { nextProcess(pixels); }); // sets imageData['roughEdgeFrequency'] const canny = function (pixels) { var img_u8 = new jsfeat.matrix_t(width, height, jsfeat.U8C1_t); var pixelArray = new Int32Array(pixels.buffer); jsfeat.imgproc.grayscale(pixelArray, width, height, img_u8); jsfeat.imgproc.gaussian_blur(img_u8, img_u8, (blurRadius+1) << 1, 0); jsfeat.imgproc.canny(img_u8, img_u8, lowThreshhold|0, highThreshold|0); // determine rough edge frequency var edgePixels = 0; var size = img_u8.cols * img_u8.rows; for (var i = 0; i < size; ++i) { var pixelData = img_u8.data[i]; if (pixelData === 255) { ++edgePixels; } } var roughEdgeFrequency = edgePixels / size; imageData['roughEdgeFrequency'] = roughEdgeFrequency; nextProcess(pixels); }; // sets numCorners and cornerSpread const corners = function(pixels) { // set up the paramters for fast corners const threshold = 20; jsfeat.fast_corners.set_threshold(threshold); var corners = []; var border = 3; // set up the keypoint array for(var i = 0; i < width * height; ++i) { corners[i] = new jsfeat.keypoint_t(0, 0, 0, 0); } var img_u8 = new jsfeat.matrix_t(width, height, jsfeat.U8C1_t); var pixelArray = new Int32Array(pixels.buffer); jsfeat.imgproc.grayscale(pixelArray, width, height, img_u8); var numCorners = jsfeat.fast_corners.detect(img_u8, corners, border); var cornerDensity = numCorners / (width * height); imageData['cornerDensity'] = cornerDensity; var scoredCorners = []; var i = 0; while (corners[i].score > 0 && i < corners.length) { scoredCorners.push({x: corners[i].x, y: corners[i].y,}); ++i; } const clusteringFactor = 1.05; var clusters = []; while (scoredCorners.length > 0) { var point = scoredCorners.shift(); var minDist = Math.min.apply(null, scoredCorners.map((p) => { return Math.pow(point.x - p.x, 2) + Math.pow(point.y - p.y, 2); })); var thresholdDistance = minDist * clusteringFactor; var buildCluster = [point]; while (true) { var addToCluster = []; buildCluster.forEach((p1) => { scoredCorners.forEach((p2) => { var dist = Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2); if (dist <= thresholdDistance) { addToCluster.push(p2); } }); }); if (addToCluster.length <= 0) { clusters.push(buildCluster); break; } addToCluster.forEach((p) => { buildCluster.push(p); scoredCorners.splice(scoredCorners.indexOf(p), 1); }); } } imageData['numClusters'] = clusters.length; nextProcess(pixels); } // sets averageRed, averageGreen, averageBlue, and hueDist const colorProfile = function (pixels) { imageData['averageRed'] = 0; imageData['averageGreen'] = 0; imageData['averageBlue'] = 0; imageData['hueDist'] = [0,0,0,0,0,0]; nextProcess(pixels); } const weights = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; const processes = [canny, colorProfile, corners]; var currentProcess = 0; const nextProcess = function(pixels) { if (currentProcess >= processes.length) { const outVector = [ imageData['roughEdgeFrequency'], imageData['averageRed'], imageData['averageGreen'], imageData['averageBlue'], imageData['hueDist'][0], imageData['hueDist'][1], imageData['hueDist'][2], imageData['hueDist'][3], imageData['hueDist'][4], imageData['hueDist'][5], imageData['cornerDensity'], imageData['numClusters'] ]; var weighted = []; for (var i = 0; i < outVector.length; ++i) { weighted.push(outVector[i] * weights[i]); } callback(weighted); return; } processes[currentProcess++](pixels); } }; function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; } module.exports = { processImage: processImage };
classification.js
'use strict'; var fs = require('fs'); var PNG = require('png-js'); var jsfeat = require('jsfeat'); /* Creates a vector representing important features of the image given an image. */ const processImage = function(path, callback) { const blurRadius = 2; const lowThreshhold = 20; const highThreshold = 50; console.log('attempting to load image at path: ' + path); const image = new PNG.load(path); const width = image.width; const height = image.height; // roughEdgeFrequency: percentage of pixels that contain a rough edge (0-1) // averageRed: average pixel red value from (0-1) // averageGreen: average pixel green value from (0-1) // averageBlue: average pixel blue value from (0-1) // hueDist: array containing hue distributions at intervals of 1/6 spectrums var imageData = {}; image.decode(function(pixels) { nextProcess(pixels); }); // sets imageData['roughEdgeFrequency'] const canny = function (pixels) { var img_u8 = new jsfeat.matrix_t(width, height, jsfeat.U8C1_t); var pixelArray = new Int32Array(pixels.buffer); jsfeat.imgproc.grayscale(pixelArray, width, height, img_u8); jsfeat.imgproc.gaussian_blur(img_u8, img_u8, (blurRadius+1) << 1, 0); jsfeat.imgproc.canny(img_u8, img_u8, lowThreshhold|0, highThreshold|0); // determine rough edge frequency var edgePixels = 0; var size = img_u8.cols * img_u8.rows; for (var i = 0; i < size; ++i) { var pixelData = img_u8.data[i]; if (pixelData === 255) { ++edgePixels; } } var roughEdgeFrequency = edgePixels / size; imageData['roughEdgeFrequency'] = roughEdgeFrequency; nextProcess(pixels); }; // sets averageRed, averageGreen, averageBlue, and hueDist const colorProfile = function (pixels) { imageData['averageRed'] = 0; imageData['averageGreen'] = 0; imageData['averageBlue'] = 0; imageData['hueDist'] = [0,0,0,0,0,0]; nextProcess(pixels); } const weights = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; const processes = [canny, colorProfile]; var currentProcess = 0; const nextProcess = function(pixels) { if (currentProcess >= processes.length) { const outVector = [ imageData['roughEdgeFrequency'], imageData['averageRed'], imageData['averageGreen'], imageData['averageBlue'], imageData['hueDist'][0], imageData['hueDist'][1], imageData['hueDist'][2], imageData['hueDist'][3], imageData['hueDist'][4], imageData['hueDist'][5], ]; var weighted = []; for (var i = 0; i < outVector.length; ++i) { weighted.push(outVector[i] * weights[i]); } callback(weighted); return; } console.log('running process ' + currentProcess) processes[currentProcess++](pixels); } }; module.exports = { processImage: processImage };
added corner based classification
classification.js
added corner based classification
<ide><path>lassification.js <ide> var fs = require('fs'); <ide> var PNG = require('png-js'); <ide> var jsfeat = require('jsfeat'); <del> <ide> <ide> /* <ide> Creates a vector representing important features of the image given an image. <ide> // averageGreen: average pixel green value from (0-1) <ide> // averageBlue: average pixel blue value from (0-1) <ide> // hueDist: array containing hue distributions at intervals of 1/6 spectrums <add> // cornerDensity: the number of corners detected in the image <add> // numClusters: the average distance in pixels between corners O(n^3)? <ide> var imageData = {}; <ide> <ide> image.decode(function(pixels) { <ide> nextProcess(pixels); <ide> }); <del> <del> <ide> <ide> <ide> // sets imageData['roughEdgeFrequency'] <ide> nextProcess(pixels); <ide> }; <ide> <add> // sets numCorners and cornerSpread <add> const corners = function(pixels) { <add> // set up the paramters for fast corners <add> const threshold = 20; <add> jsfeat.fast_corners.set_threshold(threshold); <add> var corners = []; <add> var border = 3; <add> <add> // set up the keypoint array <add> for(var i = 0; i < width * height; ++i) { <add> corners[i] = new jsfeat.keypoint_t(0, 0, 0, 0); <add> } <add> <add> var img_u8 = new jsfeat.matrix_t(width, height, jsfeat.U8C1_t); <add> var pixelArray = new Int32Array(pixels.buffer); <add> jsfeat.imgproc.grayscale(pixelArray, width, height, img_u8); <add> var numCorners = jsfeat.fast_corners.detect(img_u8, corners, border); <add> <add> var cornerDensity = numCorners / (width * height); <add> <add> imageData['cornerDensity'] = cornerDensity; <add> <add> var scoredCorners = []; <add> var i = 0; <add> while (corners[i].score > 0 && i < corners.length) { <add> scoredCorners.push({x: corners[i].x, y: corners[i].y,}); <add> ++i; <add> } <add> <add> const clusteringFactor = 1.05; <add> <add> var clusters = []; <add> <add> while (scoredCorners.length > 0) { <add> var point = scoredCorners.shift(); <add> <add> var minDist = Math.min.apply(null, scoredCorners.map((p) => { <add> return Math.pow(point.x - p.x, 2) + Math.pow(point.y - p.y, 2); <add> })); <add> <add> var thresholdDistance = minDist * clusteringFactor; <add> <add> var buildCluster = [point]; <add> while (true) { <add> var addToCluster = []; <add> buildCluster.forEach((p1) => { <add> scoredCorners.forEach((p2) => { <add> var dist = Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2); <add> if (dist <= thresholdDistance) { <add> addToCluster.push(p2); <add> } <add> }); <add> }); <add> <add> if (addToCluster.length <= 0) { <add> clusters.push(buildCluster); <add> break; <add> } <add> <add> addToCluster.forEach((p) => { <add> buildCluster.push(p); <add> scoredCorners.splice(scoredCorners.indexOf(p), 1); <add> }); <add> } <add> } <add> <add> imageData['numClusters'] = clusters.length; <add> <add> nextProcess(pixels); <add> } <add> <ide> // sets averageRed, averageGreen, averageBlue, and hueDist <ide> const colorProfile = function (pixels) { <ide> imageData['averageRed'] = 0; <ide> nextProcess(pixels); <ide> } <ide> <del> const weights = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; <add> const weights = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; <ide> <del> const processes = [canny, colorProfile]; <add> const processes = [canny, colorProfile, corners]; <ide> var currentProcess = 0; <ide> <ide> const nextProcess = function(pixels) { <ide> imageData['hueDist'][3], <ide> imageData['hueDist'][4], <ide> imageData['hueDist'][5], <add> imageData['cornerDensity'], <add> imageData['numClusters'] <ide> ]; <ide> var weighted = []; <ide> for (var i = 0; i < outVector.length; ++i) { <ide> callback(weighted); <ide> return; <ide> } <del> console.log('running process ' + currentProcess) <ide> processes[currentProcess++](pixels); <del> <ide> } <add>}; <ide> <del> <del> <del>}; <add>function getRandomInt(min, max) { <add> min = Math.ceil(min); <add> max = Math.floor(max); <add> return Math.floor(Math.random() * (max - min)) + min; <add>} <ide> <ide> module.exports = { <ide> processImage: processImage
JavaScript
apache-2.0
83d2ac9be26d433528ab8323474a34d392947e30
0
Chinachu/Mirakurun,kanreisa/Mirakurun,upsilon/Mirakurun,akimasa/Mirakurun,upsilon/Mirakurun,Chinachu/Mirakurun,Chinachu/Mirakurun,kanreisa/Mirakurun,kanreisa/Mirakurun,Chinachu/Mirakurun,upsilon/Mirakurun,akimasa/Mirakurun,akimasa/Mirakurun
/* Copyright 2016 Yuki KAN 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. */ "use strict"; if (process.env["npm_config_global"] !== "true") { process.exit(0); } const fs = require("fs"); const path = require("path"); const child_process = require("child_process"); // init if (process.platform === "linux" || process.platform === "darwin") { if (process.getuid() !== 0) { process.exit(0); } child_process.execSync("mkdir -vp /usr/local/etc/mirakurun"); child_process.execSync("mkdir -vp /usr/local/var/log"); child_process.execSync("mkdir -vp /usr/local/var/run"); child_process.execSync("mkdir -vp /usr/local/var/db/mirakurun"); child_process.execSync("cp -vn config/server.yml /usr/local/etc/mirakurun/server.yml"); child_process.execSync("cp -vn config/tuners.yml /usr/local/etc/mirakurun/tuners.yml"); child_process.execSync("cp -vn config/channels.yml /usr/local/etc/mirakurun/channels.yml"); // pm2 let platform = ""; if (fs.existsSync("/usr/bin/systemctl") === true) { platform = "systemd"; } if (fs.existsSync("/etc/redhat-release") === true) { platform = "centos"; } else if (fs.existsSync("/etc/issue") === true) { const issue = fs.readFileSync("/etc/issue", { encoding: "utf-8" }); if (/Ubuntu/.test(issue) === true) { platform = "ubuntu"; } } child_process.execSync(`pm2 startup ${platform}`, { stdio: [ null, process.stdout, process.stderr ] }); child_process.execSync("pm2 start processes.json", { stdio: [ null, process.stdout, process.stderr ] }); child_process.execSync("pm2 save", { stdio: [ null, process.stdout, process.stderr ] }); } else if (process.platform === "win32") { const configDir = path.join(process.env.USERPROFILE, ".Mirakurun"); const dataDir = path.join(process.env.LOCALAPPDATA, "Mirakurun"); if (fs.existsSync(configDir) === false) { fs.mkdirSync(configDir); } if (fs.existsSync(dataDir) === false) { fs.mkdirSync(dataDir); } const serverConfigPath = path.join(configDir, "server.yml"); const tunersConfigPath = path.join(configDir, "tuners.yml"); const channelsConfigPath = path.join(configDir, "channels.yml"); if (fs.existsSync(serverConfigPath) === false) { copyFileSync("config\\server.win32.yml", serverConfigPath); } if (fs.existsSync(tunersConfigPath) === false) { copyFileSync("config\\tuners.win32.yml", tunersConfigPath); } if (fs.existsSync(channelsConfigPath) === false) { copyFileSync("config\\channels.win32.yml", channelsConfigPath); } // winser const stdoutLogPath = path.join(dataDir, "stdout"); const stderrLogPath = path.join(dataDir, "stderr"); child_process.execFileSync( "winser.cmd", [ "-i", "-a", "--startuptype", "delayed", "--startcmd", `node.exe bin\\init.win32.js`, "--set", "AppPriority ABOVE_NORMAL_PRIORITY_CLASS", "--set", "Type SERVICE_WIN32_OWN_PROCESS", "--set", `AppStdout ${ stdoutLogPath }`, "--set", `AppStderr ${ stderrLogPath }`, "--env", `LOG_STDOUT=${ stdoutLogPath }`, "--env", `LOG_STDERR=${ stderrLogPath }`, "--env", `USERPROFILE=${ process.env.USERPROFILE }`, "--env", `LOCALAPPDATA=${ process.env.LOCALAPPDATA }`, "--env", "USING_WINSER=1" ], { stdio: [ null, process.stdout, process.stderr ] } ); } function copyFileSync(src, dest) { fs.writeFileSync(dest, fs.readFileSync(src)); }
bin/postinstall.js
/* Copyright 2016 Yuki KAN 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. */ "use strict"; if (process.env["npm_config_global"] !== "true") { process.exit(0); } const fs = require("fs"); const path = require("path"); const child_process = require("child_process"); // init if (process.platform === "linux" || process.platform === "darwin") { if (process.getuid() !== 0) { process.exit(0); } child_process.execSync("mkdir -vp /usr/local/etc/mirakurun"); child_process.execSync("mkdir -vp /usr/local/var/log"); child_process.execSync("mkdir -vp /usr/local/var/run"); child_process.execSync("mkdir -vp /usr/local/var/db/mirakurun"); child_process.execSync("cp -vn config/server.yml /usr/local/etc/mirakurun/server.yml"); child_process.execSync("cp -vn config/tuners.yml /usr/local/etc/mirakurun/tuners.yml"); child_process.execSync("cp -vn config/channels.yml /usr/local/etc/mirakurun/channels.yml"); // pm2 child_process.execSync("pm2 start processes.json", { stdio: [ null, process.stdout, process.stderr ] }); let platform = ""; if (fs.existsSync("/usr/bin/systemctl") === true) { platform = "systemd"; } if (fs.existsSync("/etc/redhat-release") === true) { platform = "centos"; } else if (fs.existsSync("/etc/issue") === true) { const issue = fs.readFileSync("/etc/issue", { encoding: "utf-8" }); if (/Ubuntu/.test(issue) === true) { platform = "ubuntu"; } } child_process.execSync(`pm2 startup ${platform}`, { stdio: [ null, process.stdout, process.stderr ] }); child_process.execSync("pm2 save", { stdio: [ null, process.stdout, process.stderr ] }); } else if (process.platform === "win32") { const configDir = path.join(process.env.USERPROFILE, ".Mirakurun"); const dataDir = path.join(process.env.LOCALAPPDATA, "Mirakurun"); if (fs.existsSync(configDir) === false) { fs.mkdirSync(configDir); } if (fs.existsSync(dataDir) === false) { fs.mkdirSync(dataDir); } const serverConfigPath = path.join(configDir, "server.yml"); const tunersConfigPath = path.join(configDir, "tuners.yml"); const channelsConfigPath = path.join(configDir, "channels.yml"); if (fs.existsSync(serverConfigPath) === false) { copyFileSync("config\\server.win32.yml", serverConfigPath); } if (fs.existsSync(tunersConfigPath) === false) { copyFileSync("config\\tuners.win32.yml", tunersConfigPath); } if (fs.existsSync(channelsConfigPath) === false) { copyFileSync("config\\channels.win32.yml", channelsConfigPath); } // winser const stdoutLogPath = path.join(dataDir, "stdout"); const stderrLogPath = path.join(dataDir, "stderr"); child_process.execFileSync( "winser.cmd", [ "-i", "-a", "--startuptype", "delayed", "--startcmd", `node.exe bin\\init.win32.js`, "--set", "AppPriority ABOVE_NORMAL_PRIORITY_CLASS", "--set", "Type SERVICE_WIN32_OWN_PROCESS", "--set", `AppStdout ${ stdoutLogPath }`, "--set", `AppStderr ${ stderrLogPath }`, "--env", `LOG_STDOUT=${ stdoutLogPath }`, "--env", `LOG_STDERR=${ stderrLogPath }`, "--env", `USERPROFILE=${ process.env.USERPROFILE }`, "--env", `LOCALAPPDATA=${ process.env.LOCALAPPDATA }`, "--env", "USING_WINSER=1" ], { stdio: [ null, process.stdout, process.stderr ] } ); } function copyFileSync(src, dest) { fs.writeFileSync(dest, fs.readFileSync(src)); }
fix pm2 command sequence (#6)
bin/postinstall.js
fix pm2 command sequence (#6)
<ide><path>in/postinstall.js <ide> <ide> // pm2 <ide> <del> child_process.execSync("pm2 start processes.json", { <del> stdio: [ <del> null, <del> process.stdout, <del> process.stderr <del> ] <del> }); <del> <ide> let platform = ""; <ide> <ide> if (fs.existsSync("/usr/bin/systemctl") === true) { <ide> } <ide> <ide> child_process.execSync(`pm2 startup ${platform}`, { <add> stdio: [ <add> null, <add> process.stdout, <add> process.stderr <add> ] <add> }); <add> <add> child_process.execSync("pm2 start processes.json", { <ide> stdio: [ <ide> null, <ide> process.stdout,
JavaScript
apache-2.0
88ec725703554d915d8b2222e4813f81e61610e6
0
d00rman/restbase,Pchelolo/restbase,wikimedia/restbase,milimetric/restbase,cscott/restbase,wikimedia/mediawiki-services-restbase,d00rman/restbase,cscott/restbase,wikimedia/restbase,Pchelolo/restbase,milimetric/restbase,wikimedia/mediawiki-services-restbase
'use strict'; const P = require('bluebird'); const HyperSwitch = require('hyperswitch'); const mwUtil = require('../lib/mwUtil'); const HTTPError = HyperSwitch.HTTPError; const spec = HyperSwitch.utils.loadSpec(`${__dirname}/parsoid.yaml`); const OPERATIONS = [ 'getHtml', 'getDataParsoid', 'getLintErrors', 'transformHtmlToHtml', 'transformHtmlToWikitext', 'transformWikitextToHtml', 'transformWikitextToLint', 'transformChangesToWikitext' ]; const invert = (v) => v === 'js' ? 'php' : 'js'; class ParsoidProxy { constructor(opts = {}) { const modOpts = this._initOpts(opts); const jsOpts = Object.assign({}, modOpts); const phpOpts = Object.assign({}, modOpts); delete jsOpts.php_host; phpOpts.host = phpOpts.php_host; delete phpOpts.php_host; this._initMods(jsOpts, phpOpts); } _initOpts(opts) { const retOpts = Object.assign({}, opts); retOpts.host = retOpts.host || retOpts.parsoidHost; if (!retOpts.host && !retOpts.php_host) { throw new Error('Parsoid proxy: no host option specified!'); } this.options = retOpts.proxy || {}; // possible values are 'js' and 'php' this.default_variant = this.options.default_variant || 'js'; if (!['js', 'php'].includes(this.default_variant)) { throw new Error('Parsoid proxy: valid variants are js and php!'); } // possible values are 'single', 'mirror' and 'split' this.mode = this.options.mode || 'single'; if (!['single', 'mirror', 'split'].includes(this.mode)) { throw new Error('Parsoid proxy: valid modes are single, mirror and split!'); } this.percentage = parseFloat(this.options.percentage || 0); if (isNaN(this.percentage) || this.percentage < 0 || this.percentage > 100) { throw new Error('Parsoid proxy: percentage must a number between 0 and 100!'); } if (this.percentage === 0 && this.mode === 'mirror') { // a special case of mirror mode with 0% is in fact the single mode this.mode = 'single'; } this.splitRegex = mwUtil.constructRegex(this.options.pattern); if (!this.splitRegex && this.mode === 'split') { // split mode with no pattern is single mode this.mode = 'single'; this.splitRegex = /^$/; } else if (this.mode !== 'split') { this.splitRegex = /^$/; } if (this.mode === 'split') { this.percentage = 100; } this.resources = []; delete retOpts.parsoidHost; delete retOpts.proxy; return retOpts; } _initMods(jsOpts, phpOpts) { if (!phpOpts.host) { if (this.mode !== 'single') { // php_host was not provided but the config expects // both modules to be functional, so error out throw new Error('Parsoid proxy: expected both host and php_host options!'); } if (this.default_variant === 'php') { phpOpts.host = jsOpts.host; delete jsOpts.host; } } if (this.mode === 'mirror') { if (this.default_variant === 'php') { throw new Error('Parsoid proxy: when mirroring, only js can be the default variant!'); } // js is the default, so don't let php issue dependency update events phpOpts.skip_updates = true; } this.mods = { js: this._addMod('js', jsOpts), php: this._addMod('php', phpOpts) }; } _backendNotSupported() { throw new HTTPError({ status: 400, body: { type: 'bad_request', description: 'Parsoid variant not configured!' } }); } _addMod(variant, opts) { if (opts.host) { const mod = require(`./parsoid-${variant}.js`)(opts); // we are interested only in the operations and resources this.resources = this.resources.concat(mod.resources); return mod.operations; } // return operations that error out if no host is specified const ret = {}; OPERATIONS.forEach((o) => { ret[o] = this._backendNotSupported; }); return ret; } _getStickyVariant(hyper, req) { let variant = hyper._rootReq.headers['x-parsoid-variant'] || req.headers['x-parsoid-variant']; if (!variant && hyper._rootReq.headers.cookie) { const match = /parsoid_variant=([^;]+)/i.exec(hyper._rootReq.headers.cookie); if (match) { variant = match[1]; } } if (!variant) { return undefined; } variant = variant.toLowerCase(); if (!['js', 'php'].includes(variant)) { throw new HTTPError({ status: 400, body: { type: 'bad_request', description: `Parsoid variant ${variant} not configured!` } }); } return variant; } _req(variant, operation, hyper, req, setHdr = true, sticky = false) { if (setHdr) { req.headers = req.headers || {}; req.headers['x-parsoid-variant'] = variant; } return this.mods[variant][operation](hyper, req) .then((res) => { res.headers = res.headers || {}; res.headers['x-parsoid-variant'] = variant; return P.resolve(res); }).catch({ status: 404 }, { status: 421 }, (e) => { // if we actually get a 421, we might be in trouble, so log it if (e.status === 421) { hyper.logger.log('warn/parsoidproxy/421', e); } // if we are in split mode, provide a fallback for transforms except lint if (!sticky && this.mode === 'split' && /transform/.test(operation) && !/Lint/.test(operation)) { if (setHdr) { req.headers['x-parsoid-variant'] = invert(variant); } return this.mods[invert(variant)][operation](hyper, req) .then((res) => { res.headers = res.headers || {}; res.headers['x-parsoid-variant'] = invert(variant); return P.resolve(res); }); } throw e; }); } doRequest(operation, hyper, req) { // TEMP TEMP TEMP // all html2html requests go to JS and are mirrored to PHP if (operation === 'transformHtmlToHtml') { if (Math.round(Math.random() * 100) <= 6.5) { this._req('php', operation, hyper, req, false, true) .catch((e) => hyper.logger.log('info/parsoidproxy/html2html', e)); } return this._req('js', operation, hyper, req, false, true); } // END TEMP let variant = this._getStickyVariant(hyper, req); // TEMP: Do not honour the header or cookie for now /* if (variant) { // the variant has been set explicitly by the client, honour it return this._req(variant, operation, hyper, req, true, true); } */ // END TEMP // we can safely check simply where to direct the request // using splitRegex because it won't match anything for any // mode other than split if (this.splitRegex.test(req.params.domain)) { variant = invert(this.default_variant); } else { variant = this.default_variant; } // mirror mode works only for getFormat, since for mirroring // tranforms we would need to be sure we have the php output // stashed // also, if we are in split mode, then we must pretend we are // also in 100% mirror mode since we want to keep both // variants in storage fresh /* Mirroring all the traffic causes too much load to withstand if (this.mode !== 'single' && !/transform/.test(operation)) { if (Math.round(Math.random() * 100) <= this.percentage) { // clone the request and its headers const mReq = { method: req.method, uri: req.uri, headers: Object.assign({}, req.headers), query: req.query, body: req.body, params: req.params }; // issue an async request to the second variant and // don't wait for the return value this._req(invert(variant), operation, hyper, mReq, false) .catch((e) => hyper.logger.log(`info/parsoidproxy/${invert(variant)}`, e)); } }*/ return this._req(variant, operation, hyper, req); } getOperations() { const ret = {}; OPERATIONS.forEach((o) => { ret[o] = this.doRequest.bind(this, o); }); return ret; } } module.exports = (options = {}) => { const ps = new ParsoidProxy(options); return { spec, operations: ps.getOperations(), resources: ps.resources }; };
sys/parsoid.js
'use strict'; const P = require('bluebird'); const HyperSwitch = require('hyperswitch'); const mwUtil = require('../lib/mwUtil'); const HTTPError = HyperSwitch.HTTPError; const spec = HyperSwitch.utils.loadSpec(`${__dirname}/parsoid.yaml`); const OPERATIONS = [ 'getHtml', 'getDataParsoid', 'getLintErrors', 'transformHtmlToHtml', 'transformHtmlToWikitext', 'transformWikitextToHtml', 'transformWikitextToLint', 'transformChangesToWikitext' ]; const invert = (v) => v === 'js' ? 'php' : 'js'; class ParsoidProxy { constructor(opts = {}) { const modOpts = this._initOpts(opts); const jsOpts = Object.assign({}, modOpts); const phpOpts = Object.assign({}, modOpts); delete jsOpts.php_host; phpOpts.host = phpOpts.php_host; delete phpOpts.php_host; this._initMods(jsOpts, phpOpts); } _initOpts(opts) { const retOpts = Object.assign({}, opts); retOpts.host = retOpts.host || retOpts.parsoidHost; if (!retOpts.host && !retOpts.php_host) { throw new Error('Parsoid proxy: no host option specified!'); } this.options = retOpts.proxy || {}; // possible values are 'js' and 'php' this.default_variant = this.options.default_variant || 'js'; if (!['js', 'php'].includes(this.default_variant)) { throw new Error('Parsoid proxy: valid variants are js and php!'); } // possible values are 'single', 'mirror' and 'split' this.mode = this.options.mode || 'single'; if (!['single', 'mirror', 'split'].includes(this.mode)) { throw new Error('Parsoid proxy: valid modes are single, mirror and split!'); } this.percentage = parseFloat(this.options.percentage || 0); if (isNaN(this.percentage) || this.percentage < 0 || this.percentage > 100) { throw new Error('Parsoid proxy: percentage must a number between 0 and 100!'); } if (this.percentage === 0 && this.mode === 'mirror') { // a special case of mirror mode with 0% is in fact the single mode this.mode = 'single'; } this.splitRegex = mwUtil.constructRegex(this.options.pattern); if (!this.splitRegex && this.mode === 'split') { // split mode with no pattern is single mode this.mode = 'single'; this.splitRegex = /^$/; } else if (this.mode !== 'split') { this.splitRegex = /^$/; } if (this.mode === 'split') { this.percentage = 100; } this.resources = []; delete retOpts.parsoidHost; delete retOpts.proxy; return retOpts; } _initMods(jsOpts, phpOpts) { if (!phpOpts.host) { if (this.mode !== 'single') { // php_host was not provided but the config expects // both modules to be functional, so error out throw new Error('Parsoid proxy: expected both host and php_host options!'); } if (this.default_variant === 'php') { phpOpts.host = jsOpts.host; delete jsOpts.host; } } if (this.mode === 'mirror') { if (this.default_variant === 'php') { throw new Error('Parsoid proxy: when mirroring, only js can be the default variant!'); } // js is the default, so don't let php issue dependency update events phpOpts.skip_updates = true; } this.mods = { js: this._addMod('js', jsOpts), php: this._addMod('php', phpOpts) }; } _backendNotSupported() { throw new HTTPError({ status: 400, body: { type: 'bad_request', description: 'Parsoid variant not configured!' } }); } _addMod(variant, opts) { if (opts.host) { const mod = require(`./parsoid-${variant}.js`)(opts); // we are interested only in the operations and resources this.resources = this.resources.concat(mod.resources); return mod.operations; } // return operations that error out if no host is specified const ret = {}; OPERATIONS.forEach((o) => { ret[o] = this._backendNotSupported; }); return ret; } _getStickyVariant(hyper, req) { let variant = hyper._rootReq.headers['x-parsoid-variant'] || req.headers['x-parsoid-variant']; if (!variant && hyper._rootReq.headers.cookie) { const match = /parsoid_variant=([^;]+)/i.exec(hyper._rootReq.headers.cookie); if (match) { variant = match[1]; } } if (!variant) { return undefined; } variant = variant.toLowerCase(); if (!['js', 'php'].includes(variant)) { throw new HTTPError({ status: 400, body: { type: 'bad_request', description: `Parsoid variant ${variant} not configured!` } }); } return variant; } _req(variant, operation, hyper, req, setHdr = true, sticky = false) { if (setHdr) { req.headers = req.headers || {}; req.headers['x-parsoid-variant'] = variant; } return this.mods[variant][operation](hyper, req) .then((res) => { res.headers = res.headers || {}; res.headers['x-parsoid-variant'] = variant; return P.resolve(res); }).catch({ status: 404 }, { status: 421 }, (e) => { // if we actually get a 421, we might be in trouble, so log it if (e.status === 421) { hyper.logger.log('warn/parsoidproxy/421', e); } // if we are in split mode, provide a fallback for transforms except lint if (!sticky && this.mode === 'split' && /transform/.test(operation) && !/Lint/.test(operation)) { if (setHdr) { req.headers['x-parsoid-variant'] = invert(variant); } return this.mods[invert(variant)][operation](hyper, req) .then((res) => { res.headers = res.headers || {}; res.headers['x-parsoid-variant'] = invert(variant); return P.resolve(res); }); } throw e; }); } doRequest(operation, hyper, req) { // TEMP TEMP TEMP // all linter requests go only to JS if (/Lint/.test(operation)) { return this._req('js', operation, hyper, req, false, true); } // all html2html requests go to JS and are mirrored to PHP if (operation === 'transformHtmlToHtml') { if (Math.round(Math.random() * 100) <= 6.5) { this._req('php', operation, hyper, req, false, true) .catch((e) => hyper.logger.log('info/parsoidproxy/html2html', e)); } return this._req('js', operation, hyper, req, false, true); } // END TEMP let variant = this._getStickyVariant(hyper, req); // TEMP: Do not honour the header or cookie for now /* if (variant) { // the variant has been set explicitly by the client, honour it return this._req(variant, operation, hyper, req, true, true); } */ // END TEMP // we can safely check simply where to direct the request // using splitRegex because it won't match anything for any // mode other than split if (this.splitRegex.test(req.params.domain)) { variant = invert(this.default_variant); } else { variant = this.default_variant; } // mirror mode works only for getFormat, since for mirroring // tranforms we would need to be sure we have the php output // stashed // also, if we are in split mode, then we must pretend we are // also in 100% mirror mode since we want to keep both // variants in storage fresh /* Mirroring all the traffic causes too much load to withstand if (this.mode !== 'single' && !/transform/.test(operation)) { if (Math.round(Math.random() * 100) <= this.percentage) { // clone the request and its headers const mReq = { method: req.method, uri: req.uri, headers: Object.assign({}, req.headers), query: req.query, body: req.body, params: req.params }; // issue an async request to the second variant and // don't wait for the return value this._req(invert(variant), operation, hyper, mReq, false) .catch((e) => hyper.logger.log(`info/parsoidproxy/${invert(variant)}`, e)); } }*/ return this._req(variant, operation, hyper, req); } getOperations() { const ret = {}; OPERATIONS.forEach((o) => { ret[o] = this.doRequest.bind(this, o); }); return ret; } } module.exports = (options = {}) => { const ps = new ParsoidProxy(options); return { spec, operations: ps.getOperations(), resources: ps.resources }; };
Send lint request to Parsoid/PHP
sys/parsoid.js
Send lint request to Parsoid/PHP
<ide><path>ys/parsoid.js <ide> <ide> doRequest(operation, hyper, req) { <ide> // TEMP TEMP TEMP <del> // all linter requests go only to JS <del> if (/Lint/.test(operation)) { <del> return this._req('js', operation, hyper, req, false, true); <del> } <ide> // all html2html requests go to JS and are mirrored to PHP <ide> if (operation === 'transformHtmlToHtml') { <ide> if (Math.round(Math.random() * 100) <= 6.5) {
Java
agpl-3.0
5f43d4b71c238b5c0c46c2408d962174b032bfb7
0
roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,aihua/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms
// // This file is part of the OpenNMS(R) Application. // // OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc. All rights reserved. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // code that was published under the GNU General Public License. Copyrights for modified // and included code are below. // // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // // Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.opennms.com/ // package org.opennms.web.controller; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.opennms.web.svclayer.catstatus.model.StatusSection; import org.opennms.web.svclayer.catstatus.support.DefaultCategoryStatusService; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; /** * * @author fastjay * */ public class CategoryStatusController extends AbstractController { DefaultCategoryStatusService m_categorystatusservice; Collection <StatusSection>statusSections; @Override protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { statusSections = m_categorystatusservice.getCategoriesStatus(); ModelAndView modelAndView = new ModelAndView("displayCategoryStatus","statusTree",statusSections); return modelAndView; } public void setCategoryStatusService(DefaultCategoryStatusService categoryStatusService){ m_categorystatusservice = categoryStatusService; } }
opennms-webapp/src/main/java/org/opennms/web/controller/CategoryStatusController.java
package org.opennms.web.controller; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.opennms.web.svclayer.catstatus.model.StatusSection; import org.opennms.web.svclayer.catstatus.support.DefaultCategoryStatusService; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class CategoryStatusController extends AbstractController { DefaultCategoryStatusService m_categorystatusservice; Collection <StatusSection>statusSections; @Override protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { statusSections = m_categorystatusservice.getCategoriesStatus(); ModelAndView modelAndView = new ModelAndView("displayCategoryStatus","statusTree",statusSections); return modelAndView; } public void setCategoryStatusService(DefaultCategoryStatusService categoryStatusService){ m_categorystatusservice = categoryStatusService; } }
Required GPL info for release.
opennms-webapp/src/main/java/org/opennms/web/controller/CategoryStatusController.java
Required GPL info for release.
<ide><path>pennms-webapp/src/main/java/org/opennms/web/controller/CategoryStatusController.java <add>// <add>// This file is part of the OpenNMS(R) Application. <add>// <add>// OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc. All rights reserved. <add>// OpenNMS(R) is a derivative work, containing both original code, included code and modified <add>// code that was published under the GNU General Public License. Copyrights for modified <add>// and included code are below. <add>// <add>// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. <add>// <add>// Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved. <add>// <add>// This program is free software; you can redistribute it and/or modify <add>// it under the terms of the GNU General Public License as published by <add>// the Free Software Foundation; either version 2 of the License, or <add>// (at your option) any later version. <add>// <add>// This program is distributed in the hope that it will be useful, <add>// but WITHOUT ANY WARRANTY; without even the implied warranty of <add>// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add>// GNU General Public License for more details. <add>// <add>// You should have received a copy of the GNU General Public License <add>// along with this program; if not, write to the Free Software <add>// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. <add>// <add>// For more information contact: <add>// OpenNMS Licensing <[email protected]> <add>// http://www.opennms.org/ <add>// http://www.opennms.com/ <add>// <add> <ide> package org.opennms.web.controller; <ide> <ide> import java.util.Collection; <ide> import org.springframework.web.servlet.ModelAndView; <ide> import org.springframework.web.servlet.mvc.AbstractController; <ide> <add>/** <add> * <add> * @author fastjay <add> * <add> */ <ide> public class CategoryStatusController extends AbstractController { <ide> <ide> DefaultCategoryStatusService m_categorystatusservice;
Java
agpl-3.0
badb103ea47f5d1cbe8e0cf0ba1a5a92758bd3d3
0
barspi/jPOS-EE,jrfinc/jPOS-EE,barspi/jPOS-EE,jpos/jPOS-EE,jpos/jPOS-EE,jpos/jPOS-EE,barspi/jPOS-EE,jrfinc/jPOS-EE,jrfinc/jPOS-EE
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2016 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.ee; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.hibernate.*; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.Configuration; import org.hibernate.engine.spi.CollectionKey; import org.hibernate.engine.spi.EntityKey; import org.hibernate.internal.util.ReflectHelper; import org.hibernate.proxy.HibernateProxy; import org.hibernate.resource.transaction.spi.TransactionStatus; import org.hibernate.stat.SessionStatistics; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; import org.jpos.core.ConfigurationException; import org.jpos.ee.support.ModuleUtils; import org.jpos.util.Log; import org.jpos.util.LogEvent; import org.jpos.util.Logger; import java.io.Closeable; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.*; /** * @author Alejandro P. Revilla * @version $Revision: 1.5 $ $Date: 2004/12/09 00:50:14 $ * <p> * DB encapsulate some housekeeping specific * to Hibernate O/R mapping engine */ @SuppressWarnings({"UnusedDeclaration"}) public class DB implements Closeable { Session session; Log log; String configModifier; private static volatile SessionFactory sessionFactory = null; private static String propFile; private static final String MODULES_CONFIG_PATH = "META-INF/org/jpos/ee/modules/"; /** * Creates DB Object using default Hibernate instance */ public DB() { super(); } /** * Creates DB Object using a config <i>modifier</i>. * * The <i>configModifier</i> can take a number of different forms used to locate the <code>cfg/db.properties</code> file. * * <ul> * * <li>a filename prefix, i.e.: "mysql" used as modifier would pick the configuration from * <code>cfg/mysql-db.properties</code> instead of the default <code>cfg/db.properties</code> </li> * * <li>if a colon and a second modifier is present (e.g.: "mysql:v1"), the metadata is picked from * <code>META-INF/org/jpos/ee/modules/v1-*</code> instead of just * <code>META-INF/org/jpos/ee/modules/</code> </li> * * <li>finally, if the modifier ends with <code>.hbm.xml</code> (case insensitive), then all configuration * is picked from that config file.</li> * </ul> * * @param configModifier modifier */ public DB (String configModifier) { super(); this.configModifier = configModifier; } /** * Creates DB Object using default Hibernate instance * * @param log Log object */ public DB(Log log) { super(); setLog(log); } /** * Creates DB Object using default Hibernate instance * * @param log Log object * @param configModifier modifier */ public DB(Log log, String configModifier) { this(configModifier); setLog(log); } /** * @return Hibernate's session factory */ public SessionFactory getSessionFactory() { if (sessionFactory == null) { synchronized (DB.class) { if (sessionFactory == null) { try { sessionFactory = newSessionFactory(); } catch (IOException | ConfigurationException | DocumentException e) { throw new RuntimeException("Could not configure session factory", e); } } } } return sessionFactory; } public static synchronized void invalidateSessionFactory() { sessionFactory = null; } private SessionFactory newSessionFactory() throws IOException, ConfigurationException, DocumentException { return getMetadata().buildSessionFactory(); } private void configureProperties(Configuration cfg) throws IOException { String propFile = System.getProperty("DB_PROPERTIES", "cfg/db.properties"); Properties dbProps = loadProperties(propFile); if (dbProps != null) { cfg.addProperties(dbProps); } } private void configureMappings(Configuration cfg) throws ConfigurationException, IOException { try { List<String> moduleConfigs = ModuleUtils.getModuleEntries("META-INF/org/jpos/ee/modules/"); for (String moduleConfig : moduleConfigs) { addMappings(cfg, moduleConfig); } } catch (DocumentException e) { throw new ConfigurationException("Could not parse mappings document", e); } } private void addMappings(Configuration cfg, String moduleConfig) throws ConfigurationException, DocumentException { Element module = readMappingElements(moduleConfig); if (module != null) { for (Iterator l = module.elementIterator("mapping"); l.hasNext(); ) { Element mapping = (Element) l.next(); parseMapping(cfg, mapping, moduleConfig); } } } private void parseMapping(Configuration cfg, Element mapping, String moduleName) throws ConfigurationException { final String resource = mapping.attributeValue("resource"); final String clazz = mapping.attributeValue("class"); if (resource != null) { cfg.addResource(resource); } else if (clazz != null) { try { cfg.addAnnotatedClass(ReflectHelper.classForName(clazz)); } catch (ClassNotFoundException e) { throw new ConfigurationException("Class " + clazz + " specified in mapping for module " + moduleName + " cannot be found"); } } else { throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName); } } private Element readMappingElements(String moduleConfig) throws DocumentException { SAXReader reader = new SAXReader(); final URL url = getClass().getClassLoader().getResource(moduleConfig); assert url != null; final Document doc = reader.read(url); return doc.getRootElement().element("mappings"); } private Properties loadProperties(String filename) throws IOException { Properties props = new Properties(); final String s = filename.replaceAll("/", "\\" + File.separator); final File f = new File(s); if (f.exists()) { props.load(new FileReader(f)); } return props; } /** * Creates database schema * * @param outputFile optional output file (may be null) * @param create true to actually issue the create statements */ public void createSchema(String outputFile, boolean create) throws HibernateException, DocumentException { try { // SchemaExport export = new SchemaExport(getMetadata()); SchemaExport export = new SchemaExport(); List<TargetType> targetTypes=new ArrayList<>(); if (outputFile != null) { if(outputFile.trim().equals("-")) targetTypes.add(TargetType.STDOUT); else { export.setOutputFile(outputFile); export.setDelimiter(";"); targetTypes.add(TargetType.SCRIPT); } } if (create) targetTypes.add(TargetType.DATABASE); if(targetTypes.size()>0) export.create(EnumSet.copyOf(targetTypes), getMetadata()); } catch (IOException | ConfigurationException e) { throw new HibernateException("Could not create schema", e); } } /** * open a new HibernateSession if none exists * * @return HibernateSession associated with this DB object * @throws HibernateException */ public synchronized Session open() throws HibernateException { if (session == null) { session = getSessionFactory().openSession(); } return session; } /** * close hibernate session * * @throws HibernateException */ public synchronized void close() throws HibernateException { if (session != null) { session.close(); session = null; } } /** * @return session hibernate Session */ public Session session() { return session; } /** * handy method used to avoid having to call db.session().save (xxx) * * @param obj to save */ public void save(Object obj) throws HibernateException { session.save(obj); } /** * handy method used to avoid having to call db.session().saveOrUpdate (xxx) * * @param obj to save or update */ public void saveOrUpdate(Object obj) throws HibernateException { session.saveOrUpdate(obj); } public void delete(Object obj) { session.delete(obj); } /** * @return newly created Transaction * @throws HibernateException */ public synchronized Transaction beginTransaction() throws HibernateException { return session.beginTransaction(); } public synchronized void commit() { if (session() != null) { Transaction tx = session().getTransaction(); if (tx != null && tx.getStatus().isOneOf(TransactionStatus.ACTIVE)) { tx.commit(); } } } public synchronized void rollback() { if (session() != null) { Transaction tx = session().getTransaction(); if (tx != null && tx.getStatus().canRollback()) { tx.rollback(); } } } /** * @param timeout in seconds * @return newly created Transaction * @throws HibernateException */ public synchronized Transaction beginTransaction(int timeout) throws HibernateException { Transaction tx = session.getTransaction(); if (timeout > 0) tx.setTimeout(timeout); tx.begin(); return tx; } public synchronized Log getLog() { if (log == null) { log = Log.getLog("Q2", "DB"); // Q2 standard Logger } return log; } public synchronized void setLog(Log log) { this.log = log; } public static Object exec(DBAction action) throws Exception { try (DB db = new DB()) { db.open(); return action.exec(db); } } public static Object execWithTransaction(DBAction action) throws Exception { try (DB db = new DB()) { db.open(); db.beginTransaction(); Object obj = action.exec(db); db.commit(); return obj; } } @SuppressWarnings("unchecked") public static <T> T unwrap (T proxy) { Hibernate.getClass(proxy); Hibernate.initialize(proxy); return (proxy instanceof HibernateProxy) ? (T) ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation() : proxy; } @SuppressWarnings({"unchecked"}) public void printStats() { if (getLog() != null) { LogEvent info = getLog().createInfo(); if (session != null) { info.addMessage("==== STATISTICS ===="); SessionStatistics statistics = session().getStatistics(); info.addMessage("==== ENTITIES ===="); Set<EntityKey> entityKeys = statistics.getEntityKeys(); for (EntityKey ek : entityKeys) { info.addMessage(String.format("[%s] %s", ek.getIdentifier(), ek.getEntityName())); } info.addMessage("==== COLLECTIONS ===="); Set<CollectionKey> collectionKeys = statistics.getCollectionKeys(); for (CollectionKey ck : collectionKeys) { info.addMessage(String.format("[%s] %s", ck.getKey(), ck.getRole())); } info.addMessage("====================="); } else { info.addMessage("Session is not open"); } Logger.log(info); } } private MetadataImplementor getMetadata() throws IOException, ConfigurationException, DocumentException { StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(); String propFile; String dbPropertiesPrefix = ""; String metadataPrefix = ""; if (configModifier != null) { String[] ss = configModifier.split(":"); if (ss.length > 0) dbPropertiesPrefix = ss[0] + "-"; if (ss.length > 1) metadataPrefix = ss[1] + "-"; } String hibCfg = System.getProperty("HIBERNATE_CFG","/" + dbPropertiesPrefix + "hibernate.cfg.xml"); if (getClass().getClassLoader().getResource(hibCfg) == null) hibCfg = null; if (hibCfg == null) hibCfg = System.getProperty("HIBERNATE_CFG","/hibernate.cfg.xml"); ssrb.configure(hibCfg); propFile = System.getProperty(dbPropertiesPrefix + "DB_PROPERTIES", "cfg/" + dbPropertiesPrefix + "db.properties"); Properties dbProps = loadProperties(propFile); if (dbProps != null) { for (Map.Entry entry : dbProps.entrySet()) { ssrb.applySetting((String) entry.getKey(), entry.getValue()); } } MetadataSources mds = new MetadataSources(ssrb.build()); List<String> moduleConfigs = ModuleUtils.getModuleEntries(MODULES_CONFIG_PATH); for (String moduleConfig : moduleConfigs) { if (metadataPrefix.length() == 0 || moduleConfig.substring(MODULES_CONFIG_PATH.length()).startsWith(metadataPrefix)) { addMappings(mds, moduleConfig); } } return (MetadataImplementor) mds.buildMetadata(); } private void addMappings(MetadataSources mds, String moduleConfig) throws ConfigurationException, DocumentException { Element module = readMappingElements(moduleConfig); if (module != null) { for (Iterator l = module.elementIterator("mapping"); l.hasNext(); ) { Element mapping = (Element) l.next(); parseMapping(mds, mapping, moduleConfig); } } } private void parseMapping (MetadataSources mds, Element mapping, String moduleName) throws ConfigurationException { final String resource = mapping.attributeValue("resource"); final String clazz = mapping.attributeValue("class"); if (resource != null) mds.addResource(resource); else if (clazz != null) mds.addAnnotatedClassName(clazz); else throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName); } }
modules/dbsupport/src/main/java/org/jpos/ee/DB.java
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2016 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.ee; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.hibernate.*; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.Configuration; import org.hibernate.engine.spi.CollectionKey; import org.hibernate.engine.spi.EntityKey; import org.hibernate.internal.util.ReflectHelper; import org.hibernate.proxy.HibernateProxy; import org.hibernate.resource.transaction.spi.TransactionStatus; import org.hibernate.stat.SessionStatistics; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; import org.jpos.core.ConfigurationException; import org.jpos.ee.support.ModuleUtils; import org.jpos.util.Log; import org.jpos.util.LogEvent; import org.jpos.util.Logger; import java.io.Closeable; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.*; /** * @author Alejandro P. Revilla * @version $Revision: 1.5 $ $Date: 2004/12/09 00:50:14 $ * <p> * DB encapsulate some housekeeping specific * to Hibernate O/R mapping engine */ @SuppressWarnings({"UnusedDeclaration"}) public class DB implements Closeable { Session session; Log log; String configModifier; private static volatile SessionFactory sessionFactory = null; private static String propFile; private static final String MODULES_CONFIG_PATH = "META-INF/org/jpos/ee/modules/"; /** * Creates DB Object using default Hibernate instance */ public DB() { super(); } /** * Creates DB Object using a config <i>modifier</i>. * * The <i>configModifier</i> can take a number of different forms used to locate the <code>cfg/db.properties</code> file. * * <ul> * * <li>a filename prefix, i.e.: "mysql" used as modifier would pick the configuration from * <code>cfg/mysql-db.properties</code> instead of the default <code>cfg/db.properties</code> </li> * * <li>if a colon and a second modifier is present (e.g.: "mysql:v1"), the metadata is picked from * <code>META-INF/org/jpos/ee/modules/v1-*</code> instead of just * <code>META-INF/org/jpos/ee/modules/</code> </li> * * <li>finally, if the modifier ends with <code>.hbm.xml</code> (case insensitive), then all configuration * is picked from that config file.</li> * </ul> * * @param configModifier modifier */ public DB (String configModifier) { super(); this.configModifier = configModifier; } /** * Creates DB Object using default Hibernate instance * * @param log Log object */ public DB(Log log) { super(); setLog(log); } /** * Creates DB Object using default Hibernate instance * * @param log Log object * @param configModifier modifier */ public DB(Log log, String configModifier) { this(configModifier); setLog(log); } /** * @return Hibernate's session factory */ public SessionFactory getSessionFactory() { if (sessionFactory == null) { synchronized (DB.class) { if (sessionFactory == null) { try { sessionFactory = newSessionFactory(); } catch (IOException | ConfigurationException | DocumentException e) { throw new RuntimeException("Could not configure session factory", e); } } } } return sessionFactory; } public static synchronized void invalidateSessionFactory() { sessionFactory = null; } private SessionFactory newSessionFactory() throws IOException, ConfigurationException, DocumentException { return getMetadata().buildSessionFactory(); } private void configureProperties(Configuration cfg) throws IOException { String propFile = System.getProperty("DB_PROPERTIES", "cfg/db.properties"); Properties dbProps = loadProperties(propFile); if (dbProps != null) { cfg.addProperties(dbProps); } } private void configureMappings(Configuration cfg) throws ConfigurationException, IOException { try { List<String> moduleConfigs = ModuleUtils.getModuleEntries("META-INF/org/jpos/ee/modules/"); for (String moduleConfig : moduleConfigs) { addMappings(cfg, moduleConfig); } } catch (DocumentException e) { throw new ConfigurationException("Could not parse mappings document", e); } } private void addMappings(Configuration cfg, String moduleConfig) throws ConfigurationException, DocumentException { Element module = readMappingElements(moduleConfig); if (module != null) { for (Iterator l = module.elementIterator("mapping"); l.hasNext(); ) { Element mapping = (Element) l.next(); parseMapping(cfg, mapping, moduleConfig); } } } private void parseMapping(Configuration cfg, Element mapping, String moduleName) throws ConfigurationException { final String resource = mapping.attributeValue("resource"); final String clazz = mapping.attributeValue("class"); if (resource != null) { cfg.addResource(resource); } else if (clazz != null) { try { cfg.addAnnotatedClass(ReflectHelper.classForName(clazz)); } catch (ClassNotFoundException e) { throw new ConfigurationException("Class " + clazz + " specified in mapping for module " + moduleName + " cannot be found"); } } else { throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName); } } private Element readMappingElements(String moduleConfig) throws DocumentException { SAXReader reader = new SAXReader(); final URL url = getClass().getClassLoader().getResource(moduleConfig); assert url != null; final Document doc = reader.read(url); return doc.getRootElement().element("mappings"); } private Properties loadProperties(String filename) throws IOException { Properties props = new Properties(); final String s = filename.replaceAll("/", "\\" + File.separator); final File f = new File(s); if (f.exists()) { props.load(new FileReader(f)); } return props; } /** * Creates database schema * * @param outputFile optional output file (may be null) * @param create true to actually issue the create statements */ public void createSchema(String outputFile, boolean create) throws HibernateException, DocumentException { try { // SchemaExport export = new SchemaExport(getMetadata()); SchemaExport export = new SchemaExport(); List<TargetType> targetTypes=new ArrayList<>(); if (outputFile != null) { if(outputFile.trim().equals("-")) targetTypes.add(TargetType.STDOUT); else { export.setOutputFile(outputFile); export.setDelimiter(";"); targetTypes.add(TargetType.SCRIPT); } } if (create) targetTypes.add(TargetType.DATABASE); if(targetTypes.size()>0) export.create(EnumSet.copyOf(targetTypes), getMetadata()); } catch (IOException | ConfigurationException e) { throw new HibernateException("Could not create schema", e); } } /** * open a new HibernateSession if none exists * * @return HibernateSession associated with this DB object * @throws HibernateException */ public synchronized Session open() throws HibernateException { if (session == null) { session = getSessionFactory().openSession(); } return session; } /** * close hibernate session * * @throws HibernateException */ public synchronized void close() throws HibernateException { if (session != null) { session.close(); session = null; } } /** * @return session hibernate Session */ public Session session() { return session; } /** * handy method used to avoid having to call db.session().save (xxx) * * @param obj to save */ public void save(Object obj) throws HibernateException { session.save(obj); } /** * handy method used to avoid having to call db.session().saveOrUpdate (xxx) * * @param obj to save or update */ public void saveOrUpdate(Object obj) throws HibernateException { session.saveOrUpdate(obj); } public void delete(Object obj) { session.delete(obj); } /** * @return newly created Transaction * @throws HibernateException */ public synchronized Transaction beginTransaction() throws HibernateException { return session.beginTransaction(); } public synchronized void commit() { if (session() != null) { Transaction tx = session().getTransaction(); if (tx != null && tx.getStatus().isOneOf(TransactionStatus.ACTIVE)) { tx.commit(); } } } public synchronized void rollback() { if (session() != null) { Transaction tx = session().getTransaction(); if (tx != null && tx.getStatus().canRollback()) { tx.rollback(); } } } /** * @param timeout in seconds * @return newly created Transaction * @throws HibernateException */ public synchronized Transaction beginTransaction(int timeout) throws HibernateException { Transaction tx = session.beginTransaction(); if (timeout > 0) { tx.setTimeout(timeout); } return tx; } public synchronized Log getLog() { if (log == null) { log = Log.getLog("Q2", "DB"); // Q2 standard Logger } return log; } public synchronized void setLog(Log log) { this.log = log; } public static Object exec(DBAction action) throws Exception { try (DB db = new DB()) { db.open(); return action.exec(db); } } public static Object execWithTransaction(DBAction action) throws Exception { try (DB db = new DB()) { db.open(); db.beginTransaction(); Object obj = action.exec(db); db.commit(); return obj; } } @SuppressWarnings("unchecked") public static <T> T unwrap (T proxy) { Hibernate.getClass(proxy); Hibernate.initialize(proxy); return (proxy instanceof HibernateProxy) ? (T) ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation() : proxy; } @SuppressWarnings({"unchecked"}) public void printStats() { if (getLog() != null) { LogEvent info = getLog().createInfo(); if (session != null) { info.addMessage("==== STATISTICS ===="); SessionStatistics statistics = session().getStatistics(); info.addMessage("==== ENTITIES ===="); Set<EntityKey> entityKeys = statistics.getEntityKeys(); for (EntityKey ek : entityKeys) { info.addMessage(String.format("[%s] %s", ek.getIdentifier(), ek.getEntityName())); } info.addMessage("==== COLLECTIONS ===="); Set<CollectionKey> collectionKeys = statistics.getCollectionKeys(); for (CollectionKey ck : collectionKeys) { info.addMessage(String.format("[%s] %s", ck.getKey(), ck.getRole())); } info.addMessage("====================="); } else { info.addMessage("Session is not open"); } Logger.log(info); } } private MetadataImplementor getMetadata() throws IOException, ConfigurationException, DocumentException { StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(); String propFile; String dbPropertiesPrefix = ""; String metadataPrefix = ""; if (configModifier != null) { String[] ss = configModifier.split(":"); if (ss.length > 0) dbPropertiesPrefix = ss[0] + "-"; if (ss.length > 1) metadataPrefix = ss[1] + "-"; } String hibCfg = System.getProperty("HIBERNATE_CFG","/" + dbPropertiesPrefix + "hibernate.cfg.xml"); if (getClass().getClassLoader().getResource(hibCfg) == null) hibCfg = null; if (hibCfg == null) hibCfg = System.getProperty("HIBERNATE_CFG","/hibernate.cfg.xml"); ssrb.configure(hibCfg); propFile = System.getProperty(dbPropertiesPrefix + "DB_PROPERTIES", "cfg/" + dbPropertiesPrefix + "db.properties"); Properties dbProps = loadProperties(propFile); if (dbProps != null) { for (Map.Entry entry : dbProps.entrySet()) { ssrb.applySetting((String) entry.getKey(), entry.getValue()); } } MetadataSources mds = new MetadataSources(ssrb.build()); List<String> moduleConfigs = ModuleUtils.getModuleEntries(MODULES_CONFIG_PATH); for (String moduleConfig : moduleConfigs) { if (metadataPrefix.length() == 0 || moduleConfig.substring(MODULES_CONFIG_PATH.length()).startsWith(metadataPrefix)) { addMappings(mds, moduleConfig); } } return (MetadataImplementor) mds.buildMetadata(); } private void addMappings(MetadataSources mds, String moduleConfig) throws ConfigurationException, DocumentException { Element module = readMappingElements(moduleConfig); if (module != null) { for (Iterator l = module.elementIterator("mapping"); l.hasNext(); ) { Element mapping = (Element) l.next(); parseMapping(mds, mapping, moduleConfig); } } } private void parseMapping (MetadataSources mds, Element mapping, String moduleName) throws ConfigurationException { final String resource = mapping.attributeValue("resource"); final String clazz = mapping.attributeValue("class"); if (resource != null) mds.addResource(resource); else if (clazz != null) mds.addAnnotatedClassName(clazz); else throw new ConfigurationException("<mapping> element in configuration specifies no known attributes at module " + moduleName); } }
properly set timeout on beginTransaction Thank you Amiel for the catch!
modules/dbsupport/src/main/java/org/jpos/ee/DB.java
properly set timeout on beginTransaction
<ide><path>odules/dbsupport/src/main/java/org/jpos/ee/DB.java <ide> */ <ide> public synchronized Transaction beginTransaction(int timeout) throws HibernateException <ide> { <del> Transaction tx = session.beginTransaction(); <add> Transaction tx = session.getTransaction(); <ide> if (timeout > 0) <del> { <ide> tx.setTimeout(timeout); <del> } <add> tx.begin(); <ide> return tx; <ide> } <ide>
Java
mit
error: pathspec 'src/test/java/hu/unideb/inf/JCardGamesFX/klondike/KlondikeRulesTest.java' did not match any file(s) known to git
74dd0fd82f35adf59d909a6e7b65097b11148045
1
ZoltanDalmadi/JCardGamesFX
package hu.unideb.inf.JCardGamesFX.klondike; import hu.unideb.inf.JCardGamesFX.model.CardPile; import hu.unideb.inf.JCardGamesFX.model.FrenchCard; import hu.unideb.inf.JCardGamesFX.model.FrenchRank; import hu.unideb.inf.JCardGamesFX.model.FrenchSuit; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import static org.junit.Assert.*; public class KlondikeRulesTest { KlondikeRules klondikeRules; @Before public void setUp() throws Exception { klondikeRules = new KlondikeRules(); } @Test public void testParameterConstructor() { List<CardPile> testStandardPiles = new ArrayList<>(); List<CardPile> testFoundations = new ArrayList<>(); CardPile testWaste = new CardPile(); CardPile testStock = new CardPile(); KlondikeRules klondikeRules1 = new KlondikeRules( testStandardPiles, testFoundations, testWaste, testStock); assertEquals(testStandardPiles, klondikeRules1.getStandardPiles()); assertEquals(testFoundations, klondikeRules1.getFoundations()); assertEquals(testWaste, klondikeRules1.getWaste()); assertEquals(testStock, klondikeRules1.getStock()); } @Test public void testLookForPile() { List<CardPile> testStandardPiles = new ArrayList<>(); IntStream.range(0, 7).parallel() .forEach(i -> testStandardPiles.add(new CardPile())); List<CardPile> testFoundations = new ArrayList<>(); IntStream.range(0, 4).parallel() .forEach(i -> testFoundations.add(new CardPile())); CardPile testWaste = new CardPile(); CardPile testStock = new CardPile(); klondikeRules.setStandardPiles(testStandardPiles); klondikeRules.setFoundations(testFoundations); klondikeRules.setWaste(testWaste); klondikeRules.setStock(testStock); FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Four); testStandardPiles.get(3).addCard(card1); assertEquals(testStandardPiles.get(3), klondikeRules.lookForPile(card1)); FrenchCard card2 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Ace); testFoundations.get(1).addCard(card2); assertEquals(testFoundations.get(1), klondikeRules.lookForPile(card2)); FrenchCard card3 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Ten); testWaste.addCard(card3); assertEquals(testWaste, klondikeRules.lookForPile(card3)); FrenchCard card4 = new FrenchCard(false, FrenchSuit.Clubs, FrenchRank.King); testStock.addCard(card4); assertEquals(testStock, klondikeRules.lookForPile(card4)); } @Test public void testIsOppositeColorAndIsSameColor() { FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Jack); FrenchCard card2 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Ten); FrenchCard card3 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Six); FrenchCard card4 = new FrenchCard(false, FrenchSuit.Clubs, FrenchRank.Ace); FrenchCard card5 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Three); FrenchCard card6 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Nine); FrenchCard card7 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Queen); FrenchCard card8 = new FrenchCard(false, FrenchSuit.Clubs, FrenchRank.Two); assertTrue(klondikeRules.isOppositeColor(card1, card2)); assertTrue(klondikeRules.isOppositeColor(card1, card3)); assertFalse(klondikeRules.isOppositeColor(card1, card4)); assertFalse(klondikeRules.isOppositeColor(card2, card3)); assertTrue(klondikeRules.isOppositeColor(card2, card4)); assertTrue(klondikeRules.isOppositeColor(card3, card4)); assertTrue(klondikeRules.isSameSuit(card1, card5)); assertTrue(klondikeRules.isSameSuit(card2, card6)); assertTrue(klondikeRules.isSameSuit(card3, card7)); assertTrue(klondikeRules.isSameSuit(card4, card8)); assertFalse(klondikeRules.isSameSuit(card1, card2)); assertFalse(klondikeRules.isSameSuit(card1, card3)); assertFalse(klondikeRules.isSameSuit(card1, card4)); } @Test public void testIsSmallerByOne() { FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Ten); FrenchCard card2 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Jack); FrenchCard card3 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Six); assertTrue(klondikeRules.isSmallerByOne(card1, card2)); assertFalse(klondikeRules.isSmallerByOne(card1, card3)); } @Test public void testIsSmallerByOneAndOppositeColor() { FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Ten); FrenchCard card2 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Jack); FrenchCard card3 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Six); assertTrue(klondikeRules.isSmallerByOneAndOppositeColor(card1, card2)); assertFalse(klondikeRules.isSmallerByOneAndOppositeColor(card1, card3)); } @Test public void testIsSmallerByOneAndSameSuit() { FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Ten); FrenchCard card2 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Jack); FrenchCard card3 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Six); assertTrue(klondikeRules.isSmallerByOneAndSameSuit(card1, card2)); assertFalse(klondikeRules.isSmallerByOneAndSameSuit(card1, card3)); } }
src/test/java/hu/unideb/inf/JCardGamesFX/klondike/KlondikeRulesTest.java
Added Unit test for KlondikeRules class
src/test/java/hu/unideb/inf/JCardGamesFX/klondike/KlondikeRulesTest.java
Added Unit test for KlondikeRules class
<ide><path>rc/test/java/hu/unideb/inf/JCardGamesFX/klondike/KlondikeRulesTest.java <add>package hu.unideb.inf.JCardGamesFX.klondike; <add> <add>import hu.unideb.inf.JCardGamesFX.model.CardPile; <add>import hu.unideb.inf.JCardGamesFX.model.FrenchCard; <add>import hu.unideb.inf.JCardGamesFX.model.FrenchRank; <add>import hu.unideb.inf.JCardGamesFX.model.FrenchSuit; <add>import org.junit.Before; <add>import org.junit.Test; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add>import java.util.stream.IntStream; <add> <add>import static org.junit.Assert.*; <add> <add>public class KlondikeRulesTest { <add> <add> KlondikeRules klondikeRules; <add> <add> @Before <add> public void setUp() throws Exception { <add> klondikeRules = new KlondikeRules(); <add> } <add> <add> @Test <add> public void testParameterConstructor() { <add> List<CardPile> testStandardPiles = new ArrayList<>(); <add> List<CardPile> testFoundations = new ArrayList<>(); <add> CardPile testWaste = new CardPile(); <add> CardPile testStock = new CardPile(); <add> <add> KlondikeRules klondikeRules1 = new KlondikeRules( <add> testStandardPiles, testFoundations, testWaste, testStock); <add> <add> assertEquals(testStandardPiles, klondikeRules1.getStandardPiles()); <add> assertEquals(testFoundations, klondikeRules1.getFoundations()); <add> assertEquals(testWaste, klondikeRules1.getWaste()); <add> assertEquals(testStock, klondikeRules1.getStock()); <add> } <add> <add> @Test <add> public void testLookForPile() { <add> List<CardPile> testStandardPiles = new ArrayList<>(); <add> IntStream.range(0, 7).parallel() <add> .forEach(i -> testStandardPiles.add(new CardPile())); <add> <add> List<CardPile> testFoundations = new ArrayList<>(); <add> IntStream.range(0, 4).parallel() <add> .forEach(i -> testFoundations.add(new CardPile())); <add> <add> CardPile testWaste = new CardPile(); <add> CardPile testStock = new CardPile(); <add> <add> klondikeRules.setStandardPiles(testStandardPiles); <add> klondikeRules.setFoundations(testFoundations); <add> klondikeRules.setWaste(testWaste); <add> klondikeRules.setStock(testStock); <add> <add> FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Four); <add> testStandardPiles.get(3).addCard(card1); <add> assertEquals(testStandardPiles.get(3), klondikeRules.lookForPile(card1)); <add> <add> FrenchCard card2 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Ace); <add> testFoundations.get(1).addCard(card2); <add> assertEquals(testFoundations.get(1), klondikeRules.lookForPile(card2)); <add> <add> FrenchCard card3 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Ten); <add> testWaste.addCard(card3); <add> assertEquals(testWaste, klondikeRules.lookForPile(card3)); <add> <add> FrenchCard card4 = new FrenchCard(false, FrenchSuit.Clubs, FrenchRank.King); <add> testStock.addCard(card4); <add> assertEquals(testStock, klondikeRules.lookForPile(card4)); <add> } <add> <add> @Test <add> public void testIsOppositeColorAndIsSameColor() { <add> FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Jack); <add> FrenchCard card2 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Ten); <add> FrenchCard card3 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Six); <add> FrenchCard card4 = new FrenchCard(false, FrenchSuit.Clubs, FrenchRank.Ace); <add> <add> FrenchCard card5 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Three); <add> FrenchCard card6 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Nine); <add> FrenchCard card7 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Queen); <add> FrenchCard card8 = new FrenchCard(false, FrenchSuit.Clubs, FrenchRank.Two); <add> <add> assertTrue(klondikeRules.isOppositeColor(card1, card2)); <add> assertTrue(klondikeRules.isOppositeColor(card1, card3)); <add> assertFalse(klondikeRules.isOppositeColor(card1, card4)); <add> <add> assertFalse(klondikeRules.isOppositeColor(card2, card3)); <add> assertTrue(klondikeRules.isOppositeColor(card2, card4)); <add> <add> assertTrue(klondikeRules.isOppositeColor(card3, card4)); <add> <add> assertTrue(klondikeRules.isSameSuit(card1, card5)); <add> assertTrue(klondikeRules.isSameSuit(card2, card6)); <add> assertTrue(klondikeRules.isSameSuit(card3, card7)); <add> assertTrue(klondikeRules.isSameSuit(card4, card8)); <add> <add> assertFalse(klondikeRules.isSameSuit(card1, card2)); <add> assertFalse(klondikeRules.isSameSuit(card1, card3)); <add> assertFalse(klondikeRules.isSameSuit(card1, card4)); <add> } <add> <add> @Test <add> public void testIsSmallerByOne() { <add> FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Ten); <add> FrenchCard card2 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Jack); <add> FrenchCard card3 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Six); <add> <add> assertTrue(klondikeRules.isSmallerByOne(card1, card2)); <add> assertFalse(klondikeRules.isSmallerByOne(card1, card3)); <add> } <add> <add> @Test <add> public void testIsSmallerByOneAndOppositeColor() { <add> FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Ten); <add> FrenchCard card2 = new FrenchCard(false, FrenchSuit.Diamonds, FrenchRank.Jack); <add> FrenchCard card3 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Six); <add> <add> assertTrue(klondikeRules.isSmallerByOneAndOppositeColor(card1, card2)); <add> assertFalse(klondikeRules.isSmallerByOneAndOppositeColor(card1, card3)); <add> } <add> <add> @Test <add> public void testIsSmallerByOneAndSameSuit() { <add> FrenchCard card1 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Ten); <add> FrenchCard card2 = new FrenchCard(false, FrenchSuit.Spades, FrenchRank.Jack); <add> FrenchCard card3 = new FrenchCard(false, FrenchSuit.Hearts, FrenchRank.Six); <add> <add> assertTrue(klondikeRules.isSmallerByOneAndSameSuit(card1, card2)); <add> assertFalse(klondikeRules.isSmallerByOneAndSameSuit(card1, card3)); <add> } <add>}
Java
mit
20a9c71fc58f8cdde64cc1944a23b04f59b33553
0
projectdanube/neustar-discovery-service,neustarpc/neustar-discovery-service
src/main/java/biz/neustar/discovery/DiscoveryMessagingTarget.java
package biz.neustar.discovery; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.openxri.XRI; import org.openxri.proxy.impl.AbstractProxy; import org.openxri.resolve.Resolver; import org.openxri.resolve.ResolverFlags; import org.openxri.resolve.ResolverState; import org.openxri.resolve.exception.PartialResolutionException; import org.openxri.util.PrioritizedList; import org.openxri.xml.SEPType; import org.openxri.xml.SEPUri; import org.openxri.xml.Service; import org.openxri.xml.Status; import org.openxri.xml.XRD; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xdi2.core.Graph; import xdi2.core.features.equivalence.Equivalence; import xdi2.core.features.nodetypes.XdiAbstractMemberUnordered; import xdi2.core.features.nodetypes.XdiAttributeCollection; import xdi2.core.features.nodetypes.XdiAttributeMember; import xdi2.core.features.nodetypes.XdiAttributeSingleton; import xdi2.core.features.nodetypes.XdiLocalRoot; import xdi2.core.features.nodetypes.XdiPeerRoot; import xdi2.core.util.XRI2Util; import xdi2.core.xri3.XDI3Segment; import xdi2.core.xri3.XDI3SubSegment; import xdi2.messaging.GetOperation; import xdi2.messaging.MessageResult; import xdi2.messaging.exceptions.Xdi2MessagingException; import xdi2.messaging.target.AbstractContextHandler; import xdi2.messaging.target.AbstractMessagingTarget; import xdi2.messaging.target.AddressHandler; import xdi2.messaging.target.ExecutionContext; public class DiscoveryMessagingTarget extends AbstractMessagingTarget { private static final Logger log = LoggerFactory.getLogger(DiscoveryMessagingTarget.class); public static final XDI3Segment XRI_SELF = XDI3Segment.create("[=]"); public static final XDI3SubSegment XRI_URI = XDI3SubSegment.create("$uri"); private AbstractProxy proxy; @Override public void init() throws Exception { super.init(); } @Override public AddressHandler getAddressHandler(XDI3Segment address) throws Xdi2MessagingException { return this.addressHandler; } public AbstractProxy getProxy() { return this.proxy; } public void setProxy(AbstractProxy proxy) { this.proxy = proxy; } private AddressHandler addressHandler = new AbstractContextHandler() { @Override public void executeGetOnAddress(XDI3Segment targetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException { // prepare XRI XDI3Segment xri; if (XdiPeerRoot.isPeerRootArcXri(targetAddress.getLastSubSegment())) { xri = XdiPeerRoot.getXriOfPeerRootArcXri(targetAddress.getLastSubSegment()); } else { xri = targetAddress; } String canonicalId = XRI2Util.cloudNumberToCanonicalId(xri); if (canonicalId != null) xri = XDI3Segment.create(canonicalId); // resolve the XRI if (log.isDebugEnabled()) log.debug("Resolving " + xri); Resolver resolver = DiscoveryMessagingTarget.this.proxy.getResolver(); ResolverFlags resolverFlags = new ResolverFlags(); ResolverState resolverState = new ResolverState(); XRD xrd; try { xrd = resolver.resolveSEPToXRD(new XRI(xri.toString()), null, null, resolverFlags, resolverState); } catch (PartialResolutionException ex) { xrd = ex.getPartialXRDS().getFinalXRD(); } if (log.isDebugEnabled()) log.debug("XRD Status: " + xrd.getStatus().getCode()); if ((! Status.SUCCESS.equals(xrd.getStatusCode())) && (! Status.SEP_NOT_FOUND.equals(xrd.getStatusCode()))) { throw new Xdi2MessagingException("XRI Resolution 2.0 Problem: " + xrd.getStatusCode() + " (" + xrd.getStatus().getValue() + ")", null, executionContext); } // extract cloud number XDI3Segment cloudNumber = XRI2Util.canonicalIdToCloudNumber(xrd.getCanonicalID().getValue()); if (log.isDebugEnabled()) log.debug("Cloud Number: " + cloudNumber); // extract URIs Map<String, List<String>> uriMap = new HashMap<String, List<String>> (); for (int i=0; i<xrd.getNumServices(); i++) { Service service = xrd.getServiceAt(i); if (service.getNumTypes() == 0) continue; for (int ii=0; ii<service.getNumTypes(); ii++) { SEPType type = service.getTypeAt(ii); if (type == null || type.getType() == null || type.getType().trim().isEmpty()) continue; List<String> uriList = uriMap.get(type.getType()); if (uriList == null) { uriList = new ArrayList<String> (); uriMap.put(type.getType(), uriList); } List<?> uris = service.getURIs(); Collections.sort(uris, new Comparator<Object> () { @Override public int compare(Object uri1, Object uri2) { Integer priority1 = ((SEPUri) uri1).getPriority(); Integer priority2 = ((SEPUri) uri2).getPriority(); if (priority1 == null && priority2 == null) return 0; if (priority1 == null && priority2 != null) return 1; if (priority1 != null && priority2 == null) return -1; if (priority1.intValue() == priority2.intValue()) return 0; return priority1.intValue() > priority2.intValue() ? 1 : -1; } }); for (int iii = 0; iii<uris.size(); iii++) { SEPUri uri = (SEPUri) uris.get(iii); if (uri == null || uri.getUriString() == null || uri.getUriString().trim().isEmpty()) continue; uriList.add(uri.getUriString()); } } } if (log.isDebugEnabled()) log.debug("URIs: " + uriMap); // extract default URI PrioritizedList defaultUriPrioritizedList = xrd.getSelectedServices(); ArrayList<?> defaultUriList = defaultUriPrioritizedList == null ? null : defaultUriPrioritizedList.getList(); Service defaultUriService = defaultUriList == null || defaultUriList.size() < 1 ? null : (Service) defaultUriList.get(0); String defaultUri = defaultUriService == null ? null : defaultUriService.getURIAt(0).getUriString(); if (log.isDebugEnabled()) log.debug("Default URI: " + defaultUri); // prepare result graph Graph graph = messageResult.getGraph(); // add "self" peer root XdiLocalRoot.findLocalRoot(graph).setSelfPeerRoot(XRI_SELF); // add cloud number peer root XdiPeerRoot cloudNumberXdiPeerRoot = XdiLocalRoot.findLocalRoot(graph).findPeerRoot(cloudNumber, true); // add all URIs for all types XdiAttributeCollection uriXdiAttributeCollection = cloudNumberXdiPeerRoot.getXdiAttributeCollection(XRI_URI, true); for (Entry<String, List<String>> uriMapEntry : uriMap.entrySet()) { String type = uriMapEntry.getKey(); List<String> uriList = uriMapEntry.getValue(); XDI3SubSegment typeXdiEntitySingletonArcXri = XRI2Util.typeToXdiEntitySingletonArcXri(type); for (String uri : uriList) { XDI3SubSegment uriXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createHashArcXri(uri, true); XdiAttributeMember uriXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(uriXdiMemberUnorderedArcXri); uriXdiAttributeMember.getXdiValue(true).getContextNode().setLiteral(uri); XdiAttributeCollection typeXdiAttributeCollection = cloudNumberXdiPeerRoot.getXdiEntitySingleton(typeXdiEntitySingletonArcXri, true).getXdiAttributeCollection(XRI_URI, true); XdiAttributeMember typeXdiAttributeMember = typeXdiAttributeCollection.setXdiMemberOrdered(-1); Equivalence.setReferenceContextNode(typeXdiAttributeMember.getContextNode(), uriXdiAttributeMember.getContextNode()); } // add default URI for this type if (uriList.size() > 0) { String defaultUriForType = uriList.get(0); XDI3SubSegment defaultUriForTypeXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createHashArcXri(defaultUriForType, true); XdiAttributeMember defaultUriForTypeXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(defaultUriForTypeXdiMemberUnorderedArcXri); XdiAttributeSingleton defaultUriForTypeXdiAttributeSingleton = cloudNumberXdiPeerRoot.getXdiEntitySingleton(typeXdiEntitySingletonArcXri, true).getXdiAttributeSingleton(XRI_URI, true); Equivalence.setReferenceContextNode(defaultUriForTypeXdiAttributeSingleton.getContextNode(), defaultUriForTypeXdiAttributeMember.getContextNode()); } } // add default URI if (defaultUri != null) { XDI3SubSegment defaultUriXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createHashArcXri(defaultUri, true); XdiAttributeMember defaultUriXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(defaultUriXdiMemberUnorderedArcXri); XdiAttributeSingleton defaultUriXdiAttributeSingleton = cloudNumberXdiPeerRoot.getXdiAttributeSingleton(XRI_URI, true); Equivalence.setReferenceContextNode(defaultUriXdiAttributeSingleton.getContextNode(), defaultUriXdiAttributeMember.getContextNode()); } // add original peer root if (! xri.equals(cloudNumber)) { XdiPeerRoot xriXdiPeerRoot = XdiLocalRoot.findLocalRoot(graph).findPeerRoot(xri, true); Equivalence.setReferenceContextNode(xriXdiPeerRoot.getContextNode(), cloudNumberXdiPeerRoot.getContextNode()); } } }; }
removing the messaging target, we use the contributor instead
src/main/java/biz/neustar/discovery/DiscoveryMessagingTarget.java
removing the messaging target, we use the contributor instead
<ide><path>rc/main/java/biz/neustar/discovery/DiscoveryMessagingTarget.java <del>package biz.neustar.discovery; <del> <del>import java.util.ArrayList; <del>import java.util.Collections; <del>import java.util.Comparator; <del>import java.util.HashMap; <del>import java.util.List; <del>import java.util.Map; <del>import java.util.Map.Entry; <del> <del>import org.openxri.XRI; <del>import org.openxri.proxy.impl.AbstractProxy; <del>import org.openxri.resolve.Resolver; <del>import org.openxri.resolve.ResolverFlags; <del>import org.openxri.resolve.ResolverState; <del>import org.openxri.resolve.exception.PartialResolutionException; <del>import org.openxri.util.PrioritizedList; <del>import org.openxri.xml.SEPType; <del>import org.openxri.xml.SEPUri; <del>import org.openxri.xml.Service; <del>import org.openxri.xml.Status; <del>import org.openxri.xml.XRD; <del>import org.slf4j.Logger; <del>import org.slf4j.LoggerFactory; <del> <del>import xdi2.core.Graph; <del>import xdi2.core.features.equivalence.Equivalence; <del>import xdi2.core.features.nodetypes.XdiAbstractMemberUnordered; <del>import xdi2.core.features.nodetypes.XdiAttributeCollection; <del>import xdi2.core.features.nodetypes.XdiAttributeMember; <del>import xdi2.core.features.nodetypes.XdiAttributeSingleton; <del>import xdi2.core.features.nodetypes.XdiLocalRoot; <del>import xdi2.core.features.nodetypes.XdiPeerRoot; <del>import xdi2.core.util.XRI2Util; <del>import xdi2.core.xri3.XDI3Segment; <del>import xdi2.core.xri3.XDI3SubSegment; <del>import xdi2.messaging.GetOperation; <del>import xdi2.messaging.MessageResult; <del>import xdi2.messaging.exceptions.Xdi2MessagingException; <del>import xdi2.messaging.target.AbstractContextHandler; <del>import xdi2.messaging.target.AbstractMessagingTarget; <del>import xdi2.messaging.target.AddressHandler; <del>import xdi2.messaging.target.ExecutionContext; <del> <del>public class DiscoveryMessagingTarget extends AbstractMessagingTarget { <del> <del> private static final Logger log = LoggerFactory.getLogger(DiscoveryMessagingTarget.class); <del> <del> public static final XDI3Segment XRI_SELF = XDI3Segment.create("[=]"); <del> public static final XDI3SubSegment XRI_URI = XDI3SubSegment.create("$uri"); <del> <del> private AbstractProxy proxy; <del> <del> @Override <del> public void init() throws Exception { <del> <del> super.init(); <del> } <del> <del> @Override <del> public AddressHandler getAddressHandler(XDI3Segment address) throws Xdi2MessagingException { <del> <del> return this.addressHandler; <del> } <del> <del> public AbstractProxy getProxy() { <del> <del> return this.proxy; <del> } <del> <del> public void setProxy(AbstractProxy proxy) { <del> <del> this.proxy = proxy; <del> } <del> <del> private AddressHandler addressHandler = new AbstractContextHandler() { <del> <del> @Override <del> public void executeGetOnAddress(XDI3Segment targetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException { <del> <del> // prepare XRI <del> <del> XDI3Segment xri; <del> <del> if (XdiPeerRoot.isPeerRootArcXri(targetAddress.getLastSubSegment())) { <del> <del> xri = XdiPeerRoot.getXriOfPeerRootArcXri(targetAddress.getLastSubSegment()); <del> } else { <del> <del> xri = targetAddress; <del> } <del> <del> String canonicalId = XRI2Util.cloudNumberToCanonicalId(xri); <del> if (canonicalId != null) xri = XDI3Segment.create(canonicalId); <del> <del> // resolve the XRI <del> <del> if (log.isDebugEnabled()) log.debug("Resolving " + xri); <del> <del> Resolver resolver = DiscoveryMessagingTarget.this.proxy.getResolver(); <del> <del> ResolverFlags resolverFlags = new ResolverFlags(); <del> ResolverState resolverState = new ResolverState(); <del> <del> XRD xrd; <del> <del> try { <del> <del> xrd = resolver.resolveSEPToXRD(new XRI(xri.toString()), null, null, resolverFlags, resolverState); <del> } catch (PartialResolutionException ex) { <del> <del> xrd = ex.getPartialXRDS().getFinalXRD(); <del> } <del> <del> if (log.isDebugEnabled()) log.debug("XRD Status: " + xrd.getStatus().getCode()); <del> <del> if ((! Status.SUCCESS.equals(xrd.getStatusCode())) && (! Status.SEP_NOT_FOUND.equals(xrd.getStatusCode()))) { <del> <del> throw new Xdi2MessagingException("XRI Resolution 2.0 Problem: " + xrd.getStatusCode() + " (" + xrd.getStatus().getValue() + ")", null, executionContext); <del> } <del> <del> // extract cloud number <del> <del> XDI3Segment cloudNumber = XRI2Util.canonicalIdToCloudNumber(xrd.getCanonicalID().getValue()); <del> <del> if (log.isDebugEnabled()) log.debug("Cloud Number: " + cloudNumber); <del> <del> // extract URIs <del> <del> Map<String, List<String>> uriMap = new HashMap<String, List<String>> (); <del> <del> for (int i=0; i<xrd.getNumServices(); i++) { <del> <del> Service service = xrd.getServiceAt(i); <del> if (service.getNumTypes() == 0) continue; <del> <del> for (int ii=0; ii<service.getNumTypes(); ii++) { <del> <del> SEPType type = service.getTypeAt(ii); <del> if (type == null || type.getType() == null || type.getType().trim().isEmpty()) continue; <del> <del> List<String> uriList = uriMap.get(type.getType()); <del> <del> if (uriList == null) { <del> <del> uriList = new ArrayList<String> (); <del> uriMap.put(type.getType(), uriList); <del> } <del> <del> List<?> uris = service.getURIs(); <del> Collections.sort(uris, new Comparator<Object> () { <del> <del> @Override <del> public int compare(Object uri1, Object uri2) { <del> <del> Integer priority1 = ((SEPUri) uri1).getPriority(); <del> Integer priority2 = ((SEPUri) uri2).getPriority(); <del> <del> if (priority1 == null && priority2 == null) return 0; <del> if (priority1 == null && priority2 != null) return 1; <del> if (priority1 != null && priority2 == null) return -1; <del> <del> if (priority1.intValue() == priority2.intValue()) return 0; <del> <del> return priority1.intValue() > priority2.intValue() ? 1 : -1; <del> } <del> }); <del> <del> for (int iii = 0; iii<uris.size(); iii++) { <del> <del> SEPUri uri = (SEPUri) uris.get(iii); <del> if (uri == null || uri.getUriString() == null || uri.getUriString().trim().isEmpty()) continue; <del> <del> uriList.add(uri.getUriString()); <del> } <del> } <del> } <del> <del> if (log.isDebugEnabled()) log.debug("URIs: " + uriMap); <del> <del> // extract default URI <del> <del> PrioritizedList defaultUriPrioritizedList = xrd.getSelectedServices(); <del> ArrayList<?> defaultUriList = defaultUriPrioritizedList == null ? null : defaultUriPrioritizedList.getList(); <del> Service defaultUriService = defaultUriList == null || defaultUriList.size() < 1 ? null : (Service) defaultUriList.get(0); <del> String defaultUri = defaultUriService == null ? null : defaultUriService.getURIAt(0).getUriString(); <del> <del> if (log.isDebugEnabled()) log.debug("Default URI: " + defaultUri); <del> <del> // prepare result graph <del> <del> Graph graph = messageResult.getGraph(); <del> <del> // add "self" peer root <del> <del> XdiLocalRoot.findLocalRoot(graph).setSelfPeerRoot(XRI_SELF); <del> <del> // add cloud number peer root <del> <del> XdiPeerRoot cloudNumberXdiPeerRoot = XdiLocalRoot.findLocalRoot(graph).findPeerRoot(cloudNumber, true); <del> <del> // add all URIs for all types <del> <del> XdiAttributeCollection uriXdiAttributeCollection = cloudNumberXdiPeerRoot.getXdiAttributeCollection(XRI_URI, true); <del> <del> for (Entry<String, List<String>> uriMapEntry : uriMap.entrySet()) { <del> <del> String type = uriMapEntry.getKey(); <del> List<String> uriList = uriMapEntry.getValue(); <del> <del> XDI3SubSegment typeXdiEntitySingletonArcXri = XRI2Util.typeToXdiEntitySingletonArcXri(type); <del> <del> for (String uri : uriList) { <del> <del> XDI3SubSegment uriXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createHashArcXri(uri, true); <del> <del> XdiAttributeMember uriXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(uriXdiMemberUnorderedArcXri); <del> uriXdiAttributeMember.getXdiValue(true).getContextNode().setLiteral(uri); <del> <del> XdiAttributeCollection typeXdiAttributeCollection = cloudNumberXdiPeerRoot.getXdiEntitySingleton(typeXdiEntitySingletonArcXri, true).getXdiAttributeCollection(XRI_URI, true); <del> XdiAttributeMember typeXdiAttributeMember = typeXdiAttributeCollection.setXdiMemberOrdered(-1); <del> Equivalence.setReferenceContextNode(typeXdiAttributeMember.getContextNode(), uriXdiAttributeMember.getContextNode()); <del> } <del> <del> // add default URI for this type <del> <del> if (uriList.size() > 0) { <del> <del> String defaultUriForType = uriList.get(0); <del> <del> XDI3SubSegment defaultUriForTypeXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createHashArcXri(defaultUriForType, true); <del> <del> XdiAttributeMember defaultUriForTypeXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(defaultUriForTypeXdiMemberUnorderedArcXri); <del> XdiAttributeSingleton defaultUriForTypeXdiAttributeSingleton = cloudNumberXdiPeerRoot.getXdiEntitySingleton(typeXdiEntitySingletonArcXri, true).getXdiAttributeSingleton(XRI_URI, true); <del> Equivalence.setReferenceContextNode(defaultUriForTypeXdiAttributeSingleton.getContextNode(), defaultUriForTypeXdiAttributeMember.getContextNode()); <del> } <del> } <del> <del> // add default URI <del> <del> if (defaultUri != null) { <del> <del> XDI3SubSegment defaultUriXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createHashArcXri(defaultUri, true); <del> <del> XdiAttributeMember defaultUriXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(defaultUriXdiMemberUnorderedArcXri); <del> XdiAttributeSingleton defaultUriXdiAttributeSingleton = cloudNumberXdiPeerRoot.getXdiAttributeSingleton(XRI_URI, true); <del> Equivalence.setReferenceContextNode(defaultUriXdiAttributeSingleton.getContextNode(), defaultUriXdiAttributeMember.getContextNode()); <del> } <del> <del> // add original peer root <del> <del> if (! xri.equals(cloudNumber)) { <del> <del> XdiPeerRoot xriXdiPeerRoot = XdiLocalRoot.findLocalRoot(graph).findPeerRoot(xri, true); <del> <del> Equivalence.setReferenceContextNode(xriXdiPeerRoot.getContextNode(), cloudNumberXdiPeerRoot.getContextNode()); <del> } <del> } <del> }; <del>}
Java
apache-2.0
9ab65ec568f42636ceefe60969d3fcadb15886e1
0
TEAM-Gummy/android_external_gson,byterom/android_external_gson,Mahdi-Rom/android_external_gson,neopeak/google-gson,eatnumber1/google-gson,vnc-biz/zcs-lib-gson,ThirdProject/android_external_gson,CyanogenMod/android_external_gson
/* * 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.gson.stream; import java.io.IOException; /** * Thrown when a reader encounters malformed JSON. Some syntax errors can be * ignored by calling {@link JsonReader#setLenient(boolean)}. */ public final class MalformedJsonException extends IOException { private static final long serialVersionUID = 1L; public MalformedJsonException(String msg) { super(msg); } public MalformedJsonException(String msg, Throwable throwable) { super(msg); initCause(throwable); } public MalformedJsonException(Throwable throwable) { initCause(throwable); } }
src/main/java/com/google/gson/stream/MalformedJsonException.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.gson.stream; import java.io.IOException; /** * Thrown when a reader encounters malformed JSON. Some syntax errors can be * ignored by calling {@link JsonReader#setLenient(boolean)}. */ public final class MalformedJsonException extends IOException { private static final long serialVersionUID = 1L; public MalformedJsonException(String s) { super(s); } }
New overloads for constructing MalformedJsonException git-svn-id: 7b8be7b2f8bf58e8147c910303b95fa2b8d9948f@648 2534bb62-2c4b-0410-85e8-b5006b95c4ae
src/main/java/com/google/gson/stream/MalformedJsonException.java
New overloads for constructing MalformedJsonException
<ide><path>rc/main/java/com/google/gson/stream/MalformedJsonException.java <ide> public final class MalformedJsonException extends IOException { <ide> private static final long serialVersionUID = 1L; <ide> <del> public MalformedJsonException(String s) { <del> super(s); <add> public MalformedJsonException(String msg) { <add> super(msg); <add> } <add> <add> public MalformedJsonException(String msg, Throwable throwable) { <add> super(msg); <add> initCause(throwable); <add> } <add> <add> public MalformedJsonException(Throwable throwable) { <add> initCause(throwable); <ide> } <ide> }
Java
apache-2.0
4e59785407183131c84c48071c1f2948a998095c
0
mohanaraosv/commons-dbcp,mohanaraosv/commons-dbcp,mohanaraosv/commons-dbcp
/* * 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 org.apache.commons.dbcp2; import java.sql.PreparedStatement; /** * A key uniquely identifying {@link PreparedStatement}s. */ public class PStmtKey { /** SQL defining Prepared or Callable Statement */ private final String _sql; /** Result set type */ private final Integer _resultSetType; /** Result set concurrency */ private final Integer _resultSetConcurrency; /** Database catalog */ private final String _catalog; /** * Statement type. Either STATEMENT_PREPAREDSTMT (PreparedStatement) * or STATEMENT_CALLABLESTMT (CallableStatement) */ private final byte _stmtType; public PStmtKey(String sql) { this(sql, null, PoolingConnection.STATEMENT_PREPAREDSTMT); } public PStmtKey(String sql, String catalog) { this(sql, catalog, PoolingConnection.STATEMENT_PREPAREDSTMT); } public PStmtKey(String sql, String catalog, byte stmtType) { _sql = sql; _catalog = catalog; _stmtType = stmtType; _resultSetType = null; _resultSetConcurrency = null; } public PStmtKey(String sql, int resultSetType, int resultSetConcurrency) { this(sql, null, resultSetType, resultSetConcurrency, PoolingConnection.STATEMENT_PREPAREDSTMT); } public PStmtKey(String sql, String catalog, int resultSetType, int resultSetConcurrency) { this(sql, catalog, resultSetType, resultSetConcurrency, PoolingConnection.STATEMENT_PREPAREDSTMT); } public PStmtKey(String sql, String catalog, int resultSetType, int resultSetConcurrency, byte stmtType) { _sql = sql; _catalog = catalog; _resultSetType = new Integer(resultSetType); _resultSetConcurrency = new Integer(resultSetConcurrency); _stmtType = stmtType; } public String getSql() { return _sql; } public Integer getResultSetType() { return _resultSetType; } public Integer getResultSetConcurrency() { return _resultSetConcurrency; } public String getCatalog() { return _catalog; } public byte getStmtType() { return _stmtType; } @Override public boolean equals(Object that) { try { PStmtKey key = (PStmtKey)that; return( ((null == _sql && null == key._sql) || _sql.equals(key._sql)) && ((null == _catalog && null == key._catalog) || _catalog.equals(key._catalog)) && ((null == _resultSetType && null == key._resultSetType) || _resultSetType.equals(key._resultSetType)) && ((null == _resultSetConcurrency && null == key._resultSetConcurrency) || _resultSetConcurrency.equals(key._resultSetConcurrency)) && (_stmtType == key._stmtType) ); } catch(ClassCastException e) { return false; } catch(NullPointerException e) { return false; } } @Override public int hashCode() { if (_catalog==null) return(null == _sql ? 0 : _sql.hashCode()); else return(null == _sql ? _catalog.hashCode() : (_catalog + _sql).hashCode()); } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("PStmtKey: sql="); buf.append(_sql); buf.append(", catalog="); buf.append(_catalog); buf.append(", resultSetType="); buf.append(_resultSetType); buf.append(", resultSetConcurrency="); buf.append(_resultSetConcurrency); buf.append(", statmentType="); buf.append(_stmtType); return buf.toString(); } }
src/java/org/apache/commons/dbcp2/PStmtKey.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 org.apache.commons.dbcp2; import java.sql.PreparedStatement; /** * A key uniquely identifying {@link PreparedStatement}s. */ public class PStmtKey { /** SQL defining Prepared or Callable Statement */ private String _sql = null; /** Result set type */ private Integer _resultSetType = null; /** Result set concurrency */ private Integer _resultSetConcurrency = null; /** Database catalog */ private String _catalog = null; /** * Statement type. Either STATEMENT_PREPAREDSTMT (PreparedStatement) * or STATEMENT_CALLABLESTMT (CallableStatement) */ private byte _stmtType = PoolingConnection.STATEMENT_PREPAREDSTMT; public PStmtKey(String sql) { _sql = sql; } public PStmtKey(String sql, String catalog) { _sql = sql; _catalog = catalog; } public PStmtKey(String sql, String catalog, byte stmtType) { _sql = sql; _catalog = catalog; _stmtType = stmtType; } public PStmtKey(String sql, int resultSetType, int resultSetConcurrency) { _sql = sql; _resultSetType = new Integer(resultSetType); _resultSetConcurrency = new Integer(resultSetConcurrency); } public PStmtKey(String sql, String catalog, int resultSetType, int resultSetConcurrency) { _sql = sql; _catalog = catalog; _resultSetType = new Integer(resultSetType); _resultSetConcurrency = new Integer(resultSetConcurrency); } public PStmtKey(String sql, String catalog, int resultSetType, int resultSetConcurrency, byte stmtType) { _sql = sql; _catalog = catalog; _resultSetType = new Integer(resultSetType); _resultSetConcurrency = new Integer(resultSetConcurrency); _stmtType = stmtType; } public String getSql() { return _sql; } public Integer getResultSetType() { return _resultSetType; } public Integer getResultSetConcurrency() { return _resultSetConcurrency; } public String getCatalog() { return _catalog; } public byte getStmtType() { return _stmtType; } @Override public boolean equals(Object that) { try { PStmtKey key = (PStmtKey)that; return( ((null == _sql && null == key._sql) || _sql.equals(key._sql)) && ((null == _catalog && null == key._catalog) || _catalog.equals(key._catalog)) && ((null == _resultSetType && null == key._resultSetType) || _resultSetType.equals(key._resultSetType)) && ((null == _resultSetConcurrency && null == key._resultSetConcurrency) || _resultSetConcurrency.equals(key._resultSetConcurrency)) && (_stmtType == key._stmtType) ); } catch(ClassCastException e) { return false; } catch(NullPointerException e) { return false; } } @Override public int hashCode() { if (_catalog==null) return(null == _sql ? 0 : _sql.hashCode()); else return(null == _sql ? _catalog.hashCode() : (_catalog + _sql).hashCode()); } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("PStmtKey: sql="); buf.append(_sql); buf.append(", catalog="); buf.append(_catalog); buf.append(", resultSetType="); buf.append(_resultSetType); buf.append(", resultSetConcurrency="); buf.append(_resultSetConcurrency); buf.append(", statmentType="); buf.append(_stmtType); return buf.toString(); } }
Make immutable private fields final git-svn-id: ad951d5a084f562764370c7a59da74380db26404@1331144 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/dbcp2/PStmtKey.java
Make immutable private fields final
<ide><path>rc/java/org/apache/commons/dbcp2/PStmtKey.java <ide> public class PStmtKey { <ide> <ide> /** SQL defining Prepared or Callable Statement */ <del> private String _sql = null; <add> private final String _sql; <ide> <ide> /** Result set type */ <del> private Integer _resultSetType = null; <add> private final Integer _resultSetType; <ide> <ide> /** Result set concurrency */ <del> private Integer _resultSetConcurrency = null; <add> private final Integer _resultSetConcurrency; <ide> <ide> /** Database catalog */ <del> private String _catalog = null; <add> private final String _catalog; <ide> <ide> /** <ide> * Statement type. Either STATEMENT_PREPAREDSTMT (PreparedStatement) <ide> * or STATEMENT_CALLABLESTMT (CallableStatement) <ide> */ <del> private byte _stmtType = PoolingConnection.STATEMENT_PREPAREDSTMT; <add> private final byte _stmtType; <ide> <ide> public PStmtKey(String sql) { <del> _sql = sql; <add> this(sql, null, PoolingConnection.STATEMENT_PREPAREDSTMT); <ide> } <ide> <ide> public PStmtKey(String sql, String catalog) { <del> _sql = sql; <del> _catalog = catalog; <add> this(sql, catalog, PoolingConnection.STATEMENT_PREPAREDSTMT); <ide> } <ide> <ide> public PStmtKey(String sql, String catalog, byte stmtType) { <ide> _sql = sql; <ide> _catalog = catalog; <ide> _stmtType = stmtType; <add> _resultSetType = null; <add> _resultSetConcurrency = null; <ide> } <ide> <ide> public PStmtKey(String sql, int resultSetType, int resultSetConcurrency) { <del> _sql = sql; <del> _resultSetType = new Integer(resultSetType); <del> _resultSetConcurrency = new Integer(resultSetConcurrency); <add> this(sql, null, resultSetType, resultSetConcurrency, PoolingConnection.STATEMENT_PREPAREDSTMT); <ide> } <ide> <ide> public PStmtKey(String sql, String catalog, int resultSetType, int resultSetConcurrency) { <del> _sql = sql; <del> _catalog = catalog; <del> _resultSetType = new Integer(resultSetType); <del> _resultSetConcurrency = new Integer(resultSetConcurrency); <add> this(sql, catalog, resultSetType, resultSetConcurrency, PoolingConnection.STATEMENT_PREPAREDSTMT); <ide> } <ide> <ide> public PStmtKey(String sql, String catalog, int resultSetType, int resultSetConcurrency, byte stmtType) {
JavaScript
mit
61ed23b28f13cb8b615a78228f6fdafeb427d317
0
ello/webapp,ello/webapp,ello/webapp
import React, { Component, PropTypes } from 'react' import ReactDOM from 'react-dom' import { connect } from 'react-redux' import classNames from 'classnames' import { delay, isEqual } from 'lodash' import Avatar from '../assets/Avatar' import Block from './Block' import EmbedBlock from './EmbedBlock' import ImageBlock from './ImageBlock' import QuickEmoji from './QuickEmoji' import RepostBlock from './RepostBlock' import TextBlock from './TextBlock' import PostActionBar from './PostActionBar' import { addBlock, addDragBlock, addEmptyTextBlock, removeBlock, removeDragBlock, reorderBlocks, saveAsset, updateBlock, } from '../../actions/editor' import { closeOmnibar } from '../../actions/omnibar' import { scrollToTop } from '../../vendor/scrollTop' import * as ACTION_TYPES from '../../constants/action_types' import { addDragObject, removeDragObject } from './DragComponent' import { addInputObject, removeInputObject } from './InputComponent' class BlockCollection extends Component { static propTypes = { avatar: PropTypes.object, blocks: PropTypes.array, cancelAction: PropTypes.func.isRequired, currentUsername: PropTypes.string, collection: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, dragBlock: PropTypes.object, editorId: PropTypes.string.isRequired, hasContent: PropTypes.bool, hasMention: PropTypes.bool, isComment: PropTypes.bool, isLoading: PropTypes.bool, isOwnPost: PropTypes.bool, isNavbarHidden: PropTypes.bool, order: PropTypes.array.isRequired, pathname: PropTypes.string.isRequired, postId: PropTypes.string, repostContent: PropTypes.array, submitAction: PropTypes.func.isRequired, submitText: PropTypes.string, } static defaultProps = { blocks: [], isComment: false, repostContent: [], submitText: 'Post', } componentWillMount() { const { blocks, dispatch, editorId, repostContent } = this.props this.state = { hasDragOver: false } if (repostContent.length) { dispatch(addBlock({ kind: 'repost', data: repostContent }, editorId)) } if (blocks.length) { for (const block of blocks) { dispatch(addBlock(block, editorId)) } } } componentDidMount() { const { dispatch, editorId } = this.props this.dragObject = { component: this, dragId: editorId } dispatch(addEmptyTextBlock(editorId)) addDragObject(this.dragObject) addInputObject(this) } shouldComponentUpdate(nextProps, nextState) { return !isEqual(nextProps, this.props) || !isEqual(nextState, this.state) } componentWillUnmount() { if (this.dragObject) { removeDragObject(this.dragObject) } removeInputObject(this) } onCloseOmnibar() { const { dispatch, isComment } = this.props if (!isComment) { dispatch(closeOmnibar()) } } onDragStart(props) { const { collection, dispatch, editorId } = this.props this.blockNode = props.target.parentNode.parentNode this.startOffset = this.blockNode.offsetTop this.startHeight = this.blockNode.offsetHeight this.prevBlock = this.blockNode.previousSibling this.nextBlock = this.blockNode.nextSibling const dragUid = this.blockNode.dataset.collectionId dispatch(addDragBlock(collection[dragUid], editorId)) // swap the dragging block for a // normal block and set the height/width const block = { data: { width: this.blockNode.offsetWidth, height: this.blockNode.offsetHeight, }, kind: 'block', uid: collection[dragUid].uid, } dispatch(updateBlock(block, dragUid, editorId, true)) this.onDragMove(props) ReactDOM.findDOMNode(document.body).classList.add('isDragging') } onDragMove(props) { // move the block we are currently dragging this.setState({ dragBlockTop: props.dragY + this.startOffset }) // determine if we should change order if (props.dragY < props.lastDragY) { this.onDragUp(props) } else if (props.dragY > props.lastDragY) { this.onDragDown(props) } } onDragUp(props) { if (this.prevBlock && !this.prevBlock.classList.contains('readonly') && (props.dragY + this.startOffset) < (this.prevBlock.offsetTop + this.prevBlock.offsetHeight * 0.5)) { this.onMoveBlock(-1) } } onDragDown(props) { if (this.nextBlock && (props.dragY + this.startOffset + this.startHeight) > (this.nextBlock.offsetTop + this.nextBlock.offsetHeight * 0.5)) { this.onMoveBlock(1) } } onMoveBlock(delta) { if (!this.refs.blockPlaceholder) return const { dispatch, dragBlock, editorId } = this.props dispatch(reorderBlocks(dragBlock.uid, delta, editorId)) const placeholder = this.refs.blockPlaceholder.refs.editorBlock this.prevBlock = placeholder.previousSibling this.nextBlock = placeholder.nextSibling } onDragEnd() { const { dispatch, dragBlock, editorId } = this.props // swap the normal block out for // the one that was removed initially const dragUid = dragBlock.uid dispatch(updateBlock(dragBlock, dragUid, editorId)) dispatch(removeDragBlock(editorId)) ReactDOM.findDOMNode(document.body).classList.remove('isDragging') this.setState({ dragBlockTop: null }) dispatch(addEmptyTextBlock(editorId)) } onDragOver = (e) => { e.preventDefault() if (!this.state.hasDragOver) { this.setState({ hasDragOver: true }) } } onDragLeave = () => { if (this.state.hasDragOver) { this.setState({ hasDragOver: false }) } } onDrop = (e) => { e.preventDefault() e.stopPropagation() this.setState({ hasDragOver: false }) if (e.dataTransfer.files.length) { this.acceptFiles(e.dataTransfer.files) } if (e.dataTransfer.types.indexOf('application/json') > -1) { const data = JSON.parse(e.dataTransfer.getData('application/json')) if (data.username) { this.appendText(`@${data.username} `) } if (data.emojiCode) { this.appendText(`${data.emojiCode} `) } if (data.imgSrc) { this.appendText(`![img-drop](${data.imgSrc})\n\n`) } if (data.href) { if (data.href === data.linkText) { this.appendText(`${data.href}`) } else { this.appendText(`[${data.linkText}](${data.href}) `) } } } } onSubmitPost() { const { editorId } = this.props if (document.activeElement.parentNode.dataset.editorId === editorId) { this.submit() } } onInsertEmoji = ({ value }) => { this.appendText(value) } getBlockElement(block) { const { editorId } = this.props const isUploading = block.isLoading const blockProps = { data: block.data, editorId, key: `${JSON.stringify(block.data)}_${block.uid}`, kind: block.kind, onRemoveBlock: this.remove, uid: block.uid, className: classNames({ isUploading }), } switch (block.kind) { case 'block': return ( <Block { ...blockProps } className={ classNames('BlockPlaceholder', { isUploading }) } ref="blockPlaceholder" /> ) case 'embed': return ( <EmbedBlock { ...blockProps } /> ) case 'image': return ( <ImageBlock blob={ block.blob } { ...blockProps } /> ) case 'repost': return ( <RepostBlock { ...blockProps } onRemoveBlock={ null } /> ) case 'text': return ( <TextBlock { ...blockProps } onInput={ this.handleTextBlockInput } shouldAutofocus={ this.shouldAutofocus() } /> ) default: return null } } isElementInViewport(el, topOffset = 0) { const rect = el.getBoundingClientRect() return ( rect.top >= topOffset && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ) } scrollToLastTextBlock() { const { editorId, isNavbarHidden } = this.props const textBlocks = document.querySelectorAll(`[data-editor-id='${editorId}'] div.text`) const lastTextBlock = textBlocks[textBlocks.length - 1] if (lastTextBlock && !this.isElementInViewport(lastTextBlock, isNavbarHidden ? 0 : 80)) { const pos = lastTextBlock.getBoundingClientRect() scrollToTop(window.scrollY + (pos.top - 100)) } } shouldAutofocus() { const { pathname, isComment } = this.props const postRegex = /^\/[\w\-]+\/post\/.+/ return !(isComment && postRegex.test(pathname)) } appendText = (content) => { const { dispatch, editorId } = this.props dispatch({ type: ACTION_TYPES.EDITOR.APPEND_TEXT, payload: { editorId, text: content } }) this.scrollToLastTextBlock() } remove = (uid) => { const { dispatch, editorId } = this.props dispatch(removeBlock(uid, editorId)) } handleTextBlockInput = (vo) => { const { dispatch, editorId } = this.props dispatch(updateBlock(vo, vo.uid, editorId)) } replyAll = () => { const { currentUsername, postId } = this.props if (!postId) { return } const nameArr = [] const usernames = document.querySelectorAll(`#Post_${postId} .CommentUsername`) for (const node of usernames) { if (nameArr.indexOf(node.innerHTML) === -1 && node.innerHTML !== `@${currentUsername}`) { nameArr.push(node.innerHTML) } } if (nameArr.length) { this.appendText(`${nameArr.join(' ')} `) } } submit = () => { const { submitAction } = this.props const data = this.serialize() submitAction(data) } serialize() { const { collection, order } = this.props const results = [] for (const uid of order) { const block = collection[uid] switch (block.kind) { case 'text': if (block.data.length) { results.push({ kind: block.kind, data: block.data }) } break case 'repost': break default: results.push({ kind: block.kind, data: block.data }) break } } return results } handleFiles = (e) => { if (e.target.files.length) { this.acceptFiles(e.target.files) } } acceptFiles(files) { const { dispatch, editorId } = this.props for (let index = 0, len = files.length; index < len; index += 1) { // This guard may not be necessary if (files.item(index)) { // need to delay a bit or else the images clobber each other delay(dispatch, 100 * index, saveAsset(files[index], editorId)) } } } render() { const { avatar, cancelAction, collection, dragBlock, editorId, hasContent, hasMention, isComment, isLoading, isOwnPost, order, submitText } = this.props const { dragBlockTop, hasDragOver } = this.state const firstBlockIsText = collection[order[0]] ? collection[order[0]].kind === 'text' : true const showQuickEmoji = isComment && firstBlockIsText const editorClassNames = classNames('editor', { withQuickEmoji: showQuickEmoji, hasDragOver, hasMention, hasContent, isComment, isLoading, }) return ( <div className={ editorClassNames } data-placeholder="Say Ello..." onDragLeave={ this.onDragLeave } onDragOver={ this.onDragOver } onDrop={ this.onDrop } > { isComment ? <Avatar sources={ avatar } /> : null } <div className="editor-region" data-num-blocks={ order.length } > { order.map((uid) => this.getBlockElement(collection[uid])) } { dragBlock ? <div className="DragBlock" style={{ top: dragBlockTop }}> { this.getBlockElement(dragBlock) } </div> : null } </div> { showQuickEmoji ? <QuickEmoji onAddEmoji={ this.onInsertEmoji } /> : null } <PostActionBar cancelAction={ cancelAction } disableSubmitAction={ isLoading || !hasContent } editorId={ editorId } handleFileAction={ this.handleFiles } ref="postActionBar" replyAllAction={ isComment && isOwnPost ? this.replyAll : null } submitAction={ this.submit } submitText={ submitText } /> </div> ) } } function mapStateToProps(state, ownProps) { const editor = state.editor[ownProps.editorId] return { avatar: state.profile.avatar, collection: editor.collection, currentUsername: state.profile.username, dragBlock: editor.dragBlock, hasContent: editor.hasContent, hasMention: editor.hasMention, isLoading: editor.isLoading, isNavbarHidden: state.gui.isNavbarHidden, order: editor.order, orderLength: editor.order.length, pathname: state.routing.location.pathname, postId: ownProps.post ? `${ownProps.post.id}` : null, } } export default connect(mapStateToProps, null, null, { withRef: true })(BlockCollection)
src/components/editor/BlockCollection.js
import React, { Component, PropTypes } from 'react' import ReactDOM from 'react-dom' import { connect } from 'react-redux' import classNames from 'classnames' import { delay, isEqual } from 'lodash' import Avatar from '../assets/Avatar' import Block from './Block' import EmbedBlock from './EmbedBlock' import ImageBlock from './ImageBlock' import QuickEmoji from './QuickEmoji' import RepostBlock from './RepostBlock' import TextBlock from './TextBlock' import PostActionBar from './PostActionBar' import { addBlock, addDragBlock, addEmptyTextBlock, removeBlock, removeDragBlock, reorderBlocks, saveAsset, updateBlock, } from '../../actions/editor' import { closeOmnibar } from '../../actions/omnibar' import { scrollToTop } from '../../vendor/scrollTop' import * as ACTION_TYPES from '../../constants/action_types' import { addDragObject, removeDragObject } from './DragComponent' import { addInputObject, removeInputObject } from './InputComponent' class BlockCollection extends Component { static propTypes = { avatar: PropTypes.object, blocks: PropTypes.array, cancelAction: PropTypes.func.isRequired, collection: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, dragBlock: PropTypes.object, editorId: PropTypes.string.isRequired, hasContent: PropTypes.bool, hasMention: PropTypes.bool, isComment: PropTypes.bool, isLoading: PropTypes.bool, isOwnPost: PropTypes.bool, isNavbarHidden: PropTypes.bool, order: PropTypes.array.isRequired, pathname: PropTypes.string.isRequired, postId: PropTypes.string, repostContent: PropTypes.array, submitAction: PropTypes.func.isRequired, submitText: PropTypes.string, } static defaultProps = { blocks: [], isComment: false, repostContent: [], submitText: 'Post', } componentWillMount() { const { blocks, dispatch, editorId, repostContent } = this.props this.state = { hasDragOver: false } if (repostContent.length) { dispatch(addBlock({ kind: 'repost', data: repostContent }, editorId)) } if (blocks.length) { for (const block of blocks) { dispatch(addBlock(block, editorId)) } } } componentDidMount() { const { dispatch, editorId } = this.props this.dragObject = { component: this, dragId: editorId } dispatch(addEmptyTextBlock(editorId)) addDragObject(this.dragObject) addInputObject(this) } shouldComponentUpdate(nextProps, nextState) { return !isEqual(nextProps, this.props) || !isEqual(nextState, this.state) } componentWillUnmount() { if (this.dragObject) { removeDragObject(this.dragObject) } removeInputObject(this) } onCloseOmnibar() { const { dispatch, isComment } = this.props if (!isComment) { dispatch(closeOmnibar()) } } onDragStart(props) { const { collection, dispatch, editorId } = this.props this.blockNode = props.target.parentNode.parentNode this.startOffset = this.blockNode.offsetTop this.startHeight = this.blockNode.offsetHeight this.prevBlock = this.blockNode.previousSibling this.nextBlock = this.blockNode.nextSibling const dragUid = this.blockNode.dataset.collectionId dispatch(addDragBlock(collection[dragUid], editorId)) // swap the dragging block for a // normal block and set the height/width const block = { data: { width: this.blockNode.offsetWidth, height: this.blockNode.offsetHeight, }, kind: 'block', uid: collection[dragUid].uid, } dispatch(updateBlock(block, dragUid, editorId, true)) this.onDragMove(props) ReactDOM.findDOMNode(document.body).classList.add('isDragging') } onDragMove(props) { // move the block we are currently dragging this.setState({ dragBlockTop: props.dragY + this.startOffset }) // determine if we should change order if (props.dragY < props.lastDragY) { this.onDragUp(props) } else if (props.dragY > props.lastDragY) { this.onDragDown(props) } } onDragUp(props) { if (this.prevBlock && !this.prevBlock.classList.contains('readonly') && (props.dragY + this.startOffset) < (this.prevBlock.offsetTop + this.prevBlock.offsetHeight * 0.5)) { this.onMoveBlock(-1) } } onDragDown(props) { if (this.nextBlock && (props.dragY + this.startOffset + this.startHeight) > (this.nextBlock.offsetTop + this.nextBlock.offsetHeight * 0.5)) { this.onMoveBlock(1) } } onMoveBlock(delta) { if (!this.refs.blockPlaceholder) return const { dispatch, dragBlock, editorId } = this.props dispatch(reorderBlocks(dragBlock.uid, delta, editorId)) const placeholder = this.refs.blockPlaceholder.refs.editorBlock this.prevBlock = placeholder.previousSibling this.nextBlock = placeholder.nextSibling } onDragEnd() { const { dispatch, dragBlock, editorId } = this.props // swap the normal block out for // the one that was removed initially const dragUid = dragBlock.uid dispatch(updateBlock(dragBlock, dragUid, editorId)) dispatch(removeDragBlock(editorId)) ReactDOM.findDOMNode(document.body).classList.remove('isDragging') this.setState({ dragBlockTop: null }) dispatch(addEmptyTextBlock(editorId)) } onDragOver = (e) => { e.preventDefault() if (!this.state.hasDragOver) { this.setState({ hasDragOver: true }) } } onDragLeave = () => { if (this.state.hasDragOver) { this.setState({ hasDragOver: false }) } } onDrop = (e) => { e.preventDefault() e.stopPropagation() this.setState({ hasDragOver: false }) if (e.dataTransfer.files.length) { this.acceptFiles(e.dataTransfer.files) } if (e.dataTransfer.types.indexOf('application/json') > -1) { const data = JSON.parse(e.dataTransfer.getData('application/json')) if (data.username) { this.appendText(`@${data.username} `) } if (data.emojiCode) { this.appendText(`${data.emojiCode} `) } if (data.imgSrc) { this.appendText(`![img-drop](${data.imgSrc})\n\n`) } if (data.href) { if (data.href === data.linkText) { this.appendText(`${data.href}`) } else { this.appendText(`[${data.linkText}](${data.href}) `) } } } } onSubmitPost() { const { editorId } = this.props if (document.activeElement.parentNode.dataset.editorId === editorId) { this.submit() } } onInsertEmoji = ({ value }) => { this.appendText(value) } getBlockElement(block) { const { editorId } = this.props const isUploading = block.isLoading const blockProps = { data: block.data, editorId, key: `${JSON.stringify(block.data)}_${block.uid}`, kind: block.kind, onRemoveBlock: this.remove, uid: block.uid, className: classNames({ isUploading }), } switch (block.kind) { case 'block': return ( <Block { ...blockProps } className={ classNames('BlockPlaceholder', { isUploading }) } ref="blockPlaceholder" /> ) case 'embed': return ( <EmbedBlock { ...blockProps } /> ) case 'image': return ( <ImageBlock blob={ block.blob } { ...blockProps } /> ) case 'repost': return ( <RepostBlock { ...blockProps } onRemoveBlock={ null } /> ) case 'text': return ( <TextBlock { ...blockProps } onInput={ this.handleTextBlockInput } shouldAutofocus={ this.shouldAutofocus() } /> ) default: return null } } isElementInViewport(el, topOffset = 0) { const rect = el.getBoundingClientRect() return ( rect.top >= topOffset && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ) } scrollToLastTextBlock() { const { editorId, isNavbarHidden } = this.props const textBlocks = document.querySelectorAll(`[data-editor-id='${editorId}'] div.text`) const lastTextBlock = textBlocks[textBlocks.length - 1] if (lastTextBlock && !this.isElementInViewport(lastTextBlock, isNavbarHidden ? 0 : 80)) { const pos = lastTextBlock.getBoundingClientRect() scrollToTop(window.scrollY + (pos.top - 100)) } } shouldAutofocus() { const { pathname, isComment } = this.props const postRegex = /^\/[\w\-]+\/post\/.+/ return !(isComment && postRegex.test(pathname)) } appendText = (content) => { const { dispatch, editorId } = this.props dispatch({ type: ACTION_TYPES.EDITOR.APPEND_TEXT, payload: { editorId, text: content } }) this.scrollToLastTextBlock() } remove = (uid) => { const { dispatch, editorId } = this.props dispatch(removeBlock(uid, editorId)) } handleTextBlockInput = (vo) => { const { dispatch, editorId } = this.props dispatch(updateBlock(vo, vo.uid, editorId)) } replyAll = () => { const { postId } = this.props if (!postId) { return } const nameArr = [] const usernames = document.querySelectorAll(`#Post_${postId} .CommentUsername`) for (const node of usernames) { if (nameArr.indexOf(node.innerHTML) === -1) { nameArr.push(node.innerHTML) } } if (nameArr.length) { this.appendText(`${nameArr.join(' ')} `) } } submit = () => { const { submitAction } = this.props const data = this.serialize() submitAction(data) } serialize() { const { collection, order } = this.props const results = [] for (const uid of order) { const block = collection[uid] switch (block.kind) { case 'text': if (block.data.length) { results.push({ kind: block.kind, data: block.data }) } break case 'repost': break default: results.push({ kind: block.kind, data: block.data }) break } } return results } handleFiles = (e) => { if (e.target.files.length) { this.acceptFiles(e.target.files) } } acceptFiles(files) { const { dispatch, editorId } = this.props for (let index = 0, len = files.length; index < len; index += 1) { // This guard may not be necessary if (files.item(index)) { // need to delay a bit or else the images clobber each other delay(dispatch, 100 * index, saveAsset(files[index], editorId)) } } } render() { const { avatar, cancelAction, collection, dragBlock, editorId, hasContent, hasMention, isComment, isLoading, isOwnPost, order, submitText } = this.props const { dragBlockTop, hasDragOver } = this.state const firstBlockIsText = collection[order[0]] ? collection[order[0]].kind === 'text' : true const showQuickEmoji = isComment && firstBlockIsText const editorClassNames = classNames('editor', { withQuickEmoji: showQuickEmoji, hasDragOver, hasMention, hasContent, isComment, isLoading, }) return ( <div className={ editorClassNames } data-placeholder="Say Ello..." onDragLeave={ this.onDragLeave } onDragOver={ this.onDragOver } onDrop={ this.onDrop } > { isComment ? <Avatar sources={ avatar } /> : null } <div className="editor-region" data-num-blocks={ order.length } > { order.map((uid) => this.getBlockElement(collection[uid])) } { dragBlock ? <div className="DragBlock" style={{ top: dragBlockTop }}> { this.getBlockElement(dragBlock) } </div> : null } </div> { showQuickEmoji ? <QuickEmoji onAddEmoji={ this.onInsertEmoji } /> : null } <PostActionBar cancelAction={ cancelAction } disableSubmitAction={ isLoading || !hasContent } editorId={ editorId } handleFileAction={ this.handleFiles } ref="postActionBar" replyAllAction={ isComment && isOwnPost ? this.replyAll : null } submitAction={ this.submit } submitText={ submitText } /> </div> ) } } function mapStateToProps(state, ownProps) { const editor = state.editor[ownProps.editorId] return { avatar: state.profile.avatar, collection: editor.collection, dragBlock: editor.dragBlock, hasContent: editor.hasContent, hasMention: editor.hasMention, isLoading: editor.isLoading, isNavbarHidden: state.gui.isNavbarHidden, order: editor.order, orderLength: editor.order.length, pathname: state.routing.location.pathname, postId: ownProps.post ? `${ownProps.post.id}` : null, } } export default connect(mapStateToProps, null, null, { withRef: true })(BlockCollection)
Don't include current user's name in reply all. [#118520581](https://www.pivotaltracker.com/story/show/118520581)
src/components/editor/BlockCollection.js
Don't include current user's name in reply all.
<ide><path>rc/components/editor/BlockCollection.js <ide> avatar: PropTypes.object, <ide> blocks: PropTypes.array, <ide> cancelAction: PropTypes.func.isRequired, <add> currentUsername: PropTypes.string, <ide> collection: PropTypes.object.isRequired, <ide> dispatch: PropTypes.func.isRequired, <ide> dragBlock: PropTypes.object, <ide> } <ide> <ide> replyAll = () => { <del> const { postId } = this.props <add> const { currentUsername, postId } = this.props <ide> if (!postId) { return } <ide> const nameArr = [] <ide> const usernames = document.querySelectorAll(`#Post_${postId} .CommentUsername`) <ide> for (const node of usernames) { <del> if (nameArr.indexOf(node.innerHTML) === -1) { <add> if (nameArr.indexOf(node.innerHTML) === -1 && node.innerHTML !== `@${currentUsername}`) { <ide> nameArr.push(node.innerHTML) <ide> } <ide> } <ide> return { <ide> avatar: state.profile.avatar, <ide> collection: editor.collection, <add> currentUsername: state.profile.username, <ide> dragBlock: editor.dragBlock, <ide> hasContent: editor.hasContent, <ide> hasMention: editor.hasMention,
Java
apache-2.0
0a2ae87e449210ff31bdeda3d02c368447202867
0
elunez/eladmin
package me.zhengjie.service.impl; import cn.hutool.extra.mail.Mail; import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailUtil; import me.zhengjie.domain.EmailConfig; import me.zhengjie.domain.vo.EmailVo; import me.zhengjie.exception.BadRequestException; import me.zhengjie.repository.EmailRepository; import me.zhengjie.service.EmailService; import me.zhengjie.utils.ElAdminConstant; import me.zhengjie.utils.EncryptUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; /** * @author Zheng Jie * @date 2018-12-26 */ @Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class EmailServiceImpl implements EmailService { @Autowired private EmailRepository emailRepository; @Override @Transactional(rollbackFor = Exception.class) public EmailConfig update(EmailConfig emailConfig, EmailConfig old) { try { if(!emailConfig.getPass().equals(old.getPass())){ // 对称加密 emailConfig.setPass(EncryptUtils.desEncrypt(emailConfig.getPass())); } } catch (Exception e) { e.printStackTrace(); } return emailRepository.save(emailConfig); } @Override public EmailConfig find() { Optional<EmailConfig> emailConfig = emailRepository.findById(1L); if(emailConfig.isPresent()){ return emailConfig.get(); } else { return new EmailConfig(); } } @Override @Transactional(rollbackFor = Exception.class) public void send(EmailVo emailVo, EmailConfig emailConfig){ if(emailConfig == null){ throw new BadRequestException("请先配置,再操作"); } /** * 封装 */ MailAccount account = new MailAccount(); account.setHost(emailConfig.getHost()); account.setPort(Integer.parseInt(emailConfig.getPort())); account.setAuth(true); try { // 对称解密 account.setPass(EncryptUtils.desDecrypt(emailConfig.getPass())); } catch (Exception e) { throw new BadRequestException(e.getMessage()); } account.setFrom(emailConfig.getUser()+"<"+emailConfig.getFromUser()+">"); //ssl方式发送 account.setSslEnable(true); String content = emailVo.getContent(); /** * 发送 */ try { Mail.create(account) .setTos(emailVo.getTos().toArray(new String[emailVo.getTos().size()])) .setTitle(emailVo.getSubject()) .setContent(content) .setHtml(true) //关闭session .setUseGlobalSession(false) .send(); }catch (Exception e){ throw new BadRequestException(e.getMessage()); } } }
eladmin-tools/src/main/java/me/zhengjie/service/impl/EmailServiceImpl.java
package me.zhengjie.service.impl; import cn.hutool.extra.mail.Mail; import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailUtil; import me.zhengjie.domain.EmailConfig; import me.zhengjie.domain.vo.EmailVo; import me.zhengjie.exception.BadRequestException; import me.zhengjie.repository.EmailRepository; import me.zhengjie.service.EmailService; import me.zhengjie.utils.ElAdminConstant; import me.zhengjie.utils.EncryptUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; /** * @author Zheng Jie * @date 2018-12-26 */ @Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class EmailServiceImpl implements EmailService { @Autowired private EmailRepository emailRepository; @Override @Transactional(rollbackFor = Exception.class) public EmailConfig update(EmailConfig emailConfig, EmailConfig old) { try { if(!emailConfig.getPass().equals(old.getPass())){ // 对称加密 emailConfig.setPass(EncryptUtils.desEncrypt(emailConfig.getPass())); } } catch (Exception e) { e.printStackTrace(); } return emailRepository.save(emailConfig); } @Override public EmailConfig find() { Optional<EmailConfig> emailConfig = emailRepository.findById(1L); if(emailConfig.isPresent()){ return emailConfig.get(); } else { return new EmailConfig(); } } @Override @Transactional(rollbackFor = Exception.class) public void send(EmailVo emailVo, EmailConfig emailConfig){ if(emailConfig == null){ throw new BadRequestException("请先配置,再操作"); } /** * 封装 */ MailAccount account = new MailAccount(); account.setHost(emailConfig.getHost()); account.setPort(Integer.parseInt(emailConfig.getPort())); account.setAuth(true); try { // 对称解密 account.setPass(EncryptUtils.desDecrypt(emailConfig.getPass())); } catch (Exception e) { throw new BadRequestException(e.getMessage()); } account.setFrom(emailConfig.getUser()+"<"+emailConfig.getFromUser()+">"); //ssl方式发送 account.setStartttlsEnable(true); String content = emailVo.getContent(); /** * 发送 */ try { Mail.create(account) .setTos(emailVo.getTos().toArray(new String[emailVo.getTos().size()])) .setTitle(emailVo.getSubject()) .setContent(content) .setHtml(true) //关闭session .setUseGlobalSession(false) .send(); }catch (Exception e){ throw new BadRequestException(e.getMessage()); } } }
EmailService
eladmin-tools/src/main/java/me/zhengjie/service/impl/EmailServiceImpl.java
EmailService
<ide><path>ladmin-tools/src/main/java/me/zhengjie/service/impl/EmailServiceImpl.java <ide> } <ide> account.setFrom(emailConfig.getUser()+"<"+emailConfig.getFromUser()+">"); <ide> //ssl方式发送 <del> account.setStartttlsEnable(true); <add> account.setSslEnable(true); <ide> String content = emailVo.getContent(); <ide> /** <ide> * 发送
Java
apache-2.0
1e1b1b7694c09e8213c4d824389a08b56c44ffa4
0
masm11/contextplayer,masm11/contextplayer,masm11/contextplayer
package jp.ddo.masm11.cplayer; import android.app.Service; import android.media.MediaPlayer; import android.net.Uri; import android.content.Intent; import android.os.IBinder; import java.io.File; import java.util.ArrayList; import java.util.Collections; public class PlayerService extends Service { private String topDir; private String playingPath, nextPath; private MediaPlayer curPlayer, nextPlayer; @Override public void onCreate() { topDir = "/sdcard/Music"; } @Override public int onStartCommand(Intent intent, int flags, int startId) { String action = intent != null ? intent.getAction() : null; if (action != null) { String path; int ctxt; switch (action) { case "PLAY": path = intent.getStringExtra("path"); if (path == null) break; play(path); enqueueNext(); break; case "SET_TOPDIR": path = intent.getStringExtra("path"); if (path == null) break; // setTopDir(path); break; } } return START_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } private void play(String path) { android.util.Log.i("PlayerService", "path=" + path); playingPath = path; try { if (curPlayer != null) { curPlayer.release(); curPlayer = null; } if (nextPlayer != null) { nextPlayer.release(); nextPlayer = null; } curPlayer = MediaPlayer.create(this, Uri.parse("file://" + playingPath)); curPlayer.start(); } catch (Exception e) { android.util.Log.e("cplayer", "exception", e); } } private void enqueueNext() { nextPath = selectNext(); android.util.Log.i("PlayerService", "nextPath=" + nextPath); nextPlayer = MediaPlayer.create(this, Uri.parse("file://" + nextPath)); curPlayer.setNextMediaPlayer(nextPlayer); } private String selectNext() { // fixme: もちっと効率良く。 ArrayList<String> list = new ArrayList<>(); scan(new File(topDir), list); Collections.sort(list); for (String path: list) { if (path.compareTo(playingPath) > 0) return path; } try { // loop. return list.get(0); } catch (IndexOutOfBoundsException e) { // ファイルが一つも見つからなかった。 return null; } } private void scan(File dir, ArrayList<String> scanResult) { for (File file: dir.listFiles()) { if (file.isDirectory()) scan(file, scanResult); else scanResult.add(file.getAbsolutePath()); } } }
app/src/main/java/jp/ddo/masm11/cplayer/PlayerService.java
package jp.ddo.masm11.cplayer; import android.app.Service; import android.media.MediaPlayer; import android.net.Uri; import android.content.Intent; import android.os.IBinder; public class PlayerService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { String action = intent != null ? intent.getAction() : null; if (action != null) { String path; int ctxt; switch (action) { case "PLAY": path = intent.getStringExtra("path"); if (path == null) break; play(path); break; case "SET_TOPDIR": path = intent.getStringExtra("path"); if (path == null) break; // setTopDir(path); break; case "SWITCH": ctxt = intent.getIntExtra("context", -1); if (ctxt == -1) break; } } return START_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } private void play(String path) { android.util.Log.i("PlayerService", "path=" + path); try { MediaPlayer mp; mp = MediaPlayer.create(this, Uri.parse("file://" + path)); mp.start(); // mp.setNextMediaPlayer(mp2); } catch (Exception e) { android.util.Log.e("cplayer", "exception", e); } } }
次の曲を enqueue するようにした。 ただしまだ1曲だけ。
app/src/main/java/jp/ddo/masm11/cplayer/PlayerService.java
次の曲を enqueue するようにした。
<ide><path>pp/src/main/java/jp/ddo/masm11/cplayer/PlayerService.java <ide> import android.content.Intent; <ide> import android.os.IBinder; <ide> <add>import java.io.File; <add>import java.util.ArrayList; <add>import java.util.Collections; <add> <ide> public class PlayerService extends Service { <add> private String topDir; <add> private String playingPath, nextPath; <add> private MediaPlayer curPlayer, nextPlayer; <add> <add> @Override <add> public void onCreate() { <add> topDir = "/sdcard/Music"; <add> } <ide> <ide> @Override <ide> public int onStartCommand(Intent intent, int flags, int startId) { <ide> if (path == null) <ide> break; <ide> play(path); <add> enqueueNext(); <ide> break; <ide> <ide> case "SET_TOPDIR": <ide> break; <ide> // setTopDir(path); <ide> break; <del> <del> case "SWITCH": <del> ctxt = intent.getIntExtra("context", -1); <del> if (ctxt == -1) <del> break; <ide> } <ide> } <ide> return START_STICKY; <ide> <ide> private void play(String path) { <ide> android.util.Log.i("PlayerService", "path=" + path); <add> playingPath = path; <ide> <ide> try { <del> MediaPlayer mp; <del> mp = MediaPlayer.create(this, Uri.parse("file://" + path)); <del> mp.start(); <del> // mp.setNextMediaPlayer(mp2); <add> if (curPlayer != null) { <add> curPlayer.release(); <add> curPlayer = null; <add> } <add> if (nextPlayer != null) { <add> nextPlayer.release(); <add> nextPlayer = null; <add> } <add> <add> curPlayer = MediaPlayer.create(this, Uri.parse("file://" + playingPath)); <add> curPlayer.start(); <ide> } catch (Exception e) { <ide> android.util.Log.e("cplayer", "exception", e); <ide> } <ide> } <add> <add> private void enqueueNext() { <add> nextPath = selectNext(); <add> android.util.Log.i("PlayerService", "nextPath=" + nextPath); <add> nextPlayer = MediaPlayer.create(this, Uri.parse("file://" + nextPath)); <add> curPlayer.setNextMediaPlayer(nextPlayer); <add> } <add> <add> private String selectNext() { <add> // fixme: もちっと効率良く。 <add> ArrayList<String> list = new ArrayList<>(); <add> scan(new File(topDir), list); <add> Collections.sort(list); <add> for (String path: list) { <add> if (path.compareTo(playingPath) > 0) <add> return path; <add> } <add> try { <add> // loop. <add> return list.get(0); <add> } catch (IndexOutOfBoundsException e) { <add> // ファイルが一つも見つからなかった。 <add> return null; <add> } <add> } <add> <add> private void scan(File dir, ArrayList<String> scanResult) { <add> for (File file: dir.listFiles()) { <add> if (file.isDirectory()) <add> scan(file, scanResult); <add> else <add> scanResult.add(file.getAbsolutePath()); <add> } <add> } <ide> }
Java
apache-2.0
79a0cd2323454be656dd2404688111a0b3ae2772
0
kdbanman/nodes
package nodes; import java.util.HashMap; import java.util.ArrayList; import com.hp.hpl.jena.rdf.model.*; import controlP5.ControlP5; import controlP5.ControlWindow; import controlP5.ControllerGroup; import controlP5.Tab; import java.util.Collection; import java.util.Comparator; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Set; import processing.core.PApplet; import processing.core.PFont; import processing.core.PVector; /** * * @author kdbanman */ public class Graph implements Iterable<GraphElement> { UnProjector proj; ControlP5 cp5; Nodes pApp; ControllerGroup graphElementGroup; private static final String FONTRESOURCE = "resources/labelFont.ttf"; private Selection selection; private Model triples; private Model allPreviouslyAddedTriples; private int nodeCount; private int edgeCount; private float initPositionSparsity; // adjacent maps node ids (uris and literal values) to lists of node ids // NOTE: it's formally redundant to include a set of edges along with // an adjacency list, but it's definitely convenient private HashMap<Node, ArrayList<Node>> adjacent; private HashSet<Edge> edges; private HashMap<Integer, PFont> fonts; Graph(UnProjector u, Nodes p) { proj = u; pApp = p; cp5 = new ControlP5(p) .setMoveable(false); cp5.disableShortcuts(); graphElementGroup = new DepthSortedGroup(cp5, "GraphElementGroup") .open(); selection = new Selection(); triples = ModelFactory.createDefaultModel(); nodeCount = 0; edgeCount = 0; initPositionSparsity = 10e7f; adjacent = new HashMap<>(); edges = new HashSet<>(); fonts = new HashMap<>(); } public PriorityQueue<GraphElement> getDistanceSortedGraphElements() { Collection<GraphElement> elements = cp5.getAll(GraphElement.class); PriorityQueue<GraphElement> sorted = new PriorityQueue(100, new Comparator<GraphElement>() { PVector referencePoint = pApp.getCamPosition(); @Override public int compare(GraphElement e1, GraphElement e2) { if (e1 == e2) return 0; float e1Dist = referencePoint.dist(e1.getPosition()); float e2Dist = referencePoint.dist(e2.getPosition()); // order is swapped to prioritize furthest elements return Float.compare(e2Dist, e1Dist); } }); for (GraphElement e : elements) { sorted.offer(e); } return sorted; } /** * iterative force-directed layout algorithm. one layout() call is one iteration. */ public void layout() { // initialize map of changes in node positions HashMap<Node, PVector> deltas = new HashMap<>(); for (Node node : adjacent.keySet()) { deltas.put(node, new PVector(0, 0, 0)); } // repulsive force between nodes float coulomb = 15000; // attractive force between connected nodes float hooke = .1f; // gravitational force to camera center float gravity = .5f; // base of damping logarithm. higher => less jitter, slower stabilization float saturationLogBase = 10f; // calculate position delta for each node for (Node n : adjacent.keySet()) { PVector delta = deltas.get(n); PVector nodePos = n.getPosition(); // add attractive force movement from neighbors for (Node nbr : adjacent.get(n)) { PVector diff = nbr.getPosition().get(); diff.sub(nodePos); float dist = diff.mag(); diff.normalize(); diff.mult(hooke * Nodes.sq(dist)); delta.add(diff); } // add repulsive force movement from all other nodes for (Node other : adjacent.keySet()) { if (!other.equals(n)) { float degreeScale = (float) (getDegree(other) * getDegree(other)); PVector diff = other.getPosition().get(); diff.sub(nodePos); float dist = diff.mag(); diff.normalize(); diff.mult(degreeScale * coulomb / (dist * dist)); delta.sub(diff); } } // add gravitational force from camera centre PVector diff = new PVector(0, 0, 0); diff.sub(nodePos); float dist = diff.mag(); diff.normalize(); diff.mult(gravity * dist); delta.add(diff); } // apply damping and set new positions for (Node node : adjacent.keySet()) { //apply saturation damping to delta PVector delta = deltas.get(node); float mag = delta.mag(); delta.limit(Nodes.log(mag) / Nodes.log(saturationLogBase)); // apply delta to position PVector pos = node.getPosition(); pos.add(delta); } } /* * adds triples to model, adding Nodes and Edges as necessary */ public void addTriples(Model toAdd) { // triples to be added are now the most recently added triples allPreviouslyAddedTriples = toAdd; // add yet undiscovered namespace prefixes to the model triples.withDefaultMappings(toAdd); // add each triple in the model to the graph StmtIterator it = toAdd.listStatements(); if (it.hasNext()) { // stop ControlP5 from doing stuff for possible concurrency issues cp5.setAutoDraw(false); while (it.hasNext()) { Statement s = it.nextStatement(); addTriple(s); } // begin rendering again cp5.setAutoDraw(true); } else { Nodes.println("Empty query result - no triples to add."); } } public Model getRenderedTriples() { return triples; } public Model getAllPreviouslyAddedTriples() { return allPreviouslyAddedTriples; } public Selection getSelection() { return selection; } public Resource getResource(String uri) { return triples.getResource(uri); } /** * * @param uri * @return namespace prefixed version of uri. * Example: http://www.w3.org/1999/02/22-rdf-syntax-ns#type --> rdf:type */ public String prefixed(String uri) { return triples.shortForm(uri); } public String expanded(String prefixed) { return triples.expandPrefix(prefixed); } public String prefix(String uri) { return triples.getNsURIPrefix(uri); } public String prefixURI(String uri) { return triples.getNsPrefixURI(uri); } /** * Creates a copy of the passed Statement with the Graph's model "triples", * adds the copy to "triples", adds the copy to the correct Edge (either by * adding it to an existing edge or creating a new one), and returns the copy. * * @param triple Statement to add to the Graph * @return Statement originating from the Graph's model */ public Statement addTriple(Statement triple) { String sub = triple.getSubject().toString(); String obj = triple.getObject().toString(); Edge e; // addNode just returns the existing Node if a new one need not be created addNode(sub); addNode(obj); // addEdge returns the existing edge if one already exists between the two nodes // note: node order does not matter. e = addEdge(sub, obj); // create the triple using the Graph's model so that Statement.getModel() // works as expected Statement tripleToAdd = triples.createStatement(triple.getSubject(), triple.getPredicate(), triple.getObject()); // add the created triple to the model triples.add(tripleToAdd); // associate the triple with the edge e.addTriple(tripleToAdd); return tripleToAdd; } public Set<Node> getNodes() { return adjacent.keySet(); } public Set<Edge> getEdges() { return edges; } public int nodeCount() { return nodeCount; } public int edgeCount() { return edgeCount; } public int tripleCount() { long size = triples.size(); //DEBUG: jena models return their size as doubles... never forget. ugh //System.out.println(size + "\n" + (int) size); return (int) size; } @Override public GraphIterator iterator() { return new GraphIterator(); } /** * returns null if node nonexistent */ public ArrayList<Node> getNbrs(String id) { return adjacent.get((Node) cp5.getController(id)); } /** * returns null if node nonexistent */ @SuppressWarnings("unchecked") public ArrayList<Node> getNbrs(Node n) { return (ArrayList<Node>) adjacent.get(n).clone(); } /** * Given two nodes this will return the common neighbours that they share * @param a node * @param b node * @return list of common neighbours */ public ArrayList<Node> getCommonNbrs(Node a, Node b) { if(a == null || b == null) return (ArrayList<Node>) Collections.<Node>emptyList(); ArrayList<Node> rtn = getNbrs(a); rtn.retainAll(getNbrs(b)); return rtn; } /** * return node's degree for view graph, not for the relational graph */ public int getDegree(String id) { return getNbrs(id).size(); } public int getDegree(Node n) { return getNbrs(n).size(); } /* * to be called by addTriple. affects cp5, nodeCount, and adjacent iff the * node is new. a new entry in adjacent will map to an empty ArrayList since * no edges may exist yet. * * returns the new node or the existing node. */ private Node addNode(String id) { // ControlP5's source has been checked, this should be reliable and fast Node n = (Node) cp5.getController(id); if (n != null) { return n; } else { // set random initial position within reasonable boundary. // (cube root for volume) float initBoundary = Nodes.pow((float) nodeCount, 0.333f) * initPositionSparsity; initBoundary = Nodes.min(initBoundary, 300); n = new Node(this, id) .setPosition(pApp.random(-initBoundary, initBoundary), pApp.random(-initBoundary, initBoundary), pApp.random(-initBoundary, initBoundary)) .setSize(10) .setGroup(graphElementGroup); adjacent.put(n, new ArrayList<Node>()); nodeCount += 1; return n; } } /** * to be called by addTriple, both nodes must exist. affects cp5, edgeCount, * and adjacent iff the edge is new. * * returns the new edge or the existing edge. */ private Edge addEdge(String s, String d) { Node src = (Node) cp5.getController(s); Node dst = (Node) cp5.getController(d); // make sure the nodes exist if (src == null || dst == null) { printNullEdgeTargets(s, d, src, dst); } if (adjacent.get(src).contains(dst)) { return getEdge(s, d); } else { Edge e = new Edge(this, s + "|" + d, src, dst) .setSize(5) .setGroup(graphElementGroup); adjacent.get(src).add(dst); adjacent.get(dst).add(src); edges.add(e); edgeCount += 1; return e; } } private Edge addEdge(Node s, Node d) { return addEdge(s.getName(), d.getName()); } /** * returns true if successful, false otherwise. removes all connected edges. */ public boolean removeNode(String id) { Node n = (Node) cp5.getController(id); if (n == null) { System.out.println("ERROR: Cannot remove nonexistent node\n" + id); return false; } // removing all connected edges will leave this node as a singleton, // so removeEdge will remove the node on its last call. // a copy of the adjacency list is iterated through so that the original // may be modified during iteration (within removeEdge() call). // NOTE: the nbr Nodes are copied, then the copies are used to call the // removal method. this only works because the removeEdge(Node, Node) // method is just a wrapper for removeEdge(String, String), which // uses String names, not object references. boolean success = false; ArrayList<Node> adjCopy = new ArrayList<>(getNbrs(n)); for (Node nbr : adjCopy) { success = removeEdge(n, nbr); } return success; } public boolean removeNode(Node n) { return removeNode(n.getName()); } /** * returns true if successful, false otherwise. succeeds iff given src and * dst nodes exist and edge exists between them. */ public boolean removeEdge(String s, String d) { Node src = (Node) cp5.getController(s); Node dst = (Node) cp5.getController(d); if (src == null || dst == null) { printNullEdgeTargets(s, d, src, dst); return false; } else if (!adjacent.get(src).contains(dst)) { Nodes.println("ERROR: Cannot remove nonexistent edge between:\n" + s + "\n" + d); return false; } else { Edge e = getEdge(s, d); // remove edge from selection selection.remove(e); // remove triples from the model for (Statement stmt : e.getTriples()) { triples.remove(stmt); } // remove controller edges.remove(e); e.remove(); // adjust adjacency list and size adjacent.get(src).remove(dst); adjacent.get(dst).remove(src); edgeCount -= 1; // test if src or dst are singleton, remove if so if (adjacent.get(src).isEmpty()) { adjacent.remove(src); selection.remove(src); selection.removeFromBuffer(src); src.remove(); } if (adjacent.get(dst).isEmpty()) { adjacent.remove(dst); selection.remove(dst); selection.removeFromBuffer(dst); dst.remove(); } return true; } } public boolean removeEdge(Node s, Node d) { return removeEdge(s.getName(), d.getName()); } public boolean removeEdge(Edge e) { return removeEdge(e.getSourceNode(), e.getDestinationNode()); } /** * * @param n string id of node to be retrieved * @return Node referred to by string parameter. Returns null if the passed * uri identifies either an Edge or nothing at all. */ public Node getNode(String n) { Node ret; try { ret = (Node) cp5.getController(n); } catch (ClassCastException e) { ret = null; } return ret; } /** * returns the existing edge between s and d. order of s and d are actually * irrelevant, the correct edge will be retrieved. returns null if there is * no edge between the passed node ids, or if one of the passed node ids * doesn't actually identify a node. * @param s id of source node * @param d id of destination node * @return Edge between nodes, or null if nonexistent */ public Edge getEdge(String s, String d) { Edge e = (Edge) cp5.getController(s + "|" + d); if (e == null) { e = (Edge) cp5.getController(d + "|" + s); } if (e == null) { Nodes.println("Edge connecting\n" + s + "\nand\n" + d + "\nnot found."); } return e; } public Edge getEdge(Node s, Node d) { return getEdge(s.getName(), d.getName()); } /** * prints error message for edge creation between nonexistent nodes. */ private void printNullEdgeTargets(String s, String d, Node src, Node dst) { Nodes.println("ERROR: Edge cannot be retrieved between \n\t" + s + "\nand \nt" + d); String problem = (src == null) ? s : d; Nodes.println("\n" + problem + "\n doesn't exist as Node."); } /** * To avoid duplication of font object creations this method will return a font object for a specific * size or create a new font element if it doesn't exists * @param size size of font > 0 * @return font element NULL if invalid size */ public PFont getFontBySize(int size) { if(size <= 0) return null; if(fonts.containsKey(size)) return fonts.get(size); PFont font = cp5.getFont().getFont(); try { font = pApp.createFont(FONTRESOURCE, size); } catch(Exception e) { System.out.println("ERROR: font not loaded. ensure " + FONTRESOURCE + " is in program directory."); } return font; } /** * iterates through all nodes then all edges */ public class GraphIterator implements Iterator<GraphElement> { Iterator itNodes; Iterator itEdges; public GraphIterator() { itNodes = getNodes().iterator(); itEdges = getEdges().iterator(); } @Override public boolean hasNext() { return itNodes.hasNext() || itEdges.hasNext(); } @Override public GraphElement next() { GraphElement ret = null; if (itNodes.hasNext()) ret = (GraphElement) itNodes.next(); else if (itEdges.hasNext()) ret = (GraphElement) itEdges.next(); else throw new NoSuchElementException(); return ret; } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } /** * DepthSortedTab is meant to hold GraphElements only. The point of it is to * override the drawControllers() method so that the order in which the * elements are rendered can be controlled. It renders whether or not it * is open (see ControllerGroup.drawControllers() for context). */ private final class DepthSortedGroup extends ControllerGroup<DepthSortedGroup> { public DepthSortedGroup(ControlP5 theControlP5, String theName) { super(theControlP5, theName); } @Override public void drawControllers(PApplet theApplet) { // draw graph in order of depth PriorityQueue<GraphElement> elementQueue = getDistanceSortedGraphElements(); while (!elementQueue.isEmpty()) { GraphElement currentElement = elementQueue.poll(); currentElement.updateInternalEvents(pApp); currentElement.draw(pApp); } } } }
src/nodes/Graph.java
package nodes; import java.util.HashMap; import java.util.ArrayList; import com.hp.hpl.jena.rdf.model.*; import controlP5.ControlP5; import controlP5.ControlWindow; import controlP5.ControllerGroup; import controlP5.Tab; import java.util.Collection; import java.util.Comparator; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Set; import processing.core.PApplet; import processing.core.PFont; import processing.core.PVector; /** * * @author kdbanman */ public class Graph implements Iterable<GraphElement> { UnProjector proj; ControlP5 cp5; Nodes pApp; ControllerGroup graphElementGroup; private static final String FONTRESOURCE = "resources/labelFont.ttf"; private Selection selection; private Model triples; private Model allPreviouslyAddedTriples; private int nodeCount; private int edgeCount; private float initPositionSparsity; // adjacent maps node ids (uris and literal values) to lists of node ids // NOTE: it's formally redundant to include a set of edges along with // an adjacency list, but it's definitely convenient private HashMap<Node, ArrayList<Node>> adjacent; private HashSet<Edge> edges; private HashMap<Integer, PFont> fonts; Graph(UnProjector u, Nodes p) { proj = u; pApp = p; cp5 = new ControlP5(p) .setMoveable(false); cp5.disableShortcuts(); graphElementGroup = new DepthSortedGroup(cp5, "GraphElementGroup") .open(); selection = new Selection(); triples = ModelFactory.createDefaultModel(); nodeCount = 0; edgeCount = 0; initPositionSparsity = 10e7f; adjacent = new HashMap<>(); edges = new HashSet<>(); fonts = new HashMap<>(); } public PriorityQueue<GraphElement> getDistanceSortedGraphElements() { Collection<GraphElement> elements = cp5.getAll(GraphElement.class); PriorityQueue<GraphElement> sorted = new PriorityQueue(100, new Comparator<GraphElement>() { PVector referencePoint = pApp.getCamPosition(); @Override public int compare(GraphElement e1, GraphElement e2) { if (e1 == e2) return 0; float e1Dist = referencePoint.dist(e1.getPosition()); float e2Dist = referencePoint.dist(e2.getPosition()); // order is swapped to prioritize furthest elements return Float.compare(e2Dist, e1Dist); } }); for (GraphElement e : elements) { sorted.offer(e); } return sorted; } /** * iterative force-directed layout algorithm. one layout() call is one iteration. */ public void layout() { // initialize map of changes in node positions HashMap<Node, PVector> deltas = new HashMap<>(); for (Node node : adjacent.keySet()) { deltas.put(node, new PVector(0, 0, 0)); } // repulsive force between nodes float coulomb = 15000; // attractive force between connected nodes float hooke = .1f; // gravitational force to camera center float gravity = .5f; // base of damping logarithm. higher => less jitter, slower stabilization float saturationLogBase = 10f; // calculate position delta for each node for (Node n : adjacent.keySet()) { PVector delta = deltas.get(n); PVector nodePos = n.getPosition(); // add attractive force movement from neighbors for (Node nbr : adjacent.get(n)) { PVector diff = nbr.getPosition().get(); diff.sub(nodePos); float dist = diff.mag(); diff.normalize(); diff.mult(hooke * Nodes.sq(dist)); delta.add(diff); } // add repulsive force movement from all other nodes for (Node other : adjacent.keySet()) { if (!other.equals(n)) { float degreeScale = (float) (getDegree(other) * getDegree(other)); PVector diff = other.getPosition().get(); diff.sub(nodePos); float dist = diff.mag(); diff.normalize(); diff.mult(degreeScale * coulomb / (dist * dist)); delta.sub(diff); } } // add gravitational force from camera centre PVector diff = new PVector(0, 0, 0); diff.sub(nodePos); float dist = diff.mag(); diff.normalize(); diff.mult(gravity * dist); delta.add(diff); } // apply damping and set new positions for (Node node : adjacent.keySet()) { //apply saturation damping to delta PVector delta = deltas.get(node); float mag = delta.mag(); delta.limit(Nodes.log(mag) / Nodes.log(saturationLogBase)); // apply delta to position PVector pos = node.getPosition(); pos.add(delta); } } /* * adds triples to model, adding Nodes and Edges as necessary */ public void addTriples(Model toAdd) { // triples to be added are now the most recently added triples allPreviouslyAddedTriples = toAdd; // add yet undiscovered namespace prefixes to the model triples.withDefaultMappings(toAdd); // add each triple in the model to the graph StmtIterator it = toAdd.listStatements(); if (it.hasNext()) { // stop ControlP5 from doing stuff for possible concurrency issues cp5.setAutoDraw(false); while (it.hasNext()) { Statement s = it.nextStatement(); addTriple(s); } // begin rendering again cp5.setAutoDraw(true); } else { Nodes.println("Empty query result - no triples to add."); } } public Model getRenderedTriples() { return triples; } public Model getAllPreviouslyAddedTriples() { return allPreviouslyAddedTriples; } public Selection getSelection() { return selection; } public Resource getResource(String uri) { return triples.getResource(uri); } public String prefixed(String uri) { return triples.shortForm(uri); } public String expanded(String prefixed) { return triples.expandPrefix(prefixed); } public String prefix(String uri) { return triples.getNsURIPrefix(uri); } public String prefixURI(String uri) { return triples.getNsPrefixURI(uri); } /** * Creates a copy of the passed Statement with the Graph's model "triples", * adds the copy to "triples", adds the copy to the correct Edge (either by * adding it to an existing edge or creating a new one), and returns the copy. * * @param triple Statement to add to the Graph * @return Statement originating from the Graph's model */ public Statement addTriple(Statement triple) { String sub = triple.getSubject().toString(); String obj = triple.getObject().toString(); Edge e; // addNode just returns the existing Node if a new one need not be created addNode(sub); addNode(obj); // addEdge returns the existing edge if one already exists between the two nodes // note: node order does not matter. e = addEdge(sub, obj); // create the triple using the Graph's model so that Statement.getModel() // works as expected Statement tripleToAdd = triples.createStatement(triple.getSubject(), triple.getPredicate(), triple.getObject()); // add the created triple to the model triples.add(tripleToAdd); // associate the triple with the edge e.addTriple(tripleToAdd); return tripleToAdd; } public Set<Node> getNodes() { return adjacent.keySet(); } public Set<Edge> getEdges() { return edges; } public int nodeCount() { return nodeCount; } public int edgeCount() { return edgeCount; } public int tripleCount() { long size = triples.size(); //DEBUG: jena models return their size as doubles... never forget. ugh //System.out.println(size + "\n" + (int) size); return (int) size; } @Override public GraphIterator iterator() { return new GraphIterator(); } /** * returns null if node nonexistent */ public ArrayList<Node> getNbrs(String id) { return adjacent.get((Node) cp5.getController(id)); } /** * returns null if node nonexistent */ @SuppressWarnings("unchecked") public ArrayList<Node> getNbrs(Node n) { return (ArrayList<Node>) adjacent.get(n).clone(); } /** * Given two nodes this will return the common neighbours that they share * @param a node * @param b node * @return list of common neighbours */ public ArrayList<Node> getCommonNbrs(Node a, Node b) { if(a == null || b == null) return (ArrayList<Node>) Collections.<Node>emptyList(); ArrayList<Node> rtn = getNbrs(a); rtn.retainAll(getNbrs(b)); return rtn; } /** * return node's degree for view graph, not for the relational graph */ public int getDegree(String id) { return getNbrs(id).size(); } public int getDegree(Node n) { return getNbrs(n).size(); } /* * to be called by addTriple. affects cp5, nodeCount, and adjacent iff the * node is new. a new entry in adjacent will map to an empty ArrayList since * no edges may exist yet. * * returns the new node or the existing node. */ private Node addNode(String id) { // ControlP5's source has been checked, this should be reliable and fast Node n = (Node) cp5.getController(id); if (n != null) { return n; } else { // set random initial position within reasonable boundary. // (cube root for volume) float initBoundary = Nodes.pow((float) nodeCount, 0.333f) * initPositionSparsity; initBoundary = Nodes.min(initBoundary, 300); n = new Node(this, id) .setPosition(pApp.random(-initBoundary, initBoundary), pApp.random(-initBoundary, initBoundary), pApp.random(-initBoundary, initBoundary)) .setSize(10) .setGroup(graphElementGroup); adjacent.put(n, new ArrayList<Node>()); nodeCount += 1; return n; } } /** * to be called by addTriple, both nodes must exist. affects cp5, edgeCount, * and adjacent iff the edge is new. * * returns the new edge or the existing edge. */ private Edge addEdge(String s, String d) { Node src = (Node) cp5.getController(s); Node dst = (Node) cp5.getController(d); // make sure the nodes exist if (src == null || dst == null) { printNullEdgeTargets(s, d, src, dst); } if (adjacent.get(src).contains(dst)) { return getEdge(s, d); } else { Edge e = new Edge(this, s + "|" + d, src, dst) .setSize(5) .setGroup(graphElementGroup); adjacent.get(src).add(dst); adjacent.get(dst).add(src); edges.add(e); edgeCount += 1; return e; } } private Edge addEdge(Node s, Node d) { return addEdge(s.getName(), d.getName()); } /** * returns true if successful, false otherwise. removes all connected edges. */ public boolean removeNode(String id) { Node n = (Node) cp5.getController(id); if (n == null) { System.out.println("ERROR: Cannot remove nonexistent node\n" + id); return false; } // removing all connected edges will leave this node as a singleton, // so removeEdge will remove the node on its last call. // a copy of the adjacency list is iterated through so that the original // may be modified during iteration (within removeEdge() call). // NOTE: the nbr Nodes are copied, then the copies are used to call the // removal method. this only works because the removeEdge(Node, Node) // method is just a wrapper for removeEdge(String, String), which // uses String names, not object references. boolean success = false; ArrayList<Node> adjCopy = new ArrayList<>(getNbrs(n)); for (Node nbr : adjCopy) { success = removeEdge(n, nbr); } return success; } public boolean removeNode(Node n) { return removeNode(n.getName()); } /** * returns true if successful, false otherwise. succeeds iff given src and * dst nodes exist and edge exists between them. */ public boolean removeEdge(String s, String d) { Node src = (Node) cp5.getController(s); Node dst = (Node) cp5.getController(d); if (src == null || dst == null) { printNullEdgeTargets(s, d, src, dst); return false; } else if (!adjacent.get(src).contains(dst)) { Nodes.println("ERROR: Cannot remove nonexistent edge between:\n" + s + "\n" + d); return false; } else { Edge e = getEdge(s, d); // remove edge from selection selection.remove(e); // remove triples from the model for (Statement stmt : e.getTriples()) { triples.remove(stmt); } // remove controller edges.remove(e); e.remove(); // adjust adjacency list and size adjacent.get(src).remove(dst); adjacent.get(dst).remove(src); edgeCount -= 1; // test if src or dst are singleton, remove if so if (adjacent.get(src).isEmpty()) { adjacent.remove(src); selection.remove(src); selection.removeFromBuffer(src); src.remove(); } if (adjacent.get(dst).isEmpty()) { adjacent.remove(dst); selection.remove(dst); selection.removeFromBuffer(dst); dst.remove(); } return true; } } public boolean removeEdge(Node s, Node d) { return removeEdge(s.getName(), d.getName()); } public boolean removeEdge(Edge e) { return removeEdge(e.getSourceNode(), e.getDestinationNode()); } /** * * @param n string id of node to be retrieved * @return Node referred to by string parameter. Returns null if the passed * uri identifies either an Edge or nothing at all. */ public Node getNode(String n) { Node ret; try { ret = (Node) cp5.getController(n); } catch (ClassCastException e) { ret = null; } return ret; } /** * returns the existing edge between s and d. order of s and d are actually * irrelevant, the correct edge will be retrieved. returns null if there is * no edge between the passed node ids, or if one of the passed node ids * doesn't actually identify a node. * @param s id of source node * @param d id of destination node * @return Edge between nodes, or null if nonexistent */ public Edge getEdge(String s, String d) { Edge e = (Edge) cp5.getController(s + "|" + d); if (e == null) { e = (Edge) cp5.getController(d + "|" + s); } if (e == null) { Nodes.println("Edge connecting\n" + s + "\nand\n" + d + "\nnot found."); } return e; } public Edge getEdge(Node s, Node d) { return getEdge(s.getName(), d.getName()); } /** * prints error message for edge creation between nonexistent nodes. */ private void printNullEdgeTargets(String s, String d, Node src, Node dst) { Nodes.println("ERROR: Edge cannot be retrieved between \n\t" + s + "\nand \nt" + d); String problem = (src == null) ? s : d; Nodes.println("\n" + problem + "\n doesn't exist as Node."); } /** * To avoid duplication of font object creations this method will return a font object for a specific * size or create a new font element if it doesn't exists * @param size size of font > 0 * @return font element NULL if invalid size */ public PFont getFontBySize(int size) { if(size <= 0) return null; if(fonts.containsKey(size)) return fonts.get(size); PFont font = cp5.getFont().getFont(); try { font = pApp.createFont(FONTRESOURCE, size); } catch(Exception e) { System.out.println("ERROR: font not loaded. ensure " + FONTRESOURCE + " is in program directory."); } return font; } /** * iterates through all nodes then all edges */ public class GraphIterator implements Iterator<GraphElement> { Iterator itNodes; Iterator itEdges; public GraphIterator() { itNodes = getNodes().iterator(); itEdges = getEdges().iterator(); } @Override public boolean hasNext() { return itNodes.hasNext() || itEdges.hasNext(); } @Override public GraphElement next() { GraphElement ret = null; if (itNodes.hasNext()) ret = (GraphElement) itNodes.next(); else if (itEdges.hasNext()) ret = (GraphElement) itEdges.next(); else throw new NoSuchElementException(); return ret; } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } /** * DepthSortedTab is meant to hold GraphElements only. The point of it is to * override the drawControllers() method so that the order in which the * elements are rendered can be controlled. It renders whether or not it * is open (see ControllerGroup.drawControllers() for context). */ private final class DepthSortedGroup extends ControllerGroup<DepthSortedGroup> { public DepthSortedGroup(ControlP5 theControlP5, String theName) { super(theControlP5, theName); } @Override public void drawControllers(PApplet theApplet) { // draw graph in order of depth PriorityQueue<GraphElement> elementQueue = getDistanceSortedGraphElements(); while (!elementQueue.isEmpty()) { GraphElement currentElement = elementQueue.poll(); currentElement.updateInternalEvents(pApp); currentElement.draw(pApp); } } } }
document prefixed() method
src/nodes/Graph.java
document prefixed() method
<ide><path>rc/nodes/Graph.java <ide> return triples.getResource(uri); <ide> } <ide> <add> /** <add> * <add> * @param uri <add> * @return namespace prefixed version of uri. <add> * Example: http://www.w3.org/1999/02/22-rdf-syntax-ns#type --> rdf:type <add> */ <ide> public String prefixed(String uri) { <ide> return triples.shortForm(uri); <ide> }
Java
apache-2.0
533226c909ab82801d95f2a49742eeb1daef4521
0
failsafe-lib/failsafe,jhalterman/failsafe,failsafe-lib/failsafe,jhalterman/failsafe,jhalterman/recurrent,jhalterman/recurrent
/* * Copyright 2016 the original author or authors. * * 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 net.jodah.failsafe; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; import net.jodah.failsafe.Functions.ContextualCallableWrapper; import net.jodah.failsafe.function.CheckedRunnable; import net.jodah.failsafe.function.ContextualCallable; import net.jodah.failsafe.function.ContextualRunnable; import net.jodah.failsafe.internal.util.Assert; import net.jodah.failsafe.util.concurrent.Scheduler; import net.jodah.failsafe.util.concurrent.Schedulers; /** * Performs synchronous executions with failures handled according to a configured {@link #with(RetryPolicy) retry * policy}, {@link #with(CircuitBreaker) circuit breaker} and * {@link #withFallback(net.jodah.failsafe.function.CheckedBiFunction) fallback}. * * @author Jonathan Halterman * @param <R> listener result type */ public class SyncFailsafe<R> extends FailsafeConfig<R, SyncFailsafe<R>> { SyncFailsafe(CircuitBreaker circuitBreaker) { this.circuitBreaker = circuitBreaker; } SyncFailsafe(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; } /** * Executes the {@code callable} until a successful result is returned or the configured {@link RetryPolicy} is * exceeded. * * @throws NullPointerException if the {@code callable} is null * @throws FailsafeException if the {@code callable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit is open. */ public <T> T get(Callable<T> callable) { return call(Assert.notNull(callable, "callable")); } /** * Executes the {@code callable} until a successful result is returned or the configured {@link RetryPolicy} is * exceeded. * * @throws NullPointerException if the {@code callable} is null * @throws FailsafeException if the {@code callable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit is open. */ public <T> T get(ContextualCallable<T> callable) { return call(Functions.callableOf(callable)); } /** * Executes the {@code runnable} until successful or until the configured {@link RetryPolicy} is exceeded. * * @throws NullPointerException if the {@code runnable} is null * @throws FailsafeException if the {@code callable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit is open. */ public void run(CheckedRunnable runnable) { call(Functions.callableOf(runnable)); } /** * Executes the {@code runnable} until successful or until the configured {@link RetryPolicy} is exceeded. * * @throws NullPointerException if the {@code runnable} is null * @throws FailsafeException if the {@code runnable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit is open. */ public void run(ContextualRunnable runnable) { call(Functions.callableOf(runnable)); } /** * Creates and returns a new AsyncFailsafe instance that will perform executions and retries asynchronously via the * {@code executor}. * * @throws NullPointerException if {@code executor} is null */ public AsyncFailsafe<R> with(ScheduledExecutorService executor) { return new AsyncFailsafe<R>(this, Schedulers.of(executor)); } /** * Creates and returns a new AsyncFailsafe instance that will perform executions and retries asynchronously via the * {@code scheduler}. * * @throws NullPointerException if {@code scheduler} is null */ public AsyncFailsafe<R> with(Scheduler scheduler) { return new AsyncFailsafe<R>(this, Assert.notNull(scheduler, "scheduler")); } /** * Calls the {@code callable} synchronously, performing retries according to the {@code retryPolicy}. * * @throws FailsafeException if the {@code callable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit breaker is open */ @SuppressWarnings("unchecked") private <T> T call(Callable<T> callable) { Execution execution = new Execution((FailsafeConfig<Object, ?>) this); // Handle contextual calls if (callable instanceof ContextualCallableWrapper) ((ContextualCallableWrapper<T>) callable).inject(execution); T result = null; Throwable failure; while (true) { if (circuitBreaker != null && !circuitBreaker.allowsExecution()) { CircuitBreakerOpenException e = new CircuitBreakerOpenException(); if (fallback != null) return fallbackFor((R) result, e); throw e; } try { execution.before(); failure = null; result = callable.call(); } catch (Throwable t) { // Re-throw nested execution interruptions if (t instanceof FailsafeException && InterruptedException.class.isInstance(t.getCause())) throw (FailsafeException) t; failure = t; } // Attempt to complete execution if (execution.complete(result, failure, true)) { if (execution.success || (failure == null && fallback == null)) return result; if (fallback != null) return fallbackFor((R) result, failure); throw failure instanceof RuntimeException ? (RuntimeException) failure : new FailsafeException(failure); } else { try { Thread.sleep(execution.getWaitTime().toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new FailsafeException(e); } handleRetry((R) result, failure, execution); } } } @SuppressWarnings("unchecked") private <T> T fallbackFor(R result, Throwable failure) { try { return (T) fallback.apply(result, failure); } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new FailsafeException(e); } } }
src/main/java/net/jodah/failsafe/SyncFailsafe.java
/* * Copyright 2016 the original author or authors. * * 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 net.jodah.failsafe; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; import net.jodah.failsafe.Functions.ContextualCallableWrapper; import net.jodah.failsafe.function.CheckedRunnable; import net.jodah.failsafe.function.ContextualCallable; import net.jodah.failsafe.function.ContextualRunnable; import net.jodah.failsafe.internal.util.Assert; import net.jodah.failsafe.util.concurrent.Scheduler; import net.jodah.failsafe.util.concurrent.Schedulers; /** * Performs synchronous executions with failures handled according to a configured {@link #with(RetryPolicy) retry * policy}, {@link #with(CircuitBreaker) circuit breaker} and * {@link #withFallback(net.jodah.failsafe.function.BiFunction) fallback}. * * @author Jonathan Halterman * @param <R> listener result type */ public class SyncFailsafe<R> extends FailsafeConfig<R, SyncFailsafe<R>> { SyncFailsafe(CircuitBreaker circuitBreaker) { this.circuitBreaker = circuitBreaker; } SyncFailsafe(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; } /** * Executes the {@code callable} until a successful result is returned or the configured {@link RetryPolicy} is * exceeded. * * @throws NullPointerException if the {@code callable} is null * @throws FailsafeException if the {@code callable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit is open. */ public <T> T get(Callable<T> callable) { return call(Assert.notNull(callable, "callable")); } /** * Executes the {@code callable} until a successful result is returned or the configured {@link RetryPolicy} is * exceeded. * * @throws NullPointerException if the {@code callable} is null * @throws FailsafeException if the {@code callable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit is open. */ public <T> T get(ContextualCallable<T> callable) { return call(Functions.callableOf(callable)); } /** * Executes the {@code runnable} until successful or until the configured {@link RetryPolicy} is exceeded. * * @throws NullPointerException if the {@code runnable} is null * @throws FailsafeException if the {@code callable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit is open. */ public void run(CheckedRunnable runnable) { call(Functions.callableOf(runnable)); } /** * Executes the {@code runnable} until successful or until the configured {@link RetryPolicy} is exceeded. * * @throws NullPointerException if the {@code runnable} is null * @throws FailsafeException if the {@code runnable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit is open. */ public void run(ContextualRunnable runnable) { call(Functions.callableOf(runnable)); } /** * Creates and returns a new AsyncFailsafe instance that will perform executions and retries asynchronously via the * {@code executor}. * * @throws NullPointerException if {@code executor} is null */ public AsyncFailsafe<R> with(ScheduledExecutorService executor) { return new AsyncFailsafe<R>(this, Schedulers.of(executor)); } /** * Creates and returns a new AsyncFailsafe instance that will perform executions and retries asynchronously via the * {@code scheduler}. * * @throws NullPointerException if {@code scheduler} is null */ public AsyncFailsafe<R> with(Scheduler scheduler) { return new AsyncFailsafe<R>(this, Assert.notNull(scheduler, "scheduler")); } /** * Calls the {@code callable} synchronously, performing retries according to the {@code retryPolicy}. * * @throws FailsafeException if the {@code callable} fails with a checked Exception or if interrupted while waiting to * perform a retry. * @throws CircuitBreakerOpenException if a configured circuit breaker is open */ @SuppressWarnings("unchecked") private <T> T call(Callable<T> callable) { Execution execution = new Execution((FailsafeConfig<Object, ?>) this); // Handle contextual calls if (callable instanceof ContextualCallableWrapper) ((ContextualCallableWrapper<T>) callable).inject(execution); T result = null; Throwable failure; while (true) { if (circuitBreaker != null && !circuitBreaker.allowsExecution()) { CircuitBreakerOpenException e = new CircuitBreakerOpenException(); if (fallback != null) return fallbackFor((R) result, e); throw e; } try { execution.before(); failure = null; result = callable.call(); } catch (Throwable t) { // Re-throw nested execution interruptions if (t instanceof FailsafeException && InterruptedException.class.isInstance(t.getCause())) throw (FailsafeException) t; failure = t; } // Attempt to complete execution if (execution.complete(result, failure, true)) { if (execution.success || (failure == null && fallback == null)) return result; if (fallback != null) return fallbackFor((R) result, failure); throw failure instanceof RuntimeException ? (RuntimeException) failure : new FailsafeException(failure); } else { try { Thread.sleep(execution.getWaitTime().toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new FailsafeException(e); } handleRetry((R) result, failure, execution); } } } @SuppressWarnings("unchecked") private <T> T fallbackFor(R result, Throwable failure) { try { return (T) fallback.apply(result, failure); } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new FailsafeException(e); } } }
Fix javadoc link
src/main/java/net/jodah/failsafe/SyncFailsafe.java
Fix javadoc link
<ide><path>rc/main/java/net/jodah/failsafe/SyncFailsafe.java <ide> /** <ide> * Performs synchronous executions with failures handled according to a configured {@link #with(RetryPolicy) retry <ide> * policy}, {@link #with(CircuitBreaker) circuit breaker} and <del> * {@link #withFallback(net.jodah.failsafe.function.BiFunction) fallback}. <add> * {@link #withFallback(net.jodah.failsafe.function.CheckedBiFunction) fallback}. <ide> * <ide> * @author Jonathan Halterman <ide> * @param <R> listener result type
Java
apache-2.0
6c1515dfa6150b654bcc9b406428807289f7dcd5
0
troels/nz-presto,troels/nz-presto,troels/nz-presto,troels/nz-presto,troels/nz-presto
/* * 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.facebook.presto.cost; import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.Double.NaN; import static java.lang.Double.POSITIVE_INFINITY; import static java.lang.Double.isNaN; public class PlanNodeCostEstimate { public static final PlanNodeCostEstimate INFINITE_COST = new PlanNodeCostEstimate(POSITIVE_INFINITY, POSITIVE_INFINITY, POSITIVE_INFINITY); public static final PlanNodeCostEstimate UNKNOWN_COST = new PlanNodeCostEstimate(NaN, NaN, NaN); public static final PlanNodeCostEstimate ZERO_COST = PlanNodeCostEstimate.builder().build(); private final double cpuCost; private final double memoryCost; private final double networkCost; private PlanNodeCostEstimate(double cpuCost, double memoryCost, double networkCost) { checkArgument(isNaN(cpuCost) || cpuCost >= 0, "cpuCost cannot be negative"); checkArgument(isNaN(memoryCost) || memoryCost >= 0, "memoryCost cannot be negative"); checkArgument(isNaN(networkCost) || networkCost >= 0, "networkCost cannot be negative"); this.cpuCost = cpuCost; this.memoryCost = memoryCost; this.networkCost = networkCost; } /** * Returns CPU component of the cost. Unknown value is represented by {@link Double#NaN} */ public double getCpuCost() { return cpuCost; } /** * Returns memory component of the cost. Unknown value is represented by {@link Double#NaN} */ public double getMemoryCost() { return memoryCost; } /** * Returns network component of the cost. Unknown value is represented by {@link Double#NaN} */ public double getNetworkCost() { return networkCost; } /** * Returns true if cost is unknowny. That is any of the components of cost is unknown. */ public boolean isUnknown() { return isNaN(cpuCost) || isNaN(memoryCost) || isNaN(networkCost); } @Override public String toString() { return toStringHelper(this) .add("cpuCost", cpuCost) .add("memoryCost", memoryCost) .add("networkCost", networkCost) .toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PlanNodeCostEstimate that = (PlanNodeCostEstimate) o; return Double.compare(that.cpuCost, cpuCost) == 0 && Double.compare(that.memoryCost, memoryCost) == 0 && Double.compare(that.networkCost, networkCost) == 0; } @Override public int hashCode() { return Objects.hash(cpuCost, memoryCost, networkCost); } public PlanNodeCostEstimate add(PlanNodeCostEstimate other) { return new PlanNodeCostEstimate( cpuCost + other.cpuCost, memoryCost + other.memoryCost, networkCost + other.networkCost); } public static PlanNodeCostEstimate networkCost(double networkCost) { return builder().setNetworkCost(networkCost).build(); } public static PlanNodeCostEstimate cpuCost(double cpuCost) { return builder().setCpuCost(cpuCost).build(); } public static PlanNodeCostEstimate memoryCost(double memoryCost) { return builder().setMemoryCost(memoryCost).build(); } public static Builder builder() { return new Builder(); } public static final class Builder { private double cpuCost = 0; private double memoryCost = 0; private double networkCost = 0; public Builder setFrom(PlanNodeCostEstimate otherStatistics) { return setCpuCost(otherStatistics.getCpuCost()) .setMemoryCost(otherStatistics.getMemoryCost()) .setNetworkCost(otherStatistics.getNetworkCost()); } public Builder setCpuCost(double cpuCost) { this.cpuCost = cpuCost; return this; } public Builder setMemoryCost(double memoryCost) { this.memoryCost = memoryCost; return this; } public Builder setNetworkCost(double networkCost) { this.networkCost = networkCost; return this; } public PlanNodeCostEstimate build() { return new PlanNodeCostEstimate(cpuCost, memoryCost, networkCost); } } }
presto-main/src/main/java/com/facebook/presto/cost/PlanNodeCostEstimate.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.facebook.presto.cost; import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.Double.NaN; import static java.lang.Double.POSITIVE_INFINITY; import static java.lang.Double.isNaN; public class PlanNodeCostEstimate { public static final PlanNodeCostEstimate INFINITE_COST = new PlanNodeCostEstimate(POSITIVE_INFINITY, POSITIVE_INFINITY, POSITIVE_INFINITY); public static final PlanNodeCostEstimate UNKNOWN_COST = new PlanNodeCostEstimate(NaN, NaN, NaN); public static final PlanNodeCostEstimate ZERO_COST = PlanNodeCostEstimate.builder().build(); private final double cpuCost; private final double memoryCost; private final double networkCost; private PlanNodeCostEstimate(double cpuCost, double memoryCost, double networkCost) { checkArgument(isNaN(cpuCost) || cpuCost >= 0, "cpuCost cannot be negative"); checkArgument(isNaN(memoryCost) || memoryCost >= 0, "memoryCost cannot be negative"); checkArgument(isNaN(networkCost) || networkCost >= 0, "networkCost cannot be negative"); this.cpuCost = cpuCost; this.memoryCost = memoryCost; this.networkCost = networkCost; } /** * Returns CPU component of the cost. Unknown value is represented by {@link Double#NaN} */ public double getCpuCost() { return cpuCost; } /** * Returns memory component of the cost. Unknown value is represented by {@link Double#NaN} */ public double getMemoryCost() { return memoryCost; } /** * Returns network component of the cost. Unknown value is represented by {@link Double#NaN} */ public double getNetworkCost() { return networkCost; } /** * Returns true if this cost has unknown components. */ public boolean hasUnknownComponents() { return isNaN(cpuCost) || isNaN(memoryCost) || isNaN(networkCost); } @Override public String toString() { return toStringHelper(this) .add("cpuCost", cpuCost) .add("memoryCost", memoryCost) .add("networkCost", networkCost) .toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PlanNodeCostEstimate that = (PlanNodeCostEstimate) o; return Double.compare(that.cpuCost, cpuCost) == 0 && Double.compare(that.memoryCost, memoryCost) == 0 && Double.compare(that.networkCost, networkCost) == 0; } @Override public int hashCode() { return Objects.hash(cpuCost, memoryCost, networkCost); } public PlanNodeCostEstimate add(PlanNodeCostEstimate other) { return new PlanNodeCostEstimate( cpuCost + other.cpuCost, memoryCost + other.memoryCost, networkCost + other.networkCost); } public static PlanNodeCostEstimate networkCost(double networkCost) { return builder().setNetworkCost(networkCost).build(); } public static PlanNodeCostEstimate cpuCost(double cpuCost) { return builder().setCpuCost(cpuCost).build(); } public static PlanNodeCostEstimate memoryCost(double memoryCost) { return builder().setMemoryCost(memoryCost).build(); } public static Builder builder() { return new Builder(); } public static final class Builder { private double cpuCost = 0; private double memoryCost = 0; private double networkCost = 0; public Builder setFrom(PlanNodeCostEstimate otherStatistics) { return setCpuCost(otherStatistics.getCpuCost()) .setMemoryCost(otherStatistics.getMemoryCost()) .setNetworkCost(otherStatistics.getNetworkCost()); } public Builder setCpuCost(double cpuCost) { this.cpuCost = cpuCost; return this; } public Builder setMemoryCost(double memoryCost) { this.memoryCost = memoryCost; return this; } public Builder setNetworkCost(double networkCost) { this.networkCost = networkCost; return this; } public PlanNodeCostEstimate build() { return new PlanNodeCostEstimate(cpuCost, memoryCost, networkCost); } } }
Revert "fixup! Introduce CostCalculator interface" This reverts commit ca886de6fc64f1a2c92627e6646fbfde2c9c67b9.
presto-main/src/main/java/com/facebook/presto/cost/PlanNodeCostEstimate.java
Revert "fixup! Introduce CostCalculator interface"
<ide><path>resto-main/src/main/java/com/facebook/presto/cost/PlanNodeCostEstimate.java <ide> } <ide> <ide> /** <del> * Returns true if this cost has unknown components. <add> * Returns true if cost is unknowny. That is any of the components of cost is unknown. <ide> */ <del> public boolean hasUnknownComponents() <add> public boolean isUnknown() <ide> { <ide> return isNaN(cpuCost) || isNaN(memoryCost) || isNaN(networkCost); <ide> }
Java
apache-2.0
f06166e16edca71a23f9ee74ee689ce2b042fce0
0
rapidoid/rapidoid,rapidoid/rapidoid,rapidoid/rapidoid,rapidoid/rapidoid
package org.rapidoid.app; import java.util.List; import java.util.Map; import java.util.Set; import org.rapidoid.annotation.Authors; import org.rapidoid.annotation.Since; import org.rapidoid.http.HTTP; import org.rapidoid.http.HttpClient; import org.rapidoid.http.HttpExchange; import org.rapidoid.http.Services; import org.rapidoid.http.ServicesClient; import org.rapidoid.plugins.Plugins; import org.rapidoid.plugins.cache.CachePlugin; import org.rapidoid.plugins.db.DBPlugin; import org.rapidoid.plugins.email.EmailPlugin; import org.rapidoid.plugins.entities.EntitiesPlugin; import org.rapidoid.plugins.languages.LanguagesPlugin; import org.rapidoid.plugins.lifecycle.LifecyclePlugin; import org.rapidoid.plugins.sms.SMSPlugin; import org.rapidoid.plugins.templates.TemplatesPlugin; import org.rapidoid.plugins.users.UsersPlugin; import org.rapidoid.sql.SQL; import org.rapidoid.sql.SQLAPI; import org.rapidoid.util.U; /* * #%L * rapidoid-app * %% * Copyright (C) 2014 - 2015 Nikolche Mihajlovski and contributors * %% * 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. * #L% */ @Authors("Nikolche Mihajlovski") @Since("4.1.0") public class Dollar { public final Map<?, ?> map = U.map(); public final Map<Object, Map<Object, Object>> maps = U.mapOfMaps(); public final Map<Object, List<Object>> lists = U.mapOfLists(); public final Map<Object, Set<Object>> sets = U.mapOfSets(); public final HttpClient http = HTTP.DEFAULT_CLIENT; public final ServicesClient services = Services.DEFAULT_CLIENT; public final LifecyclePlugin lifecycle = Plugins.lifecycle(); public final LanguagesPlugin languages = Plugins.languages(); public final DBPlugin db = Plugins.db(); public final DBPlugin hibernate = Plugins.db("hibernate"); public final DBPlugin cassandra = Plugins.db("cassandra"); public final EntitiesPlugin entities = Plugins.entities(); public final UsersPlugin users = Plugins.users(); public final EmailPlugin email = Plugins.email(); public final SMSPlugin sms = Plugins.sms(); public final CachePlugin cache = Plugins.cache(); public final TemplatesPlugin templates = Plugins.templates(); public final SQLAPI jdbc; public final Map<String, Object> bindings; public final HttpExchange req; public Dollar(HttpExchange x, Map<String, Object> bindings) { this.req = x; this.bindings = bindings; this.jdbc = SQL.newInstance().mysql(); } public List<Map<String, Object>> sql(String sql, Object... args) { if (sql.trim().toLowerCase().startsWith("select ")) { return jdbc.query(sql, args); } else { jdbc.execute(sql, args); return null; } } public Iterable<Map<String, Object>> cql(String cql, Object... args) { return cassandra.query(cql, args); } public DollarPage page(Object value, Map<String, Object> config) { return new DollarPage(value, config); } }
rapidoid-app/src/main/java/org/rapidoid/app/Dollar.java
package org.rapidoid.app; import java.util.List; import java.util.Map; import java.util.Set; import org.rapidoid.annotation.Authors; import org.rapidoid.annotation.Since; import org.rapidoid.http.HTTP; import org.rapidoid.http.HttpClient; import org.rapidoid.http.HttpExchange; import org.rapidoid.http.Services; import org.rapidoid.http.ServicesClient; import org.rapidoid.plugins.Plugins; import org.rapidoid.plugins.cache.CachePlugin; import org.rapidoid.plugins.db.DBPlugin; import org.rapidoid.plugins.email.EmailPlugin; import org.rapidoid.plugins.entities.EntitiesPlugin; import org.rapidoid.plugins.languages.LanguagesPlugin; import org.rapidoid.plugins.lifecycle.LifecyclePlugin; import org.rapidoid.plugins.sms.SMSPlugin; import org.rapidoid.plugins.templates.TemplatesPlugin; import org.rapidoid.plugins.users.UsersPlugin; import org.rapidoid.sql.SQL; import org.rapidoid.sql.SQLAPI; import org.rapidoid.util.U; /* * #%L * rapidoid-app * %% * Copyright (C) 2014 - 2015 Nikolche Mihajlovski and contributors * %% * 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. * #L% */ @Authors("Nikolche Mihajlovski") @Since("4.1.0") public class Dollar { public final Map<?, ?> map = U.map(); public final Map<Object, Map<Object, Object>> maps = U.mapOfMaps(); public final Map<Object, List<Object>> lists = U.mapOfLists(); public final Map<Object, Set<Object>> sets = U.mapOfSets(); public final HttpClient http = HTTP.DEFAULT_CLIENT; public final ServicesClient services = Services.DEFAULT_CLIENT; public final LifecyclePlugin lifecycle = Plugins.lifecycle(); public final LanguagesPlugin languages = Plugins.languages(); public final DBPlugin db = Plugins.db(); public final DBPlugin hibernate = Plugins.db("hibernate"); public final DBPlugin cassandra = Plugins.db("cassandra"); public final EntitiesPlugin entities = Plugins.entities(); public final UsersPlugin users = Plugins.users(); public final EmailPlugin email = Plugins.email(); public final SMSPlugin sms = Plugins.sms(); public final CachePlugin cache = Plugins.cache(); public final TemplatesPlugin templates = Plugins.templates(); public final SQLAPI jdbc; public final Map<String, Object> bindings; private final HttpExchange exchange; public Dollar(HttpExchange x, Map<String, Object> bindings) { this.exchange = x; this.bindings = bindings; this.jdbc = SQL.newInstance().mysql(); } public List<Map<String, Object>> sql(String sql, Object... args) { if (sql.trim().toLowerCase().startsWith("select ")) { return jdbc.query(sql, args); } else { jdbc.execute(sql, args); return null; } } public Iterable<Map<String, Object>> cql(String cql, Object... args) { return cassandra.query(cql, args); } public HttpExchange req() { return exchange; } public DollarPage page(Object value, Map<String, Object> config) { return new DollarPage(value, config); } }
Simplified JS context "req" method with field.
rapidoid-app/src/main/java/org/rapidoid/app/Dollar.java
Simplified JS context "req" method with field.
<ide><path>apidoid-app/src/main/java/org/rapidoid/app/Dollar.java <ide> <ide> public final Map<String, Object> bindings; <ide> <del> private final HttpExchange exchange; <add> public final HttpExchange req; <ide> <ide> public Dollar(HttpExchange x, Map<String, Object> bindings) { <del> this.exchange = x; <add> this.req = x; <ide> this.bindings = bindings; <ide> this.jdbc = SQL.newInstance().mysql(); <ide> } <ide> return cassandra.query(cql, args); <ide> } <ide> <del> public HttpExchange req() { <del> return exchange; <del> } <del> <ide> public DollarPage page(Object value, Map<String, Object> config) { <ide> return new DollarPage(value, config); <ide> }
Java
apache-2.0
03c7e33ca042c97524fe704d278ce53ad5edd56b
0
AndroidX/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,androidx/androidx
/* * Copyright (C) 2014 The Android Open Source Project * * 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 android.support.v7.widget; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.MenuRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.annotation.StyleRes; import android.support.v4.os.ParcelableCompat; import android.support.v4.os.ParcelableCompatCreatorCallbacks; import android.support.v4.view.AbsSavedState; import android.support.v4.view.GravityCompat; import android.support.v4.view.MarginLayoutParamsCompat; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBar; import android.support.v7.appcompat.R; import android.support.v7.content.res.AppCompatResources; import android.support.v7.view.CollapsibleActionView; import android.support.v7.view.SupportMenuInflater; import android.support.v7.view.menu.MenuBuilder; import android.support.v7.view.menu.MenuItemImpl; import android.support.v7.view.menu.MenuPresenter; import android.support.v7.view.menu.MenuView; import android.support.v7.view.menu.SubMenuBuilder; import android.text.Layout; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * A standard toolbar for use within application content. * * <p>A Toolbar is a generalization of {@link ActionBar action bars} for use * within application layouts. While an action bar is traditionally part of an * {@link android.app.Activity Activity's} opaque window decor controlled by the framework, * a Toolbar may be placed at any arbitrary level of nesting within a view hierarchy. * An application may choose to designate a Toolbar as the action bar for an Activity * using the {@link android.support.v7.app.AppCompatActivity#setSupportActionBar(Toolbar) * setSupportActionBar()} method.</p> * * <p>Toolbar supports a more focused feature set than ActionBar. From start to end, a toolbar * may contain a combination of the following optional elements: * * <ul> * <li><em>A navigation button.</em> This may be an Up arrow, navigation menu toggle, close, * collapse, done or another glyph of the app's choosing. This button should always be used * to access other navigational destinations within the container of the Toolbar and * its signified content or otherwise leave the current context signified by the Toolbar. * The navigation button is vertically aligned within the Toolbar's minimum height, * if set.</li> * <li><em>A branded logo image.</em> This may extend to the height of the bar and can be * arbitrarily wide.</li> * <li><em>A title and subtitle.</em> The title should be a signpost for the Toolbar's current * position in the navigation hierarchy and the content contained there. The subtitle, * if present should indicate any extended information about the current content. * If an app uses a logo image it should strongly consider omitting a title and subtitle.</li> * <li><em>One or more custom views.</em> The application may add arbitrary child views * to the Toolbar. They will appear at this position within the layout. If a child view's * {@link LayoutParams} indicates a {@link Gravity} value of * {@link Gravity#CENTER_HORIZONTAL CENTER_HORIZONTAL} the view will attempt to center * within the available space remaining in the Toolbar after all other elements have been * measured.</li> * <li><em>An {@link ActionMenuView action menu}.</em> The menu of actions will pin to the * end of the Toolbar offering a few * <a href="http://developer.android.com/design/patterns/actionbar.html#ActionButtons"> * frequent, important or typical</a> actions along with an optional overflow menu for * additional actions. Action buttons are vertically aligned within the Toolbar's * minimum height, if set.</li> * </ul> * </p> * * <p>In modern Android UIs developers should lean more on a visually distinct color scheme for * toolbars than on their application icon. The use of application icon plus title as a standard * layout is discouraged on API 21 devices and newer.</p> * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_buttonGravity * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_collapseContentDescription * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_collapseIcon * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEnd * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetLeft * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetRight * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStart * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStartWithNavigation * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEndWithActions * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_android_gravity * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_logo * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_logoDescription * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_maxButtonHeight * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationContentDescription * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationIcon * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_popupTheme * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_subtitle * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_subtitleTextAppearance * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_subtitleTextColor * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_title * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMargin * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginBottom * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginEnd * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginStart * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginTop * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleTextAppearance * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleTextColor */ public class Toolbar extends ViewGroup { private static final String TAG = "Toolbar"; private ActionMenuView mMenuView; private TextView mTitleTextView; private TextView mSubtitleTextView; private ImageButton mNavButtonView; private ImageView mLogoView; private Drawable mCollapseIcon; private CharSequence mCollapseDescription; private ImageButton mCollapseButtonView; View mExpandedActionView; /** Context against which to inflate popup menus. */ private Context mPopupContext; /** Theme resource against which to inflate popup menus. */ private int mPopupTheme; private int mTitleTextAppearance; private int mSubtitleTextAppearance; private int mButtonGravity; private int mMaxButtonHeight; private int mTitleMarginStart; private int mTitleMarginEnd; private int mTitleMarginTop; private int mTitleMarginBottom; private RtlSpacingHelper mContentInsets; private int mContentInsetStartWithNavigation; private int mContentInsetEndWithActions; private int mGravity = GravityCompat.START | Gravity.CENTER_VERTICAL; private CharSequence mTitleText; private CharSequence mSubtitleText; private int mTitleTextColor; private int mSubtitleTextColor; private boolean mEatingTouch; private boolean mEatingHover; // Clear me after use. private final ArrayList<View> mTempViews = new ArrayList<View>(); // Used to hold views that will be removed while we have an expanded action view. private final ArrayList<View> mHiddenViews = new ArrayList<>(); private final int[] mTempMargins = new int[2]; private OnMenuItemClickListener mOnMenuItemClickListener; private final ActionMenuView.OnMenuItemClickListener mMenuViewItemClickListener = new ActionMenuView.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (mOnMenuItemClickListener != null) { return mOnMenuItemClickListener.onMenuItemClick(item); } return false; } }; private ToolbarWidgetWrapper mWrapper; private ActionMenuPresenter mOuterActionMenuPresenter; private ExpandedActionViewMenuPresenter mExpandedMenuPresenter; private MenuPresenter.Callback mActionMenuPresenterCallback; private MenuBuilder.Callback mMenuBuilderCallback; private boolean mCollapsible; private final Runnable mShowOverflowMenuRunnable = new Runnable() { @Override public void run() { showOverflowMenu(); } }; public Toolbar(Context context) { this(context, null); } public Toolbar(Context context, @Nullable AttributeSet attrs) { this(context, attrs, R.attr.toolbarStyle); } public Toolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // Need to use getContext() here so that we use the themed context final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.Toolbar, defStyleAttr, 0); mTitleTextAppearance = a.getResourceId(R.styleable.Toolbar_titleTextAppearance, 0); mSubtitleTextAppearance = a.getResourceId(R.styleable.Toolbar_subtitleTextAppearance, 0); mGravity = a.getInteger(R.styleable.Toolbar_android_gravity, mGravity); mButtonGravity = a.getInteger(R.styleable.Toolbar_buttonGravity, Gravity.TOP); // First read the correct attribute int titleMargin = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMargin, 0); if (a.hasValue(R.styleable.Toolbar_titleMargins)) { // Now read the deprecated attribute, if it has a value titleMargin = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMargins, titleMargin); } mTitleMarginStart = mTitleMarginEnd = mTitleMarginTop = mTitleMarginBottom = titleMargin; final int marginStart = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMarginStart, -1); if (marginStart >= 0) { mTitleMarginStart = marginStart; } final int marginEnd = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMarginEnd, -1); if (marginEnd >= 0) { mTitleMarginEnd = marginEnd; } final int marginTop = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMarginTop, -1); if (marginTop >= 0) { mTitleMarginTop = marginTop; } final int marginBottom = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMarginBottom, -1); if (marginBottom >= 0) { mTitleMarginBottom = marginBottom; } mMaxButtonHeight = a.getDimensionPixelSize(R.styleable.Toolbar_maxButtonHeight, -1); final int contentInsetStart = a.getDimensionPixelOffset(R.styleable.Toolbar_contentInsetStart, RtlSpacingHelper.UNDEFINED); final int contentInsetEnd = a.getDimensionPixelOffset(R.styleable.Toolbar_contentInsetEnd, RtlSpacingHelper.UNDEFINED); final int contentInsetLeft = a.getDimensionPixelSize(R.styleable.Toolbar_contentInsetLeft, 0); final int contentInsetRight = a.getDimensionPixelSize(R.styleable.Toolbar_contentInsetRight, 0); ensureContentInsets(); mContentInsets.setAbsolute(contentInsetLeft, contentInsetRight); if (contentInsetStart != RtlSpacingHelper.UNDEFINED || contentInsetEnd != RtlSpacingHelper.UNDEFINED) { mContentInsets.setRelative(contentInsetStart, contentInsetEnd); } mContentInsetStartWithNavigation = a.getDimensionPixelOffset( R.styleable.Toolbar_contentInsetStartWithNavigation, RtlSpacingHelper.UNDEFINED); mContentInsetEndWithActions = a.getDimensionPixelOffset( R.styleable.Toolbar_contentInsetEndWithActions, RtlSpacingHelper.UNDEFINED); mCollapseIcon = a.getDrawable(R.styleable.Toolbar_collapseIcon); mCollapseDescription = a.getText(R.styleable.Toolbar_collapseContentDescription); final CharSequence title = a.getText(R.styleable.Toolbar_title); if (!TextUtils.isEmpty(title)) { setTitle(title); } final CharSequence subtitle = a.getText(R.styleable.Toolbar_subtitle); if (!TextUtils.isEmpty(subtitle)) { setSubtitle(subtitle); } // Set the default context, since setPopupTheme() may be a no-op. mPopupContext = getContext(); setPopupTheme(a.getResourceId(R.styleable.Toolbar_popupTheme, 0)); final Drawable navIcon = a.getDrawable(R.styleable.Toolbar_navigationIcon); if (navIcon != null) { setNavigationIcon(navIcon); } final CharSequence navDesc = a.getText(R.styleable.Toolbar_navigationContentDescription); if (!TextUtils.isEmpty(navDesc)) { setNavigationContentDescription(navDesc); } final Drawable logo = a.getDrawable(R.styleable.Toolbar_logo); if (logo != null) { setLogo(logo); } final CharSequence logoDesc = a.getText(R.styleable.Toolbar_logoDescription); if (!TextUtils.isEmpty(logoDesc)) { setLogoDescription(logoDesc); } if (a.hasValue(R.styleable.Toolbar_titleTextColor)) { setTitleTextColor(a.getColor(R.styleable.Toolbar_titleTextColor, 0xffffffff)); } if (a.hasValue(R.styleable.Toolbar_subtitleTextColor)) { setSubtitleTextColor(a.getColor(R.styleable.Toolbar_subtitleTextColor, 0xffffffff)); } a.recycle(); } /** * Specifies the theme to use when inflating popup menus. By default, uses * the same theme as the toolbar itself. * * @param resId theme used to inflate popup menus * @see #getPopupTheme() */ public void setPopupTheme(@StyleRes int resId) { if (mPopupTheme != resId) { mPopupTheme = resId; if (resId == 0) { mPopupContext = getContext(); } else { mPopupContext = new ContextThemeWrapper(getContext(), resId); } } } /** * @return resource identifier of the theme used to inflate popup menus, or * 0 if menus are inflated against the toolbar theme * @see #setPopupTheme(int) */ public int getPopupTheme() { return mPopupTheme; } /** * Sets the title margin. * * @param start the starting title margin in pixels * @param top the top title margin in pixels * @param end the ending title margin in pixels * @param bottom the bottom title margin in pixels * @see #getTitleMarginStart() * @see #getTitleMarginTop() * @see #getTitleMarginEnd() * @see #getTitleMarginBottom() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMargin */ public void setTitleMargin(int start, int top, int end, int bottom) { mTitleMarginStart = start; mTitleMarginTop = top; mTitleMarginEnd = end; mTitleMarginBottom = bottom; requestLayout(); } /** * @return the starting title margin in pixels * @see #setTitleMarginStart(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginStart */ public int getTitleMarginStart() { return mTitleMarginStart; } /** * Sets the starting title margin in pixels. * * @param margin the starting title margin in pixels * @see #getTitleMarginStart() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginStart */ public void setTitleMarginStart(int margin) { mTitleMarginStart = margin; requestLayout(); } /** * @return the top title margin in pixels * @see #setTitleMarginTop(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginTop */ public int getTitleMarginTop() { return mTitleMarginTop; } /** * Sets the top title margin in pixels. * * @param margin the top title margin in pixels * @see #getTitleMarginTop() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginTop */ public void setTitleMarginTop(int margin) { mTitleMarginTop = margin; requestLayout(); } /** * @return the ending title margin in pixels * @see #setTitleMarginEnd(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginEnd */ public int getTitleMarginEnd() { return mTitleMarginEnd; } /** * Sets the ending title margin in pixels. * * @param margin the ending title margin in pixels * @see #getTitleMarginEnd() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginEnd */ public void setTitleMarginEnd(int margin) { mTitleMarginEnd = margin; requestLayout(); } /** * @return the bottom title margin in pixels * @see #setTitleMarginBottom(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginBottom */ public int getTitleMarginBottom() { return mTitleMarginBottom; } /** * Sets the bottom title margin in pixels. * * @param margin the bottom title margin in pixels * @see #getTitleMarginBottom() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginBottom */ public void setTitleMarginBottom(int margin) { mTitleMarginBottom = margin; requestLayout(); } public void onRtlPropertiesChanged(int layoutDirection) { if (Build.VERSION.SDK_INT >= 17) { super.onRtlPropertiesChanged(layoutDirection); } ensureContentInsets(); mContentInsets.setDirection(layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL); } /** * Set a logo drawable from a resource id. * * <p>This drawable should generally take the place of title text. The logo cannot be * clicked. Apps using a logo should also supply a description using * {@link #setLogoDescription(int)}.</p> * * @param resId ID of a drawable resource */ public void setLogo(@DrawableRes int resId) { setLogo(AppCompatResources.getDrawable(getContext(), resId)); } /** @hide */ public boolean canShowOverflowMenu() { return getVisibility() == VISIBLE && mMenuView != null && mMenuView.isOverflowReserved(); } /** * Check whether the overflow menu is currently showing. This may not reflect * a pending show operation in progress. * * @return true if the overflow menu is currently showing */ public boolean isOverflowMenuShowing() { return mMenuView != null && mMenuView.isOverflowMenuShowing(); } /** @hide */ public boolean isOverflowMenuShowPending() { return mMenuView != null && mMenuView.isOverflowMenuShowPending(); } /** * Show the overflow items from the associated menu. * * @return true if the menu was able to be shown, false otherwise */ public boolean showOverflowMenu() { return mMenuView != null && mMenuView.showOverflowMenu(); } /** * Hide the overflow items from the associated menu. * * @return true if the menu was able to be hidden, false otherwise */ public boolean hideOverflowMenu() { return mMenuView != null && mMenuView.hideOverflowMenu(); } /** @hide */ public void setMenu(MenuBuilder menu, ActionMenuPresenter outerPresenter) { if (menu == null && mMenuView == null) { return; } ensureMenuView(); final MenuBuilder oldMenu = mMenuView.peekMenu(); if (oldMenu == menu) { return; } if (oldMenu != null) { oldMenu.removeMenuPresenter(mOuterActionMenuPresenter); oldMenu.removeMenuPresenter(mExpandedMenuPresenter); } if (mExpandedMenuPresenter == null) { mExpandedMenuPresenter = new ExpandedActionViewMenuPresenter(); } outerPresenter.setExpandedActionViewsExclusive(true); if (menu != null) { menu.addMenuPresenter(outerPresenter, mPopupContext); menu.addMenuPresenter(mExpandedMenuPresenter, mPopupContext); } else { outerPresenter.initForMenu(mPopupContext, null); mExpandedMenuPresenter.initForMenu(mPopupContext, null); outerPresenter.updateMenuView(true); mExpandedMenuPresenter.updateMenuView(true); } mMenuView.setPopupTheme(mPopupTheme); mMenuView.setPresenter(outerPresenter); mOuterActionMenuPresenter = outerPresenter; } /** * Dismiss all currently showing popup menus, including overflow or submenus. */ public void dismissPopupMenus() { if (mMenuView != null) { mMenuView.dismissPopupMenus(); } } /** @hide */ public boolean isTitleTruncated() { if (mTitleTextView == null) { return false; } final Layout titleLayout = mTitleTextView.getLayout(); if (titleLayout == null) { return false; } final int lineCount = titleLayout.getLineCount(); for (int i = 0; i < lineCount; i++) { if (titleLayout.getEllipsisCount(i) > 0) { return true; } } return false; } /** * Set a logo drawable. * * <p>This drawable should generally take the place of title text. The logo cannot be * clicked. Apps using a logo should also supply a description using * {@link #setLogoDescription(int)}.</p> * * @param drawable Drawable to use as a logo */ public void setLogo(Drawable drawable) { if (drawable != null) { ensureLogoView(); if (!isChildOrHidden(mLogoView)) { addSystemView(mLogoView, true); } } else if (mLogoView != null && isChildOrHidden(mLogoView)) { removeView(mLogoView); mHiddenViews.remove(mLogoView); } if (mLogoView != null) { mLogoView.setImageDrawable(drawable); } } /** * Return the current logo drawable. * * @return The current logo drawable * @see #setLogo(int) * @see #setLogo(android.graphics.drawable.Drawable) */ public Drawable getLogo() { return mLogoView != null ? mLogoView.getDrawable() : null; } /** * Set a description of the toolbar's logo. * * <p>This description will be used for accessibility or other similar descriptions * of the UI.</p> * * @param resId String resource id */ public void setLogoDescription(@StringRes int resId) { setLogoDescription(getContext().getText(resId)); } /** * Set a description of the toolbar's logo. * * <p>This description will be used for accessibility or other similar descriptions * of the UI.</p> * * @param description Description to set */ public void setLogoDescription(CharSequence description) { if (!TextUtils.isEmpty(description)) { ensureLogoView(); } if (mLogoView != null) { mLogoView.setContentDescription(description); } } /** * Return the description of the toolbar's logo. * * @return A description of the logo */ public CharSequence getLogoDescription() { return mLogoView != null ? mLogoView.getContentDescription() : null; } private void ensureLogoView() { if (mLogoView == null) { mLogoView = new ImageView(getContext()); } } /** * Check whether this Toolbar is currently hosting an expanded action view. * * <p>An action view may be expanded either directly from the * {@link android.view.MenuItem MenuItem} it belongs to or by user action. If the Toolbar * has an expanded action view it can be collapsed using the {@link #collapseActionView()} * method.</p> * * @return true if the Toolbar has an expanded action view */ public boolean hasExpandedActionView() { return mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null; } /** * Collapse a currently expanded action view. If this Toolbar does not have an * expanded action view this method has no effect. * * <p>An action view may be expanded either directly from the * {@link android.view.MenuItem MenuItem} it belongs to or by user action.</p> * * @see #hasExpandedActionView() */ public void collapseActionView() { final MenuItemImpl item = mExpandedMenuPresenter == null ? null : mExpandedMenuPresenter.mCurrentExpandedItem; if (item != null) { item.collapseActionView(); } } /** * Returns the title of this toolbar. * * @return The current title. */ public CharSequence getTitle() { return mTitleText; } /** * Set the title of this toolbar. * * <p>A title should be used as the anchor for a section of content. It should * describe or name the content being viewed.</p> * * @param resId Resource ID of a string to set as the title */ public void setTitle(@StringRes int resId) { setTitle(getContext().getText(resId)); } /** * Set the title of this toolbar. * * <p>A title should be used as the anchor for a section of content. It should * describe or name the content being viewed.</p> * * @param title Title to set */ public void setTitle(CharSequence title) { if (!TextUtils.isEmpty(title)) { if (mTitleTextView == null) { final Context context = getContext(); mTitleTextView = new TextView(context); mTitleTextView.setSingleLine(); mTitleTextView.setEllipsize(TextUtils.TruncateAt.END); if (mTitleTextAppearance != 0) { mTitleTextView.setTextAppearance(context, mTitleTextAppearance); } if (mTitleTextColor != 0) { mTitleTextView.setTextColor(mTitleTextColor); } } if (!isChildOrHidden(mTitleTextView)) { addSystemView(mTitleTextView, true); } } else if (mTitleTextView != null && isChildOrHidden(mTitleTextView)) { removeView(mTitleTextView); mHiddenViews.remove(mTitleTextView); } if (mTitleTextView != null) { mTitleTextView.setText(title); } mTitleText = title; } /** * Return the subtitle of this toolbar. * * @return The current subtitle */ public CharSequence getSubtitle() { return mSubtitleText; } /** * Set the subtitle of this toolbar. * * <p>Subtitles should express extended information about the current content.</p> * * @param resId String resource ID */ public void setSubtitle(@StringRes int resId) { setSubtitle(getContext().getText(resId)); } /** * Set the subtitle of this toolbar. * * <p>Subtitles should express extended information about the current content.</p> * * @param subtitle Subtitle to set */ public void setSubtitle(CharSequence subtitle) { if (!TextUtils.isEmpty(subtitle)) { if (mSubtitleTextView == null) { final Context context = getContext(); mSubtitleTextView = new TextView(context); mSubtitleTextView.setSingleLine(); mSubtitleTextView.setEllipsize(TextUtils.TruncateAt.END); if (mSubtitleTextAppearance != 0) { mSubtitleTextView.setTextAppearance(context, mSubtitleTextAppearance); } if (mSubtitleTextColor != 0) { mSubtitleTextView.setTextColor(mSubtitleTextColor); } } if (!isChildOrHidden(mSubtitleTextView)) { addSystemView(mSubtitleTextView, true); } } else if (mSubtitleTextView != null && isChildOrHidden(mSubtitleTextView)) { removeView(mSubtitleTextView); mHiddenViews.remove(mSubtitleTextView); } if (mSubtitleTextView != null) { mSubtitleTextView.setText(subtitle); } mSubtitleText = subtitle; } /** * Sets the text color, size, style, hint color, and highlight color * from the specified TextAppearance resource. */ public void setTitleTextAppearance(Context context, @StyleRes int resId) { mTitleTextAppearance = resId; if (mTitleTextView != null) { mTitleTextView.setTextAppearance(context, resId); } } /** * Sets the text color, size, style, hint color, and highlight color * from the specified TextAppearance resource. */ public void setSubtitleTextAppearance(Context context, @StyleRes int resId) { mSubtitleTextAppearance = resId; if (mSubtitleTextView != null) { mSubtitleTextView.setTextAppearance(context, resId); } } /** * Sets the text color of the title, if present. * * @param color The new text color in 0xAARRGGBB format */ public void setTitleTextColor(@ColorInt int color) { mTitleTextColor = color; if (mTitleTextView != null) { mTitleTextView.setTextColor(color); } } /** * Sets the text color of the subtitle, if present. * * @param color The new text color in 0xAARRGGBB format */ public void setSubtitleTextColor(@ColorInt int color) { mSubtitleTextColor = color; if (mSubtitleTextView != null) { mSubtitleTextView.setTextColor(color); } } /** * Retrieve the currently configured content description for the navigation button view. * This will be used to describe the navigation action to users through mechanisms such * as screen readers or tooltips. * * @return The navigation button's content description * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationContentDescription */ @Nullable public CharSequence getNavigationContentDescription() { return mNavButtonView != null ? mNavButtonView.getContentDescription() : null; } /** * Set a content description for the navigation button if one is present. The content * description will be read via screen readers or other accessibility systems to explain * the action of the navigation button. * * @param resId Resource ID of a content description string to set, or 0 to * clear the description * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationContentDescription */ public void setNavigationContentDescription(@StringRes int resId) { setNavigationContentDescription(resId != 0 ? getContext().getText(resId) : null); } /** * Set a content description for the navigation button if one is present. The content * description will be read via screen readers or other accessibility systems to explain * the action of the navigation button. * * @param description Content description to set, or <code>null</code> to * clear the content description * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationContentDescription */ public void setNavigationContentDescription(@Nullable CharSequence description) { if (!TextUtils.isEmpty(description)) { ensureNavButtonView(); } if (mNavButtonView != null) { mNavButtonView.setContentDescription(description); } } /** * Set the icon to use for the toolbar's navigation button. * * <p>The navigation button appears at the start of the toolbar if present. Setting an icon * will make the navigation button visible.</p> * * <p>If you use a navigation icon you should also set a description for its action using * {@link #setNavigationContentDescription(int)}. This is used for accessibility and * tooltips.</p> * * @param resId Resource ID of a drawable to set * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationIcon */ public void setNavigationIcon(@DrawableRes int resId) { setNavigationIcon(AppCompatResources.getDrawable(getContext(), resId)); } /** * Set the icon to use for the toolbar's navigation button. * * <p>The navigation button appears at the start of the toolbar if present. Setting an icon * will make the navigation button visible.</p> * * <p>If you use a navigation icon you should also set a description for its action using * {@link #setNavigationContentDescription(int)}. This is used for accessibility and * tooltips.</p> * * @param icon Drawable to set, may be null to clear the icon * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationIcon */ public void setNavigationIcon(@Nullable Drawable icon) { if (icon != null) { ensureNavButtonView(); if (!isChildOrHidden(mNavButtonView)) { addSystemView(mNavButtonView, true); } } else if (mNavButtonView != null && isChildOrHidden(mNavButtonView)) { removeView(mNavButtonView); mHiddenViews.remove(mNavButtonView); } if (mNavButtonView != null) { mNavButtonView.setImageDrawable(icon); } } /** * Return the current drawable used as the navigation icon. * * @return The navigation icon drawable * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationIcon */ @Nullable public Drawable getNavigationIcon() { return mNavButtonView != null ? mNavButtonView.getDrawable() : null; } /** * Set a listener to respond to navigation events. * * <p>This listener will be called whenever the user clicks the navigation button * at the start of the toolbar. An icon must be set for the navigation button to appear.</p> * * @param listener Listener to set * @see #setNavigationIcon(android.graphics.drawable.Drawable) */ public void setNavigationOnClickListener(OnClickListener listener) { ensureNavButtonView(); mNavButtonView.setOnClickListener(listener); } /** * Return the Menu shown in the toolbar. * * <p>Applications that wish to populate the toolbar's menu can do so from here. To use * an XML menu resource, use {@link #inflateMenu(int)}.</p> * * @return The toolbar's Menu */ public Menu getMenu() { ensureMenu(); return mMenuView.getMenu(); } /** * Set the icon to use for the overflow button. * * @param icon Drawable to set, may be null to clear the icon */ public void setOverflowIcon(@Nullable Drawable icon) { ensureMenu(); mMenuView.setOverflowIcon(icon); } /** * Return the current drawable used as the overflow icon. * * @return The overflow icon drawable */ @Nullable public Drawable getOverflowIcon() { ensureMenu(); return mMenuView.getOverflowIcon(); } private void ensureMenu() { ensureMenuView(); if (mMenuView.peekMenu() == null) { // Initialize a new menu for the first time. final MenuBuilder menu = (MenuBuilder) mMenuView.getMenu(); if (mExpandedMenuPresenter == null) { mExpandedMenuPresenter = new ExpandedActionViewMenuPresenter(); } mMenuView.setExpandedActionViewsExclusive(true); menu.addMenuPresenter(mExpandedMenuPresenter, mPopupContext); } } private void ensureMenuView() { if (mMenuView == null) { mMenuView = new ActionMenuView(getContext()); mMenuView.setPopupTheme(mPopupTheme); mMenuView.setOnMenuItemClickListener(mMenuViewItemClickListener); mMenuView.setMenuCallbacks(mActionMenuPresenterCallback, mMenuBuilderCallback); final LayoutParams lp = generateDefaultLayoutParams(); lp.gravity = GravityCompat.END | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK); mMenuView.setLayoutParams(lp); addSystemView(mMenuView, false); } } private MenuInflater getMenuInflater() { return new SupportMenuInflater(getContext()); } /** * Inflate a menu resource into this toolbar. * * <p>Inflate an XML menu resource into this toolbar. Existing items in the menu will not * be modified or removed.</p> * * @param resId ID of a menu resource to inflate */ public void inflateMenu(@MenuRes int resId) { getMenuInflater().inflate(resId, getMenu()); } /** * Set a listener to respond to menu item click events. * * <p>This listener will be invoked whenever a user selects a menu item from * the action buttons presented at the end of the toolbar or the associated overflow.</p> * * @param listener Listener to set */ public void setOnMenuItemClickListener(OnMenuItemClickListener listener) { mOnMenuItemClickListener = listener; } /** * Sets the content insets for this toolbar relative to layout direction. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @param contentInsetStart Content inset for the toolbar starting edge * @param contentInsetEnd Content inset for the toolbar ending edge * * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetEnd() * @see #getContentInsetLeft() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEnd * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStart */ public void setContentInsetsRelative(int contentInsetStart, int contentInsetEnd) { ensureContentInsets(); mContentInsets.setRelative(contentInsetStart, contentInsetEnd); } /** * Gets the starting content inset for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @return The starting content inset for this toolbar * * @see #setContentInsetsRelative(int, int) * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetEnd() * @see #getContentInsetLeft() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStart */ public int getContentInsetStart() { return mContentInsets != null ? mContentInsets.getStart() : 0; } /** * Gets the ending content inset for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @return The ending content inset for this toolbar * * @see #setContentInsetsRelative(int, int) * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetLeft() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEnd */ public int getContentInsetEnd() { return mContentInsets != null ? mContentInsets.getEnd() : 0; } /** * Sets the content insets for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @param contentInsetLeft Content inset for the toolbar's left edge * @param contentInsetRight Content inset for the toolbar's right edge * * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetEnd() * @see #getContentInsetLeft() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetLeft * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetRight */ public void setContentInsetsAbsolute(int contentInsetLeft, int contentInsetRight) { ensureContentInsets(); mContentInsets.setAbsolute(contentInsetLeft, contentInsetRight); } /** * Gets the left content inset for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @return The left content inset for this toolbar * * @see #setContentInsetsRelative(int, int) * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetEnd() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetLeft */ public int getContentInsetLeft() { return mContentInsets != null ? mContentInsets.getLeft() : 0; } /** * Gets the right content inset for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @return The right content inset for this toolbar * * @see #setContentInsetsRelative(int, int) * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetEnd() * @see #getContentInsetLeft() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetRight */ public int getContentInsetRight() { return mContentInsets != null ? mContentInsets.getRight() : 0; } /** * Gets the start content inset to use when a navigation button is present. * * <p>Different content insets are often called for when additional buttons are present * in the toolbar, as well as at different toolbar sizes. The larger value of * {@link #getContentInsetStart()} and this value will be used during layout.</p> * * @return the start content inset used when a navigation icon has been set in pixels * * @see #setContentInsetStartWithNavigation(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStartWithNavigation */ public int getContentInsetStartWithNavigation() { return mContentInsetStartWithNavigation != RtlSpacingHelper.UNDEFINED ? mContentInsetStartWithNavigation : getContentInsetStart(); } /** * Sets the start content inset to use when a navigation button is present. * * <p>Different content insets are often called for when additional buttons are present * in the toolbar, as well as at different toolbar sizes. The larger value of * {@link #getContentInsetStart()} and this value will be used during layout.</p> * * @param insetStartWithNavigation the inset to use when a navigation icon has been set * in pixels * * @see #getContentInsetStartWithNavigation() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStartWithNavigation */ public void setContentInsetStartWithNavigation(int insetStartWithNavigation) { if (insetStartWithNavigation < 0) { insetStartWithNavigation = RtlSpacingHelper.UNDEFINED; } if (insetStartWithNavigation != mContentInsetStartWithNavigation) { mContentInsetStartWithNavigation = insetStartWithNavigation; if (getNavigationIcon() != null) { requestLayout(); } } } /** * Gets the end content inset to use when action buttons are present. * * <p>Different content insets are often called for when additional buttons are present * in the toolbar, as well as at different toolbar sizes. The larger value of * {@link #getContentInsetEnd()} and this value will be used during layout.</p> * * @return the end content inset used when a menu has been set in pixels * * @see #setContentInsetEndWithActions(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEndWithActions */ public int getContentInsetEndWithActions() { return mContentInsetEndWithActions != RtlSpacingHelper.UNDEFINED ? mContentInsetEndWithActions : getContentInsetEnd(); } /** * Sets the start content inset to use when action buttons are present. * * <p>Different content insets are often called for when additional buttons are present * in the toolbar, as well as at different toolbar sizes. The larger value of * {@link #getContentInsetEnd()} and this value will be used during layout.</p> * * @param insetEndWithActions the inset to use when a menu has been set in pixels * * @see #getContentInsetEndWithActions() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEndWithActions */ public void setContentInsetEndWithActions(int insetEndWithActions) { if (insetEndWithActions < 0) { insetEndWithActions = RtlSpacingHelper.UNDEFINED; } if (insetEndWithActions != mContentInsetEndWithActions) { mContentInsetEndWithActions = insetEndWithActions; if (getNavigationIcon() != null) { requestLayout(); } } } /** * Gets the content inset that will be used on the starting side of the bar in the current * toolbar configuration. * * @return the current content inset start in pixels * * @see #getContentInsetStartWithNavigation() */ public int getCurrentContentInsetStart() { return getNavigationIcon() != null ? Math.max(getContentInsetStart(), Math.max(mContentInsetStartWithNavigation, 0)) : getContentInsetStart(); } /** * Gets the content inset that will be used on the ending side of the bar in the current * toolbar configuration. * * @return the current content inset end in pixels * * @see #getContentInsetEndWithActions() */ public int getCurrentContentInsetEnd() { boolean hasActions = false; if (mMenuView != null) { final MenuBuilder mb = mMenuView.peekMenu(); hasActions = mb != null && mb.hasVisibleItems(); } return hasActions ? Math.max(getContentInsetEnd(), Math.max(mContentInsetEndWithActions, 0)) : getContentInsetEnd(); } /** * Gets the content inset that will be used on the left side of the bar in the current * toolbar configuration. * * @return the current content inset left in pixels * * @see #getContentInsetStartWithNavigation() * @see #getContentInsetEndWithActions() */ public int getCurrentContentInsetLeft() { return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL ? getCurrentContentInsetEnd() : getCurrentContentInsetStart(); } /** * Gets the content inset that will be used on the right side of the bar in the current * toolbar configuration. * * @return the current content inset right in pixels * * @see #getContentInsetStartWithNavigation() * @see #getContentInsetEndWithActions() */ public int getCurrentContentInsetRight() { return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL ? getCurrentContentInsetStart() : getCurrentContentInsetEnd(); } private void ensureNavButtonView() { if (mNavButtonView == null) { mNavButtonView = new ImageButton(getContext(), null, R.attr.toolbarNavigationButtonStyle); final LayoutParams lp = generateDefaultLayoutParams(); lp.gravity = GravityCompat.START | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK); mNavButtonView.setLayoutParams(lp); } } private void ensureCollapseButtonView() { if (mCollapseButtonView == null) { mCollapseButtonView = new ImageButton(getContext(), null, R.attr.toolbarNavigationButtonStyle); mCollapseButtonView.setImageDrawable(mCollapseIcon); mCollapseButtonView.setContentDescription(mCollapseDescription); final LayoutParams lp = generateDefaultLayoutParams(); lp.gravity = GravityCompat.START | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK); lp.mViewType = LayoutParams.EXPANDED; mCollapseButtonView.setLayoutParams(lp); mCollapseButtonView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { collapseActionView(); } }); } } private void addSystemView(View v, boolean allowHide) { final ViewGroup.LayoutParams vlp = v.getLayoutParams(); final LayoutParams lp; if (vlp == null) { lp = generateDefaultLayoutParams(); } else if (!checkLayoutParams(vlp)) { lp = generateLayoutParams(vlp); } else { lp = (LayoutParams) vlp; } lp.mViewType = LayoutParams.SYSTEM; if (allowHide && mExpandedActionView != null) { v.setLayoutParams(lp); mHiddenViews.add(v); } else { addView(v, lp); } } @Override protected Parcelable onSaveInstanceState() { SavedState state = new SavedState(super.onSaveInstanceState()); if (mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null) { state.expandedMenuItemId = mExpandedMenuPresenter.mCurrentExpandedItem.getItemId(); } state.isOverflowOpen = isOverflowMenuShowing(); return state; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); final Menu menu = mMenuView != null ? mMenuView.peekMenu() : null; if (ss.expandedMenuItemId != 0 && mExpandedMenuPresenter != null && menu != null) { final MenuItem item = menu.findItem(ss.expandedMenuItemId); if (item != null) { MenuItemCompat.expandActionView(item); } } if (ss.isOverflowOpen) { postShowOverflowMenu(); } } private void postShowOverflowMenu() { removeCallbacks(mShowOverflowMenuRunnable); post(mShowOverflowMenuRunnable); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeCallbacks(mShowOverflowMenuRunnable); } @Override public boolean onTouchEvent(MotionEvent ev) { // Toolbars always eat touch events, but should still respect the touch event dispatch // contract. If the normal View implementation doesn't want the events, we'll just silently // eat the rest of the gesture without reporting the events to the default implementation // since that's what it expects. final int action = MotionEventCompat.getActionMasked(ev); if (action == MotionEvent.ACTION_DOWN) { mEatingTouch = false; } if (!mEatingTouch) { final boolean handled = super.onTouchEvent(ev); if (action == MotionEvent.ACTION_DOWN && !handled) { mEatingTouch = true; } } if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { mEatingTouch = false; } return true; } @Override public boolean onHoverEvent(MotionEvent ev) { // Same deal as onTouchEvent() above. Eat all hover events, but still // respect the touch event dispatch contract. final int action = MotionEventCompat.getActionMasked(ev); if (action == MotionEvent.ACTION_HOVER_ENTER) { mEatingHover = false; } if (!mEatingHover) { final boolean handled = super.onHoverEvent(ev); if (action == MotionEvent.ACTION_HOVER_ENTER && !handled) { mEatingHover = true; } } if (action == MotionEvent.ACTION_HOVER_EXIT || action == MotionEvent.ACTION_CANCEL) { mEatingHover = false; } return true; } private void measureChildConstrained(View child, int parentWidthSpec, int widthUsed, int parentHeightSpec, int heightUsed, int heightConstraint) { final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int childWidthSpec = getChildMeasureSpec(parentWidthSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin + widthUsed, lp.width); int childHeightSpec = getChildMeasureSpec(parentHeightSpec, getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin + heightUsed, lp.height); final int childHeightMode = MeasureSpec.getMode(childHeightSpec); if (childHeightMode != MeasureSpec.EXACTLY && heightConstraint >= 0) { final int size = childHeightMode != MeasureSpec.UNSPECIFIED ? Math.min(MeasureSpec.getSize(childHeightSpec), heightConstraint) : heightConstraint; childHeightSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY); } child.measure(childWidthSpec, childHeightSpec); } /** * Returns the width + uncollapsed margins */ private int measureChildCollapseMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed, int[] collapsingMargins) { final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); final int leftDiff = lp.leftMargin - collapsingMargins[0]; final int rightDiff = lp.rightMargin - collapsingMargins[1]; final int leftMargin = Math.max(0, leftDiff); final int rightMargin = Math.max(0, rightDiff); final int hMargins = leftMargin + rightMargin; collapsingMargins[0] = Math.max(0, -leftDiff); collapsingMargins[1] = Math.max(0, -rightDiff); final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() + getPaddingRight() + hMargins + widthUsed, lp.width); final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin + heightUsed, lp.height); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); return child.getMeasuredWidth() + hMargins; } /** * Returns true if the Toolbar is collapsible and has no child views with a measured size > 0. */ private boolean shouldCollapse() { if (!mCollapsible) return false; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (shouldLayout(child) && child.getMeasuredWidth() > 0 && child.getMeasuredHeight() > 0) { return false; } } return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = 0; int height = 0; int childState = 0; final int[] collapsingMargins = mTempMargins; final int marginStartIndex; final int marginEndIndex; if (ViewUtils.isLayoutRtl(this)) { marginStartIndex = 1; marginEndIndex = 0; } else { marginStartIndex = 0; marginEndIndex = 1; } // System views measure first. int navWidth = 0; if (shouldLayout(mNavButtonView)) { measureChildConstrained(mNavButtonView, widthMeasureSpec, width, heightMeasureSpec, 0, mMaxButtonHeight); navWidth = mNavButtonView.getMeasuredWidth() + getHorizontalMargins(mNavButtonView); height = Math.max(height, mNavButtonView.getMeasuredHeight() + getVerticalMargins(mNavButtonView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mNavButtonView)); } if (shouldLayout(mCollapseButtonView)) { measureChildConstrained(mCollapseButtonView, widthMeasureSpec, width, heightMeasureSpec, 0, mMaxButtonHeight); navWidth = mCollapseButtonView.getMeasuredWidth() + getHorizontalMargins(mCollapseButtonView); height = Math.max(height, mCollapseButtonView.getMeasuredHeight() + getVerticalMargins(mCollapseButtonView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mCollapseButtonView)); } final int contentInsetStart = getCurrentContentInsetStart(); width += Math.max(contentInsetStart, navWidth); collapsingMargins[marginStartIndex] = Math.max(0, contentInsetStart - navWidth); int menuWidth = 0; if (shouldLayout(mMenuView)) { measureChildConstrained(mMenuView, widthMeasureSpec, width, heightMeasureSpec, 0, mMaxButtonHeight); menuWidth = mMenuView.getMeasuredWidth() + getHorizontalMargins(mMenuView); height = Math.max(height, mMenuView.getMeasuredHeight() + getVerticalMargins(mMenuView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mMenuView)); } final int contentInsetEnd = getCurrentContentInsetEnd(); width += Math.max(contentInsetEnd, menuWidth); collapsingMargins[marginEndIndex] = Math.max(0, contentInsetEnd - menuWidth); if (shouldLayout(mExpandedActionView)) { width += measureChildCollapseMargins(mExpandedActionView, widthMeasureSpec, width, heightMeasureSpec, 0, collapsingMargins); height = Math.max(height, mExpandedActionView.getMeasuredHeight() + getVerticalMargins(mExpandedActionView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mExpandedActionView)); } if (shouldLayout(mLogoView)) { width += measureChildCollapseMargins(mLogoView, widthMeasureSpec, width, heightMeasureSpec, 0, collapsingMargins); height = Math.max(height, mLogoView.getMeasuredHeight() + getVerticalMargins(mLogoView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mLogoView)); } final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mViewType != LayoutParams.CUSTOM || !shouldLayout(child)) { // We already got all system views above. Skip them and GONE views. continue; } width += measureChildCollapseMargins(child, widthMeasureSpec, width, heightMeasureSpec, 0, collapsingMargins); height = Math.max(height, child.getMeasuredHeight() + getVerticalMargins(child)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(child)); } int titleWidth = 0; int titleHeight = 0; final int titleVertMargins = mTitleMarginTop + mTitleMarginBottom; final int titleHorizMargins = mTitleMarginStart + mTitleMarginEnd; if (shouldLayout(mTitleTextView)) { titleWidth = measureChildCollapseMargins(mTitleTextView, widthMeasureSpec, width + titleHorizMargins, heightMeasureSpec, titleVertMargins, collapsingMargins); titleWidth = mTitleTextView.getMeasuredWidth() + getHorizontalMargins(mTitleTextView); titleHeight = mTitleTextView.getMeasuredHeight() + getVerticalMargins(mTitleTextView); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mTitleTextView)); } if (shouldLayout(mSubtitleTextView)) { titleWidth = Math.max(titleWidth, measureChildCollapseMargins(mSubtitleTextView, widthMeasureSpec, width + titleHorizMargins, heightMeasureSpec, titleHeight + titleVertMargins, collapsingMargins)); titleHeight += mSubtitleTextView.getMeasuredHeight() + getVerticalMargins(mSubtitleTextView); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mSubtitleTextView)); } width += titleWidth; height = Math.max(height, titleHeight); // Measurement already took padding into account for available space for the children, // add it in for the final size. width += getPaddingLeft() + getPaddingRight(); height += getPaddingTop() + getPaddingBottom(); final int measuredWidth = ViewCompat.resolveSizeAndState( Math.max(width, getSuggestedMinimumWidth()), widthMeasureSpec, childState & ViewCompat.MEASURED_STATE_MASK); final int measuredHeight = ViewCompat.resolveSizeAndState( Math.max(height, getSuggestedMinimumHeight()), heightMeasureSpec, childState << ViewCompat.MEASURED_HEIGHT_STATE_SHIFT); setMeasuredDimension(measuredWidth, shouldCollapse() ? 0 : measuredHeight); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final boolean isRtl = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL; final int width = getWidth(); final int height = getHeight(); final int paddingLeft = getPaddingLeft(); final int paddingRight = getPaddingRight(); final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); int left = paddingLeft; int right = width - paddingRight; final int[] collapsingMargins = mTempMargins; collapsingMargins[0] = collapsingMargins[1] = 0; // Align views within the minimum toolbar height, if set. final int minHeight = ViewCompat.getMinimumHeight(this); final int alignmentHeight = minHeight >= 0 ? Math.min(minHeight, b - t) : 0; if (shouldLayout(mNavButtonView)) { if (isRtl) { right = layoutChildRight(mNavButtonView, right, collapsingMargins, alignmentHeight); } else { left = layoutChildLeft(mNavButtonView, left, collapsingMargins, alignmentHeight); } } if (shouldLayout(mCollapseButtonView)) { if (isRtl) { right = layoutChildRight(mCollapseButtonView, right, collapsingMargins, alignmentHeight); } else { left = layoutChildLeft(mCollapseButtonView, left, collapsingMargins, alignmentHeight); } } if (shouldLayout(mMenuView)) { if (isRtl) { left = layoutChildLeft(mMenuView, left, collapsingMargins, alignmentHeight); } else { right = layoutChildRight(mMenuView, right, collapsingMargins, alignmentHeight); } } final int contentInsetLeft = getCurrentContentInsetLeft(); final int contentInsetRight = getCurrentContentInsetRight(); collapsingMargins[0] = Math.max(0, contentInsetLeft - left); collapsingMargins[1] = Math.max(0, contentInsetRight - (width - paddingRight - right)); left = Math.max(left, contentInsetLeft); right = Math.min(right, width - paddingRight - contentInsetRight); if (shouldLayout(mExpandedActionView)) { if (isRtl) { right = layoutChildRight(mExpandedActionView, right, collapsingMargins, alignmentHeight); } else { left = layoutChildLeft(mExpandedActionView, left, collapsingMargins, alignmentHeight); } } if (shouldLayout(mLogoView)) { if (isRtl) { right = layoutChildRight(mLogoView, right, collapsingMargins, alignmentHeight); } else { left = layoutChildLeft(mLogoView, left, collapsingMargins, alignmentHeight); } } final boolean layoutTitle = shouldLayout(mTitleTextView); final boolean layoutSubtitle = shouldLayout(mSubtitleTextView); int titleHeight = 0; if (layoutTitle) { final LayoutParams lp = (LayoutParams) mTitleTextView.getLayoutParams(); titleHeight += lp.topMargin + mTitleTextView.getMeasuredHeight() + lp.bottomMargin; } if (layoutSubtitle) { final LayoutParams lp = (LayoutParams) mSubtitleTextView.getLayoutParams(); titleHeight += lp.topMargin + mSubtitleTextView.getMeasuredHeight() + lp.bottomMargin; } if (layoutTitle || layoutSubtitle) { int titleTop; final View topChild = layoutTitle ? mTitleTextView : mSubtitleTextView; final View bottomChild = layoutSubtitle ? mSubtitleTextView : mTitleTextView; final LayoutParams toplp = (LayoutParams) topChild.getLayoutParams(); final LayoutParams bottomlp = (LayoutParams) bottomChild.getLayoutParams(); final boolean titleHasWidth = layoutTitle && mTitleTextView.getMeasuredWidth() > 0 || layoutSubtitle && mSubtitleTextView.getMeasuredWidth() > 0; switch (mGravity & Gravity.VERTICAL_GRAVITY_MASK) { case Gravity.TOP: titleTop = getPaddingTop() + toplp.topMargin + mTitleMarginTop; break; default: case Gravity.CENTER_VERTICAL: final int space = height - paddingTop - paddingBottom; int spaceAbove = (space - titleHeight) / 2; if (spaceAbove < toplp.topMargin + mTitleMarginTop) { spaceAbove = toplp.topMargin + mTitleMarginTop; } else { final int spaceBelow = height - paddingBottom - titleHeight - spaceAbove - paddingTop; if (spaceBelow < toplp.bottomMargin + mTitleMarginBottom) { spaceAbove = Math.max(0, spaceAbove - (bottomlp.bottomMargin + mTitleMarginBottom - spaceBelow)); } } titleTop = paddingTop + spaceAbove; break; case Gravity.BOTTOM: titleTop = height - paddingBottom - bottomlp.bottomMargin - mTitleMarginBottom - titleHeight; break; } if (isRtl) { final int rd = (titleHasWidth ? mTitleMarginStart : 0) - collapsingMargins[1]; right -= Math.max(0, rd); collapsingMargins[1] = Math.max(0, -rd); int titleRight = right; int subtitleRight = right; if (layoutTitle) { final LayoutParams lp = (LayoutParams) mTitleTextView.getLayoutParams(); final int titleLeft = titleRight - mTitleTextView.getMeasuredWidth(); final int titleBottom = titleTop + mTitleTextView.getMeasuredHeight(); mTitleTextView.layout(titleLeft, titleTop, titleRight, titleBottom); titleRight = titleLeft - mTitleMarginEnd; titleTop = titleBottom + lp.bottomMargin; } if (layoutSubtitle) { final LayoutParams lp = (LayoutParams) mSubtitleTextView.getLayoutParams(); titleTop += lp.topMargin; final int subtitleLeft = subtitleRight - mSubtitleTextView.getMeasuredWidth(); final int subtitleBottom = titleTop + mSubtitleTextView.getMeasuredHeight(); mSubtitleTextView.layout(subtitleLeft, titleTop, subtitleRight, subtitleBottom); subtitleRight = subtitleRight - mTitleMarginEnd; titleTop = subtitleBottom + lp.bottomMargin; } if (titleHasWidth) { right = Math.min(titleRight, subtitleRight); } } else { final int ld = (titleHasWidth ? mTitleMarginStart : 0) - collapsingMargins[0]; left += Math.max(0, ld); collapsingMargins[0] = Math.max(0, -ld); int titleLeft = left; int subtitleLeft = left; if (layoutTitle) { final LayoutParams lp = (LayoutParams) mTitleTextView.getLayoutParams(); final int titleRight = titleLeft + mTitleTextView.getMeasuredWidth(); final int titleBottom = titleTop + mTitleTextView.getMeasuredHeight(); mTitleTextView.layout(titleLeft, titleTop, titleRight, titleBottom); titleLeft = titleRight + mTitleMarginEnd; titleTop = titleBottom + lp.bottomMargin; } if (layoutSubtitle) { final LayoutParams lp = (LayoutParams) mSubtitleTextView.getLayoutParams(); titleTop += lp.topMargin; final int subtitleRight = subtitleLeft + mSubtitleTextView.getMeasuredWidth(); final int subtitleBottom = titleTop + mSubtitleTextView.getMeasuredHeight(); mSubtitleTextView.layout(subtitleLeft, titleTop, subtitleRight, subtitleBottom); subtitleLeft = subtitleRight + mTitleMarginEnd; titleTop = subtitleBottom + lp.bottomMargin; } if (titleHasWidth) { left = Math.max(titleLeft, subtitleLeft); } } } // Get all remaining children sorted for layout. This is all prepared // such that absolute layout direction can be used below. addCustomViewsWithGravity(mTempViews, Gravity.LEFT); final int leftViewsCount = mTempViews.size(); for (int i = 0; i < leftViewsCount; i++) { left = layoutChildLeft(mTempViews.get(i), left, collapsingMargins, alignmentHeight); } addCustomViewsWithGravity(mTempViews, Gravity.RIGHT); final int rightViewsCount = mTempViews.size(); for (int i = 0; i < rightViewsCount; i++) { right = layoutChildRight(mTempViews.get(i), right, collapsingMargins, alignmentHeight); } // Centered views try to center with respect to the whole bar, but views pinned // to the left or right can push the mass of centered views to one side or the other. addCustomViewsWithGravity(mTempViews, Gravity.CENTER_HORIZONTAL); final int centerViewsWidth = getViewListMeasuredWidth(mTempViews, collapsingMargins); final int parentCenter = paddingLeft + (width - paddingLeft - paddingRight) / 2; final int halfCenterViewsWidth = centerViewsWidth / 2; int centerLeft = parentCenter - halfCenterViewsWidth; final int centerRight = centerLeft + centerViewsWidth; if (centerLeft < left) { centerLeft = left; } else if (centerRight > right) { centerLeft -= centerRight - right; } final int centerViewsCount = mTempViews.size(); for (int i = 0; i < centerViewsCount; i++) { centerLeft = layoutChildLeft(mTempViews.get(i), centerLeft, collapsingMargins, alignmentHeight); } mTempViews.clear(); } private int getViewListMeasuredWidth(List<View> views, int[] collapsingMargins) { int collapseLeft = collapsingMargins[0]; int collapseRight = collapsingMargins[1]; int width = 0; final int count = views.size(); for (int i = 0; i < count; i++) { final View v = views.get(i); final LayoutParams lp = (LayoutParams) v.getLayoutParams(); final int l = lp.leftMargin - collapseLeft; final int r = lp.rightMargin - collapseRight; final int leftMargin = Math.max(0, l); final int rightMargin = Math.max(0, r); collapseLeft = Math.max(0, -l); collapseRight = Math.max(0, -r); width += leftMargin + v.getMeasuredWidth() + rightMargin; } return width; } private int layoutChildLeft(View child, int left, int[] collapsingMargins, int alignmentHeight) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int l = lp.leftMargin - collapsingMargins[0]; left += Math.max(0, l); collapsingMargins[0] = Math.max(0, -l); final int top = getChildTop(child, alignmentHeight); final int childWidth = child.getMeasuredWidth(); child.layout(left, top, left + childWidth, top + child.getMeasuredHeight()); left += childWidth + lp.rightMargin; return left; } private int layoutChildRight(View child, int right, int[] collapsingMargins, int alignmentHeight) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int r = lp.rightMargin - collapsingMargins[1]; right -= Math.max(0, r); collapsingMargins[1] = Math.max(0, -r); final int top = getChildTop(child, alignmentHeight); final int childWidth = child.getMeasuredWidth(); child.layout(right - childWidth, top, right, top + child.getMeasuredHeight()); right -= childWidth + lp.leftMargin; return right; } private int getChildTop(View child, int alignmentHeight) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int childHeight = child.getMeasuredHeight(); final int alignmentOffset = alignmentHeight > 0 ? (childHeight - alignmentHeight) / 2 : 0; switch (getChildVerticalGravity(lp.gravity)) { case Gravity.TOP: return getPaddingTop() - alignmentOffset; case Gravity.BOTTOM: return getHeight() - getPaddingBottom() - childHeight - lp.bottomMargin - alignmentOffset; default: case Gravity.CENTER_VERTICAL: final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); final int height = getHeight(); final int space = height - paddingTop - paddingBottom; int spaceAbove = (space - childHeight) / 2; if (spaceAbove < lp.topMargin) { spaceAbove = lp.topMargin; } else { final int spaceBelow = height - paddingBottom - childHeight - spaceAbove - paddingTop; if (spaceBelow < lp.bottomMargin) { spaceAbove = Math.max(0, spaceAbove - (lp.bottomMargin - spaceBelow)); } } return paddingTop + spaceAbove; } } private int getChildVerticalGravity(int gravity) { final int vgrav = gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (vgrav) { case Gravity.TOP: case Gravity.BOTTOM: case Gravity.CENTER_VERTICAL: return vgrav; default: return mGravity & Gravity.VERTICAL_GRAVITY_MASK; } } /** * Prepare a list of non-SYSTEM child views. If the layout direction is RTL * this will be in reverse child order. * * @param views List to populate. It will be cleared before use. * @param gravity Horizontal gravity to match against */ private void addCustomViewsWithGravity(List<View> views, int gravity) { final boolean isRtl = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL; final int childCount = getChildCount(); final int absGrav = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); views.clear(); if (isRtl) { for (int i = childCount - 1; i >= 0; i--) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mViewType == LayoutParams.CUSTOM && shouldLayout(child) && getChildHorizontalGravity(lp.gravity) == absGrav) { views.add(child); } } } else { for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mViewType == LayoutParams.CUSTOM && shouldLayout(child) && getChildHorizontalGravity(lp.gravity) == absGrav) { views.add(child); } } } } private int getChildHorizontalGravity(int gravity) { final int ld = ViewCompat.getLayoutDirection(this); final int absGrav = GravityCompat.getAbsoluteGravity(gravity, ld); final int hGrav = absGrav & Gravity.HORIZONTAL_GRAVITY_MASK; switch (hGrav) { case Gravity.LEFT: case Gravity.RIGHT: case Gravity.CENTER_HORIZONTAL: return hGrav; default: return ld == ViewCompat.LAYOUT_DIRECTION_RTL ? Gravity.RIGHT : Gravity.LEFT; } } private boolean shouldLayout(View view) { return view != null && view.getParent() == this && view.getVisibility() != GONE; } private int getHorizontalMargins(View v) { final MarginLayoutParams mlp = (MarginLayoutParams) v.getLayoutParams(); return MarginLayoutParamsCompat.getMarginStart(mlp) + MarginLayoutParamsCompat.getMarginEnd(mlp); } private int getVerticalMargins(View v) { final MarginLayoutParams mlp = (MarginLayoutParams) v.getLayoutParams(); return mlp.topMargin + mlp.bottomMargin; } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { if (p instanceof LayoutParams) { return new LayoutParams((LayoutParams) p); } else if (p instanceof ActionBar.LayoutParams) { return new LayoutParams((ActionBar.LayoutParams) p); } else if (p instanceof MarginLayoutParams) { return new LayoutParams((MarginLayoutParams) p); } else { return new LayoutParams(p); } } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return super.checkLayoutParams(p) && p instanceof LayoutParams; } private static boolean isCustomView(View child) { return ((LayoutParams) child.getLayoutParams()).mViewType == LayoutParams.CUSTOM; } /** @hide */ public DecorToolbar getWrapper() { if (mWrapper == null) { mWrapper = new ToolbarWidgetWrapper(this, true); } return mWrapper; } void removeChildrenForExpandedActionView() { final int childCount = getChildCount(); // Go backwards since we're removing from the list for (int i = childCount - 1; i >= 0; i--) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mViewType != LayoutParams.EXPANDED && child != mMenuView) { removeViewAt(i); mHiddenViews.add(child); } } } void addChildrenForExpandedActionView() { final int count = mHiddenViews.size(); // Re-add in reverse order since we removed in reverse order for (int i = count - 1; i >= 0; i--) { addView(mHiddenViews.get(i)); } mHiddenViews.clear(); } private boolean isChildOrHidden(View child) { return child.getParent() == this || mHiddenViews.contains(child); } /** * Force the toolbar to collapse to zero-height during measurement if * it could be considered "empty" (no visible elements with nonzero measured size) * @hide */ public void setCollapsible(boolean collapsible) { mCollapsible = collapsible; requestLayout(); } /** * Must be called before the menu is accessed * @hide */ public void setMenuCallbacks(MenuPresenter.Callback pcb, MenuBuilder.Callback mcb) { mActionMenuPresenterCallback = pcb; mMenuBuilderCallback = mcb; if (mMenuView != null) { mMenuView.setMenuCallbacks(pcb, mcb); } } private void ensureContentInsets() { if (mContentInsets == null) { mContentInsets = new RtlSpacingHelper(); } } /** * Interface responsible for receiving menu item click events if the items themselves * do not have individual item click listeners. */ public interface OnMenuItemClickListener { /** * This method will be invoked when a menu item is clicked if the item itself did * not already handle the event. * * @param item {@link MenuItem} that was clicked * @return <code>true</code> if the event was handled, <code>false</code> otherwise. */ public boolean onMenuItemClick(MenuItem item); } /** * Layout information for child views of Toolbars. * * <p>Toolbar.LayoutParams extends ActionBar.LayoutParams for compatibility with existing * ActionBar API. See * {@link android.support.v7.app.AppCompatActivity#setSupportActionBar(Toolbar) * ActionBarActivity.setActionBar} * for more info on how to use a Toolbar as your Activity's ActionBar.</p> */ public static class LayoutParams extends ActionBar.LayoutParams { static final int CUSTOM = 0; static final int SYSTEM = 1; static final int EXPANDED = 2; int mViewType = CUSTOM; public LayoutParams(@NonNull Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); this.gravity = Gravity.CENTER_VERTICAL | GravityCompat.START; } public LayoutParams(int width, int height, int gravity) { super(width, height); this.gravity = gravity; } public LayoutParams(int gravity) { this(WRAP_CONTENT, MATCH_PARENT, gravity); } public LayoutParams(LayoutParams source) { super(source); mViewType = source.mViewType; } public LayoutParams(ActionBar.LayoutParams source) { super(source); } public LayoutParams(MarginLayoutParams source) { super(source); // ActionBar.LayoutParams doesn't have a MarginLayoutParams constructor. // Fake it here and copy over the relevant data. copyMarginsFromCompat(source); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } void copyMarginsFromCompat(MarginLayoutParams source) { this.leftMargin = source.leftMargin; this.topMargin = source.topMargin; this.rightMargin = source.rightMargin; this.bottomMargin = source.bottomMargin; } } public static class SavedState extends AbsSavedState { int expandedMenuItemId; boolean isOverflowOpen; public SavedState(Parcel source) { this(source, null); } public SavedState(Parcel source, ClassLoader loader) { super(source, loader); expandedMenuItemId = source.readInt(); isOverflowOpen = source.readInt() != 0; } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(expandedMenuItemId); out.writeInt(isOverflowOpen ? 1 : 0); } public static final Creator<SavedState> CREATOR = ParcelableCompat.newCreator( new ParcelableCompatCreatorCallbacks<SavedState>() { @Override public SavedState createFromParcel(Parcel in, ClassLoader loader) { return new SavedState(in, loader); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }); } private class ExpandedActionViewMenuPresenter implements MenuPresenter { MenuBuilder mMenu; MenuItemImpl mCurrentExpandedItem; @Override public void initForMenu(Context context, MenuBuilder menu) { // Clear the expanded action view when menus change. if (mMenu != null && mCurrentExpandedItem != null) { mMenu.collapseItemActionView(mCurrentExpandedItem); } mMenu = menu; } @Override public MenuView getMenuView(ViewGroup root) { return null; } @Override public void updateMenuView(boolean cleared) { // Make sure the expanded item we have is still there. if (mCurrentExpandedItem != null) { boolean found = false; if (mMenu != null) { final int count = mMenu.size(); for (int i = 0; i < count; i++) { final MenuItem item = mMenu.getItem(i); if (item == mCurrentExpandedItem) { found = true; break; } } } if (!found) { // The item we had expanded disappeared. Collapse. collapseItemActionView(mMenu, mCurrentExpandedItem); } } } @Override public void setCallback(Callback cb) { } @Override public boolean onSubMenuSelected(SubMenuBuilder subMenu) { return false; } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { } @Override public boolean flagActionItems() { return false; } @Override public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) { ensureCollapseButtonView(); if (mCollapseButtonView.getParent() != Toolbar.this) { addView(mCollapseButtonView); } mExpandedActionView = item.getActionView(); mCurrentExpandedItem = item; if (mExpandedActionView.getParent() != Toolbar.this) { final LayoutParams lp = generateDefaultLayoutParams(); lp.gravity = GravityCompat.START | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK); lp.mViewType = LayoutParams.EXPANDED; mExpandedActionView.setLayoutParams(lp); addView(mExpandedActionView); } removeChildrenForExpandedActionView(); requestLayout(); item.setActionViewExpanded(true); if (mExpandedActionView instanceof CollapsibleActionView) { ((CollapsibleActionView) mExpandedActionView).onActionViewExpanded(); } return true; } @Override public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) { // Do this before detaching the actionview from the hierarchy, in case // it needs to dismiss the soft keyboard, etc. if (mExpandedActionView instanceof CollapsibleActionView) { ((CollapsibleActionView) mExpandedActionView).onActionViewCollapsed(); } removeView(mExpandedActionView); removeView(mCollapseButtonView); mExpandedActionView = null; addChildrenForExpandedActionView(); mCurrentExpandedItem = null; requestLayout(); item.setActionViewExpanded(false); return true; } @Override public int getId() { return 0; } @Override public Parcelable onSaveInstanceState() { return null; } @Override public void onRestoreInstanceState(Parcelable state) { } } }
v7/appcompat/src/android/support/v7/widget/Toolbar.java
/* * Copyright (C) 2014 The Android Open Source Project * * 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 android.support.v7.widget; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.MenuRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.annotation.StyleRes; import android.support.v4.os.ParcelableCompat; import android.support.v4.os.ParcelableCompatCreatorCallbacks; import android.support.v4.view.AbsSavedState; import android.support.v4.view.GravityCompat; import android.support.v4.view.MarginLayoutParamsCompat; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBar; import android.support.v7.appcompat.R; import android.support.v7.content.res.AppCompatResources; import android.support.v7.view.CollapsibleActionView; import android.support.v7.view.SupportMenuInflater; import android.support.v7.view.menu.MenuBuilder; import android.support.v7.view.menu.MenuItemImpl; import android.support.v7.view.menu.MenuPresenter; import android.support.v7.view.menu.MenuView; import android.support.v7.view.menu.SubMenuBuilder; import android.text.Layout; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * A standard toolbar for use within application content. * * <p>A Toolbar is a generalization of {@link ActionBar action bars} for use * within application layouts. While an action bar is traditionally part of an * {@link android.app.Activity Activity's} opaque window decor controlled by the framework, * a Toolbar may be placed at any arbitrary level of nesting within a view hierarchy. * An application may choose to designate a Toolbar as the action bar for an Activity * using the {@link android.support.v7.app.AppCompatActivity#setSupportActionBar(Toolbar) * setSupportActionBar()} method.</p> * * <p>Toolbar supports a more focused feature set than ActionBar. From start to end, a toolbar * may contain a combination of the following optional elements: * * <ul> * <li><em>A navigation button.</em> This may be an Up arrow, navigation menu toggle, close, * collapse, done or another glyph of the app's choosing. This button should always be used * to access other navigational destinations within the container of the Toolbar and * its signified content or otherwise leave the current context signified by the Toolbar. * The navigation button is vertically aligned within the Toolbar's minimum height, * if set.</li> * <li><em>A branded logo image.</em> This may extend to the height of the bar and can be * arbitrarily wide.</li> * <li><em>A title and subtitle.</em> The title should be a signpost for the Toolbar's current * position in the navigation hierarchy and the content contained there. The subtitle, * if present should indicate any extended information about the current content. * If an app uses a logo image it should strongly consider omitting a title and subtitle.</li> * <li><em>One or more custom views.</em> The application may add arbitrary child views * to the Toolbar. They will appear at this position within the layout. If a child view's * {@link LayoutParams} indicates a {@link Gravity} value of * {@link Gravity#CENTER_HORIZONTAL CENTER_HORIZONTAL} the view will attempt to center * within the available space remaining in the Toolbar after all other elements have been * measured.</li> * <li><em>An {@link ActionMenuView action menu}.</em> The menu of actions will pin to the * end of the Toolbar offering a few * <a href="http://developer.android.com/design/patterns/actionbar.html#ActionButtons"> * frequent, important or typical</a> actions along with an optional overflow menu for * additional actions. Action buttons are vertically aligned within the Toolbar's * minimum height, if set.</li> * </ul> * </p> * * <p>In modern Android UIs developers should lean more on a visually distinct color scheme for * toolbars than on their application icon. The use of application icon plus title as a standard * layout is discouraged on API 21 devices and newer.</p> * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_buttonGravity * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_collapseContentDescription * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_collapseIcon * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEnd * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetLeft * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetRight * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStart * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStartWithNavigation * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEndWithActions * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_android_gravity * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_logo * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_logoDescription * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_maxButtonHeight * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationContentDescription * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationIcon * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_popupTheme * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_subtitle * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_subtitleTextAppearance * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_subtitleTextColor * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_title * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMargin * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginBottom * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginEnd * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginStart * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginTop * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleTextAppearance * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleTextColor */ public class Toolbar extends ViewGroup { private static final String TAG = "Toolbar"; private ActionMenuView mMenuView; private TextView mTitleTextView; private TextView mSubtitleTextView; private ImageButton mNavButtonView; private ImageView mLogoView; private Drawable mCollapseIcon; private CharSequence mCollapseDescription; private ImageButton mCollapseButtonView; View mExpandedActionView; /** Context against which to inflate popup menus. */ private Context mPopupContext; /** Theme resource against which to inflate popup menus. */ private int mPopupTheme; private int mTitleTextAppearance; private int mSubtitleTextAppearance; private int mButtonGravity; private int mMaxButtonHeight; private int mTitleMarginStart; private int mTitleMarginEnd; private int mTitleMarginTop; private int mTitleMarginBottom; private RtlSpacingHelper mContentInsets; private int mContentInsetStartWithNavigation; private int mContentInsetEndWithActions; private int mGravity = GravityCompat.START | Gravity.CENTER_VERTICAL; private CharSequence mTitleText; private CharSequence mSubtitleText; private int mTitleTextColor; private int mSubtitleTextColor; private boolean mEatingTouch; private boolean mEatingHover; // Clear me after use. private final ArrayList<View> mTempViews = new ArrayList<View>(); // Used to hold views that will be removed while we have an expanded action view. private final ArrayList<View> mHiddenViews = new ArrayList<>(); private final int[] mTempMargins = new int[2]; private OnMenuItemClickListener mOnMenuItemClickListener; private final ActionMenuView.OnMenuItemClickListener mMenuViewItemClickListener = new ActionMenuView.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (mOnMenuItemClickListener != null) { return mOnMenuItemClickListener.onMenuItemClick(item); } return false; } }; private ToolbarWidgetWrapper mWrapper; private ActionMenuPresenter mOuterActionMenuPresenter; private ExpandedActionViewMenuPresenter mExpandedMenuPresenter; private MenuPresenter.Callback mActionMenuPresenterCallback; private MenuBuilder.Callback mMenuBuilderCallback; private boolean mCollapsible; private final Runnable mShowOverflowMenuRunnable = new Runnable() { @Override public void run() { showOverflowMenu(); } }; public Toolbar(Context context) { this(context, null); } public Toolbar(Context context, @Nullable AttributeSet attrs) { this(context, attrs, R.attr.toolbarStyle); } public Toolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // Need to use getContext() here so that we use the themed context final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.Toolbar, defStyleAttr, 0); mTitleTextAppearance = a.getResourceId(R.styleable.Toolbar_titleTextAppearance, 0); mSubtitleTextAppearance = a.getResourceId(R.styleable.Toolbar_subtitleTextAppearance, 0); mGravity = a.getInteger(R.styleable.Toolbar_android_gravity, mGravity); mButtonGravity = a.getInteger(R.styleable.Toolbar_buttonGravity, Gravity.TOP); // First read the correct attribute int titleMargin = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMargin, 0); if (a.hasValue(R.styleable.Toolbar_titleMargins)) { // Now read the deprecated attribute, if it has a value titleMargin = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMargins, titleMargin); } mTitleMarginStart = mTitleMarginEnd = mTitleMarginTop = mTitleMarginBottom = titleMargin; final int marginStart = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMarginStart, -1); if (marginStart >= 0) { mTitleMarginStart = marginStart; } final int marginEnd = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMarginEnd, -1); if (marginEnd >= 0) { mTitleMarginEnd = marginEnd; } final int marginTop = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMarginTop, -1); if (marginTop >= 0) { mTitleMarginTop = marginTop; } final int marginBottom = a.getDimensionPixelOffset(R.styleable.Toolbar_titleMarginBottom, -1); if (marginBottom >= 0) { mTitleMarginBottom = marginBottom; } mMaxButtonHeight = a.getDimensionPixelSize(R.styleable.Toolbar_maxButtonHeight, -1); final int contentInsetStart = a.getDimensionPixelOffset(R.styleable.Toolbar_contentInsetStart, RtlSpacingHelper.UNDEFINED); final int contentInsetEnd = a.getDimensionPixelOffset(R.styleable.Toolbar_contentInsetEnd, RtlSpacingHelper.UNDEFINED); final int contentInsetLeft = a.getDimensionPixelSize(R.styleable.Toolbar_contentInsetLeft, 0); final int contentInsetRight = a.getDimensionPixelSize(R.styleable.Toolbar_contentInsetRight, 0); ensureContentInsets(); mContentInsets.setAbsolute(contentInsetLeft, contentInsetRight); if (contentInsetStart != RtlSpacingHelper.UNDEFINED || contentInsetEnd != RtlSpacingHelper.UNDEFINED) { mContentInsets.setRelative(contentInsetStart, contentInsetEnd); } mContentInsetStartWithNavigation = a.getDimensionPixelOffset( R.styleable.Toolbar_contentInsetStartWithNavigation, RtlSpacingHelper.UNDEFINED); mContentInsetEndWithActions = a.getDimensionPixelOffset( R.styleable.Toolbar_contentInsetEndWithActions, RtlSpacingHelper.UNDEFINED); mCollapseIcon = a.getDrawable(R.styleable.Toolbar_collapseIcon); mCollapseDescription = a.getText(R.styleable.Toolbar_collapseContentDescription); final CharSequence title = a.getText(R.styleable.Toolbar_title); if (!TextUtils.isEmpty(title)) { setTitle(title); } final CharSequence subtitle = a.getText(R.styleable.Toolbar_subtitle); if (!TextUtils.isEmpty(subtitle)) { setSubtitle(subtitle); } // Set the default context, since setPopupTheme() may be a no-op. mPopupContext = getContext(); setPopupTheme(a.getResourceId(R.styleable.Toolbar_popupTheme, 0)); final Drawable navIcon = a.getDrawable(R.styleable.Toolbar_navigationIcon); if (navIcon != null) { setNavigationIcon(navIcon); } final CharSequence navDesc = a.getText(R.styleable.Toolbar_navigationContentDescription); if (!TextUtils.isEmpty(navDesc)) { setNavigationContentDescription(navDesc); } final Drawable logo = a.getDrawable(R.styleable.Toolbar_logo); if (logo != null) { setLogo(logo); } final CharSequence logoDesc = a.getText(R.styleable.Toolbar_logoDescription); if (!TextUtils.isEmpty(logoDesc)) { setLogoDescription(logoDesc); } if (a.hasValue(R.styleable.Toolbar_titleTextColor)) { setTitleTextColor(a.getColor(R.styleable.Toolbar_titleTextColor, 0xffffffff)); } if (a.hasValue(R.styleable.Toolbar_subtitleTextColor)) { setSubtitleTextColor(a.getColor(R.styleable.Toolbar_subtitleTextColor, 0xffffffff)); } a.recycle(); } /** * Specifies the theme to use when inflating popup menus. By default, uses * the same theme as the toolbar itself. * * @param resId theme used to inflate popup menus * @see #getPopupTheme() */ public void setPopupTheme(@StyleRes int resId) { if (mPopupTheme != resId) { mPopupTheme = resId; if (resId == 0) { mPopupContext = getContext(); } else { mPopupContext = new ContextThemeWrapper(getContext(), resId); } } } /** * @return resource identifier of the theme used to inflate popup menus, or * 0 if menus are inflated against the toolbar theme * @see #setPopupTheme(int) */ public int getPopupTheme() { return mPopupTheme; } /** * Sets the title margin. * * @param start the starting title margin in pixels * @param top the top title margin in pixels * @param end the ending title margin in pixels * @param bottom the bottom title margin in pixels * @see #getTitleMarginStart() * @see #getTitleMarginTop() * @see #getTitleMarginEnd() * @see #getTitleMarginBottom() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMargin */ public void setTitleMargin(int start, int top, int end, int bottom) { mTitleMarginStart = start; mTitleMarginTop = top; mTitleMarginEnd = end; mTitleMarginBottom = bottom; requestLayout(); } /** * @return the starting title margin in pixels * @see #setTitleMarginStart(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginStart */ public int getTitleMarginStart() { return mTitleMarginStart; } /** * Sets the starting title margin in pixels. * * @param margin the starting title margin in pixels * @see #getTitleMarginStart() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginStart */ public void setTitleMarginStart(int margin) { mTitleMarginStart = margin; requestLayout(); } /** * @return the top title margin in pixels * @see #setTitleMarginTop(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginTop */ public int getTitleMarginTop() { return mTitleMarginTop; } /** * Sets the top title margin in pixels. * * @param margin the top title margin in pixels * @see #getTitleMarginTop() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginTop */ public void setTitleMarginTop(int margin) { mTitleMarginTop = margin; requestLayout(); } /** * @return the ending title margin in pixels * @see #setTitleMarginEnd(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginEnd */ public int getTitleMarginEnd() { return mTitleMarginEnd; } /** * Sets the ending title margin in pixels. * * @param margin the ending title margin in pixels * @see #getTitleMarginEnd() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginEnd */ public void setTitleMarginEnd(int margin) { mTitleMarginEnd = margin; requestLayout(); } /** * @return the bottom title margin in pixels * @see #setTitleMarginBottom(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginBottom */ public int getTitleMarginBottom() { return mTitleMarginBottom; } /** * Sets the bottom title margin in pixels. * * @param margin the bottom title margin in pixels * @see #getTitleMarginBottom() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_titleMarginBottom */ public void setTitleMarginBottom(int margin) { mTitleMarginBottom = margin; requestLayout(); } public void onRtlPropertiesChanged(int layoutDirection) { if (Build.VERSION.SDK_INT >= 17) { super.onRtlPropertiesChanged(layoutDirection); } ensureContentInsets(); mContentInsets.setDirection(layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL); } /** * Set a logo drawable from a resource id. * * <p>This drawable should generally take the place of title text. The logo cannot be * clicked. Apps using a logo should also supply a description using * {@link #setLogoDescription(int)}.</p> * * @param resId ID of a drawable resource */ public void setLogo(@DrawableRes int resId) { setLogo(AppCompatResources.getDrawable(getContext(), resId)); } /** @hide */ public boolean canShowOverflowMenu() { return getVisibility() == VISIBLE && mMenuView != null && mMenuView.isOverflowReserved(); } /** * Check whether the overflow menu is currently showing. This may not reflect * a pending show operation in progress. * * @return true if the overflow menu is currently showing */ public boolean isOverflowMenuShowing() { return mMenuView != null && mMenuView.isOverflowMenuShowing(); } /** @hide */ public boolean isOverflowMenuShowPending() { return mMenuView != null && mMenuView.isOverflowMenuShowPending(); } /** * Show the overflow items from the associated menu. * * @return true if the menu was able to be shown, false otherwise */ public boolean showOverflowMenu() { return mMenuView != null && mMenuView.showOverflowMenu(); } /** * Hide the overflow items from the associated menu. * * @return true if the menu was able to be hidden, false otherwise */ public boolean hideOverflowMenu() { return mMenuView != null && mMenuView.hideOverflowMenu(); } /** @hide */ public void setMenu(MenuBuilder menu, ActionMenuPresenter outerPresenter) { if (menu == null && mMenuView == null) { return; } ensureMenuView(); final MenuBuilder oldMenu = mMenuView.peekMenu(); if (oldMenu == menu) { return; } if (oldMenu != null) { oldMenu.removeMenuPresenter(mOuterActionMenuPresenter); oldMenu.removeMenuPresenter(mExpandedMenuPresenter); } if (mExpandedMenuPresenter == null) { mExpandedMenuPresenter = new ExpandedActionViewMenuPresenter(); } outerPresenter.setExpandedActionViewsExclusive(true); if (menu != null) { menu.addMenuPresenter(outerPresenter, mPopupContext); menu.addMenuPresenter(mExpandedMenuPresenter, mPopupContext); } else { outerPresenter.initForMenu(mPopupContext, null); mExpandedMenuPresenter.initForMenu(mPopupContext, null); outerPresenter.updateMenuView(true); mExpandedMenuPresenter.updateMenuView(true); } mMenuView.setPopupTheme(mPopupTheme); mMenuView.setPresenter(outerPresenter); mOuterActionMenuPresenter = outerPresenter; } /** * Dismiss all currently showing popup menus, including overflow or submenus. */ public void dismissPopupMenus() { if (mMenuView != null) { mMenuView.dismissPopupMenus(); } } /** @hide */ public boolean isTitleTruncated() { if (mTitleTextView == null) { return false; } final Layout titleLayout = mTitleTextView.getLayout(); if (titleLayout == null) { return false; } final int lineCount = titleLayout.getLineCount(); for (int i = 0; i < lineCount; i++) { if (titleLayout.getEllipsisCount(i) > 0) { return true; } } return false; } /** * Set a logo drawable. * * <p>This drawable should generally take the place of title text. The logo cannot be * clicked. Apps using a logo should also supply a description using * {@link #setLogoDescription(int)}.</p> * * @param drawable Drawable to use as a logo */ public void setLogo(Drawable drawable) { if (drawable != null) { ensureLogoView(); if (!isChildOrHidden(mLogoView)) { addSystemView(mLogoView, true); } } else if (mLogoView != null && isChildOrHidden(mLogoView)) { removeView(mLogoView); mHiddenViews.remove(mLogoView); } if (mLogoView != null) { mLogoView.setImageDrawable(drawable); } } /** * Return the current logo drawable. * * @return The current logo drawable * @see #setLogo(int) * @see #setLogo(android.graphics.drawable.Drawable) */ public Drawable getLogo() { return mLogoView != null ? mLogoView.getDrawable() : null; } /** * Set a description of the toolbar's logo. * * <p>This description will be used for accessibility or other similar descriptions * of the UI.</p> * * @param resId String resource id */ public void setLogoDescription(@StringRes int resId) { setLogoDescription(getContext().getText(resId)); } /** * Set a description of the toolbar's logo. * * <p>This description will be used for accessibility or other similar descriptions * of the UI.</p> * * @param description Description to set */ public void setLogoDescription(CharSequence description) { if (!TextUtils.isEmpty(description)) { ensureLogoView(); } if (mLogoView != null) { mLogoView.setContentDescription(description); } } /** * Return the description of the toolbar's logo. * * @return A description of the logo */ public CharSequence getLogoDescription() { return mLogoView != null ? mLogoView.getContentDescription() : null; } private void ensureLogoView() { if (mLogoView == null) { mLogoView = new ImageView(getContext()); } } /** * Check whether this Toolbar is currently hosting an expanded action view. * * <p>An action view may be expanded either directly from the * {@link android.view.MenuItem MenuItem} it belongs to or by user action. If the Toolbar * has an expanded action view it can be collapsed using the {@link #collapseActionView()} * method.</p> * * @return true if the Toolbar has an expanded action view */ public boolean hasExpandedActionView() { return mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null; } /** * Collapse a currently expanded action view. If this Toolbar does not have an * expanded action view this method has no effect. * * <p>An action view may be expanded either directly from the * {@link android.view.MenuItem MenuItem} it belongs to or by user action.</p> * * @see #hasExpandedActionView() */ public void collapseActionView() { final MenuItemImpl item = mExpandedMenuPresenter == null ? null : mExpandedMenuPresenter.mCurrentExpandedItem; if (item != null) { item.collapseActionView(); } } /** * Returns the title of this toolbar. * * @return The current title. */ public CharSequence getTitle() { return mTitleText; } /** * Set the title of this toolbar. * * <p>A title should be used as the anchor for a section of content. It should * describe or name the content being viewed.</p> * * @param resId Resource ID of a string to set as the title */ public void setTitle(@StringRes int resId) { setTitle(getContext().getText(resId)); } /** * Set the title of this toolbar. * * <p>A title should be used as the anchor for a section of content. It should * describe or name the content being viewed.</p> * * @param title Title to set */ public void setTitle(CharSequence title) { if (!TextUtils.isEmpty(title)) { if (mTitleTextView == null) { final Context context = getContext(); mTitleTextView = new TextView(context); mTitleTextView.setSingleLine(); mTitleTextView.setEllipsize(TextUtils.TruncateAt.END); if (mTitleTextAppearance != 0) { mTitleTextView.setTextAppearance(context, mTitleTextAppearance); } if (mTitleTextColor != 0) { mTitleTextView.setTextColor(mTitleTextColor); } } if (!isChildOrHidden(mTitleTextView)) { addSystemView(mTitleTextView, true); } } else if (mTitleTextView != null && isChildOrHidden(mTitleTextView)) { removeView(mTitleTextView); mHiddenViews.remove(mTitleTextView); } if (mTitleTextView != null) { mTitleTextView.setText(title); } mTitleText = title; } /** * Return the subtitle of this toolbar. * * @return The current subtitle */ public CharSequence getSubtitle() { return mSubtitleText; } /** * Set the subtitle of this toolbar. * * <p>Subtitles should express extended information about the current content.</p> * * @param resId String resource ID */ public void setSubtitle(@StringRes int resId) { setSubtitle(getContext().getText(resId)); } /** * Set the subtitle of this toolbar. * * <p>Subtitles should express extended information about the current content.</p> * * @param subtitle Subtitle to set */ public void setSubtitle(CharSequence subtitle) { if (!TextUtils.isEmpty(subtitle)) { if (mSubtitleTextView == null) { final Context context = getContext(); mSubtitleTextView = new TextView(context); mSubtitleTextView.setSingleLine(); mSubtitleTextView.setEllipsize(TextUtils.TruncateAt.END); if (mSubtitleTextAppearance != 0) { mSubtitleTextView.setTextAppearance(context, mSubtitleTextAppearance); } if (mSubtitleTextColor != 0) { mSubtitleTextView.setTextColor(mSubtitleTextColor); } } if (!isChildOrHidden(mSubtitleTextView)) { addSystemView(mSubtitleTextView, true); } } else if (mSubtitleTextView != null && isChildOrHidden(mSubtitleTextView)) { removeView(mSubtitleTextView); mHiddenViews.remove(mSubtitleTextView); } if (mSubtitleTextView != null) { mSubtitleTextView.setText(subtitle); } mSubtitleText = subtitle; } /** * Sets the text color, size, style, hint color, and highlight color * from the specified TextAppearance resource. */ public void setTitleTextAppearance(Context context, @StyleRes int resId) { mTitleTextAppearance = resId; if (mTitleTextView != null) { mTitleTextView.setTextAppearance(context, resId); } } /** * Sets the text color, size, style, hint color, and highlight color * from the specified TextAppearance resource. */ public void setSubtitleTextAppearance(Context context, @StyleRes int resId) { mSubtitleTextAppearance = resId; if (mSubtitleTextView != null) { mSubtitleTextView.setTextAppearance(context, resId); } } /** * Sets the text color of the title, if present. * * @param color The new text color in 0xAARRGGBB format */ public void setTitleTextColor(@ColorInt int color) { mTitleTextColor = color; if (mTitleTextView != null) { mTitleTextView.setTextColor(color); } } /** * Sets the text color of the subtitle, if present. * * @param color The new text color in 0xAARRGGBB format */ public void setSubtitleTextColor(@ColorInt int color) { mSubtitleTextColor = color; if (mSubtitleTextView != null) { mSubtitleTextView.setTextColor(color); } } /** * Retrieve the currently configured content description for the navigation button view. * This will be used to describe the navigation action to users through mechanisms such * as screen readers or tooltips. * * @return The navigation button's content description * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationContentDescription */ @Nullable public CharSequence getNavigationContentDescription() { return mNavButtonView != null ? mNavButtonView.getContentDescription() : null; } /** * Set a content description for the navigation button if one is present. The content * description will be read via screen readers or other accessibility systems to explain * the action of the navigation button. * * @param resId Resource ID of a content description string to set, or 0 to * clear the description * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationContentDescription */ public void setNavigationContentDescription(@StringRes int resId) { setNavigationContentDescription(resId != 0 ? getContext().getText(resId) : null); } /** * Set a content description for the navigation button if one is present. The content * description will be read via screen readers or other accessibility systems to explain * the action of the navigation button. * * @param description Content description to set, or <code>null</code> to * clear the content description * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationContentDescription */ public void setNavigationContentDescription(@Nullable CharSequence description) { if (!TextUtils.isEmpty(description)) { ensureNavButtonView(); } if (mNavButtonView != null) { mNavButtonView.setContentDescription(description); } } /** * Set the icon to use for the toolbar's navigation button. * * <p>The navigation button appears at the start of the toolbar if present. Setting an icon * will make the navigation button visible.</p> * * <p>If you use a navigation icon you should also set a description for its action using * {@link #setNavigationContentDescription(int)}. This is used for accessibility and * tooltips.</p> * * @param resId Resource ID of a drawable to set * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationIcon */ public void setNavigationIcon(@DrawableRes int resId) { setNavigationIcon(AppCompatResources.getDrawable(getContext(), resId)); } /** * Set the icon to use for the toolbar's navigation button. * * <p>The navigation button appears at the start of the toolbar if present. Setting an icon * will make the navigation button visible.</p> * * <p>If you use a navigation icon you should also set a description for its action using * {@link #setNavigationContentDescription(int)}. This is used for accessibility and * tooltips.</p> * * @param icon Drawable to set, may be null to clear the icon * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationIcon */ public void setNavigationIcon(@Nullable Drawable icon) { if (icon != null) { ensureNavButtonView(); if (!isChildOrHidden(mNavButtonView)) { addSystemView(mNavButtonView, true); } } else if (mNavButtonView != null && isChildOrHidden(mNavButtonView)) { removeView(mNavButtonView); mHiddenViews.remove(mNavButtonView); } if (mNavButtonView != null) { mNavButtonView.setImageDrawable(icon); } } /** * Return the current drawable used as the navigation icon. * * @return The navigation icon drawable * * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_navigationIcon */ @Nullable public Drawable getNavigationIcon() { return mNavButtonView != null ? mNavButtonView.getDrawable() : null; } /** * Set a listener to respond to navigation events. * * <p>This listener will be called whenever the user clicks the navigation button * at the start of the toolbar. An icon must be set for the navigation button to appear.</p> * * @param listener Listener to set * @see #setNavigationIcon(android.graphics.drawable.Drawable) */ public void setNavigationOnClickListener(OnClickListener listener) { ensureNavButtonView(); mNavButtonView.setOnClickListener(listener); } /** * Return the Menu shown in the toolbar. * * <p>Applications that wish to populate the toolbar's menu can do so from here. To use * an XML menu resource, use {@link #inflateMenu(int)}.</p> * * @return The toolbar's Menu */ public Menu getMenu() { ensureMenu(); return mMenuView.getMenu(); } /** * Set the icon to use for the overflow button. * * @param icon Drawable to set, may be null to clear the icon */ public void setOverflowIcon(@Nullable Drawable icon) { ensureMenu(); mMenuView.setOverflowIcon(icon); } /** * Return the current drawable used as the overflow icon. * * @return The overflow icon drawable */ @Nullable public Drawable getOverflowIcon() { ensureMenu(); return mMenuView.getOverflowIcon(); } private void ensureMenu() { ensureMenuView(); if (mMenuView.peekMenu() == null) { // Initialize a new menu for the first time. final MenuBuilder menu = (MenuBuilder) mMenuView.getMenu(); if (mExpandedMenuPresenter == null) { mExpandedMenuPresenter = new ExpandedActionViewMenuPresenter(); } mMenuView.setExpandedActionViewsExclusive(true); menu.addMenuPresenter(mExpandedMenuPresenter, mPopupContext); } } private void ensureMenuView() { if (mMenuView == null) { mMenuView = new ActionMenuView(getContext()); mMenuView.setPopupTheme(mPopupTheme); mMenuView.setOnMenuItemClickListener(mMenuViewItemClickListener); mMenuView.setMenuCallbacks(mActionMenuPresenterCallback, mMenuBuilderCallback); final LayoutParams lp = generateDefaultLayoutParams(); lp.gravity = GravityCompat.END | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK); mMenuView.setLayoutParams(lp); addSystemView(mMenuView, false); } } private MenuInflater getMenuInflater() { return new SupportMenuInflater(getContext()); } /** * Inflate a menu resource into this toolbar. * * <p>Inflate an XML menu resource into this toolbar. Existing items in the menu will not * be modified or removed.</p> * * @param resId ID of a menu resource to inflate */ public void inflateMenu(@MenuRes int resId) { getMenuInflater().inflate(resId, getMenu()); } /** * Set a listener to respond to menu item click events. * * <p>This listener will be invoked whenever a user selects a menu item from * the action buttons presented at the end of the toolbar or the associated overflow.</p> * * @param listener Listener to set */ public void setOnMenuItemClickListener(OnMenuItemClickListener listener) { mOnMenuItemClickListener = listener; } /** * Sets the content insets for this toolbar relative to layout direction. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @param contentInsetStart Content inset for the toolbar starting edge * @param contentInsetEnd Content inset for the toolbar ending edge * * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetEnd() * @see #getContentInsetLeft() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEnd * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStart */ public void setContentInsetsRelative(int contentInsetStart, int contentInsetEnd) { ensureContentInsets(); mContentInsets.setRelative(contentInsetStart, contentInsetEnd); } /** * Gets the starting content inset for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @return The starting content inset for this toolbar * * @see #setContentInsetsRelative(int, int) * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetEnd() * @see #getContentInsetLeft() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStart */ public int getContentInsetStart() { return mContentInsets != null ? mContentInsets.getStart() : 0; } /** * Gets the ending content inset for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @return The ending content inset for this toolbar * * @see #setContentInsetsRelative(int, int) * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetLeft() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEnd */ public int getContentInsetEnd() { return mContentInsets != null ? mContentInsets.getEnd() : 0; } /** * Sets the content insets for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @param contentInsetLeft Content inset for the toolbar's left edge * @param contentInsetRight Content inset for the toolbar's right edge * * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetEnd() * @see #getContentInsetLeft() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetLeft * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetRight */ public void setContentInsetsAbsolute(int contentInsetLeft, int contentInsetRight) { ensureContentInsets(); mContentInsets.setAbsolute(contentInsetLeft, contentInsetRight); } /** * Gets the left content inset for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @return The left content inset for this toolbar * * @see #setContentInsetsRelative(int, int) * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetEnd() * @see #getContentInsetRight() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetLeft */ public int getContentInsetLeft() { return mContentInsets != null ? mContentInsets.getLeft() : 0; } /** * Gets the right content inset for this toolbar. * * <p>The content inset affects the valid area for Toolbar content other than * the navigation button and menu. Insets define the minimum margin for these components * and can be used to effectively align Toolbar content along well-known gridlines.</p> * * @return The right content inset for this toolbar * * @see #setContentInsetsRelative(int, int) * @see #setContentInsetsAbsolute(int, int) * @see #getContentInsetStart() * @see #getContentInsetEnd() * @see #getContentInsetLeft() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetRight */ public int getContentInsetRight() { return mContentInsets != null ? mContentInsets.getRight() : 0; } /** * Gets the start content inset to use when a navigation button is present. * * <p>Different content insets are often called for when additional buttons are present * in the toolbar, as well as at different toolbar sizes. The larger value of * {@link #getContentInsetStart()} and this value will be used during layout.</p> * * @return the start content inset used when a navigation icon has been set in pixels * * @see #setContentInsetStartWithNavigation(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStartWithNavigation */ public int getContentInsetStartWithNavigation() { return mContentInsetStartWithNavigation != RtlSpacingHelper.UNDEFINED ? mContentInsetStartWithNavigation : getContentInsetStart(); } /** * Sets the start content inset to use when a navigation button is present. * * <p>Different content insets are often called for when additional buttons are present * in the toolbar, as well as at different toolbar sizes. The larger value of * {@link #getContentInsetStart()} and this value will be used during layout.</p> * * @param insetStartWithNavigation the inset to use when a navigation icon has been set * in pixels * * @see #getContentInsetStartWithNavigation() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetStartWithNavigation */ public void setContentInsetStartWithNavigation(int insetStartWithNavigation) { if (insetStartWithNavigation < 0) { insetStartWithNavigation = RtlSpacingHelper.UNDEFINED; } if (insetStartWithNavigation != mContentInsetStartWithNavigation) { mContentInsetStartWithNavigation = insetStartWithNavigation; if (getNavigationIcon() != null) { requestLayout(); } } } /** * Gets the end content inset to use when action buttons are present. * * <p>Different content insets are often called for when additional buttons are present * in the toolbar, as well as at different toolbar sizes. The larger value of * {@link #getContentInsetEnd()} and this value will be used during layout.</p> * * @return the end content inset used when a menu has been set in pixels * * @see #setContentInsetEndWithActions(int) * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEndWithActions */ public int getContentInsetEndWithActions() { return mContentInsetEndWithActions != RtlSpacingHelper.UNDEFINED ? mContentInsetEndWithActions : getContentInsetEnd(); } /** * Sets the start content inset to use when action buttons are present. * * <p>Different content insets are often called for when additional buttons are present * in the toolbar, as well as at different toolbar sizes. The larger value of * {@link #getContentInsetEnd()} and this value will be used during layout.</p> * * @param insetEndWithActions the inset to use when a menu has been set in pixels * * @see #getContentInsetEndWithActions() * @attr ref android.support.v7.appcompat.R.styleable#Toolbar_contentInsetEndWithActions */ public void setContentInsetEndWithActions(int insetEndWithActions) { if (insetEndWithActions < 0) { insetEndWithActions = RtlSpacingHelper.UNDEFINED; } if (insetEndWithActions != mContentInsetEndWithActions) { mContentInsetEndWithActions = insetEndWithActions; if (getNavigationIcon() != null) { requestLayout(); } } } /** * Gets the content inset that will be used on the starting side of the bar in the current * toolbar configuration. * * @return the current content inset start in pixels * * @see #getContentInsetStartWithNavigation() */ public int getCurrentContentInsetStart() { return getNavigationIcon() != null ? Math.max(getContentInsetStart(), Math.max(mContentInsetStartWithNavigation, 0)) : getContentInsetStart(); } /** * Gets the content inset that will be used on the ending side of the bar in the current * toolbar configuration. * * @return the current content inset end in pixels * * @see #getContentInsetEndWithActions() */ public int getCurrentContentInsetEnd() { boolean hasActions = false; if (mMenuView != null) { final MenuBuilder mb = mMenuView.peekMenu(); hasActions = mb != null && mb.hasVisibleItems(); } return hasActions ? Math.max(getContentInsetEnd(), Math.max(mContentInsetEndWithActions, 0)) : getContentInsetEnd(); } /** * Gets the content inset that will be used on the left side of the bar in the current * toolbar configuration. * * @return the current content inset left in pixels * * @see #getContentInsetStartWithNavigation() * @see #getContentInsetEndWithActions() */ public int getCurrentContentInsetLeft() { return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL ? getCurrentContentInsetEnd() : getCurrentContentInsetStart(); } /** * Gets the content inset that will be used on the right side of the bar in the current * toolbar configuration. * * @return the current content inset right in pixels * * @see #getContentInsetStartWithNavigation() * @see #getContentInsetEndWithActions() */ public int getCurrentContentInsetRight() { return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL ? getCurrentContentInsetStart() : getCurrentContentInsetEnd(); } private void ensureNavButtonView() { if (mNavButtonView == null) { mNavButtonView = new ImageButton(getContext(), null, R.attr.toolbarNavigationButtonStyle); final LayoutParams lp = generateDefaultLayoutParams(); lp.gravity = GravityCompat.START | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK); mNavButtonView.setLayoutParams(lp); } } private void ensureCollapseButtonView() { if (mCollapseButtonView == null) { mCollapseButtonView = new ImageButton(getContext(), null, R.attr.toolbarNavigationButtonStyle); mCollapseButtonView.setImageDrawable(mCollapseIcon); mCollapseButtonView.setContentDescription(mCollapseDescription); final LayoutParams lp = generateDefaultLayoutParams(); lp.gravity = GravityCompat.START | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK); lp.mViewType = LayoutParams.EXPANDED; mCollapseButtonView.setLayoutParams(lp); mCollapseButtonView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { collapseActionView(); } }); } } private void addSystemView(View v, boolean allowHide) { final ViewGroup.LayoutParams vlp = v.getLayoutParams(); final LayoutParams lp; if (vlp == null) { lp = generateDefaultLayoutParams(); } else if (!checkLayoutParams(vlp)) { lp = generateLayoutParams(vlp); } else { lp = (LayoutParams) vlp; } lp.mViewType = LayoutParams.SYSTEM; if (allowHide && mExpandedActionView != null) { v.setLayoutParams(lp); mHiddenViews.add(v); } else { addView(v, lp); } } @Override protected Parcelable onSaveInstanceState() { SavedState state = new SavedState(super.onSaveInstanceState()); if (mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null) { state.expandedMenuItemId = mExpandedMenuPresenter.mCurrentExpandedItem.getItemId(); } state.isOverflowOpen = isOverflowMenuShowing(); return state; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); final Menu menu = mMenuView != null ? mMenuView.peekMenu() : null; if (ss.expandedMenuItemId != 0 && mExpandedMenuPresenter != null && menu != null) { final MenuItem item = menu.findItem(ss.expandedMenuItemId); if (item != null) { MenuItemCompat.expandActionView(item); } } if (ss.isOverflowOpen) { postShowOverflowMenu(); } } private void postShowOverflowMenu() { removeCallbacks(mShowOverflowMenuRunnable); post(mShowOverflowMenuRunnable); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeCallbacks(mShowOverflowMenuRunnable); } @Override public boolean onTouchEvent(MotionEvent ev) { // Toolbars always eat touch events, but should still respect the touch event dispatch // contract. If the normal View implementation doesn't want the events, we'll just silently // eat the rest of the gesture without reporting the events to the default implementation // since that's what it expects. final int action = MotionEventCompat.getActionMasked(ev); if (action == MotionEvent.ACTION_DOWN) { mEatingTouch = false; } if (!mEatingTouch) { final boolean handled = super.onTouchEvent(ev); if (action == MotionEvent.ACTION_DOWN && !handled) { mEatingTouch = true; } } if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { mEatingTouch = false; } return true; } @Override public boolean onHoverEvent(MotionEvent ev) { // Same deal as onTouchEvent() above. Eat all hover events, but still // respect the touch event dispatch contract. final int action = MotionEventCompat.getActionMasked(ev); if (action == MotionEvent.ACTION_HOVER_ENTER) { mEatingHover = false; } if (!mEatingHover) { final boolean handled = super.onHoverEvent(ev); if (action == MotionEvent.ACTION_HOVER_ENTER && !handled) { mEatingHover = true; } } if (action == MotionEvent.ACTION_HOVER_EXIT || action == MotionEvent.ACTION_CANCEL) { mEatingHover = false; } return true; } private void measureChildConstrained(View child, int parentWidthSpec, int widthUsed, int parentHeightSpec, int heightUsed, int heightConstraint) { final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int childWidthSpec = getChildMeasureSpec(parentWidthSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin + widthUsed, lp.width); int childHeightSpec = getChildMeasureSpec(parentHeightSpec, getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin + heightUsed, lp.height); final int childHeightMode = MeasureSpec.getMode(childHeightSpec); if (childHeightMode != MeasureSpec.EXACTLY && heightConstraint >= 0) { final int size = childHeightMode != MeasureSpec.UNSPECIFIED ? Math.min(MeasureSpec.getSize(childHeightSpec), heightConstraint) : heightConstraint; childHeightSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY); } child.measure(childWidthSpec, childHeightSpec); } /** * Returns the width + uncollapsed margins */ private int measureChildCollapseMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed, int[] collapsingMargins) { final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); final int leftDiff = lp.leftMargin - collapsingMargins[0]; final int rightDiff = lp.rightMargin - collapsingMargins[1]; final int leftMargin = Math.max(0, leftDiff); final int rightMargin = Math.max(0, rightDiff); final int hMargins = leftMargin + rightMargin; collapsingMargins[0] = Math.max(0, -leftDiff); collapsingMargins[1] = Math.max(0, -rightDiff); final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft() + getPaddingRight() + hMargins + widthUsed, lp.width); final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin + heightUsed, lp.height); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); return child.getMeasuredWidth() + hMargins; } /** * Returns true if the Toolbar is collapsible and has no child views with a measured size > 0. */ private boolean shouldCollapse() { if (!mCollapsible) return false; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (shouldLayout(child) && child.getMeasuredWidth() > 0 && child.getMeasuredHeight() > 0) { return false; } } return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = 0; int height = 0; int childState = 0; final int[] collapsingMargins = mTempMargins; final int marginStartIndex; final int marginEndIndex; if (ViewUtils.isLayoutRtl(this)) { marginStartIndex = 1; marginEndIndex = 0; } else { marginStartIndex = 0; marginEndIndex = 1; } // System views measure first. int navWidth = 0; if (shouldLayout(mNavButtonView)) { measureChildConstrained(mNavButtonView, widthMeasureSpec, width, heightMeasureSpec, 0, mMaxButtonHeight); navWidth = mNavButtonView.getMeasuredWidth() + getHorizontalMargins(mNavButtonView); height = Math.max(height, mNavButtonView.getMeasuredHeight() + getVerticalMargins(mNavButtonView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mNavButtonView)); } if (shouldLayout(mCollapseButtonView)) { measureChildConstrained(mCollapseButtonView, widthMeasureSpec, width, heightMeasureSpec, 0, mMaxButtonHeight); navWidth = mCollapseButtonView.getMeasuredWidth() + getHorizontalMargins(mCollapseButtonView); height = Math.max(height, mCollapseButtonView.getMeasuredHeight() + getVerticalMargins(mCollapseButtonView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mCollapseButtonView)); } final int contentInsetStart = getCurrentContentInsetStart(); width += Math.max(contentInsetStart, navWidth); collapsingMargins[marginStartIndex] = Math.max(0, contentInsetStart - navWidth); int menuWidth = 0; if (shouldLayout(mMenuView)) { measureChildConstrained(mMenuView, widthMeasureSpec, width, heightMeasureSpec, 0, mMaxButtonHeight); menuWidth = mMenuView.getMeasuredWidth() + getHorizontalMargins(mMenuView); height = Math.max(height, mMenuView.getMeasuredHeight() + getVerticalMargins(mMenuView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mMenuView)); } final int contentInsetEnd = getCurrentContentInsetEnd(); width += Math.max(contentInsetEnd, menuWidth); collapsingMargins[marginEndIndex] = Math.max(0, contentInsetEnd - menuWidth); if (shouldLayout(mExpandedActionView)) { width += measureChildCollapseMargins(mExpandedActionView, widthMeasureSpec, width, heightMeasureSpec, 0, collapsingMargins); height = Math.max(height, mExpandedActionView.getMeasuredHeight() + getVerticalMargins(mExpandedActionView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mExpandedActionView)); } if (shouldLayout(mLogoView)) { width += measureChildCollapseMargins(mLogoView, widthMeasureSpec, width, heightMeasureSpec, 0, collapsingMargins); height = Math.max(height, mLogoView.getMeasuredHeight() + getVerticalMargins(mLogoView)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mLogoView)); } final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mViewType != LayoutParams.CUSTOM || !shouldLayout(child)) { // We already got all system views above. Skip them and GONE views. continue; } width += measureChildCollapseMargins(child, widthMeasureSpec, width, heightMeasureSpec, 0, collapsingMargins); height = Math.max(height, child.getMeasuredHeight() + getVerticalMargins(child)); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(child)); } int titleWidth = 0; int titleHeight = 0; final int titleVertMargins = mTitleMarginTop + mTitleMarginBottom; final int titleHorizMargins = mTitleMarginStart + mTitleMarginEnd; if (shouldLayout(mTitleTextView)) { titleWidth = measureChildCollapseMargins(mTitleTextView, widthMeasureSpec, width + titleHorizMargins, heightMeasureSpec, titleVertMargins, collapsingMargins); titleWidth = mTitleTextView.getMeasuredWidth() + getHorizontalMargins(mTitleTextView); titleHeight = mTitleTextView.getMeasuredHeight() + getVerticalMargins(mTitleTextView); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mTitleTextView)); } if (shouldLayout(mSubtitleTextView)) { titleWidth = Math.max(titleWidth, measureChildCollapseMargins(mSubtitleTextView, widthMeasureSpec, width + titleHorizMargins, heightMeasureSpec, titleHeight + titleVertMargins, collapsingMargins)); titleHeight += mSubtitleTextView.getMeasuredHeight() + getVerticalMargins(mSubtitleTextView); childState = ViewUtils.combineMeasuredStates(childState, ViewCompat.getMeasuredState(mSubtitleTextView)); } width += titleWidth; height = Math.max(height, titleHeight); // Measurement already took padding into account for available space for the children, // add it in for the final size. width += getPaddingLeft() + getPaddingRight(); height += getPaddingTop() + getPaddingBottom(); final int measuredWidth = ViewCompat.resolveSizeAndState( Math.max(width, getSuggestedMinimumWidth()), widthMeasureSpec, childState & ViewCompat.MEASURED_STATE_MASK); final int measuredHeight = ViewCompat.resolveSizeAndState( Math.max(height, getSuggestedMinimumHeight()), heightMeasureSpec, childState << ViewCompat.MEASURED_HEIGHT_STATE_SHIFT); setMeasuredDimension(measuredWidth, shouldCollapse() ? 0 : measuredHeight); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final boolean isRtl = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL; final int width = getWidth(); final int height = getHeight(); final int paddingLeft = getPaddingLeft(); final int paddingRight = getPaddingRight(); final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); int left = paddingLeft; int right = width - paddingRight; final int[] collapsingMargins = mTempMargins; collapsingMargins[0] = collapsingMargins[1] = 0; // Align views within the minimum toolbar height, if set. final int alignmentHeight = ViewCompat.getMinimumHeight(this); if (shouldLayout(mNavButtonView)) { if (isRtl) { right = layoutChildRight(mNavButtonView, right, collapsingMargins, alignmentHeight); } else { left = layoutChildLeft(mNavButtonView, left, collapsingMargins, alignmentHeight); } } if (shouldLayout(mCollapseButtonView)) { if (isRtl) { right = layoutChildRight(mCollapseButtonView, right, collapsingMargins, alignmentHeight); } else { left = layoutChildLeft(mCollapseButtonView, left, collapsingMargins, alignmentHeight); } } if (shouldLayout(mMenuView)) { if (isRtl) { left = layoutChildLeft(mMenuView, left, collapsingMargins, alignmentHeight); } else { right = layoutChildRight(mMenuView, right, collapsingMargins, alignmentHeight); } } final int contentInsetLeft = getCurrentContentInsetLeft(); final int contentInsetRight = getCurrentContentInsetRight(); collapsingMargins[0] = Math.max(0, contentInsetLeft - left); collapsingMargins[1] = Math.max(0, contentInsetRight - (width - paddingRight - right)); left = Math.max(left, contentInsetLeft); right = Math.min(right, width - paddingRight - contentInsetRight); if (shouldLayout(mExpandedActionView)) { if (isRtl) { right = layoutChildRight(mExpandedActionView, right, collapsingMargins, alignmentHeight); } else { left = layoutChildLeft(mExpandedActionView, left, collapsingMargins, alignmentHeight); } } if (shouldLayout(mLogoView)) { if (isRtl) { right = layoutChildRight(mLogoView, right, collapsingMargins, alignmentHeight); } else { left = layoutChildLeft(mLogoView, left, collapsingMargins, alignmentHeight); } } final boolean layoutTitle = shouldLayout(mTitleTextView); final boolean layoutSubtitle = shouldLayout(mSubtitleTextView); int titleHeight = 0; if (layoutTitle) { final LayoutParams lp = (LayoutParams) mTitleTextView.getLayoutParams(); titleHeight += lp.topMargin + mTitleTextView.getMeasuredHeight() + lp.bottomMargin; } if (layoutSubtitle) { final LayoutParams lp = (LayoutParams) mSubtitleTextView.getLayoutParams(); titleHeight += lp.topMargin + mSubtitleTextView.getMeasuredHeight() + lp.bottomMargin; } if (layoutTitle || layoutSubtitle) { int titleTop; final View topChild = layoutTitle ? mTitleTextView : mSubtitleTextView; final View bottomChild = layoutSubtitle ? mSubtitleTextView : mTitleTextView; final LayoutParams toplp = (LayoutParams) topChild.getLayoutParams(); final LayoutParams bottomlp = (LayoutParams) bottomChild.getLayoutParams(); final boolean titleHasWidth = layoutTitle && mTitleTextView.getMeasuredWidth() > 0 || layoutSubtitle && mSubtitleTextView.getMeasuredWidth() > 0; switch (mGravity & Gravity.VERTICAL_GRAVITY_MASK) { case Gravity.TOP: titleTop = getPaddingTop() + toplp.topMargin + mTitleMarginTop; break; default: case Gravity.CENTER_VERTICAL: final int space = height - paddingTop - paddingBottom; int spaceAbove = (space - titleHeight) / 2; if (spaceAbove < toplp.topMargin + mTitleMarginTop) { spaceAbove = toplp.topMargin + mTitleMarginTop; } else { final int spaceBelow = height - paddingBottom - titleHeight - spaceAbove - paddingTop; if (spaceBelow < toplp.bottomMargin + mTitleMarginBottom) { spaceAbove = Math.max(0, spaceAbove - (bottomlp.bottomMargin + mTitleMarginBottom - spaceBelow)); } } titleTop = paddingTop + spaceAbove; break; case Gravity.BOTTOM: titleTop = height - paddingBottom - bottomlp.bottomMargin - mTitleMarginBottom - titleHeight; break; } if (isRtl) { final int rd = (titleHasWidth ? mTitleMarginStart : 0) - collapsingMargins[1]; right -= Math.max(0, rd); collapsingMargins[1] = Math.max(0, -rd); int titleRight = right; int subtitleRight = right; if (layoutTitle) { final LayoutParams lp = (LayoutParams) mTitleTextView.getLayoutParams(); final int titleLeft = titleRight - mTitleTextView.getMeasuredWidth(); final int titleBottom = titleTop + mTitleTextView.getMeasuredHeight(); mTitleTextView.layout(titleLeft, titleTop, titleRight, titleBottom); titleRight = titleLeft - mTitleMarginEnd; titleTop = titleBottom + lp.bottomMargin; } if (layoutSubtitle) { final LayoutParams lp = (LayoutParams) mSubtitleTextView.getLayoutParams(); titleTop += lp.topMargin; final int subtitleLeft = subtitleRight - mSubtitleTextView.getMeasuredWidth(); final int subtitleBottom = titleTop + mSubtitleTextView.getMeasuredHeight(); mSubtitleTextView.layout(subtitleLeft, titleTop, subtitleRight, subtitleBottom); subtitleRight = subtitleRight - mTitleMarginEnd; titleTop = subtitleBottom + lp.bottomMargin; } if (titleHasWidth) { right = Math.min(titleRight, subtitleRight); } } else { final int ld = (titleHasWidth ? mTitleMarginStart : 0) - collapsingMargins[0]; left += Math.max(0, ld); collapsingMargins[0] = Math.max(0, -ld); int titleLeft = left; int subtitleLeft = left; if (layoutTitle) { final LayoutParams lp = (LayoutParams) mTitleTextView.getLayoutParams(); final int titleRight = titleLeft + mTitleTextView.getMeasuredWidth(); final int titleBottom = titleTop + mTitleTextView.getMeasuredHeight(); mTitleTextView.layout(titleLeft, titleTop, titleRight, titleBottom); titleLeft = titleRight + mTitleMarginEnd; titleTop = titleBottom + lp.bottomMargin; } if (layoutSubtitle) { final LayoutParams lp = (LayoutParams) mSubtitleTextView.getLayoutParams(); titleTop += lp.topMargin; final int subtitleRight = subtitleLeft + mSubtitleTextView.getMeasuredWidth(); final int subtitleBottom = titleTop + mSubtitleTextView.getMeasuredHeight(); mSubtitleTextView.layout(subtitleLeft, titleTop, subtitleRight, subtitleBottom); subtitleLeft = subtitleRight + mTitleMarginEnd; titleTop = subtitleBottom + lp.bottomMargin; } if (titleHasWidth) { left = Math.max(titleLeft, subtitleLeft); } } } // Get all remaining children sorted for layout. This is all prepared // such that absolute layout direction can be used below. addCustomViewsWithGravity(mTempViews, Gravity.LEFT); final int leftViewsCount = mTempViews.size(); for (int i = 0; i < leftViewsCount; i++) { left = layoutChildLeft(mTempViews.get(i), left, collapsingMargins, alignmentHeight); } addCustomViewsWithGravity(mTempViews, Gravity.RIGHT); final int rightViewsCount = mTempViews.size(); for (int i = 0; i < rightViewsCount; i++) { right = layoutChildRight(mTempViews.get(i), right, collapsingMargins, alignmentHeight); } // Centered views try to center with respect to the whole bar, but views pinned // to the left or right can push the mass of centered views to one side or the other. addCustomViewsWithGravity(mTempViews, Gravity.CENTER_HORIZONTAL); final int centerViewsWidth = getViewListMeasuredWidth(mTempViews, collapsingMargins); final int parentCenter = paddingLeft + (width - paddingLeft - paddingRight) / 2; final int halfCenterViewsWidth = centerViewsWidth / 2; int centerLeft = parentCenter - halfCenterViewsWidth; final int centerRight = centerLeft + centerViewsWidth; if (centerLeft < left) { centerLeft = left; } else if (centerRight > right) { centerLeft -= centerRight - right; } final int centerViewsCount = mTempViews.size(); for (int i = 0; i < centerViewsCount; i++) { centerLeft = layoutChildLeft(mTempViews.get(i), centerLeft, collapsingMargins, alignmentHeight); } mTempViews.clear(); } private int getViewListMeasuredWidth(List<View> views, int[] collapsingMargins) { int collapseLeft = collapsingMargins[0]; int collapseRight = collapsingMargins[1]; int width = 0; final int count = views.size(); for (int i = 0; i < count; i++) { final View v = views.get(i); final LayoutParams lp = (LayoutParams) v.getLayoutParams(); final int l = lp.leftMargin - collapseLeft; final int r = lp.rightMargin - collapseRight; final int leftMargin = Math.max(0, l); final int rightMargin = Math.max(0, r); collapseLeft = Math.max(0, -l); collapseRight = Math.max(0, -r); width += leftMargin + v.getMeasuredWidth() + rightMargin; } return width; } private int layoutChildLeft(View child, int left, int[] collapsingMargins, int alignmentHeight) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int l = lp.leftMargin - collapsingMargins[0]; left += Math.max(0, l); collapsingMargins[0] = Math.max(0, -l); final int top = getChildTop(child, alignmentHeight); final int childWidth = child.getMeasuredWidth(); child.layout(left, top, left + childWidth, top + child.getMeasuredHeight()); left += childWidth + lp.rightMargin; return left; } private int layoutChildRight(View child, int right, int[] collapsingMargins, int alignmentHeight) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int r = lp.rightMargin - collapsingMargins[1]; right -= Math.max(0, r); collapsingMargins[1] = Math.max(0, -r); final int top = getChildTop(child, alignmentHeight); final int childWidth = child.getMeasuredWidth(); child.layout(right - childWidth, top, right, top + child.getMeasuredHeight()); right -= childWidth + lp.leftMargin; return right; } private int getChildTop(View child, int alignmentHeight) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int childHeight = child.getMeasuredHeight(); final int alignmentOffset = alignmentHeight > 0 ? (childHeight - alignmentHeight) / 2 : 0; switch (getChildVerticalGravity(lp.gravity)) { case Gravity.TOP: return getPaddingTop() - alignmentOffset; case Gravity.BOTTOM: return getHeight() - getPaddingBottom() - childHeight - lp.bottomMargin - alignmentOffset; default: case Gravity.CENTER_VERTICAL: final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); final int height = getHeight(); final int space = height - paddingTop - paddingBottom; int spaceAbove = (space - childHeight) / 2; if (spaceAbove < lp.topMargin) { spaceAbove = lp.topMargin; } else { final int spaceBelow = height - paddingBottom - childHeight - spaceAbove - paddingTop; if (spaceBelow < lp.bottomMargin) { spaceAbove = Math.max(0, spaceAbove - (lp.bottomMargin - spaceBelow)); } } return paddingTop + spaceAbove; } } private int getChildVerticalGravity(int gravity) { final int vgrav = gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (vgrav) { case Gravity.TOP: case Gravity.BOTTOM: case Gravity.CENTER_VERTICAL: return vgrav; default: return mGravity & Gravity.VERTICAL_GRAVITY_MASK; } } /** * Prepare a list of non-SYSTEM child views. If the layout direction is RTL * this will be in reverse child order. * * @param views List to populate. It will be cleared before use. * @param gravity Horizontal gravity to match against */ private void addCustomViewsWithGravity(List<View> views, int gravity) { final boolean isRtl = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL; final int childCount = getChildCount(); final int absGrav = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); views.clear(); if (isRtl) { for (int i = childCount - 1; i >= 0; i--) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mViewType == LayoutParams.CUSTOM && shouldLayout(child) && getChildHorizontalGravity(lp.gravity) == absGrav) { views.add(child); } } } else { for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mViewType == LayoutParams.CUSTOM && shouldLayout(child) && getChildHorizontalGravity(lp.gravity) == absGrav) { views.add(child); } } } } private int getChildHorizontalGravity(int gravity) { final int ld = ViewCompat.getLayoutDirection(this); final int absGrav = GravityCompat.getAbsoluteGravity(gravity, ld); final int hGrav = absGrav & Gravity.HORIZONTAL_GRAVITY_MASK; switch (hGrav) { case Gravity.LEFT: case Gravity.RIGHT: case Gravity.CENTER_HORIZONTAL: return hGrav; default: return ld == ViewCompat.LAYOUT_DIRECTION_RTL ? Gravity.RIGHT : Gravity.LEFT; } } private boolean shouldLayout(View view) { return view != null && view.getParent() == this && view.getVisibility() != GONE; } private int getHorizontalMargins(View v) { final MarginLayoutParams mlp = (MarginLayoutParams) v.getLayoutParams(); return MarginLayoutParamsCompat.getMarginStart(mlp) + MarginLayoutParamsCompat.getMarginEnd(mlp); } private int getVerticalMargins(View v) { final MarginLayoutParams mlp = (MarginLayoutParams) v.getLayoutParams(); return mlp.topMargin + mlp.bottomMargin; } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { if (p instanceof LayoutParams) { return new LayoutParams((LayoutParams) p); } else if (p instanceof ActionBar.LayoutParams) { return new LayoutParams((ActionBar.LayoutParams) p); } else if (p instanceof MarginLayoutParams) { return new LayoutParams((MarginLayoutParams) p); } else { return new LayoutParams(p); } } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return super.checkLayoutParams(p) && p instanceof LayoutParams; } private static boolean isCustomView(View child) { return ((LayoutParams) child.getLayoutParams()).mViewType == LayoutParams.CUSTOM; } /** @hide */ public DecorToolbar getWrapper() { if (mWrapper == null) { mWrapper = new ToolbarWidgetWrapper(this, true); } return mWrapper; } void removeChildrenForExpandedActionView() { final int childCount = getChildCount(); // Go backwards since we're removing from the list for (int i = childCount - 1; i >= 0; i--) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mViewType != LayoutParams.EXPANDED && child != mMenuView) { removeViewAt(i); mHiddenViews.add(child); } } } void addChildrenForExpandedActionView() { final int count = mHiddenViews.size(); // Re-add in reverse order since we removed in reverse order for (int i = count - 1; i >= 0; i--) { addView(mHiddenViews.get(i)); } mHiddenViews.clear(); } private boolean isChildOrHidden(View child) { return child.getParent() == this || mHiddenViews.contains(child); } /** * Force the toolbar to collapse to zero-height during measurement if * it could be considered "empty" (no visible elements with nonzero measured size) * @hide */ public void setCollapsible(boolean collapsible) { mCollapsible = collapsible; requestLayout(); } /** * Must be called before the menu is accessed * @hide */ public void setMenuCallbacks(MenuPresenter.Callback pcb, MenuBuilder.Callback mcb) { mActionMenuPresenterCallback = pcb; mMenuBuilderCallback = mcb; if (mMenuView != null) { mMenuView.setMenuCallbacks(pcb, mcb); } } private void ensureContentInsets() { if (mContentInsets == null) { mContentInsets = new RtlSpacingHelper(); } } /** * Interface responsible for receiving menu item click events if the items themselves * do not have individual item click listeners. */ public interface OnMenuItemClickListener { /** * This method will be invoked when a menu item is clicked if the item itself did * not already handle the event. * * @param item {@link MenuItem} that was clicked * @return <code>true</code> if the event was handled, <code>false</code> otherwise. */ public boolean onMenuItemClick(MenuItem item); } /** * Layout information for child views of Toolbars. * * <p>Toolbar.LayoutParams extends ActionBar.LayoutParams for compatibility with existing * ActionBar API. See * {@link android.support.v7.app.AppCompatActivity#setSupportActionBar(Toolbar) * ActionBarActivity.setActionBar} * for more info on how to use a Toolbar as your Activity's ActionBar.</p> */ public static class LayoutParams extends ActionBar.LayoutParams { static final int CUSTOM = 0; static final int SYSTEM = 1; static final int EXPANDED = 2; int mViewType = CUSTOM; public LayoutParams(@NonNull Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); this.gravity = Gravity.CENTER_VERTICAL | GravityCompat.START; } public LayoutParams(int width, int height, int gravity) { super(width, height); this.gravity = gravity; } public LayoutParams(int gravity) { this(WRAP_CONTENT, MATCH_PARENT, gravity); } public LayoutParams(LayoutParams source) { super(source); mViewType = source.mViewType; } public LayoutParams(ActionBar.LayoutParams source) { super(source); } public LayoutParams(MarginLayoutParams source) { super(source); // ActionBar.LayoutParams doesn't have a MarginLayoutParams constructor. // Fake it here and copy over the relevant data. copyMarginsFromCompat(source); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } void copyMarginsFromCompat(MarginLayoutParams source) { this.leftMargin = source.leftMargin; this.topMargin = source.topMargin; this.rightMargin = source.rightMargin; this.bottomMargin = source.bottomMargin; } } public static class SavedState extends AbsSavedState { int expandedMenuItemId; boolean isOverflowOpen; public SavedState(Parcel source) { this(source, null); } public SavedState(Parcel source, ClassLoader loader) { super(source, loader); expandedMenuItemId = source.readInt(); isOverflowOpen = source.readInt() != 0; } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(expandedMenuItemId); out.writeInt(isOverflowOpen ? 1 : 0); } public static final Creator<SavedState> CREATOR = ParcelableCompat.newCreator( new ParcelableCompatCreatorCallbacks<SavedState>() { @Override public SavedState createFromParcel(Parcel in, ClassLoader loader) { return new SavedState(in, loader); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }); } private class ExpandedActionViewMenuPresenter implements MenuPresenter { MenuBuilder mMenu; MenuItemImpl mCurrentExpandedItem; @Override public void initForMenu(Context context, MenuBuilder menu) { // Clear the expanded action view when menus change. if (mMenu != null && mCurrentExpandedItem != null) { mMenu.collapseItemActionView(mCurrentExpandedItem); } mMenu = menu; } @Override public MenuView getMenuView(ViewGroup root) { return null; } @Override public void updateMenuView(boolean cleared) { // Make sure the expanded item we have is still there. if (mCurrentExpandedItem != null) { boolean found = false; if (mMenu != null) { final int count = mMenu.size(); for (int i = 0; i < count; i++) { final MenuItem item = mMenu.getItem(i); if (item == mCurrentExpandedItem) { found = true; break; } } } if (!found) { // The item we had expanded disappeared. Collapse. collapseItemActionView(mMenu, mCurrentExpandedItem); } } } @Override public void setCallback(Callback cb) { } @Override public boolean onSubMenuSelected(SubMenuBuilder subMenu) { return false; } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { } @Override public boolean flagActionItems() { return false; } @Override public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) { ensureCollapseButtonView(); if (mCollapseButtonView.getParent() != Toolbar.this) { addView(mCollapseButtonView); } mExpandedActionView = item.getActionView(); mCurrentExpandedItem = item; if (mExpandedActionView.getParent() != Toolbar.this) { final LayoutParams lp = generateDefaultLayoutParams(); lp.gravity = GravityCompat.START | (mButtonGravity & Gravity.VERTICAL_GRAVITY_MASK); lp.mViewType = LayoutParams.EXPANDED; mExpandedActionView.setLayoutParams(lp); addView(mExpandedActionView); } removeChildrenForExpandedActionView(); requestLayout(); item.setActionViewExpanded(true); if (mExpandedActionView instanceof CollapsibleActionView) { ((CollapsibleActionView) mExpandedActionView).onActionViewExpanded(); } return true; } @Override public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) { // Do this before detaching the actionview from the hierarchy, in case // it needs to dismiss the soft keyboard, etc. if (mExpandedActionView instanceof CollapsibleActionView) { ((CollapsibleActionView) mExpandedActionView).onActionViewCollapsed(); } removeView(mExpandedActionView); removeView(mCollapseButtonView); mExpandedActionView = null; addChildrenForExpandedActionView(); mCurrentExpandedItem = null; requestLayout(); item.setActionViewExpanded(false); return true; } @Override public int getId() { return 0; } @Override public Parcelable onSaveInstanceState() { return null; } @Override public void onRestoreInstanceState(Parcelable state) { } } }
Make Toolbar ignore its minHeight if larger than height Currently Toolbar lays out all children based on its minHeight (if set). If that minHeight is larger than the Toolbar height, then the children are laid out larger than the Toolbar and clipped. This CL fixes it back by capping the alignment height. BUG: 29049143 Change-Id: Icb7b63a4605cb0272dc415920820038c1cd7cb2e
v7/appcompat/src/android/support/v7/widget/Toolbar.java
Make Toolbar ignore its minHeight if larger than height
<ide><path>7/appcompat/src/android/support/v7/widget/Toolbar.java <ide> collapsingMargins[0] = collapsingMargins[1] = 0; <ide> <ide> // Align views within the minimum toolbar height, if set. <del> final int alignmentHeight = ViewCompat.getMinimumHeight(this); <add> final int minHeight = ViewCompat.getMinimumHeight(this); <add> final int alignmentHeight = minHeight >= 0 ? Math.min(minHeight, b - t) : 0; <ide> <ide> if (shouldLayout(mNavButtonView)) { <ide> if (isRtl) {
JavaScript
mit
c6785194ec261deb4a9e22b6a9ce1d7d65b4a100
0
aaromp/javascript-koans,aaromp/javascript-koans
var _; //globals describe("About Applying What We Have Learnt", function() { var products; beforeEach(function () { products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false }, { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true }, { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true } ]; }); /*********************************************************************************/ it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () { var i,j,hasMushrooms, productsICanEat = []; for (i = 0; i < products.length; i+=1) { if (products[i].containsNuts === false) { hasMushrooms = false; for (j = 0; j < products[i].ingredients.length; j+=1) { if (products[i].ingredients[j] === "mushrooms") { hasMushrooms = true; } } if (!hasMushrooms) productsICanEat.push(products[i]); } } expect(productsICanEat.length).toBe(FILL_ME_IN); }); it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { var productsICanEat = []; /* solve using filter() & all() / any() */ expect(productsICanEat.length).toBe(FILL_ME_IN); }); /*********************************************************************************/ it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { var sum = 0; for(var i=1; i<1000; i+=1) { if (i % 3 === 0 || i % 5 === 0) { sum += i; } } expect(sum).toBe(FILL_ME_IN); }); it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { var sum = FILL_ME_IN; /* try chaining range() and reduce() */ expect(233168).toBe(FILL_ME_IN); }); /*********************************************************************************/ it("should count the ingredient occurrence (imperative)", function () { var ingredientCount = { "{ingredient name}": 0 }; for (i = 0; i < products.length; i+=1) { for (j = 0; j < products[i].ingredients.length; j+=1) { ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1; } } expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN); }); it("should count the ingredient occurrence (functional)", function () { var ingredientCount = { "{ingredient name}": 0 }; /* chain() together map(), flatten() and reduce() */ expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN); }); /*********************************************************************************/ /* UNCOMMENT FOR EXTRA CREDIT */ it("should find the largest prime factor of a composite number", function () { }); it("should find the largest palindrome made from the product of two 3 digit numbers", function () { }); it("should find the smallest number divisible by each of the numbers 1 to 20", function () { }); it("should find the difference between the sum of the squares and the square of the sums", function () { }); it("should find the 10001st prime", function () { }); });
koans/AboutApplyingWhatWeHaveLearnt.js
var _; //globals describe("About Applying What We Have Learnt", function() { var products; beforeEach(function () { products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false }, { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true }, { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true } ]; }); /*********************************************************************************/ it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () { var i,j,hasMushrooms, productsICanEat = []; for (i = 0; i < products.length; i+=1) { if (products[i].containsNuts === false) { hasMushrooms = false; for (j = 0; j < products[i].ingredients.length; j+=1) { if (products[i].ingredients[j] === "mushrooms") { hasMushrooms = true; } } if (!hasMushrooms) productsICanEat.push(products[i]); } } expect(productsICanEat.length).toBe(3); }); it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { var productsICanEat = []; /* solve using filter() & all() / any() */ var hasMushrooms = _(products).all(function(x) { return x.ingredients !== "mushrooms"}); productsICanEat = _(hasMushrooms).filter(function(x) { return x.containsNuts !=== true }) expect(productsICanEat.length).toBe(3); }); /*********************************************************************************/ it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { var sum = 0; for(var i=1; i<1000; i+=1) { if (i % 3 === 0 || i % 5 === 0) { sum += i; } } expect(sum).toBe(FILL_ME_IN); }); it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { var sum = FILL_ME_IN; /* try chaining range() and reduce() */ expect(233168).toBe(FILL_ME_IN); }); /*********************************************************************************/ it("should count the ingredient occurrence (imperative)", function () { var ingredientCount = { "{ingredient name}": 0 }; for (i = 0; i < products.length; i+=1) { for (j = 0; j < products[i].ingredients.length; j+=1) { ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1; } } expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN); }); it("should count the ingredient occurrence (functional)", function () { var ingredientCount = { "{ingredient name}": 0 }; /* chain() together map(), flatten() and reduce() */ expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN); }); /*********************************************************************************/ /* UNCOMMENT FOR EXTRA CREDIT */ /* it("should find the largest prime factor of a composite number", function () { }); it("should find the largest palindrome made from the product of two 3 digit numbers", function () { }); it("should find the smallest number divisible by each of the numbers 1 to 20", function () { }); it("should find the difference between the sum of the squares and the square of the sums", function () { }); it("should find the 10001st prime", function () { }); */ });
Fix About Applying What We Have Learnt spec
koans/AboutApplyingWhatWeHaveLearnt.js
Fix About Applying What We Have Learnt spec
<ide><path>oans/AboutApplyingWhatWeHaveLearnt.js <ide> } <ide> } <ide> <del> expect(productsICanEat.length).toBe(3); <add> expect(productsICanEat.length).toBe(FILL_ME_IN); <ide> }); <ide> <ide> it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { <ide> var productsICanEat = []; <ide> <ide> /* solve using filter() & all() / any() */ <del> var hasMushrooms = _(products).all(function(x) { return x.ingredients !== "mushrooms"}); <del> <del> productsICanEat = _(hasMushrooms).filter(function(x) { return x.containsNuts !=== true }) <ide> <del> expect(productsICanEat.length).toBe(3); <add> expect(productsICanEat.length).toBe(FILL_ME_IN); <ide> }); <ide> <ide> /*********************************************************************************/ <ide> <ide> /*********************************************************************************/ <ide> /* UNCOMMENT FOR EXTRA CREDIT */ <del> /* <add> <ide> it("should find the largest prime factor of a composite number", function () { <ide> <ide> }); <ide> it("should find the 10001st prime", function () { <ide> <ide> }); <del> */ <ide> });
Java
apache-2.0
c4289de0284c57cb89660c1dddb96abc0a56d096
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.provision.maintenance; import com.yahoo.config.provision.Deployer; import com.yahoo.config.provision.NodeResources; import com.yahoo.config.provision.NodeType; import com.yahoo.jdisc.Metric; import com.yahoo.vespa.hosted.provision.Node; import com.yahoo.vespa.hosted.provision.NodeList; import com.yahoo.vespa.hosted.provision.NodeRepository; import com.yahoo.vespa.hosted.provision.NodesAndHosts; import com.yahoo.vespa.hosted.provision.node.Agent; import com.yahoo.vespa.hosted.provision.provisioning.HostCapacity; import java.time.Duration; /** * @author bratseth */ public class Rebalancer extends NodeMover<Rebalancer.Move> { static final Duration waitTimeAfterPreviousDeployment = Duration.ofMinutes(10); private final Deployer deployer; private final Metric metric; public Rebalancer(Deployer deployer, NodeRepository nodeRepository, Metric metric, Duration interval) { super(deployer, nodeRepository, interval, metric, Move.empty()); this.deployer = deployer; this.metric = metric; } @Override protected double maintain() { if ( ! nodeRepository().nodes().isWorking()) return 0.0; if (nodeRepository().zone().getCloud().dynamicProvisioning()) return 1.0; // Rebalancing not necessary if (nodeRepository().zone().environment().isTest()) return 1.0; // Short lived deployments; no need to rebalance if (nodeRepository().zone().system().isCd()) return 1.0; // CD tests assert on # of nodes, avoid rebalnacing as it make tests unstable // Work with an unlocked snapshot as this can take a long time and full consistency is not needed NodesAndHosts<NodeList> allNodes = NodesAndHosts.create(nodeRepository().nodes().list()); updateSkewMetric(allNodes); if ( ! zoneIsStable(allNodes.nodes())) return 1.0; findBestMove(allNodes).execute(true, Agent.Rebalancer, deployer, metric, nodeRepository()); return 1.0; } @Override protected Move suggestedMove(Node node, Node fromHost, Node toHost, NodesAndHosts<? extends NodeList> allNodes) { HostCapacity capacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator()); double skewReductionAtFromHost = skewReductionByRemoving(node, fromHost, capacity); double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity); double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost; return new Move(node, fromHost, toHost, netSkewReduction); } @Override protected Move bestMoveOf(Move a, Move b) { if (a.netSkewReduction >= b.netSkewReduction) return a; return b; } /** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */ private void updateSkewMetric(NodesAndHosts<? extends NodeList> allNodes) { HostCapacity capacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator()); double totalSkew = 0; int hostCount = 0; for (Node host : allNodes.nodes().nodeType(NodeType.host).state(Node.State.active)) { hostCount++; totalSkew += Node.skew(host.flavor().resources(), capacity.unusedCapacityOf(host)); } metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null); } private double skewReductionByRemoving(Node node, Node fromHost, HostCapacity capacity) { NodeResources freeHostCapacity = capacity.unusedCapacityOf(fromHost); double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity); double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().justNumbers())); return skewBefore - skewAfter; } private double skewReductionByAdding(Node node, Node toHost, HostCapacity capacity) { NodeResources freeHostCapacity = capacity.unusedCapacityOf(toHost); double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity); double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.resources().justNumbers())); return skewBefore - skewAfter; } static class Move extends MaintenanceDeployment.Move { final double netSkewReduction; Move(Node node, Node fromHost, Node toHost, double netSkewReduction) { super(node, fromHost, toHost); this.netSkewReduction = netSkewReduction; } @Override public String toString() { if (isEmpty()) return "move none"; return super.toString() + " [skew reduction " + netSkewReduction + "]"; } public static Move empty() { return new Move(null, null, null, 0); } } }
node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/Rebalancer.java
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.provision.maintenance; import com.yahoo.config.provision.Deployer; import com.yahoo.config.provision.NodeResources; import com.yahoo.config.provision.NodeType; import com.yahoo.jdisc.Metric; import com.yahoo.vespa.hosted.provision.Node; import com.yahoo.vespa.hosted.provision.NodeList; import com.yahoo.vespa.hosted.provision.NodeRepository; import com.yahoo.vespa.hosted.provision.NodesAndHosts; import com.yahoo.vespa.hosted.provision.node.Agent; import com.yahoo.vespa.hosted.provision.provisioning.HostCapacity; import java.time.Duration; /** * @author bratseth */ public class Rebalancer extends NodeMover<Rebalancer.Move> { static final Duration waitTimeAfterPreviousDeployment = Duration.ofMinutes(10); private final Deployer deployer; private final Metric metric; public Rebalancer(Deployer deployer, NodeRepository nodeRepository, Metric metric, Duration interval) { super(deployer, nodeRepository, interval, metric, Move.empty()); this.deployer = deployer; this.metric = metric; } @Override protected double maintain() { if ( ! nodeRepository().nodes().isWorking()) return 0.0; if (nodeRepository().zone().getCloud().dynamicProvisioning()) return 1.0; // Rebalancing not necessary if (nodeRepository().zone().environment().isTest()) return 1.0; // Short lived deployments; no need to rebalance // Work with an unlocked snapshot as this can take a long time and full consistency is not needed NodesAndHosts<NodeList> allNodes = NodesAndHosts.create(nodeRepository().nodes().list()); updateSkewMetric(allNodes); if ( ! zoneIsStable(allNodes.nodes())) return 1.0; findBestMove(allNodes).execute(true, Agent.Rebalancer, deployer, metric, nodeRepository()); return 1.0; } @Override protected Move suggestedMove(Node node, Node fromHost, Node toHost, NodesAndHosts<? extends NodeList> allNodes) { HostCapacity capacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator()); double skewReductionAtFromHost = skewReductionByRemoving(node, fromHost, capacity); double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity); double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost; return new Move(node, fromHost, toHost, netSkewReduction); } @Override protected Move bestMoveOf(Move a, Move b) { if (a.netSkewReduction >= b.netSkewReduction) return a; return b; } /** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */ private void updateSkewMetric(NodesAndHosts<? extends NodeList> allNodes) { HostCapacity capacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator()); double totalSkew = 0; int hostCount = 0; for (Node host : allNodes.nodes().nodeType(NodeType.host).state(Node.State.active)) { hostCount++; totalSkew += Node.skew(host.flavor().resources(), capacity.unusedCapacityOf(host)); } metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null); } private double skewReductionByRemoving(Node node, Node fromHost, HostCapacity capacity) { NodeResources freeHostCapacity = capacity.unusedCapacityOf(fromHost); double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity); double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().justNumbers())); return skewBefore - skewAfter; } private double skewReductionByAdding(Node node, Node toHost, HostCapacity capacity) { NodeResources freeHostCapacity = capacity.unusedCapacityOf(toHost); double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity); double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.resources().justNumbers())); return skewBefore - skewAfter; } static class Move extends MaintenanceDeployment.Move { final double netSkewReduction; Move(Node node, Node fromHost, Node toHost, double netSkewReduction) { super(node, fromHost, toHost); this.netSkewReduction = netSkewReduction; } @Override public String toString() { if (isEmpty()) return "move none"; return super.toString() + " [skew reduction " + netSkewReduction + "]"; } public static Move empty() { return new Move(null, null, null, 0); } } }
Avoid running Rebalancer in cd systems Rebalancer will make asserts on number of nodes while running tests fail
node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/Rebalancer.java
Avoid running Rebalancer in cd systems
<ide><path>ode-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/Rebalancer.java <del>// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. <add>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. <ide> package com.yahoo.vespa.hosted.provision.maintenance; <ide> <ide> import com.yahoo.config.provision.Deployer; <ide> <ide> if (nodeRepository().zone().getCloud().dynamicProvisioning()) return 1.0; // Rebalancing not necessary <ide> if (nodeRepository().zone().environment().isTest()) return 1.0; // Short lived deployments; no need to rebalance <add> if (nodeRepository().zone().system().isCd()) return 1.0; // CD tests assert on # of nodes, avoid rebalnacing as it make tests unstable <ide> <ide> // Work with an unlocked snapshot as this can take a long time and full consistency is not needed <ide> NodesAndHosts<NodeList> allNodes = NodesAndHosts.create(nodeRepository().nodes().list());
Java
apache-2.0
72ab621c2acc5daf8b3397c4677706e4d6a1eeef
0
gianm/druid,deltaprojects/druid,Fokko/druid,du00cs/druid,tubemogul/druid,himanshug/druid,dclim/druid,monetate/druid,implydata/druid,solimant/druid,michaelschiff/druid,mrijke/druid,taochaoqiang/druid,monetate/druid,deltaprojects/druid,noddi/druid,potto007/druid-avro,potto007/druid-avro,implydata/druid,lizhanhui/data_druid,du00cs/druid,knoguchi/druid,monetate/druid,rasahner/druid,zxs/druid,tubemogul/druid,guobingkun/druid,zxs/druid,knoguchi/druid,dkhwangbo/druid,taochaoqiang/druid,du00cs/druid,michaelschiff/druid,knoguchi/druid,nishantmonu51/druid,gianm/druid,pdeva/druid,gianm/druid,jon-wei/druid,praveev/druid,noddi/druid,metamx/druid,metamx/druid,lizhanhui/data_druid,leventov/druid,guobingkun/druid,michaelschiff/druid,b-slim/druid,tubemogul/druid,taochaoqiang/druid,zhihuij/druid,potto007/druid-avro,deltaprojects/druid,pjain1/druid,mghosh4/druid,zhihuij/druid,jon-wei/druid,mrijke/druid,zxs/druid,pdeva/druid,solimant/druid,KurtYoung/druid,monetate/druid,erikdubbelboer/druid,guobingkun/druid,knoguchi/druid,implydata/druid,liquidm/druid,lizhanhui/data_druid,druid-io/druid,monetate/druid,yaochitc/druid-dev,b-slim/druid,pjain1/druid,praveev/druid,deltaprojects/druid,nishantmonu51/druid,leventov/druid,Fokko/druid,implydata/druid,pjain1/druid,liquidm/druid,mghosh4/druid,yaochitc/druid-dev,solimant/druid,yaochitc/druid-dev,monetate/druid,guobingkun/druid,KurtYoung/druid,erikdubbelboer/druid,mghosh4/druid,zhihuij/druid,implydata/druid,noddi/druid,solimant/druid,zhihuij/druid,himanshug/druid,nishantmonu51/druid,gianm/druid,druid-io/druid,metamx/druid,liquidm/druid,jon-wei/druid,b-slim/druid,deltaprojects/druid,metamx/druid,b-slim/druid,leventov/druid,pjain1/druid,pjain1/druid,noddi/druid,erikdubbelboer/druid,himanshug/druid,noddi/druid,redBorder/druid,zhihuij/druid,redBorder/druid,redBorder/druid,liquidm/druid,winval/druid,dclim/druid,rasahner/druid,Fokko/druid,zxs/druid,monetate/druid,druid-io/druid,redBorder/druid,nishantmonu51/druid,dclim/druid,liquidm/druid,jon-wei/druid,tubemogul/druid,potto007/druid-avro,pdeva/druid,KurtYoung/druid,himanshug/druid,winval/druid,lizhanhui/data_druid,taochaoqiang/druid,rasahner/druid,jon-wei/druid,dclim/druid,rasahner/druid,winval/druid,zxs/druid,gianm/druid,jon-wei/druid,nishantmonu51/druid,leventov/druid,b-slim/druid,KurtYoung/druid,nishantmonu51/druid,mrijke/druid,michaelschiff/druid,andy256/druid,praveev/druid,dkhwangbo/druid,liquidm/druid,implydata/druid,Fokko/druid,erikdubbelboer/druid,mrijke/druid,yaochitc/druid-dev,gianm/druid,dclim/druid,mghosh4/druid,metamx/druid,solimant/druid,mghosh4/druid,du00cs/druid,tubemogul/druid,dkhwangbo/druid,andy256/druid,andy256/druid,praveev/druid,pdeva/druid,dkhwangbo/druid,Fokko/druid,deltaprojects/druid,nishantmonu51/druid,praveev/druid,knoguchi/druid,michaelschiff/druid,andy256/druid,mrijke/druid,pdeva/druid,mghosh4/druid,pjain1/druid,rasahner/druid,potto007/druid-avro,pjain1/druid,winval/druid,michaelschiff/druid,jon-wei/druid,Fokko/druid,lizhanhui/data_druid,mghosh4/druid,guobingkun/druid,taochaoqiang/druid,druid-io/druid,du00cs/druid,michaelschiff/druid,leventov/druid,dkhwangbo/druid,druid-io/druid,winval/druid,gianm/druid,himanshug/druid,redBorder/druid,erikdubbelboer/druid,andy256/druid,deltaprojects/druid,Fokko/druid,yaochitc/druid-dev,KurtYoung/druid
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.testing.utils; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; import com.metamx.common.ISE; import com.metamx.common.logger.Logger; import io.druid.testing.IntegrationTestingConfig; import io.druid.testing.clients.QueryResourceTestClient; import java.util.List; import java.util.Map; public class TestQueryHelper { public static Logger LOG = new Logger(TestQueryHelper.class); private final QueryResourceTestClient queryClient; private final ObjectMapper jsonMapper; private final String broker; @Inject TestQueryHelper( ObjectMapper jsonMapper, QueryResourceTestClient queryClient, IntegrationTestingConfig config ) { this.jsonMapper = jsonMapper; this.queryClient = queryClient; this.broker = config.getBrokerHost(); } public void testQueriesFromFile(String filePath, int timesToRun) throws Exception { testQueriesFromFile(getBrokerURL(), filePath, timesToRun); } public void testQueriesFromFile(String url, String filePath, int timesToRun) throws Exception { LOG.info("Starting query tests for [%s]", filePath); List<QueryWithResults> queries = jsonMapper.readValue( TestQueryHelper.class.getResourceAsStream(filePath), new TypeReference<List<QueryWithResults>>() { } ); testQueries(url, queries, timesToRun); } public void testQueriesFromString(String str, int timesToRun) throws Exception { testQueriesFromString(getBrokerURL(), str, timesToRun); } public void testQueriesFromString(String url, String str, int timesToRun) throws Exception { LOG.info("Starting query tests using\n%s", str); List<QueryWithResults> queries = jsonMapper.readValue( str, new TypeReference<List<QueryWithResults>>() { } ); testQueries(url, queries, timesToRun); } private void testQueries(String url, List<QueryWithResults> queries, int timesToRun) throws Exception { for (int i = 0; i < timesToRun; i++) { LOG.info("Starting Iteration %d", i); boolean failed = false; for (QueryWithResults queryWithResult : queries) { LOG.info("Running Query %s", queryWithResult.getQuery().getType()); List<Map<String, Object>> result = queryClient.query(url, queryWithResult.getQuery()); if (!QueryResultVerifier.compareResults(result, queryWithResult.getExpectedResults())) { LOG.error( "Failed while executing query %s \n expectedResults: %s \n actualResults : %s", queryWithResult.getQuery(), jsonMapper.writeValueAsString(queryWithResult.getExpectedResults()), jsonMapper.writeValueAsString(result) ); failed = true; } else { LOG.info("Results Verified for Query %s", queryWithResult.getQuery().getType()); } } if (failed) { throw new ISE("one or more queries failed"); } } } private String getBrokerURL() { return String.format("http://%s/druid/v2?pretty", broker); } }
integration-tests/src/main/java/io/druid/testing/utils/TestQueryHelper.java
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.testing.utils; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Inject; import com.metamx.common.ISE; import com.metamx.common.logger.Logger; import io.druid.testing.IntegrationTestingConfig; import io.druid.testing.clients.QueryResourceTestClient; import java.util.List; import java.util.Map; public class TestQueryHelper { public static Logger LOG = new Logger(TestQueryHelper.class); private final QueryResourceTestClient queryClient; private final ObjectMapper jsonMapper; private final String broker; @Inject TestQueryHelper( ObjectMapper jsonMapper, QueryResourceTestClient queryClient, IntegrationTestingConfig config ) { this.jsonMapper = jsonMapper; this.queryClient = queryClient; this.broker = config.getBrokerHost(); } public void testQueriesFromFile(String filePath, int timesToRun) throws Exception { testQueriesFromFile(getBrokerURL(), filePath, timesToRun); } public void testQueriesFromFile(String url, String filePath, int timesToRun) throws Exception { LOG.info("Starting query tests for [%s]", filePath); List<QueryWithResults> queries = jsonMapper.readValue( TestQueryHelper.class.getResourceAsStream(filePath), new TypeReference<List<QueryWithResults>>() { } ); testQueries(url, queries, timesToRun); } public void testQueriesFromString(String str, int timesToRun) throws Exception { testQueriesFromString(getBrokerURL(), str, timesToRun); } public void testQueriesFromString(String url, String str, int timesToRun) throws Exception { LOG.info("Starting query tests using\n%s", str); List<QueryWithResults> queries = jsonMapper.readValue( str, new TypeReference<List<QueryWithResults>>() { } ); testQueries(url, queries, timesToRun); } private void testQueries(String url, List<QueryWithResults> queries, int timesToRun) throws Exception { for (int i = 0; i < timesToRun; i++) { LOG.info("Starting Iteration %d", i); boolean failed = false; for (QueryWithResults queryWithResult : queries) { LOG.info("Running Query %s", queryWithResult.getQuery().getType()); List<Map<String, Object>> result = queryClient.query(url, queryWithResult.getQuery()); if (!QueryResultVerifier.compareResults(result, queryWithResult.getExpectedResults())) { LOG.error( "Failed while executing %s actualResults : %s", queryWithResult, jsonMapper.writeValueAsString(result) ); failed = true; } else { LOG.info("Results Verified for Query %s", queryWithResult.getQuery().getType()); } } if (failed) { throw new ISE("one or more queries failed"); } } } private String getBrokerURL() { return String.format("http://%s/druid/v2?pretty", broker); } }
Integration tests: print expected results in json format
integration-tests/src/main/java/io/druid/testing/utils/TestQueryHelper.java
Integration tests: print expected results in json format
<ide><path>ntegration-tests/src/main/java/io/druid/testing/utils/TestQueryHelper.java <ide> List<Map<String, Object>> result = queryClient.query(url, queryWithResult.getQuery()); <ide> if (!QueryResultVerifier.compareResults(result, queryWithResult.getExpectedResults())) { <ide> LOG.error( <del> "Failed while executing %s actualResults : %s", <del> queryWithResult, <add> "Failed while executing query %s \n expectedResults: %s \n actualResults : %s", <add> queryWithResult.getQuery(), <add> jsonMapper.writeValueAsString(queryWithResult.getExpectedResults()), <ide> jsonMapper.writeValueAsString(result) <ide> ); <ide> failed = true;
Java
mit
73db0cc6ba30c2c2704c02b55088119ad86425b0
0
Emiliyan-Sokolov/diplomna-rabota,Emiliyan-Sokolov/diplomna-rabota
package com.example.cripz.bluetoothrccarcontroller; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.hardware.Sensor; import android.hardware.SensorManager; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.widget.TextView; import android.widget.Toast; public class Accelerometer extends AppCompatActivity implements SensorEventListener { private float x, y, z; private TextView stateText; private String state = "state"; private String lastState = "lastState"; // private float x0, y0, z0; private Sensor acc; private SensorManager senMng; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.accelerometer_main); senMng = (SensorManager)getSystemService(SENSOR_SERVICE); acc = senMng.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); if(acc != null){ senMng.registerListener(this, acc, SensorManager.SENSOR_DELAY_NORMAL); Toast.makeText(getApplicationContext(), "Success!",Toast.LENGTH_LONG ).show(); }else{ Toast.makeText(getApplicationContext(), "Your device do not have an accelerometer",Toast.LENGTH_LONG ).show(); } } private String goForward(){ MainControl.sendMessage("f"); //go forward MainControl.sendMessage("g"); //stop backward MainControl.sendMessage("h"); //stop left MainControl.sendMessage("j"); //stop right lastState = "MOVING_FORWARD"; return lastState; } private String goBackward(){ MainControl.sendMessage("k"); //stop forward MainControl.sendMessage("b"); //go backward MainControl.sendMessage("h"); //stop left MainControl.sendMessage("j"); //stop right lastState = "MOVING_BACKWARD"; return lastState; } private String goRight(){ MainControl.sendMessage("k"); //stop forward MainControl.sendMessage("g"); //stop backward MainControl.sendMessage("h"); //stop left MainControl.sendMessage("r"); //go right lastState = "MOVING_RIGHT"; return lastState; } private String goLeft(){ MainControl.sendMessage("k"); //stop forward MainControl.sendMessage("g"); //stop backward MainControl.sendMessage("l"); //go left MainControl.sendMessage("j"); //stop right lastState = "MOVING_LEFT"; return lastState; } private String stop(){ MainControl.sendMessage("k"); //stop forward MainControl.sendMessage("g"); //stop backward MainControl.sendMessage("h"); //stop left MainControl.sendMessage("j"); //stop right lastState = "STAY"; return lastState; } @Override public void onSensorChanged(SensorEvent event) { x = Math.round(event.values[0]); y = Math.round(event.values[1]); z = Math.round(event.values[2]); System.out.println("X: " + x + " Y: " + y + " Z: " + z); stateText = (TextView)findViewById(R.id.stateTextID); //stateText.setText(("X: " + x + " Y: " + y + " Z: " + z + state)); if (y <= -3) { state = "MOVING_LEFT"; if(!lastState.equals(state)){ goLeft(); } stateText.setText(state); } if (y >= 3) { state = "MOVING_RIGHT"; if(!lastState.equals(state)){ goRight(); } stateText.setText(state); } if(z >= 2){ state = "MOVING_FORWARD"; if(!lastState.equals(state)){ goForward(); stateText.setText(state); } } if (z <= -2){ state = "MOVING_BACKWARD"; if(!lastState.equals(state)){ goBackward(); } stateText.setText(state); } if ((y == -1 || y == 0 || y == 1 ) && (z == -1 || z == 0 || z == 1 )) { state = "STAY"; if(!lastState.equals(state)){ stop(); } stateText.setText(state); } } @Override protected void onStop() { super.onStop(); MainControl.sendMessage("k"); MainControl.sendMessage("g"); MainControl.sendMessage("j"); MainControl.sendMessage("h"); MainControl.sendMessage("v"); senMng.unregisterListener(this, acc); } @Override protected void onResume() { super.onResume(); senMng.registerListener(this, acc, SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { //not in use } }
app/src/main/java/com/example/cripz/bluetoothrccarcontroller/Accelerometer.java
package com.example.cripz.bluetoothrccarcontroller; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.hardware.Sensor; import android.hardware.SensorManager; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.widget.TextView; import android.widget.Toast; public class Accelerometer extends AppCompatActivity implements SensorEventListener { private float x, y, z; private TextView stateText; private String state = " "; private String lastState = " "; private float x0, y0, z0; private Sensor acc; private SensorManager senMng; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.accelerometer_main); senMng = (SensorManager)getSystemService(SENSOR_SERVICE); acc = senMng.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); if(acc != null){ senMng.registerListener(this, acc, SensorManager.SENSOR_DELAY_NORMAL); Toast.makeText(getApplicationContext(), "Success!",Toast.LENGTH_LONG ).show(); }else{ Toast.makeText(getApplicationContext(), "Your device do not have an accelerometer",Toast.LENGTH_LONG ).show(); } } @Override public void onSensorChanged(SensorEvent event) { x = Math.round(event.values[0]); y = Math.round(event.values[1]); z = Math.round(event.values[2]); //if(flag == 0) { //x0Text = events.values[0]; x0 = 10; y0 = 0; z0 = 0; // flag = 1; //} System.out.println("X: " + x + " Y: " + y + " Z: " + z); stateText = (TextView)findViewById(R.id.stateTextID); // stateText.setText("X: " + x + " Y: " + y + " Z: " + z); if(z > 1) { state = "MOVING_FORWARD"; stateText.setText(state); if (!lastState.equals(state)) { MainControl.sendMessage("j"); MainControl.sendMessage("h"); MainControl.sendMessage("g"); MainControl.sendMessage("f"); lastState = state; } }else if(z < -1) { state = "MOVING_BACKWARD"; stateText.setText(state); if (!lastState.equals(state)) { MainControl.sendMessage("k"); MainControl.sendMessage("j"); MainControl.sendMessage("h"); MainControl.sendMessage("b"); lastState = state; } }else if(y <= -2){ state = "MOVING_LEFT"; stateText.setText(state); if(!lastState.equals(state)) { MainControl.sendMessage("k"); MainControl.sendMessage("g"); MainControl.sendMessage("j"); MainControl.sendMessage("l"); lastState = state; } }else if(y > 2){ state = "MOVING_RIGHT"; stateText.setText(state); if(!lastState.equals(state)){ MainControl.sendMessage("k"); MainControl.sendMessage("g"); MainControl.sendMessage("h"); MainControl.sendMessage("r"); lastState = state; } } else if((z >= -1 && z <= 1) && (y >-2 && y < 2)) { state = "STAY"; stateText.setText(state); if(!lastState.equals(state)) { MainControl.sendMessage("k"); MainControl.sendMessage("g"); MainControl.sendMessage("h"); MainControl.sendMessage("j"); lastState = state; } } } @Override protected void onStop() { super.onStop(); MainControl.sendMessage("k"); MainControl.sendMessage("g"); MainControl.sendMessage("j"); MainControl.sendMessage("h"); MainControl.sendMessage("v"); senMng.unregisterListener(this, acc); } @Override protected void onResume() { super.onResume(); senMng.registerListener(this, acc, SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { //not in use } }
Updating Accelerometer
app/src/main/java/com/example/cripz/bluetoothrccarcontroller/Accelerometer.java
Updating Accelerometer
<ide><path>pp/src/main/java/com/example/cripz/bluetoothrccarcontroller/Accelerometer.java <ide> import android.widget.TextView; <ide> import android.widget.Toast; <ide> <add> <ide> public class Accelerometer extends AppCompatActivity implements SensorEventListener { <ide> private float x, y, z; <ide> private TextView stateText; <del> private String state = " "; <del> private String lastState = " "; <del> private float x0, y0, z0; <add> private String state = "state"; <add> private String lastState = "lastState"; <add> // private float x0, y0, z0; <ide> private Sensor acc; <ide> private SensorManager senMng; <add> <ide> <ide> @Override <ide> protected void onCreate(Bundle savedInstanceState) { <ide> <ide> } <ide> <add> private String goForward(){ <add> MainControl.sendMessage("f"); //go forward <add> MainControl.sendMessage("g"); //stop backward <add> MainControl.sendMessage("h"); //stop left <add> MainControl.sendMessage("j"); //stop right <add> lastState = "MOVING_FORWARD"; <add> <add> return lastState; <add> } <add> <add> private String goBackward(){ <add> MainControl.sendMessage("k"); //stop forward <add> MainControl.sendMessage("b"); //go backward <add> MainControl.sendMessage("h"); //stop left <add> MainControl.sendMessage("j"); //stop right <add> lastState = "MOVING_BACKWARD"; <add> <add> return lastState; <add> } <add> <add> private String goRight(){ <add> MainControl.sendMessage("k"); //stop forward <add> MainControl.sendMessage("g"); //stop backward <add> MainControl.sendMessage("h"); //stop left <add> MainControl.sendMessage("r"); //go right <add> lastState = "MOVING_RIGHT"; <add> <add> return lastState; <add> } <add> <add> private String goLeft(){ <add> MainControl.sendMessage("k"); //stop forward <add> MainControl.sendMessage("g"); //stop backward <add> MainControl.sendMessage("l"); //go left <add> MainControl.sendMessage("j"); //stop right <add> lastState = "MOVING_LEFT"; <add> <add> return lastState; <add> } <add> <add> <add> private String stop(){ <add> MainControl.sendMessage("k"); //stop forward <add> MainControl.sendMessage("g"); //stop backward <add> MainControl.sendMessage("h"); //stop left <add> MainControl.sendMessage("j"); //stop right <add> lastState = "STAY"; <add> <add> return lastState; <add> } <add> <ide> @Override <ide> public void onSensorChanged(SensorEvent event) { <ide> x = Math.round(event.values[0]); <ide> y = Math.round(event.values[1]); <ide> z = Math.round(event.values[2]); <ide> <del> //if(flag == 0) { <del> //x0Text = events.values[0]; <del> x0 = 10; <del> y0 = 0; <del> z0 = 0; <del> // flag = 1; <del> //} <del> <ide> System.out.println("X: " + x + " Y: " + y + " Z: " + z); <ide> stateText = (TextView)findViewById(R.id.stateTextID); <del> <del> // stateText.setText("X: " + x + " Y: " + y + " Z: " + z); <del> <del> if(z > 1) { <del> state = "MOVING_FORWARD"; <del> stateText.setText(state); <del> <del> if (!lastState.equals(state)) { <del> MainControl.sendMessage("j"); <del> MainControl.sendMessage("h"); <del> MainControl.sendMessage("g"); <del> MainControl.sendMessage("f"); <del> lastState = state; <del> } <add> //stateText.setText(("X: " + x + " Y: " + y + " Z: " + z + state)); <ide> <ide> <del> }else if(z < -1) { <del> state = "MOVING_BACKWARD"; <add> if (y <= -3) { <add> state = "MOVING_LEFT"; <add> if(!lastState.equals(state)){ <add> goLeft(); <add> } <ide> stateText.setText(state); <add> } <ide> <del> if (!lastState.equals(state)) { <del> MainControl.sendMessage("k"); <del> MainControl.sendMessage("j"); <del> MainControl.sendMessage("h"); <del> MainControl.sendMessage("b"); <del> lastState = state; <add> if (y >= 3) { <add> state = "MOVING_RIGHT"; <add> if(!lastState.equals(state)){ <add> goRight(); <ide> } <del> }else if(y <= -2){ <del> state = "MOVING_LEFT"; <ide> stateText.setText(state); <add> } <ide> <del> if(!lastState.equals(state)) { <del> MainControl.sendMessage("k"); <del> MainControl.sendMessage("g"); <del> MainControl.sendMessage("j"); <del> MainControl.sendMessage("l"); <del> lastState = state; <del> } <del> }else if(y > 2){ <del> state = "MOVING_RIGHT"; <del> stateText.setText(state); <add> if(z >= 2){ <add> state = "MOVING_FORWARD"; <ide> if(!lastState.equals(state)){ <del> MainControl.sendMessage("k"); <del> MainControl.sendMessage("g"); <del> MainControl.sendMessage("h"); <del> MainControl.sendMessage("r"); <del> lastState = state; <del> } <del> } else if((z >= -1 && z <= 1) && (y >-2 && y < 2)) { <del> state = "STAY"; <del> stateText.setText(state); <del> if(!lastState.equals(state)) { <del> MainControl.sendMessage("k"); <del> MainControl.sendMessage("g"); <del> MainControl.sendMessage("h"); <del> MainControl.sendMessage("j"); <del> lastState = state; <add> goForward(); <add> stateText.setText(state); <ide> } <ide> } <add> <add> if (z <= -2){ <add> state = "MOVING_BACKWARD"; <add> if(!lastState.equals(state)){ <add> goBackward(); <add> } <add> stateText.setText(state); <add> } <add> <add> <add> if ((y == -1 || y == 0 || y == 1 ) && (z == -1 || z == 0 || z == 1 )) { <add> state = "STAY"; <add> if(!lastState.equals(state)){ <add> stop(); <add> } <add> stateText.setText(state); <add> } <add> <add> <ide> } <ide> <ide> @Override <ide> senMng.registerListener(this, acc, SensorManager.SENSOR_DELAY_NORMAL); <ide> } <ide> <add> <ide> @Override <ide> public void onAccuracyChanged(Sensor sensor, int accuracy) { <ide> //not in use
Java
apache-2.0
91b1890587fd0cd9e016203d97836ca3899bc707
0
ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma
/* * The Gemma project * * Copyright (c) 2005 Columbia University * * 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 edu.columbia.gemma.web.listener; import java.util.HashSet; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.columbia.gemma.web.Constants; /** * UserCounterListener class used to count the current number of active users for the applications. Does this by * counting how many user objects are stuffed into the session. It also grabs these users and exposes them in the * servlet context. * <p> * Contains code from Appfuse. * <hr> * <p> * Copyright (c) 2004 - 2005 Columbia University * * @author <a href="mailto:[email protected]">Matt Raible</a> * @author keshav * @author pavlidis * @version $Id$ * @web.listener */ public class UserCounterListener implements ServletContextListener, HttpSessionAttributeListener { public static final String COUNT_KEY = "userCounter"; public static final String USERS_KEY = "userNames"; private int counter; private final transient Log log = LogFactory.getLog( UserCounterListener.class ); private transient ServletContext servletContext; private Set<Object> users; /** * This method is designed to catch when user's login and record their name * * @see javax.servlet.http.HttpSessionAttributeListener#attributeAdded(javax.servlet.http.HttpSessionBindingEvent) */ public void attributeAdded( HttpSessionBindingEvent event ) { if ( event.getName().equals( Constants.USER_KEY ) ) { addUsername( event.getValue() ); } } /** * When users logout, remove their name from the hashMap * * @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent) */ public void attributeRemoved( HttpSessionBindingEvent event ) { if ( event.getName().equals( Constants.USER_KEY ) ) { removeUsername( event.getValue() ); } } /* * (non-Javadoc) * * @see javax.servlet.http.HttpSessionAttributeListener#attributeReplaced(javax.servlet.http.HttpSessionBindingEvent) */ @SuppressWarnings("unused") public void attributeReplaced( HttpSessionBindingEvent event ) { // I don't really care if the user changes their information } /* * (non-Javadoc) * * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) */ @SuppressWarnings("unused") public synchronized void contextDestroyed( ServletContextEvent event ) { servletContext = null; users = null; counter = 0; } /* * (non-Javadoc) * * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ public synchronized void contextInitialized( ServletContextEvent sce ) { servletContext = sce.getServletContext(); servletContext.setAttribute( ( COUNT_KEY ), Integer.toString( counter ) ); } /** * @param user */ @SuppressWarnings("unchecked") synchronized void addUsername( Object user ) { assert servletContext.getAttribute( USERS_KEY ) instanceof Set : "USERS_KEY is not a java.util.Set"; users = ( Set ) servletContext.getAttribute( USERS_KEY ); if ( users == null ) { users = new HashSet(); } if ( log.isDebugEnabled() ) { if ( users.contains( user ) ) { log.debug( "User already logged in, adding anyway..." ); } } users.add( user ); servletContext.setAttribute( USERS_KEY, users ); incrementUserCounter(); } /** * */ synchronized void decrementUserCounter() { // N.B. I'm pretty sure this was a bug, it was hiding the class property 'counter'. PP 8/28/2005 counter = Integer.parseInt( ( String ) servletContext.getAttribute( COUNT_KEY ) ); counter--; if ( counter < 0 ) { log.warn( "User count went negative" ); counter = 0; } servletContext.setAttribute( COUNT_KEY, Integer.toString( counter ) ); if ( log.isDebugEnabled() ) { log.debug( "User Count: " + counter ); } } /** * */ synchronized void incrementUserCounter() { counter = Integer.parseInt( ( String ) servletContext.getAttribute( COUNT_KEY ) ); counter++; servletContext.setAttribute( COUNT_KEY, Integer.toString( counter ) ); if ( log.isDebugEnabled() ) { log.debug( "User Count: " + counter ); } } /** * @param user */ @SuppressWarnings("unchecked") synchronized void removeUsername( Object user ) { assert servletContext.getAttribute( USERS_KEY ) instanceof Set : "USERS_KEY is not a java.util.Set"; users = ( Set ) servletContext.getAttribute( USERS_KEY ); if ( users != null ) { users.remove( user ); } servletContext.setAttribute( USERS_KEY, users ); decrementUserCounter(); } }
src/web/edu/columbia/gemma/web/listener/UserCounterListener.java
package edu.columbia.gemma.web.listener; import java.util.HashSet; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.columbia.gemma.web.Constants; /** * UserCounterListener class used to count the current number of active users for the applications. Does this by * counting how many user objects are stuffed into the session. It Also grabs these users and exposes them in the * servlet context. * <hr> * <p> * Copyright (c) 2004 - 2005 Columbia University * * @author <a href="mailto:[email protected]">Matt Raible</a> * @author keshav * @version $Id$ * @web.listener */ public class UserCounterListener implements ServletContextListener, HttpSessionAttributeListener { public static final String COUNT_KEY = "userCounter"; public static final String USERS_KEY = "userNames"; private int counter; private final transient Log log = LogFactory.getLog( UserCounterListener.class ); private transient ServletContext servletContext; private Set users; /** * This method is designed to catch when user's login and record their name * * @see javax.servlet.http.HttpSessionAttributeListener#attributeAdded(javax.servlet.http.HttpSessionBindingEvent) */ public void attributeAdded( HttpSessionBindingEvent event ) { if ( event.getName().equals( Constants.USER_KEY ) ) { addUsername( event.getValue() ); } } /** * When user's logout, remove their name from the hashMap * * @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent) */ public void attributeRemoved( HttpSessionBindingEvent event ) { if ( event.getName().equals( Constants.USER_KEY ) ) { removeUsername( event.getValue() ); } } /** * @see javax.servlet.http.HttpSessionAttributeListener#attributeReplaced(javax.servlet.http.HttpSessionBindingEvent) */ public void attributeReplaced( HttpSessionBindingEvent event ) { // I don't really care if the user changes their information } public synchronized void contextDestroyed( ServletContextEvent event ) { servletContext = null; users = null; counter = 0; } public synchronized void contextInitialized( ServletContextEvent sce ) { servletContext = sce.getServletContext(); servletContext.setAttribute( ( COUNT_KEY ), Integer.toString( counter ) ); } synchronized void addUsername( Object user ) { users = ( Set ) servletContext.getAttribute( USERS_KEY ); if ( users == null ) { users = new HashSet(); } if ( log.isDebugEnabled() ) { if ( users.contains( user ) ) { log.debug( "User already logged in, adding anyway..." ); } } users.add( user ); servletContext.setAttribute( USERS_KEY, users ); incrementUserCounter(); } synchronized void decrementUserCounter() { int counter = Integer.parseInt( ( String ) servletContext.getAttribute( COUNT_KEY ) ); counter--; if ( counter < 0 ) { counter = 0; } servletContext.setAttribute( COUNT_KEY, Integer.toString( counter ) ); if ( log.isDebugEnabled() ) { log.debug( "User Count: " + counter ); } } synchronized void incrementUserCounter() { counter = Integer.parseInt( ( String ) servletContext.getAttribute( COUNT_KEY ) ); counter++; servletContext.setAttribute( COUNT_KEY, Integer.toString( counter ) ); if ( log.isDebugEnabled() ) { log.debug( "User Count: " + counter ); } } synchronized void removeUsername( Object user ) { users = ( Set ) servletContext.getAttribute( USERS_KEY ); if ( users != null ) { users.remove( user ); } servletContext.setAttribute( USERS_KEY, users ); decrementUserCounter(); } }
cleanup
src/web/edu/columbia/gemma/web/listener/UserCounterListener.java
cleanup
<ide><path>rc/web/edu/columbia/gemma/web/listener/UserCounterListener.java <add>/* <add> * The Gemma project <add> * <add> * Copyright (c) 2005 Columbia University <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> * <add> */ <ide> package edu.columbia.gemma.web.listener; <ide> <ide> import java.util.HashSet; <ide> <ide> /** <ide> * UserCounterListener class used to count the current number of active users for the applications. Does this by <del> * counting how many user objects are stuffed into the session. It Also grabs these users and exposes them in the <add> * counting how many user objects are stuffed into the session. It also grabs these users and exposes them in the <ide> * servlet context. <add> * <p> <add> * Contains code from Appfuse. <ide> * <hr> <ide> * <p> <ide> * Copyright (c) 2004 - 2005 Columbia University <ide> * <ide> * @author <a href="mailto:[email protected]">Matt Raible</a> <ide> * @author keshav <add> * @author pavlidis <ide> * @version $Id$ <ide> * @web.listener <ide> */ <ide> private int counter; <ide> private final transient Log log = LogFactory.getLog( UserCounterListener.class ); <ide> private transient ServletContext servletContext; <del> private Set users; <add> private Set<Object> users; <ide> <ide> /** <ide> * This method is designed to catch when user's login and record their name <ide> } <ide> <ide> /** <del> * When user's logout, remove their name from the hashMap <add> * When users logout, remove their name from the hashMap <ide> * <ide> * @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent) <ide> */ <ide> } <ide> } <ide> <del> /** <add> /* <add> * (non-Javadoc) <add> * <ide> * @see javax.servlet.http.HttpSessionAttributeListener#attributeReplaced(javax.servlet.http.HttpSessionBindingEvent) <ide> */ <add> @SuppressWarnings("unused") <ide> public void attributeReplaced( HttpSessionBindingEvent event ) { <ide> // I don't really care if the user changes their information <ide> } <ide> <add> /* <add> * (non-Javadoc) <add> * <add> * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) <add> */ <add> @SuppressWarnings("unused") <ide> public synchronized void contextDestroyed( ServletContextEvent event ) { <ide> servletContext = null; <ide> users = null; <ide> counter = 0; <ide> } <ide> <add> /* <add> * (non-Javadoc) <add> * <add> * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) <add> */ <ide> public synchronized void contextInitialized( ServletContextEvent sce ) { <ide> servletContext = sce.getServletContext(); <ide> servletContext.setAttribute( ( COUNT_KEY ), Integer.toString( counter ) ); <ide> } <ide> <add> /** <add> * @param user <add> */ <add> @SuppressWarnings("unchecked") <ide> synchronized void addUsername( Object user ) { <add> assert servletContext.getAttribute( USERS_KEY ) instanceof Set : "USERS_KEY is not a java.util.Set"; <ide> users = ( Set ) servletContext.getAttribute( USERS_KEY ); <ide> <ide> if ( users == null ) { <ide> incrementUserCounter(); <ide> } <ide> <add> /** <add> * <add> */ <ide> synchronized void decrementUserCounter() { <del> int counter = Integer.parseInt( ( String ) servletContext.getAttribute( COUNT_KEY ) ); <add> // N.B. I'm pretty sure this was a bug, it was hiding the class property 'counter'. PP 8/28/2005 <add> counter = Integer.parseInt( ( String ) servletContext.getAttribute( COUNT_KEY ) ); <ide> counter--; <ide> <ide> if ( counter < 0 ) { <add> log.warn( "User count went negative" ); <ide> counter = 0; <ide> } <ide> <ide> } <ide> } <ide> <add> /** <add> * <add> */ <ide> synchronized void incrementUserCounter() { <ide> counter = Integer.parseInt( ( String ) servletContext.getAttribute( COUNT_KEY ) ); <ide> counter++; <ide> } <ide> } <ide> <add> /** <add> * @param user <add> */ <add> @SuppressWarnings("unchecked") <ide> synchronized void removeUsername( Object user ) { <add> assert servletContext.getAttribute( USERS_KEY ) instanceof Set : "USERS_KEY is not a java.util.Set"; <ide> users = ( Set ) servletContext.getAttribute( USERS_KEY ); <ide> <ide> if ( users != null ) {
Java
mit
error: pathspec 'Java/src/presentacio/Stats/InfoRanking.java' did not match any file(s) known to git
680090a5196c7f204fc5a90923f915eb8be6118b
1
jmigual/pKK,jmigual/pKK,jmigual/pKK
package presentacio.Stats; /** * Created by esteve on 14/12/2015. */ public class InfoRanking { private Integer rank; private String name; private Integer score; // Comentari troll perquè no es canvii de nom public InfoRanking(){ this.rank = -1; this.name = ""; this.score = 0; } public InfoRanking(int rank, String name, int score){ this.rank = rank; this.name = name; this.score = score; } public Integer getRank() { return rank; } public void setRank(Integer rank) { this.rank = rank; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } }
Java/src/presentacio/Stats/InfoRanking.java
InfoRanking no sucks
Java/src/presentacio/Stats/InfoRanking.java
InfoRanking no sucks
<ide><path>ava/src/presentacio/Stats/InfoRanking.java <add>package presentacio.Stats; <add> <add>/** <add> * Created by esteve on 14/12/2015. <add> */ <add>public class InfoRanking { <add> private Integer rank; <add> private String name; <add> private Integer score; <add> <add> // Comentari troll perquè no es canvii de nom <add> <add> public InfoRanking(){ <add> this.rank = -1; <add> this.name = ""; <add> this.score = 0; <add> } <add> <add> public InfoRanking(int rank, String name, int score){ <add> this.rank = rank; <add> this.name = name; <add> this.score = score; <add> } <add> <add> public Integer getRank() { <add> return rank; <add> } <add> <add> public void setRank(Integer rank) { <add> this.rank = rank; <add> } <add> <add> public String getName() { <add> return name; <add> } <add> <add> public void setName(String name) { <add> this.name = name; <add> } <add> <add> public Integer getScore() { <add> return score; <add> } <add> <add> public void setScore(Integer score) { <add> this.score = score; <add> } <add>}
Java
lgpl-2.1
baa45c51c13a598411f1c0d1ea9f9bacfeeb76b6
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.io; import java.io.OutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; /** * Used to write {@link Streamable} objects to an {@link OutputStream}. * Other common object types are supported as well: * * <pre> * Boolean * Byte * Character * Short * Integer * Long * Float * Double * boolean[] * byte[] * char[] * short[] * int[] * long[] * float[] * double[] * Object[] * </pre> * * @see Streamable */ public class ObjectOutputStream extends DataOutputStream { /** * Constructs an object output stream which will write its data to the * supplied target stream. */ public ObjectOutputStream (OutputStream target) { super(target); } /** * Configures this object output stream with a mapping from a classname * to a streamed name. */ public void addTranslation (String className, String streamedName) { if (_translations == null) { _translations = new HashMap(); } _translations.put(className, streamedName); } /** * Writes a {@link Streamable} instance or one of the support object * types to the output stream. */ public void writeObject (Object object) throws IOException { // if the object to be written is null, simply write a zero if (object == null) { writeShort(0); return; } // create our classmap if necessary if (_classmap == null) { _classmap = new HashMap(); } // otherwise, look up the class mapping record Class sclass = object.getClass(); ClassMapping cmap = (ClassMapping)_classmap.get(sclass); // create a class mapping for this class if we've not got one if (cmap == null) { // create a streamer instance and assign a code to this class Streamer streamer = Streamer.getStreamer(sclass); // we specifically do not inline the getStreamer() call // into the ClassMapping constructor because we want to be // sure not to call _nextCode++ if getStreamer() throws an // exception cmap = new ClassMapping(_nextCode++, sclass, streamer); _classmap.put(sclass, cmap); // make sure we didn't blow past our maximum class count if (_nextCode <= 0) { throw new RuntimeException("Too many unique classes " + "written to ObjectOutputStream"); } // writing a negative class code indicates that the class // name will follow writeShort(-cmap.code); String cname = sclass.getName(); if (_translations != null) { String tname = (String) _translations.get(cname); if (tname != null) { cname = tname; } } writeUTF(cname); } else { writeShort(cmap.code); } writeBareObject(object, cmap.streamer, true); } /** * Writes a {@link Streamable} instance or one of the support object * types <em>without associated class metadata</em> to the output * stream. The caller is responsible for knowing the exact class of * the written object, creating an instance of such and calling {@link * ObjectInputStream#readBareObject} to read its data from the stream. * * @param object the object to be written. It cannot be * <code>null</code>. */ public void writeBareObject (Object object) throws IOException { writeBareObject(object, Streamer.getStreamer(object.getClass()), true); } /** * Write a {@link Streamable} instance without associated class metadata. */ protected void writeBareObject ( Object obj, Streamer streamer, boolean useWriter) throws IOException { _current = obj; _streamer = streamer; try { _streamer.writeObject(obj, this, useWriter); } finally { _current = null; _streamer = null; } } /** * Uses the default streamable mechanism to write the contents of the * object currently being streamed. This can only be called from * within a <code>writeObject</code> implementation in a {@link * Streamable} object. */ public void defaultWriteObject () throws IOException { // sanity check if (_current == null) { throw new RuntimeException( "defaultWriteObject() called illegally."); } // Log.info("Writing default [cmap=" + _streamer + // ", current=" + _current + "]."); // write the instance data _streamer.writeObject(_current, this, false); } /** Used to map classes to numeric codes and the {@link Streamer} * instance used to write them. */ protected HashMap _classmap; /** A counter used to assign codes to streamed classes. */ protected short _nextCode = 1; /** The object currently being written to the stream. */ protected Object _current; /** The streamer being used currently. */ protected Streamer _streamer; /** An optional set of class name translations to use when serializing * objects. */ protected HashMap _translations; }
src/java/com/threerings/io/ObjectOutputStream.java
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.io; import java.io.OutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; /** * Used to write {@link Streamable} objects to an {@link OutputStream}. * Other common object types are supported as well: * * <pre> * Boolean * Byte * Character * Short * Integer * Long * Float * Double * boolean[] * byte[] * char[] * short[] * int[] * long[] * float[] * double[] * Object[] * </pre> * * @see Streamable */ public class ObjectOutputStream extends DataOutputStream { /** * Constructs an object output stream which will write its data to the * supplied target stream. */ public ObjectOutputStream (OutputStream target) { super(target); } /** * Writes a {@link Streamable} instance or one of the support object * types to the output stream. */ public void writeObject (Object object) throws IOException { // if the object to be written is null, simply write a zero if (object == null) { writeShort(0); return; } // create our classmap if necessary if (_classmap == null) { _classmap = new HashMap(); } // otherwise, look up the class mapping record Class sclass = object.getClass(); ClassMapping cmap = (ClassMapping)_classmap.get(sclass); // create a class mapping for this class if we've not got one if (cmap == null) { // create a streamer instance and assign a code to this class Streamer streamer = Streamer.getStreamer(sclass); // we specifically do not inline the getStreamer() call // into the ClassMapping constructor because we want to be // sure not to call _nextCode++ if getStreamer() throws an // exception cmap = new ClassMapping(_nextCode++, sclass, streamer); _classmap.put(sclass, cmap); // make sure we didn't blow past our maximum class count if (_nextCode <= 0) { throw new RuntimeException("Too many unique classes " + "written to ObjectOutputStream"); } // writing a negative class code indicates that the class // name will follow writeShort(-cmap.code); writeUTF(sclass.getName()); } else { writeShort(cmap.code); } writeBareObject(object, cmap.streamer, true); } /** * Writes a {@link Streamable} instance or one of the support object * types <em>without associated class metadata</em> to the output * stream. The caller is responsible for knowing the exact class of * the written object, creating an instance of such and calling {@link * ObjectInputStream#readBareObject} to read its data from the stream. * * @param object the object to be written. It cannot be * <code>null</code>. */ public void writeBareObject (Object object) throws IOException { writeBareObject(object, Streamer.getStreamer(object.getClass()), true); } /** * Write a {@link Streamable} instance without associated class metadata. */ protected void writeBareObject ( Object obj, Streamer streamer, boolean useWriter) throws IOException { _current = obj; _streamer = streamer; try { _streamer.writeObject(obj, this, useWriter); } finally { _current = null; _streamer = null; } } /** * Uses the default streamable mechanism to write the contents of the * object currently being streamed. This can only be called from * within a <code>writeObject</code> implementation in a {@link * Streamable} object. */ public void defaultWriteObject () throws IOException { // sanity check if (_current == null) { throw new RuntimeException( "defaultWriteObject() called illegally."); } // Log.info("Writing default [cmap=" + _streamer + // ", current=" + _current + "]."); // write the instance data _streamer.writeObject(_current, this, false); } /** Used to map classes to numeric codes and the {@link Streamer} * instance used to write them. */ protected HashMap _classmap; /** A counter used to assign codes to streamed classes. */ protected short _nextCode = 1; /** The object currently being written to the stream. */ protected Object _current; /** The streamer being used currently. */ protected Streamer _streamer; }
Added class translation support so that I could write a DSet converter. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@3947 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/io/ObjectOutputStream.java
Added class translation support so that I could write a DSet converter.
<ide><path>rc/java/com/threerings/io/ObjectOutputStream.java <ide> } <ide> <ide> /** <add> * Configures this object output stream with a mapping from a classname <add> * to a streamed name. <add> */ <add> public void addTranslation (String className, String streamedName) <add> { <add> if (_translations == null) { <add> _translations = new HashMap(); <add> } <add> _translations.put(className, streamedName); <add> } <add> <add> /** <ide> * Writes a {@link Streamable} instance or one of the support object <ide> * types to the output stream. <ide> */ <ide> // writing a negative class code indicates that the class <ide> // name will follow <ide> writeShort(-cmap.code); <del> writeUTF(sclass.getName()); <add> String cname = sclass.getName(); <add> if (_translations != null) { <add> String tname = (String) _translations.get(cname); <add> if (tname != null) { <add> cname = tname; <add> } <add> } <add> writeUTF(cname); <ide> <ide> } else { <ide> writeShort(cmap.code); <ide> <ide> /** The streamer being used currently. */ <ide> protected Streamer _streamer; <add> <add> /** An optional set of class name translations to use when serializing <add> * objects. */ <add> protected HashMap _translations; <ide> }
Java
epl-1.0
9320c9cdbff5be27d4e4ae598cf1bfe697f23aec
0
Techjar/ForgeEssentials,ForgeEssentials/ForgeEssentialsMain
package com.forgeessentials.scripting; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.DimensionManager; import org.apache.commons.lang3.StringUtils; import com.forgeessentials.api.APIRegistry; import com.forgeessentials.api.UserIdent; import com.forgeessentials.api.economy.Wallet; import com.forgeessentials.api.permissions.FEPermissions; import com.forgeessentials.api.permissions.Zone; import com.forgeessentials.commons.selections.WarpPoint; import com.forgeessentials.core.ForgeEssentials; import com.forgeessentials.core.misc.TaskRegistry; import com.forgeessentials.core.misc.TeleportHelper; import com.forgeessentials.core.misc.Translator; import com.forgeessentials.permissions.commands.PermissionCommandParser; import com.forgeessentials.scripting.ScriptParser.MissingPermissionException; import com.forgeessentials.scripting.ScriptParser.MissingPlayerException; import com.forgeessentials.scripting.ScriptParser.ScriptException; import com.forgeessentials.scripting.ScriptParser.ScriptMethod; import com.forgeessentials.scripting.ScriptParser.SyntaxException; import com.forgeessentials.util.CommandParserArgs; import com.forgeessentials.util.PlayerInfo; import com.forgeessentials.util.output.ChatOutputHandler; import com.google.common.collect.ImmutableMap; public final class ScriptMethods { public static Map<String, ScriptMethod> scriptMethods = new HashMap<>(); public static void add(String name, ScriptMethod argument) { if (scriptMethods.containsKey(name)) throw new RuntimeException(String.format("Script method name @%s already registered", name)); scriptMethods.put(name, argument); } public static ScriptMethod get(String name) { return scriptMethods.get(name); } public static Map<String, ScriptMethod> getAll() { return ImmutableMap.copyOf(scriptMethods); } private static void registerAll() { try { for (Field field : ScriptMethods.class.getDeclaredFields()) if (ScriptMethod.class.isAssignableFrom(field.getType()) && Modifier.isStatic(field.getModifiers())) add(field.getName().toLowerCase(), (ScriptMethod) field.get(null)); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } public static final ScriptMethod echo = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.sendMessage(sender, ChatOutputHandler.formatColors(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send message without any special formatting to the player"; } }; public static final ScriptMethod confirm = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatConfirmation(sender, StringUtils.join(args, " ")); return true; } @Override public String getHelp() { return "Send confirmation message to the player"; } }; public static final ScriptMethod notify = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatNotification(sender, StringUtils.join(args, " ")); return true; } @Override public String getHelp() { return "Send notification message to the player"; } }; public static final ScriptMethod warn = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatWarning(sender, StringUtils.join(args, " ")); return true; } @Override public String getHelp() { return "Send warning message to the player"; } }; public static final ScriptMethod error = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatError(sender, StringUtils.join(args, " ")); return true; } @Override public String getHelp() { return "Send error message to the player"; } }; public static final ScriptMethod fail = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatError(sender, StringUtils.join(args, " ")); return false; } @Override public String getHelp() { return "Send error message to the player and fail script execution"; } }; public static final ScriptMethod echoall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.formatColors(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send message without any special formatting to all players"; } }; public static final ScriptMethod confirmall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.confirmation(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send confirmation message to all players"; } }; public static final ScriptMethod notifyall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.notification(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send notification message to all players"; } }; public static final ScriptMethod warnall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.warning(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send warning message to all players"; } }; public static final ScriptMethod errorall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.error(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send error message to all players"; } }; public static final ScriptMethod failall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.error(StringUtils.join(args, " "))); return false; } @Override public String getHelp() { return "Send error message to all players and fail script execution"; } }; public static final ScriptMethod permset = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { CommandParserArgs arguments = new CommandParserArgs(null, args, MinecraftServer.getServer()); PermissionCommandParser.parseMain(arguments); return true; } @Override public String getHelp() { return "Modify permissions (like /p command)"; } }; protected static boolean getPermcheckResult(ICommandSender sender, String[] args) { if (!(sender instanceof EntityPlayerMP)) if (sender instanceof MinecraftServer) return true; else throw new MissingPlayerException(); if (args.length < 1) throw new SyntaxException("Missing argument for permchecksilent"); UserIdent ident = UserIdent.get((EntityPlayerMP) sender); String permission = args[0]; String value = args.length > 1 ? args[1] : Zone.PERMISSION_TRUE; boolean result; if (value.equals(Zone.PERMISSION_TRUE)) result = APIRegistry.perms.checkUserPermission(ident, permission); else if (value.equals(Zone.PERMISSION_FALSE)) result = !APIRegistry.perms.checkUserPermission(ident, permission); else result = APIRegistry.perms.getUserPermissionProperty(ident, permission).equals(value); return result; } public static final ScriptMethod permchecksilent = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { return getPermcheckResult(sender, args); } @Override public String getHelp() { return "`permchecksilent <perm> [value] [error message...]` \nPermission check (without error message). " + "Use `true` or `false` as value for normal permission checks (default value is `true`)." + "Other values will cause a permission-property check."; } }; public static final ScriptMethod permcheck = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (getPermcheckResult(sender, args)) return true; if (args.length > 2) throw new MissingPermissionException(args[0], StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " ")); else throw new MissingPermissionException(args[0]); } @Override public String getHelp() { return "`permcheck <perm> [value] [error message...]` \nPermission check (with error message). " + "Use `true` or `false` as value for normal permission checks (default value is `true`)." + "Other values will cause a permission-property check."; } }; public static final ScriptMethod teleport = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (args.length < 1) throw new SyntaxException("Missing player argument for teleport"); if (args.length < 2) throw new SyntaxException("Missing target argument for teleport"); UserIdent player = UserIdent.get(args[1], sender); if (!player.hasPlayer()) return false; if (args.length == 2) { UserIdent target = UserIdent.get(args[2], sender); if (!target.hasPlayer()) return false; TeleportHelper.teleport(player.getPlayerMP(), new WarpPoint(target.getPlayerMP())); } else if (args.length == 4) { int x = Integer.parseInt(args[1]); int y = Integer.parseInt(args[2]); int z = Integer.parseInt(args[3]); EntityPlayerMP p = player.getPlayerMP(); TeleportHelper.teleport(p, new WarpPoint(p.dimension, x, y, z, p.cameraPitch, p.cameraYaw)); } else if (args.length == 5) { int x = Integer.parseInt(args[1]); int y = Integer.parseInt(args[2]); int z = Integer.parseInt(args[3]); int dim = Integer.parseInt(args[4]); if (!DimensionManager.isDimensionRegistered(dim)) return false; EntityPlayerMP p = player.getPlayerMP(); TeleportHelper.teleport(p, new WarpPoint(dim, x, y, z, p.cameraPitch, p.cameraYaw)); } else throw new SyntaxException("Incorrect number of arguments"); return true; } @Override public String getHelp() { return "`teleport <player> <to-player>` \n`teleport <player> <x> <y> <z> [dim]`"; } }; public static final ScriptMethod pay = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (!(sender instanceof EntityPlayerMP)) throw new MissingPlayerException(); if (args.length < 1) throw new SyntaxException("Missing amount for pay command"); if (args.length > 2) throw new SyntaxException("Too many arguments"); long amount = Long.parseLong(args[0]); Wallet src = APIRegistry.economy.getWallet(UserIdent.get((EntityPlayerMP) sender)); Wallet dst = null; if (args.length == 2) { UserIdent dstIdent = UserIdent.get(args[1], sender); if (!dstIdent.hasUuid()) throw new ScriptException("Player %s not found", args[1]); dst = APIRegistry.economy.getWallet(dstIdent); } if (!src.withdraw(amount)) { ChatOutputHandler.chatError(sender, Translator.translate("You can't afford that!")); return false; } if (dst != null) dst.add(amount); return true; } @Override public String getHelp() { return "`pay <amount> [to-player]` \nMake the player pay some amount of money and fail, if he can't afford it"; } }; public static final ScriptMethod checkTimeout = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (!(sender instanceof EntityPlayer)) throw new MissingPlayerException(); if (args.length < 1) throw new SyntaxException(FEPermissions.MSG_NOT_ENOUGH_ARGUMENTS); PlayerInfo pi = PlayerInfo.get((EntityPlayer) sender); if (!pi.checkTimeout(args[0])) { if (args.length > 1) { String msg = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " "); String timeout = ChatOutputHandler.formatTimeDurationReadable(pi.getRemainingTimeout(args[0]) / 1000, true); ChatOutputHandler.chatError(sender, String.format(msg, timeout)); } return false; } return true; } @Override public String getHelp() { return "`checkTimeout <id> [error msg...]` \nCheck, if a timeout finished. Use \u0025s in error message to print the remaining time."; } }; public static final ScriptMethod startTimeout = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (!(sender instanceof EntityPlayer)) throw new MissingPlayerException(); if (args.length < 2) throw new SyntaxException(FEPermissions.MSG_NOT_ENOUGH_ARGUMENTS); PlayerInfo pi = PlayerInfo.get((EntityPlayer) sender); pi.startTimeout(args[0], Long.parseLong(args[1])); return true; } @Override public String getHelp() { return "`startTimeout <id> <t>` \nStart a timeout"; } }; public static final ScriptMethod timeout = new ScriptMethod() { @Override public boolean process(final ICommandSender sender, String[] args) { final String commandline = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " "); long timeout = Long.parseLong(args[0]); TaskRegistry.schedule(new Runnable() { @Override public void run() { TaskRegistry.runLater(new Runnable() { @Override public void run() { MinecraftServer.getServer().getCommandManager().executeCommand(sender, commandline); } }); } }, timeout); return true; } @Override public String getHelp() { return "`timeout <delay> <command...>` \nMake another command run after a delay (in ms). \nCan be used with pattern commands to make more complex timed scripts."; } }; public static final ScriptMethod random = new ScriptMethod() { @Override public boolean process(final ICommandSender sender, String[] args) { return ForgeEssentials.rnd.nextInt(100) < Integer.parseInt(args[0]); } @Override public String getHelp() { return "`random <success-chance-in-percent>` \nThis method will randomly success or fail. \nIf it fails, the rest of the script will not be executed any more."; } }; static { registerAll(); } }
src/main/java/com/forgeessentials/scripting/ScriptMethods.java
package com.forgeessentials.scripting; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.DimensionManager; import org.apache.commons.lang3.StringUtils; import com.forgeessentials.api.APIRegistry; import com.forgeessentials.api.UserIdent; import com.forgeessentials.api.economy.Wallet; import com.forgeessentials.api.permissions.FEPermissions; import com.forgeessentials.api.permissions.Zone; import com.forgeessentials.commons.selections.WarpPoint; import com.forgeessentials.core.ForgeEssentials; import com.forgeessentials.core.misc.TaskRegistry; import com.forgeessentials.core.misc.TeleportHelper; import com.forgeessentials.core.misc.Translator; import com.forgeessentials.permissions.commands.PermissionCommandParser; import com.forgeessentials.scripting.ScriptParser.MissingPermissionException; import com.forgeessentials.scripting.ScriptParser.MissingPlayerException; import com.forgeessentials.scripting.ScriptParser.ScriptException; import com.forgeessentials.scripting.ScriptParser.ScriptMethod; import com.forgeessentials.scripting.ScriptParser.SyntaxException; import com.forgeessentials.util.CommandParserArgs; import com.forgeessentials.util.PlayerInfo; import com.forgeessentials.util.output.ChatOutputHandler; import com.google.common.collect.ImmutableMap; public final class ScriptMethods { public static Map<String, ScriptMethod> scriptMethods = new HashMap<>(); public static void add(String name, ScriptMethod argument) { if (scriptMethods.containsKey(name)) throw new RuntimeException(String.format("Script method name @%s already registered", name)); scriptMethods.put(name, argument); } public static ScriptMethod get(String name) { return scriptMethods.get(name); } public static Map<String, ScriptMethod> getAll() { return ImmutableMap.copyOf(scriptMethods); } private static void registerAll() { try { for (Field field : ScriptMethods.class.getDeclaredFields()) if (ScriptMethod.class.isAssignableFrom(field.getType()) && Modifier.isStatic(field.getModifiers())) add(field.getName().toLowerCase(), (ScriptMethod) field.get(null)); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } public static final ScriptMethod echo = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.sendMessage(sender, ChatOutputHandler.formatColors(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send message without any special formatting to the player"; } }; public static final ScriptMethod confirm = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatConfirmation(sender, StringUtils.join(args, " ")); return true; } @Override public String getHelp() { return "Send confirmation message to the player"; } }; public static final ScriptMethod notify = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatNotification(sender, StringUtils.join(args, " ")); return true; } @Override public String getHelp() { return "Send notification message to the player"; } }; public static final ScriptMethod warn = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatWarning(sender, StringUtils.join(args, " ")); return true; } @Override public String getHelp() { return "Send warning message to the player"; } }; public static final ScriptMethod error = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatError(sender, StringUtils.join(args, " ")); return true; } @Override public String getHelp() { return "Send error message to the player"; } }; public static final ScriptMethod fail = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.chatError(sender, StringUtils.join(args, " ")); return false; } @Override public String getHelp() { return "Send error message to the player and fail script execution"; } }; public static final ScriptMethod echoall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.formatColors(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send message without any special formatting to all players"; } }; public static final ScriptMethod confirmall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.confirmation(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send confirmation message to all players"; } }; public static final ScriptMethod notifyall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.notification(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send notification message to all players"; } }; public static final ScriptMethod warnall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.warning(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send warning message to all players"; } }; public static final ScriptMethod errorall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.error(StringUtils.join(args, " "))); return true; } @Override public String getHelp() { return "Send error message to all players"; } }; public static final ScriptMethod failall = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { ChatOutputHandler.broadcast(ChatOutputHandler.error(StringUtils.join(args, " "))); return false; } @Override public String getHelp() { return "Send error message to all players and fail script execution"; } }; public static final ScriptMethod permset = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { CommandParserArgs arguments = new CommandParserArgs(null, args, MinecraftServer.getServer()); PermissionCommandParser.parseMain(arguments); return true; } @Override public String getHelp() { return "Modify permissions (like /p command)"; } }; protected static boolean getPermcheckResult(ICommandSender sender, String[] args) { if (!(sender instanceof EntityPlayerMP)) throw new MissingPlayerException(); if (args.length < 1) throw new SyntaxException("Missing argument for permchecksilent"); UserIdent ident = UserIdent.get((EntityPlayerMP) sender); String permission = args[0]; String value = args.length > 1 ? args[1] : Zone.PERMISSION_TRUE; boolean result; if (value.equals(Zone.PERMISSION_TRUE)) result = APIRegistry.perms.checkUserPermission(ident, permission); else if (value.equals(Zone.PERMISSION_FALSE)) result = !APIRegistry.perms.checkUserPermission(ident, permission); else result = APIRegistry.perms.getUserPermissionProperty(ident, permission).equals(value); return result; } public static final ScriptMethod permchecksilent = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { return getPermcheckResult(sender, args); } @Override public String getHelp() { return "`permchecksilent <perm> [value] [error message...]` \nPermission check (without error message). " + "Use `true` or `false` as value for normal permission checks (default value is `true`)." + "Other values will cause a permission-property check."; } }; public static final ScriptMethod permcheck = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (getPermcheckResult(sender, args)) return true; if (args.length > 2) throw new MissingPermissionException(args[0], StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " ")); else throw new MissingPermissionException(args[0]); } @Override public String getHelp() { return "`permcheck <perm> [value] [error message...]` \nPermission check (with error message). " + "Use `true` or `false` as value for normal permission checks (default value is `true`)." + "Other values will cause a permission-property check."; } }; public static final ScriptMethod teleport = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (args.length < 1) throw new SyntaxException("Missing player argument for teleport"); if (args.length < 2) throw new SyntaxException("Missing target argument for teleport"); UserIdent player = UserIdent.get(args[1], sender); if (!player.hasPlayer()) return false; if (args.length == 2) { UserIdent target = UserIdent.get(args[2], sender); if (!target.hasPlayer()) return false; TeleportHelper.teleport(player.getPlayerMP(), new WarpPoint(target.getPlayerMP())); } else if (args.length == 4) { int x = Integer.parseInt(args[1]); int y = Integer.parseInt(args[2]); int z = Integer.parseInt(args[3]); EntityPlayerMP p = player.getPlayerMP(); TeleportHelper.teleport(p, new WarpPoint(p.dimension, x, y, z, p.cameraPitch, p.cameraYaw)); } else if (args.length == 5) { int x = Integer.parseInt(args[1]); int y = Integer.parseInt(args[2]); int z = Integer.parseInt(args[3]); int dim = Integer.parseInt(args[4]); if (!DimensionManager.isDimensionRegistered(dim)) return false; EntityPlayerMP p = player.getPlayerMP(); TeleportHelper.teleport(p, new WarpPoint(dim, x, y, z, p.cameraPitch, p.cameraYaw)); } else throw new SyntaxException("Incorrect number of arguments"); return true; } @Override public String getHelp() { return "`teleport <player> <to-player>` \n`teleport <player> <x> <y> <z> [dim]`"; } }; public static final ScriptMethod pay = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (!(sender instanceof EntityPlayerMP)) throw new MissingPlayerException(); if (args.length < 1) throw new SyntaxException("Missing amount for pay command"); if (args.length > 2) throw new SyntaxException("Too many arguments"); long amount = Long.parseLong(args[0]); Wallet src = APIRegistry.economy.getWallet(UserIdent.get((EntityPlayerMP) sender)); Wallet dst = null; if (args.length == 2) { UserIdent dstIdent = UserIdent.get(args[1], sender); if (!dstIdent.hasUuid()) throw new ScriptException("Player %s not found", args[1]); dst = APIRegistry.economy.getWallet(dstIdent); } if (!src.withdraw(amount)) { ChatOutputHandler.chatError(sender, Translator.translate("You can't afford that!")); return false; } if (dst != null) dst.add(amount); return true; } @Override public String getHelp() { return "`pay <amount> [to-player]` \nMake the player pay some amount of money and fail, if he can't afford it"; } }; public static final ScriptMethod checkTimeout = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (!(sender instanceof EntityPlayer)) throw new MissingPlayerException(); if (args.length < 1) throw new SyntaxException(FEPermissions.MSG_NOT_ENOUGH_ARGUMENTS); PlayerInfo pi = PlayerInfo.get((EntityPlayer) sender); if (!pi.checkTimeout(args[0])) { if (args.length > 1) { String msg = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " "); String timeout = ChatOutputHandler.formatTimeDurationReadable(pi.getRemainingTimeout(args[0]) / 1000, true); ChatOutputHandler.chatError(sender, String.format(msg, timeout)); } return false; } return true; } @Override public String getHelp() { return "`checkTimeout <id> [error msg...]` \nCheck, if a timeout finished. Use \u0025s in error message to print the remaining time."; } }; public static final ScriptMethod startTimeout = new ScriptMethod() { @Override public boolean process(ICommandSender sender, String[] args) { if (!(sender instanceof EntityPlayer)) throw new MissingPlayerException(); if (args.length < 2) throw new SyntaxException(FEPermissions.MSG_NOT_ENOUGH_ARGUMENTS); PlayerInfo pi = PlayerInfo.get((EntityPlayer) sender); pi.startTimeout(args[0], Long.parseLong(args[1])); return true; } @Override public String getHelp() { return "`startTimeout <id> <t>` \nStart a timeout"; } }; public static final ScriptMethod timeout = new ScriptMethod() { @Override public boolean process(final ICommandSender sender, String[] args) { final String commandline = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " "); long timeout = Long.parseLong(args[0]); TaskRegistry.schedule(new Runnable() { @Override public void run() { TaskRegistry.runLater(new Runnable() { @Override public void run() { MinecraftServer.getServer().getCommandManager().executeCommand(sender, commandline); } }); } }, timeout); return true; } @Override public String getHelp() { return "`timeout <delay> <command...>` \nMake another command run after a delay (in ms). \nCan be used with pattern commands to make more complex timed scripts."; } }; public static final ScriptMethod random = new ScriptMethod() { @Override public boolean process(final ICommandSender sender, String[] args) { return ForgeEssentials.rnd.nextInt(100) < Integer.parseInt(args[0]); } @Override public String getHelp() { return "`random <success-chance-in-percent>` \nThis method will randomly success or fail. \nIf it fails, the rest of the script will not be executed any more."; } }; static { registerAll(); } }
Console should always get the nod for permchecks.
src/main/java/com/forgeessentials/scripting/ScriptMethods.java
Console should always get the nod for permchecks.
<ide><path>rc/main/java/com/forgeessentials/scripting/ScriptMethods.java <ide> protected static boolean getPermcheckResult(ICommandSender sender, String[] args) <ide> { <ide> if (!(sender instanceof EntityPlayerMP)) <del> throw new MissingPlayerException(); <add> if (sender instanceof MinecraftServer) <add> return true; <add> else throw new MissingPlayerException(); <ide> if (args.length < 1) <ide> throw new SyntaxException("Missing argument for permchecksilent"); <ide> UserIdent ident = UserIdent.get((EntityPlayerMP) sender);
Java
mit
5bb70f2ff8f77c95ebde1ed3f199a6149c881ced
0
ylgrgyq/batched-flume-appender
package com.ylgrgyq.clients.log4jappender; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.BinaryEncoder; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.EncoderFactory; import org.apache.avro.reflect.ReflectData; import org.apache.avro.reflect.ReflectDatumWriter; import org.apache.avro.specific.SpecificRecord; import org.apache.flume.Event; import org.apache.flume.EventDeliveryException; import org.apache.flume.FlumeException; import org.apache.flume.api.RpcClient; import org.apache.flume.api.RpcClientConfigurationConstants; import org.apache.flume.api.RpcClientFactory; import org.apache.flume.event.EventBuilder; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * Created on 15/11/2. * Author: ylgrgyq */ @SuppressWarnings("unused") public class Log4jAppender extends AppenderSkeleton { private String hostname; private int port; private boolean unsafeMode = false; private long timeout = RpcClientConfigurationConstants .DEFAULT_REQUEST_TIMEOUT_MILLIS; private boolean avroReflectionEnabled; private String avroSchemaUrl; private int batchSize; private BatchEvent batchEvent = new BatchEvent(); private long nextSend = 0; private long delayNanos; private int delayMillis; private int eventQueueSize = 10000; private BlockingQueue<Event> queue; private WorkerAppender worker = null; /** * If this constructor is used programmatically rather than from a log4j conf * you must set the <tt>port</tt> and <tt>hostname</tt> and then call * <tt>activateOptions()</tt> before calling <tt>append()</tt>. */ public Log4jAppender() { } /** * Sets the hostname and port. Even if these are passed the * <tt>activateOptions()</tt> function must be called before calling * <tt>append()</tt>, else <tt>append()</tt> will throw an Exception. * * @param hostname The first hop where the client should connect to. * @param port The port to connect on the host. */ public Log4jAppender(String hostname, int port) { this.hostname = hostname; this.port = port; } private class WorkerAppender implements Runnable { private RpcClient rpcClient; private volatile boolean workerContinue = true; public WorkerAppender(RpcClient rpcClient) { this.rpcClient = rpcClient; } private void sendBatchEvent() { LogLog.error("send with batch append. batchSize=" + batchEvent.getEvents().size()); try { rpcClient.appendBatch(batchEvent.getEvents()); } catch (EventDeliveryException e) { String msg = "Flume worker appender batch append() failed."; LogLog.error(msg, e); } } @Override public void run() { while (workerContinue) { try { Event flumeEvent = queue.take(); if (!rpcClient.isActive()) { reconnect(); } if (batchSize == 1) { try { rpcClient.append(flumeEvent); } catch (EventDeliveryException e) { String msg = "Flume worker appender append() failed."; LogLog.error(msg, e); } } else { batchEvent.addEvent(flumeEvent); final int eventCount = batchEvent.getEvents().size(); if (eventCount == 1) { nextSend = System.currentTimeMillis() + delayMillis; } else if (eventCount >= batchSize || System.currentTimeMillis() >= nextSend) { sendBatchEvent(); batchEvent = new BatchEvent(batchSize); } } } catch (InterruptedException e) { // ignore } catch (FlumeException e) { LogLog.error("Flume worker appender connection failed", e); } } } public void close(){ workerContinue = false; closeRpcClient(); } private synchronized void closeRpcClient(){ // Any append calls after this will result in an Exception. if (rpcClient != null) { try { rpcClient.close(); } catch (FlumeException ex) { LogLog.error("Error while trying to close RpcClient.", ex); if (unsafeMode) { return; } throw ex; } finally { rpcClient = null; } } else { String errorMsg = "Flume log4jappender already closed!"; LogLog.error(errorMsg); if (unsafeMode) { return; } throw new FlumeException(errorMsg); } } private synchronized void reconnect() throws FlumeException { closeRpcClient(); rpcClient = createRpcClient(); } } /** * Append the LoggingEvent, to send to the first Flume hop. * * @param event The LoggingEvent to be appended to the flume. * @throws FlumeException if the appender was closed, * or the hostname and port were not setup, there was a timeout, or there * was a connection error. */ @Override public synchronized void append(LoggingEvent event) throws FlumeException { //If worker is null, it means either this appender object was never //setup by setting hostname and port and then calling activateOptions //or this appender object was closed by calling close(), so we throw an //exception to show the appender is no longer accessible. if (worker == null){ String errorMsg = "Cannot Append to Appender! Appender either closed or" + " not setup correctly!"; LogLog.error(errorMsg); if (unsafeMode) { return; } throw new FlumeException(errorMsg); } //Client created first time append is called. Map<String, String> hdrs = new HashMap<String, String>(); hdrs.put(Log4jAvroHeaders.LOGGER_NAME.toString(), event.getLoggerName()); hdrs.put(Log4jAvroHeaders.TIMESTAMP.toString(), String.valueOf(event.timeStamp)); //To get the level back simply use //LoggerEvent.toLevel(hdrs.get(Integer.parseInt( //Log4jAvroHeaders.LOG_LEVEL.toString())) hdrs.put(Log4jAvroHeaders.LOG_LEVEL.toString(), String.valueOf(event.getLevel().toInt())); Event flumeEvent; Object message = event.getMessage(); if (message instanceof GenericRecord) { GenericRecord record = (GenericRecord) message; populateAvroHeaders(hdrs, record.getSchema(), message); flumeEvent = EventBuilder.withBody(serialize(record, record.getSchema()), hdrs); } else if (message instanceof SpecificRecord || avroReflectionEnabled) { Schema schema = ReflectData.get().getSchema(message.getClass()); populateAvroHeaders(hdrs, schema, message); flumeEvent = EventBuilder.withBody(serialize(message, schema), hdrs); } else { hdrs.put(Log4jAvroHeaders.MESSAGE_ENCODING.toString(), "UTF8"); String msg = layout != null ? layout.format(event) : message.toString(); flumeEvent = EventBuilder.withBody(msg, Charset.forName("UTF8"), hdrs); } while (! queue.offer(flumeEvent)) { LogLog.warn("Bached flume appender overflowed."); queue.poll(); } } private Schema schema; private ByteArrayOutputStream out; private DatumWriter<Object> writer; private BinaryEncoder encoder; protected void populateAvroHeaders(Map<String, String> hdrs, Schema schema, Object message) { if (avroSchemaUrl != null) { hdrs.put(Log4jAvroHeaders.AVRO_SCHEMA_URL.toString(), avroSchemaUrl); return; } LogLog.warn("Cannot find ID for schema. Adding header for schema, " + "which may be inefficient. Consider setting up an Avro Schema Cache."); hdrs.put(Log4jAvroHeaders.AVRO_SCHEMA_LITERAL.toString(), schema.toString()); } private byte[] serialize(Object datum, Schema datumSchema) throws FlumeException { if (schema == null || !datumSchema.equals(schema)) { schema = datumSchema; out = new ByteArrayOutputStream(); writer = new ReflectDatumWriter<Object>(schema); encoder = EncoderFactory.get().binaryEncoder(out, null); } out.reset(); try { writer.write(datum, encoder); encoder.flush(); return out.toByteArray(); } catch (IOException e) { throw new FlumeException(e); } } //This function should be synchronized to make sure one thread //does not close an appender another thread is using, and hence risking //a null pointer exception. /** * Closes underlying client. * If <tt>append()</tt> is called after this function is called, * it will throw an exception. * * @throws FlumeException if errors occur during close */ @Override public synchronized void close() throws FlumeException { if (worker != null){ try { worker.close(); } finally { worker = null; } } else { String errorMsg = "Flume log4jappender already closed!"; LogLog.error(errorMsg); if (unsafeMode) { return; } throw new FlumeException(errorMsg); } } @Override public boolean requiresLayout() { // This method is named quite incorrectly in the interface. It should // probably be called canUseLayout or something. According to the docs, // even if the appender can work without a layout, if it can work with one, // this method must return true. return true; } /** * Set the first flume hop hostname. * * @param hostname The first hop where the client should connect to. */ public void setHostname(String hostname) { this.hostname = hostname; } /** * Set the port on the hostname to connect to. * * @param port The port to connect on the host. */ public void setPort(int port) { this.port = port; } public void setUnsafeMode(boolean unsafeMode) { this.unsafeMode = unsafeMode; } public boolean getUnsafeMode() { return unsafeMode; } public void setTimeout(long timeout) { this.timeout = timeout; } public long getTimeout() { return this.timeout; } public void setAvroReflectionEnabled(boolean avroReflectionEnabled) { this.avroReflectionEnabled = avroReflectionEnabled; } public void setAvroSchemaUrl(String avroSchemaUrl) { this.avroSchemaUrl = avroSchemaUrl; } public int getBatchSize() { return batchSize; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public int getDelayMillis() { return delayMillis; } public void setDelayMillis(int delayMillis) { this.delayMillis = delayMillis; } public int getEventQueueSize() { return eventQueueSize; } public void setEventQueueSize(int eventQueueSize) { this.eventQueueSize = eventQueueSize; } /** * Activate the options set using <tt>setPort()</tt> * and <tt>setHostname()</tt> * * @throws FlumeException if the <tt>hostname</tt> and * <tt>port</tt> combination is invalid. */ @Override public synchronized void activateOptions() throws FlumeException { if (worker == null) { queue = new ArrayBlockingQueue<>(eventQueueSize); worker = new WorkerAppender(createRpcClient()); new Thread(worker).start(); } } private RpcClient createRpcClient() { Properties props = new Properties(); props.setProperty(RpcClientConfigurationConstants.CONFIG_HOSTS, "h1"); props.setProperty(RpcClientConfigurationConstants.CONFIG_HOSTS_PREFIX + "h1", hostname + ":" + port); props.setProperty(RpcClientConfigurationConstants.CONFIG_CONNECT_TIMEOUT, String.valueOf(timeout)); props.setProperty(RpcClientConfigurationConstants.CONFIG_REQUEST_TIMEOUT, String.valueOf(timeout)); RpcClient rpcClient; try { rpcClient = RpcClientFactory.getInstance(props); if (layout != null) { layout.activateOptions(); } } catch (FlumeException e) { String errormsg = "RPC client creation failed! " + e.getMessage(); LogLog.error(errormsg); if (unsafeMode) { return null; } throw e; } return rpcClient; } }
src/main/java/com/ylgrgyq/clients/log4jappender/Log4jAppender.java
package com.ylgrgyq.clients.log4jappender; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.BinaryEncoder; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.EncoderFactory; import org.apache.avro.reflect.ReflectData; import org.apache.avro.reflect.ReflectDatumWriter; import org.apache.avro.specific.SpecificRecord; import org.apache.flume.Event; import org.apache.flume.EventDeliveryException; import org.apache.flume.FlumeException; import org.apache.flume.api.RpcClient; import org.apache.flume.api.RpcClientConfigurationConstants; import org.apache.flume.api.RpcClientFactory; import org.apache.flume.event.EventBuilder; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * Created on 15/11/2. * Author: ylgrgyq */ @SuppressWarnings("unused") public class Log4jAppender extends AppenderSkeleton { private String hostname; private int port; private boolean unsafeMode = false; private long timeout = RpcClientConfigurationConstants .DEFAULT_REQUEST_TIMEOUT_MILLIS; private boolean avroReflectionEnabled; private String avroSchemaUrl; private int batchSize; private BatchEvent batchEvent = new BatchEvent(); private long nextSend = 0; private long delayNanos; private int delayMillis; private int eventQueueSize = 10000; private BlockingQueue<Event> queue = new ArrayBlockingQueue<>(eventQueueSize); private volatile WorkerAppender worker = null; /** * If this constructor is used programmatically rather than from a log4j conf * you must set the <tt>port</tt> and <tt>hostname</tt> and then call * <tt>activateOptions()</tt> before calling <tt>append()</tt>. */ public Log4jAppender() { } /** * Sets the hostname and port. Even if these are passed the * <tt>activateOptions()</tt> function must be called before calling * <tt>append()</tt>, else <tt>append()</tt> will throw an Exception. * * @param hostname The first hop where the client should connect to. * @param port The port to connect on the host. */ public Log4jAppender(String hostname, int port) { this.hostname = hostname; this.port = port; } private class WorkerAppender implements Runnable { private RpcClient rpcClient; private volatile boolean workerContinue = true; public WorkerAppender(RpcClient rpcClient) { this.rpcClient = rpcClient; } private void sendBatchEvent() { LogLog.error("send with batch append. batchSize=" + batchEvent.getEvents().size()); try { rpcClient.appendBatch(batchEvent.getEvents()); } catch (EventDeliveryException e) { String msg = "Flume worker appender batch append() failed."; LogLog.error(msg, e); } } @Override public void run() { while (workerContinue) { try { Event flumeEvent = queue.take(); if (!rpcClient.isActive()) { reconnect(); } if (batchSize == 1) { try { rpcClient.append(flumeEvent); } catch (EventDeliveryException e) { String msg = "Flume worker appender append() failed."; LogLog.error(msg, e); } } else { batchEvent.addEvent(flumeEvent); final int eventCount = batchEvent.getEvents().size(); if (eventCount == 1) { nextSend = System.currentTimeMillis() + delayMillis; } else if (eventCount >= batchSize || System.currentTimeMillis() >= nextSend) { sendBatchEvent(); batchEvent = new BatchEvent(batchSize); } } } catch (InterruptedException e) { // ignore } catch (FlumeException e) { LogLog.error("Flume worker appender connection failed", e); } } } public synchronized void close(){ workerContinue = false; closeRpcClient(); } private synchronized void closeRpcClient(){ // Any append calls after this will result in an Exception. if (rpcClient != null) { try { rpcClient.close(); } catch (FlumeException ex) { LogLog.error("Error while trying to close RpcClient.", ex); if (unsafeMode) { return; } throw ex; } finally { rpcClient = null; } } else { String errorMsg = "Flume log4jappender already closed!"; LogLog.error(errorMsg); if (unsafeMode) { return; } throw new FlumeException(errorMsg); } } private synchronized void reconnect() throws FlumeException { closeRpcClient(); rpcClient = createRpcClient(); } } /** * Append the LoggingEvent, to send to the first Flume hop. * * @param event The LoggingEvent to be appended to the flume. * @throws FlumeException if the appender was closed, * or the hostname and port were not setup, there was a timeout, or there * was a connection error. */ @Override public void append(LoggingEvent event) throws FlumeException { //If worker is null, it means either this appender object was never //setup by setting hostname and port and then calling activateOptions //or this appender object was closed by calling close(), so we throw an //exception to show the appender is no longer accessible. if (worker == null){ String errorMsg = "Cannot Append to Appender! Appender either closed or" + " not setup correctly!"; LogLog.error(errorMsg); if (unsafeMode) { return; } throw new FlumeException(errorMsg); } //Client created first time append is called. Map<String, String> hdrs = new HashMap<String, String>(); hdrs.put(Log4jAvroHeaders.LOGGER_NAME.toString(), event.getLoggerName()); hdrs.put(Log4jAvroHeaders.TIMESTAMP.toString(), String.valueOf(event.timeStamp)); //To get the level back simply use //LoggerEvent.toLevel(hdrs.get(Integer.parseInt( //Log4jAvroHeaders.LOG_LEVEL.toString())) hdrs.put(Log4jAvroHeaders.LOG_LEVEL.toString(), String.valueOf(event.getLevel().toInt())); Event flumeEvent; Object message = event.getMessage(); if (message instanceof GenericRecord) { GenericRecord record = (GenericRecord) message; populateAvroHeaders(hdrs, record.getSchema(), message); flumeEvent = EventBuilder.withBody(serialize(record, record.getSchema()), hdrs); } else if (message instanceof SpecificRecord || avroReflectionEnabled) { Schema schema = ReflectData.get().getSchema(message.getClass()); populateAvroHeaders(hdrs, schema, message); flumeEvent = EventBuilder.withBody(serialize(message, schema), hdrs); } else { hdrs.put(Log4jAvroHeaders.MESSAGE_ENCODING.toString(), "UTF8"); String msg = layout != null ? layout.format(event) : message.toString(); flumeEvent = EventBuilder.withBody(msg, Charset.forName("UTF8"), hdrs); } while (! queue.offer(flumeEvent)) { LogLog.warn("Bached flume appender overflowed."); queue.poll(); } } private Schema schema; private ByteArrayOutputStream out; private DatumWriter<Object> writer; private BinaryEncoder encoder; protected void populateAvroHeaders(Map<String, String> hdrs, Schema schema, Object message) { if (avroSchemaUrl != null) { hdrs.put(Log4jAvroHeaders.AVRO_SCHEMA_URL.toString(), avroSchemaUrl); return; } LogLog.warn("Cannot find ID for schema. Adding header for schema, " + "which may be inefficient. Consider setting up an Avro Schema Cache."); hdrs.put(Log4jAvroHeaders.AVRO_SCHEMA_LITERAL.toString(), schema.toString()); } private byte[] serialize(Object datum, Schema datumSchema) throws FlumeException { if (schema == null || !datumSchema.equals(schema)) { schema = datumSchema; out = new ByteArrayOutputStream(); writer = new ReflectDatumWriter<Object>(schema); encoder = EncoderFactory.get().binaryEncoder(out, null); } out.reset(); try { writer.write(datum, encoder); encoder.flush(); return out.toByteArray(); } catch (IOException e) { throw new FlumeException(e); } } //This function should be synchronized to make sure one thread //does not close an appender another thread is using, and hence risking //a null pointer exception. /** * Closes underlying client. * If <tt>append()</tt> is called after this function is called, * it will throw an exception. * * @throws FlumeException if errors occur during close */ @Override public synchronized void close() throws FlumeException { if (worker != null){ try { worker.close(); } finally { worker = null; } } else { String errorMsg = "Flume log4jappender already closed!"; LogLog.error(errorMsg); if (unsafeMode) { return; } throw new FlumeException(errorMsg); } } @Override public boolean requiresLayout() { // This method is named quite incorrectly in the interface. It should // probably be called canUseLayout or something. According to the docs, // even if the appender can work without a layout, if it can work with one, // this method must return true. return true; } /** * Set the first flume hop hostname. * * @param hostname The first hop where the client should connect to. */ public void setHostname(String hostname) { this.hostname = hostname; } /** * Set the port on the hostname to connect to. * * @param port The port to connect on the host. */ public void setPort(int port) { this.port = port; } public void setUnsafeMode(boolean unsafeMode) { this.unsafeMode = unsafeMode; } public boolean getUnsafeMode() { return unsafeMode; } public void setTimeout(long timeout) { this.timeout = timeout; } public long getTimeout() { return this.timeout; } public void setAvroReflectionEnabled(boolean avroReflectionEnabled) { this.avroReflectionEnabled = avroReflectionEnabled; } public void setAvroSchemaUrl(String avroSchemaUrl) { this.avroSchemaUrl = avroSchemaUrl; } public int getBatchSize() { return batchSize; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public int getDelayMillis() { return delayMillis; } public void setDelayMillis(int delayMillis) { this.delayMillis = delayMillis; } public int getEventQueueSize() { return eventQueueSize; } public void setEventQueueSize(int eventQueueSize) { this.eventQueueSize = eventQueueSize; } /** * Activate the options set using <tt>setPort()</tt> * and <tt>setHostname()</tt> * * @throws FlumeException if the <tt>hostname</tt> and * <tt>port</tt> combination is invalid. */ @Override public void activateOptions() throws FlumeException { if (worker == null) { worker = new WorkerAppender(createRpcClient()); new Thread(worker).start(); } } private RpcClient createRpcClient() { Properties props = new Properties(); props.setProperty(RpcClientConfigurationConstants.CONFIG_HOSTS, "h1"); props.setProperty(RpcClientConfigurationConstants.CONFIG_HOSTS_PREFIX + "h1", hostname + ":" + port); props.setProperty(RpcClientConfigurationConstants.CONFIG_CONNECT_TIMEOUT, String.valueOf(timeout)); props.setProperty(RpcClientConfigurationConstants.CONFIG_REQUEST_TIMEOUT, String.valueOf(timeout)); RpcClient rpcClient; try { rpcClient = RpcClientFactory.getInstance(props); if (layout != null) { layout.activateOptions(); } } catch (FlumeException e) { String errormsg = "RPC client creation failed! " + e.getMessage(); LogLog.error(errormsg); if (unsafeMode) { return null; } throw e; } return rpcClient; } }
(feature) init queue
src/main/java/com/ylgrgyq/clients/log4jappender/Log4jAppender.java
(feature) init queue
<ide><path>rc/main/java/com/ylgrgyq/clients/log4jappender/Log4jAppender.java <ide> private int delayMillis; <ide> <ide> private int eventQueueSize = 10000; <del> private BlockingQueue<Event> queue = new ArrayBlockingQueue<>(eventQueueSize); <del> <del> private volatile WorkerAppender worker = null; <add> private BlockingQueue<Event> queue; <add> <add> private WorkerAppender worker = null; <ide> <ide> /** <ide> * If this constructor is used programmatically rather than from a log4j conf <ide> } <ide> } <ide> <del> public synchronized void close(){ <add> public void close(){ <ide> workerContinue = false; <ide> <ide> closeRpcClient(); <ide> * was a connection error. <ide> */ <ide> @Override <del> public void append(LoggingEvent event) throws FlumeException { <add> public synchronized void append(LoggingEvent event) throws FlumeException { <ide> //If worker is null, it means either this appender object was never <ide> //setup by setting hostname and port and then calling activateOptions <ide> //or this appender object was closed by calling close(), so we throw an <ide> * <tt>port</tt> combination is invalid. <ide> */ <ide> @Override <del> public void activateOptions() throws FlumeException { <add> public synchronized void activateOptions() throws FlumeException { <ide> if (worker == null) { <add> queue = new ArrayBlockingQueue<>(eventQueueSize); <ide> worker = new WorkerAppender(createRpcClient()); <ide> new Thread(worker).start(); <ide> }
JavaScript
mit
e51f0d215ff311c2af1afc32ad83fc78f205f266
0
zinic/node-amqp,softek/node-amqp,hinson0/node-amqp,segmentio/node-amqp,segmentio/node-amqp,softek/node-amqp,seanahn/node-amqp,albert-lacki/node-amqp,zkochan/node-amqp,postwait/node-amqp,postwait/node-amqp,seanahn/node-amqp,hinson0/node-amqp,xebitstudios/node-amqp,zkochan/node-amqp,albert-lacki/node-amqp,remind101/node-amqp,zinic/node-amqp,albert-lacki/node-amqp,postwait/node-amqp,xebitstudios/node-amqp,xebitstudios/node-amqp,remind101/node-amqp,hinson0/node-amqp,zinic/node-amqp,remind101/node-amqp,zkochan/node-amqp
var events = require('events'), util = require('util'), net = require('net'), protocol, jspack = require('./jspack').jspack, Buffer = require('buffer').Buffer, Promise = require('./promise').Promise, URL = require('url'), AMQPTypes = require('./constants').AMQPTypes, Indicators = require('./constants').Indicators, FrameType = require('./constants').FrameType; function mixin () { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, source; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !(typeof target === 'function') ) target = {}; // mixin process itself if only one argument is passed if ( length == i ) { target = GLOBAL; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (source = arguments[i]) != null ) { // Extend the base object Object.getOwnPropertyNames(source).forEach(function(k){ var d = Object.getOwnPropertyDescriptor(source, k) || {value: source[k]}; if (d.get) { target.__defineGetter__(k, d.get); if (d.set) { target.__defineSetter__(k, d.set); } } else { // Prevent never-ending loop if (target === d.value) { return; } if (deep && d.value && typeof d.value === "object") { target[k] = mixin(deep, // Never move original objects, clone them source[k] || (d.value.length != null ? [] : {}) , d.value); } else { target[k] = d.value; } } }); } } // Return the modified object return target; } var debugLevel = process.env['NODE_DEBUG_AMQP'] ? 1 : 0; function debug (x) { if (debugLevel > 0) console.error(x + '\n'); } // a look up table for methods recieved // indexed on class id, method id var methodTable = {}; // methods keyed on their name var methods = {}; // classes keyed on their index var classes = {}; (function () { // anon scope for init //debug("initializing amqp methods..."); protocol = require('./amqp-definitions-0-9-1'); for (var i = 0; i < protocol.classes.length; i++) { var classInfo = protocol.classes[i]; classes[classInfo.index] = classInfo; for (var j = 0; j < classInfo.methods.length; j++) { var methodInfo = classInfo.methods[j]; var name = classInfo.name + methodInfo.name[0].toUpperCase() + methodInfo.name.slice(1); //debug(name); var method = { name: name , fields: methodInfo.fields , methodIndex: methodInfo.index , classIndex: classInfo.index }; if (!methodTable[classInfo.index]) methodTable[classInfo.index] = {}; methodTable[classInfo.index][methodInfo.index] = method; methods[name] = method; } } })(); // end anon scope // parser var maxFrameBuffer = 131072; // 128k, same as rabbitmq (which was // copying qpid) var emptyFrameSize = 8; // This is from the javaclient var maxFrameSize = maxFrameBuffer - emptyFrameSize; // An interruptible AMQP parser. // // type is either 'server' or 'client' // version is '0-9-1'. // // Instances of this class have several callbacks // - onMethod(channel, method, args); // - onHeartBeat() // - onContent(channel, buffer); // - onContentHeader(channel, class, weight, properties, size); // // This class does not subclass EventEmitter, in order to reduce the speed // of emitting the callbacks. Since this is an internal class, that should // be fine. function AMQPParser (version, type) { this.isClient = (type == 'client'); this.state = this.isClient ? 'frameHeader' : 'protocolHeader'; if (version != '0-9-1') this.throwError("Unsupported protocol version"); var frameHeader = new Buffer(7); frameHeader.used = 0; var frameBuffer, frameType, frameChannel; var self = this; function header(data) { var fh = frameHeader; var needed = fh.length - fh.used; data.copy(fh, fh.used, 0, data.length); fh.used += data.length; // sloppy if (fh.used >= fh.length) { fh.read = 0; frameType = fh[fh.read++]; frameChannel = parseInt(fh, 2); var frameSize = parseInt(fh, 4); fh.used = 0; // for reuse if (frameSize > maxFrameBuffer) { self.throwError("Oversized frame " + frameSize); } frameBuffer = new Buffer(frameSize); frameBuffer.used = 0; return frame(data.slice(needed)); } else { // need more! return header; } } function frame(data) { var fb = frameBuffer; var needed = fb.length - fb.used; data.copy(fb, fb.used, 0, data.length); fb.used += data.length; if (data.length > needed) { return frameEnd(data.slice(needed)); } else if (data.length == needed) { return frameEnd; } else { return frame; } } function frameEnd(data) { if (data.length > 0) { if (data[0] === Indicators.FRAME_END) { switch (frameType) { case FrameType.METHOD: self._parseMethodFrame(frameChannel, frameBuffer); break; case FrameType.HEADER: self._parseHeaderFrame(frameChannel, frameBuffer); break; case FrameType.BODY: if (self.onContent) { self.onContent(frameChannel, frameBuffer); } break; case FrameType.HEARTBEAT: debug("heartbeat"); if (self.onHeartBeat) self.onHeartBeat(); break; default: self.throwError("Unhandled frame type " + frameType); break; } return header(data.slice(1)); } else { self.throwError("Missing frame end marker"); } } else { return frameEnd; } } self.parse = header; } // If there's an error in the parser, call the onError handler or throw AMQPParser.prototype.throwError = function (error) { if(this.onError) this.onError(error); else throw new Error(error); }; // Everytime data is recieved on the socket, pass it to this function for // parsing. AMQPParser.prototype.execute = function (data) { // This function only deals with dismantling and buffering the frames. // It delegates to other functions for parsing the frame-body. debug('execute: ' + data.toString()); this.parse = this.parse(data); }; // parse Network Byte Order integers. size can be 1,2,4,8 function parseInt (buffer, size) { var int = 0; switch (size) { case 1: return buffer[buffer.read++]; case 2: return (buffer[buffer.read++] << 8) + buffer[buffer.read++]; case 4: return (buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) + (buffer[buffer.read++] << 8) + buffer[buffer.read++]; case 8: return (buffer[buffer.read++] << 56) + (buffer[buffer.read++] << 48) + (buffer[buffer.read++] << 40) + (buffer[buffer.read++] << 32) + (buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) + (buffer[buffer.read++] << 8) + buffer[buffer.read++]; default: throw new Error("cannot parse ints of that size"); } } function parseShortString (buffer) { var length = buffer[buffer.read++]; var s = buffer.toString('utf8', buffer.read, buffer.read+length); buffer.read += length; return s; } function parseLongString (buffer) { var length = parseInt(buffer, 4); var s = buffer.slice(buffer.read, buffer.read + length); buffer.read += length; return s.toString(); } function parseSignedInteger (buffer) { var int = parseInt(buffer, 4); if (int & 0x80000000) { int |= 0xEFFFFFFF; int = -int; } return int; } function parseValue (buffer) { switch (buffer[buffer.read++]) { case AMQPTypes.STRING: return parseLongString(buffer); case AMQPTypes.INTEGER: return parseInt(buffer, 4); case AMQPTypes.DECIMAL: var dec = parseInt(buffer, 1); var num = parseInt(buffer, 4); return num / (dec * 10); case AMQPTypes._64BIT_FLOAT: var b = []; for (var i = 0; i < 8; ++i) b[i] = buffer[buffer.read++]; return (new jspack(true)).Unpack('d', b); case AMQPTypes._32BIT_FLOAT: var b = []; for (var i = 0; i < 4; ++i) b[i] = buffer[buffer.read++]; return (new jspack(true)).Unpack('f', b); case AMQPTypes.TIME: var int = parseInt(buffer, 8); return (new Date()).setTime(int * 1000); case AMQPTypes.HASH: return parseTable(buffer); case AMQPTypes.SIGNED_64BIT: return parseInt(buffer, 8); case AMQPTypes.BOOLEAN: return (parseInt(buffer, 1) > 0); case AMQPTypes.BYTE_ARRAY: var len = parseInt(buffer, 4); var buf = new Buffer(len); buffer.copy(buf, 0, buffer.read, buffer.read + len); buffer.read += len; return buf; case AMQPTypes.ARRAY: var len = parseInt(buffer, 4); var end = buffer.read + len; var arr = new Array(); while (buffer.read < end) { arr.push(parseValue(buffer)); } return arr; default: throw new Error("Unknown field value type " + buffer[buffer.read-1]); } } function parseTable (buffer) { var length = buffer.read + parseInt(buffer, 4); var table = {}; while (buffer.read < length) { table[parseShortString(buffer)] = parseValue(buffer); } return table; } function parseFields (buffer, fields) { var args = {}; var bitIndex = 0; var value; for (var i = 0; i < fields.length; i++) { var field = fields[i]; //debug("parsing field " + field.name + " of type " + field.domain); switch (field.domain) { case 'bit': // 8 bits can be packed into one octet. // XXX check if bitIndex greater than 7? value = (buffer[buffer.read] & (1 << bitIndex)) ? true : false; if (fields[i+1] && fields[i+1].domain == 'bit') { bitIndex++; } else { bitIndex = 0; buffer.read++; } break; case 'octet': value = buffer[buffer.read++]; break; case 'short': value = parseInt(buffer, 2); break; case 'long': value = parseInt(buffer, 4); break; case 'timestamp': case 'longlong': value = parseInt(buffer, 8); break; case 'shortstr': value = parseShortString(buffer); break; case 'longstr': value = parseLongString(buffer); break; case 'table': value = parseTable(buffer); break; default: throw new Error("Unhandled parameter type " + field.domain); } //debug("got " + value); args[field.name] = value; } return args; } AMQPParser.prototype._parseMethodFrame = function (channel, buffer) { buffer.read = 0; var classId = parseInt(buffer, 2), methodId = parseInt(buffer, 2); // Make sure that this is a method that we understand. if (!methodTable[classId] || !methodTable[classId][methodId]) { this.throwError("Received unknown [classId, methodId] pair [" + classId + ", " + methodId + "]"); } var method = methodTable[classId][methodId]; if (!method) this.throwError("bad method?"); var args = parseFields(buffer, method.fields); if (this.onMethod) { this.onMethod(channel, method, args); } }; AMQPParser.prototype._parseHeaderFrame = function (channel, buffer) { buffer.read = 0; var classIndex = parseInt(buffer, 2); var weight = parseInt(buffer, 2); var size = parseInt(buffer, 8); var classInfo = classes[classIndex]; if (classInfo.fields.length > 15) { this.throwError("TODO: support more than 15 properties"); } var propertyFlags = parseInt(buffer, 2); var fields = []; for (var i = 0; i < classInfo.fields.length; i++) { var field = classInfo.fields[i]; // groan. if (propertyFlags & (1 << (15-i))) fields.push(field); } var properties = parseFields(buffer, fields); if (this.onContentHeader) { this.onContentHeader(channel, classInfo, weight, properties, size); } }; function serializeFloat(b, size, value, bigEndian) { var jp = new jspack(bigEndian); switch(size) { case 4: var x = jp.Pack('f', [value]); for (var i = 0; i < x.length; ++i) b[b.used++] = x[i]; break; case 8: var x = jp.Pack('d', [value]); for (var i = 0; i < x.length; ++i) b[b.used++] = x[i]; break; default: throw new Error("Unknown floating point size"); } } function serializeInt (b, size, int) { if (b.used + size > b.length) { throw new Error("write out of bounds"); } // Only 4 cases - just going to be explicit instead of looping. switch (size) { // octet case 1: b[b.used++] = int; break; // short case 2: b[b.used++] = (int & 0xFF00) >> 8; b[b.used++] = (int & 0x00FF) >> 0; break; // long case 4: b[b.used++] = (int & 0xFF000000) >> 24; b[b.used++] = (int & 0x00FF0000) >> 16; b[b.used++] = (int & 0x0000FF00) >> 8; b[b.used++] = (int & 0x000000FF) >> 0; break; // long long case 8: b[b.used++] = (int & 0xFF00000000000000) >> 56; b[b.used++] = (int & 0x00FF000000000000) >> 48; b[b.used++] = (int & 0x0000FF0000000000) >> 40; b[b.used++] = (int & 0x000000FF00000000) >> 32; b[b.used++] = (int & 0x00000000FF000000) >> 24; b[b.used++] = (int & 0x0000000000FF0000) >> 16; b[b.used++] = (int & 0x000000000000FF00) >> 8; b[b.used++] = (int & 0x00000000000000FF) >> 0; break; default: throw new Error("Bad size"); } } function serializeShortString (b, string) { if (typeof(string) != "string") { throw new Error("param must be a string"); } var byteLength = Buffer.byteLength(string, 'utf8'); if (byteLength > 0xFF) { throw new Error("String too long for 'shortstr' parameter"); } if (1 + byteLength + b.used >= b.length) { throw new Error("Not enough space in buffer for 'shortstr'"); } b[b.used++] = byteLength; b.write(string, b.used, 'utf8'); b.used += byteLength; } function serializeLongString (b, string) { // we accept string, object, or buffer for this parameter. // in the case of string we serialize it to utf8. if (typeof(string) == 'string') { var byteLength = Buffer.byteLength(string, 'utf8'); serializeInt(b, 4, byteLength); b.write(string, b.used, 'utf8'); b.used += byteLength; } else if (typeof(string) == 'object') { serializeTable(b, string); } else { // data is Buffer var byteLength = string.length; serializeInt(b, 4, byteLength); b.write(string, b.used); // memcpy b.used += byteLength; } } function serializeDate(b, date) { serializeInt(b, 8, date.valueOf() / 1000); } function serializeBuffer(b, buffer) { serializeInt(b, 4, buffer.length); buffer.copy(b, b.used, 0); b.used += buffer.length; } function serializeBase64(b, buffer) { serializeLongString(b, buffer.toString('base64')); } function isBigInt(value) { return value > 0xffffffff; } function getCode(dec) { var hexArray = "0123456789ABCDEF".split(''); var code1 = Math.floor(dec / 16); var code2 = dec - code1 * 16; return hexArray[code2]; } function isFloat(value) { return value === +value && value !== (value|0); } function serializeValue (b, value) { switch (typeof(value)) { case 'string': b[b.used++] = 'S'.charCodeAt(0); serializeLongString(b, value); break; case 'number': if (!isFloat(value)) { if (isBigInt(value)) { // 64-bit uint b[b.used++] = 'l'.charCodeAt(0); serializeInt(b, 8, value); } else { //32-bit uint b[b.used++] = 'I'.charCodeAt(0); serializeInt(b, 4, value); } } else { //64-bit float b[b.used++] = 'd'.charCodeAt(0); serializeFloat(b, 8, value); } break; case 'boolean': b[b.used++] = 't'.charCodeAt(0); b[b.used++] = value; break; default: if (value instanceof Date) { b[b.used++] = 'T'.charCodeAt(0); serializeDate(b, value); } else if (value instanceof Buffer) { b[b.used++] = 'x'.charCodeAt(0); serializeBuffer(b, value); } else if (util.isArray(value)) { b[b.used++] = 'A'.charCodeAt(0); serializeArray(b, value); } else if (typeof(value) === 'object') { b[b.used++] = 'F'.charCodeAt(0); serializeTable(b, value); } else { this.throwError("unsupported type in amqp table: " + typeof(value)); } } } function serializeTable (b, object) { if (typeof(object) != "object") { throw new Error("param must be an object"); } // Save our position so that we can go back and write the length of this table // at the beginning of the packet (once we know how many entries there are). var lengthIndex = b.used; b.used += 4; // sizeof long var startIndex = b.used; for (var key in object) { if (!object.hasOwnProperty(key)) continue; serializeShortString(b, key); serializeValue(b, object[key]); } var endIndex = b.used; b.used = lengthIndex; serializeInt(b, 4, endIndex - startIndex); b.used = endIndex; } function serializeArray (b, arr) { // Save our position so that we can go back and write the byte length of this array // at the beginning of the packet (once we have serialized all elements). var lengthIndex = b.used; b.used += 4; // sizeof long var startIndex = b.used; len = arr.length; for (var i = 0; i < len; i++) { serializeValue(b, arr[i]); } var endIndex = b.used; b.used = lengthIndex; serializeInt(b, 4, endIndex - startIndex); b.used = endIndex; } function serializeFields (buffer, fields, args, strict) { var bitField = 0; var bitIndex = 0; for (var i = 0; i < fields.length; i++) { var field = fields[i]; var domain = field.domain; if (!(field.name in args)) { if (strict) { throw new Error("Missing field '" + field.name + "' of type '" + domain + "' while executing AMQP method '" + arguments.callee.caller.arguments[1].name + "'"); } continue; } var param = args[field.name]; //debug("domain: " + domain + " param: " + param); switch (domain) { case 'bit': if (typeof(param) != "boolean") { throw new Error("Unmatched field " + JSON.stringify(field)); } if (param) bitField |= (1 << bitIndex); bitIndex++; if (!fields[i+1] || fields[i+1].domain != 'bit') { debug('SET bit field ' + field.name + ' 0x' + bitField.toString(16)); buffer[buffer.used++] = bitField; bitField = 0; bitIndex = 0; } break; case 'octet': if (typeof(param) != "number" || param > 0xFF) { throw new Error("Unmatched field " + JSON.stringify(field)); } buffer[buffer.used++] = param; break; case 'short': if (typeof(param) != "number" || param > 0xFFFF) { throw new Error("Unmatched field " + JSON.stringify(field)); } serializeInt(buffer, 2, param); break; case 'long': if (typeof(param) != "number" || param > 0xFFFFFFFF) { throw new Error("Unmatched field " + JSON.stringify(field)); } serializeInt(buffer, 4, param); break; case 'timestamp': case 'longlong': serializeInt(buffer, 8, param); break; case 'shortstr': if (typeof(param) != "string" || param.length > 0xFF) { throw new Error("Unmatched field " + JSON.stringify(field)); } serializeShortString(buffer, param); break; case 'longstr': serializeLongString(buffer, param); break; case 'table': if (typeof(param) != "object") { throw new Error("Unmatched field " + JSON.stringify(field)); } serializeTable(buffer, param); break; default: throw new Error("Unknown domain value type " + domain); } } } function Connection (connectionArgs, options, readyCallback) { net.Stream.call(this); var self = this; this.setOptions(connectionArgs); this.setImplOptions(options); if (typeof readyCallback === 'function') { this._readyCallback = readyCallback; } var parser; var backoffTime = null; this.connectionAttemptScheduled = false; var backoff = function () { if (self._inboundHeartbeatTimer !== null) { clearTimeout(self._inboundHeartbeatTimer); self._inboundHeartbeatTimer = null; } if (self._outboundHeartbeatTimer !== null) { clearTimeout(self._outboundHeartbeatTimer); self._outboundHeartbeatTimer = null; } if (!self.connectionAttemptScheduled) { // Set to true, as we are presently in the process of scheduling one. self.connectionAttemptScheduled = true; // Kill the socket, if it hasn't been killed already. self.end(); // Reset parser state parser = null; // In order for our reconnection to be seamless, we have to notify the // channels that they are no longer connected so that nobody attempts // to send messages which would be doomed to fail. for (var channel in self.channels) { if (channel != 0) { self.channels[channel].state = 'closed'; } } // Queues are channels (so we have already marked them as closed), but // queues have special needs, since the subscriptions will no longer // be known to the server when we reconnect. Mark the subscriptions as // closed so that we can resubscribe them once we are reconnected. for (var queue in self.queues) { for (var index in self.queues[queue].consumerTagOptions) { self.queues[queue].consumerTagOptions[index]['state'] = 'closed'; } } // Begin reconnection attempts if (self.implOptions.reconnect) { // Don't thrash, use a backoff strategy. if (backoffTime === null) { // This is the first time we've failed since a successful connection, // so use the configured backoff time without any modification. backoffTime = self.implOptions.reconnectBackoffTime; } else if (self.implOptions.reconnectBackoffStrategy === 'exponential') { // If you've configured exponential backoff, we'll double the // backoff time each subsequent attempt until success. backoffTime *= 2; // limit the maxium timeout, to avoid potentially unlimited stalls if(backoffTime > self.implOptions.reconnectExponentialLimit){ backoffTime = self.implOptions.reconnectExponentialLimit; } } else if (self.implOptions.reconnectBackoffStrategy === 'linear') { // Linear strategy is the default. In this case, we will retry at a // constant interval, so there's no need to change the backoff time // between attempts. } else { // TODO should we warn people if they picked a nonexistent strategy? } setTimeout(function () { // Set to false, so that if we fail in the reconnect attempt, we can // schedule another one. self.connectionAttemptScheduled = false; self.reconnect(); }, backoffTime); } } }; this._defaultExchange = null; this.channelCounter = 0; this._sendBuffer = new Buffer(maxFrameBuffer); self.addListener('connect', function () { // In the case where this is a reconnection, do not trample on the existing // channels. // For your reference, channel 0 is the control channel. self.channels = (self.implOptions.reconnect ? self.channels : undefined) || {0:self}; self.queues = (self.implOptions.reconnect ? self.queues : undefined) || {}; self.exchanges = (self.implOptions.reconnect ? self.exchanges : undefined) || {}; parser = new AMQPParser('0-9-1', 'client'); parser.onMethod = function (channel, method, args) { self._onMethod(channel, method, args); }; parser.onContent = function (channel, data) { debug(channel + " > content " + data.length); if (self.channels[channel] && self.channels[channel]._onContent) { self.channels[channel]._onContent(channel, data); } else { debug("unhandled content: " + data); } }; parser.onContentHeader = function (channel, classInfo, weight, properties, size) { debug(channel + " > content header " + JSON.stringify([classInfo.name, weight, properties, size])); if (self.channels[channel] && self.channels[channel]._onContentHeader) { self.channels[channel]._onContentHeader(channel, classInfo, weight, properties, size); } else { debug("unhandled content header"); } }; parser.onHeartBeat = function () { self.emit("heartbeat"); debug("heartbeat"); }; parser.onError = function (e) { self.emit("error", e); self.emit("close"); }; //debug("connected..."); // Time to start the AMQP 7-way connection initialization handshake! // 1. The client sends the server a version string self.write("AMQP" + String.fromCharCode(0,0,9,1)); }); self.addListener('data', function (data) { if(parser != null){ parser.execute(data); } self._inboundHeartbeatTimerReset(); }); self.addListener('error', function () { backoff(); }); self.addListener('ready', function () { // Reset the backoff time since we have successfully connected. backoffTime = null; if (self.implOptions.reconnect) { // Reconnect any channels which were open. for (var channel in self.channels) { if (channel != 0) { self.channels[channel].reconnect(); } } } // Restart the heartbeat to the server self._outboundHeartbeatTimerReset(); }) } util.inherits(Connection, net.Stream); exports.Connection = Connection; var defaultPorts = { 'amqp': 5672, 'amqps': 5671 }; var defaultOptions = { host: 'localhost' , port: defaultPorts['amqp'] , login: 'guest' , password: 'guest' , vhost: '/' }; // If the "reconnect" option is true, then the driver will attempt to // reconnect using the configured strategy *any time* the connection // becomes unavailable. // If this is not appropriate for your application, do not set this option. // If you would like this option, you can set parameters controlling how // aggressively the reconnections will be attempted. // Valid strategies are "linear" and "exponential". // Backoff times are in milliseconds. Under the "linear" strategy, the driver // will pause <reconnectBackoffTime> ms before the first attempt, and between // each subsequent attempt. Under the "exponential" strategy, the driver will // pause <reconnectBackoffTime> ms before the first attempt, and will double // the previous pause between each subsequent attempt until a connection is // reestablished. var defaultImplOptions = { defaultExchangeName: '', reconnect: true , reconnectBackoffStrategy: 'linear' , reconnectExponentialLimit: 120000, reconnectBackoffTime: 1000 }; function urlOptions(connectionString) { var opts = {}; var url = URL.parse(connectionString); var scheme = url.protocol.substring(0, url.protocol.lastIndexOf(':')); if (scheme != 'amqp' && scheme != 'amqps') { throw new Error('Connection URI must use amqp or amqps scheme. ' + 'For example, "amqp://bus.megacorp.internal:5766".'); } opts.ssl = ('amqps' === scheme); opts.host = url.hostname; opts.port = url.port || defaultPorts[scheme] if (url.auth) { var auth = url.auth.split(':'); auth[0] && (opts.login = auth[0]); auth[1] && (opts.password = auth[1]); } if (url.pathname) { opts.vhost = unescape(url.pathname.substr(1)); } return opts; } exports.createConnection = function (connectionArgs, options, readyCallback) { var c = new Connection(connectionArgs, options, readyCallback); // c.setOptions(connectionArgs); // c.setImplOptions(options); c.connect(); return c; }; Connection.prototype.setOptions = function (options) { var o = {}; var urlo = (options && options.url) ? urlOptions(options.url) : {}; mixin(o, defaultOptions, urlo, options || {}); this.options = o; }; Connection.prototype.setImplOptions = function (options) { var o = {} mixin(o, defaultImplOptions, options || {}); this.implOptions = o; }; Connection.prototype.reconnect = function () { // Suspend activity on channels for (var channel in this.channels) { this.channels[channel].state = 'closed'; } // Terminate socket activity this.end(); this.connect(); }; Connection.prototype.connect = function () { // If you pass a array of hosts, lets choose a random host, or then next one. var connectToHost = this.options.host; if(Array.isArray(this.options.host) == true){ if(this.hosti == null){ this.hosti = Math.random()*this.options.host.length >> 0; }else{ this.hosti = (this.hosti+1) % this.options.host.length; } connectToHost = this.options.host[this.hosti] } // Connect socket net.Socket.prototype.connect.call(this, this.options.port, connectToHost); }; Connection.prototype._onMethod = function (channel, method, args) { debug(channel + " > " + method.name + " " + JSON.stringify(args)); // Channel 0 is the control channel. If not zero then delegate to // one of the channel objects. if (channel > 0) { if (!this.channels[channel]) { debug("Received message on untracked channel."); return; } if (!this.channels[channel]._onChannelMethod) { throw new Error('Channel ' + channel + ' has no _onChannelMethod method.'); } this.channels[channel]._onChannelMethod(channel, method, args); return; } // channel 0 switch (method) { // 2. The server responds, after the version string, with the // 'connectionStart' method (contains various useless information) case methods.connectionStart: // We check that they're serving us AMQP 0-9 if (args.versionMajor != 0 && args.versionMinor != 9) { this.end(); this.emit('error', new Error("Bad server version")); return; } this.serverProperties = args.serverProperties; // 3. Then we reply with StartOk, containing our useless information. this._sendMethod(0, methods.connectionStartOk, { clientProperties: { version: '0.0.1' , platform: 'node-' + process.version , product: 'node-amqp' } , mechanism: 'AMQPLAIN' , response: { LOGIN: this.options.login , PASSWORD: this.options.password } , locale: 'en_US' }); break; // 4. The server responds with a connectionTune request case methods.connectionTune: // 5. We respond with connectionTuneOk this._sendMethod(0, methods.connectionTuneOk, { channelMax: 0 , frameMax: maxFrameBuffer , heartbeat: this.options.heartbeat || 0 }); // 6. Then we have to send a connectionOpen request this._sendMethod(0, methods.connectionOpen, { virtualHost: this.options.vhost // , capabilities: '' // , insist: true , reserved1: '' , reserved2: true }); break; case methods.connectionOpenOk: // 7. Finally they respond with connectionOpenOk // Whew! That's why they call it the Advanced MQP. if (this._readyCallback) { this._readyCallback(this); this._readyCallback = null; } this.emit('ready'); break; case methods.connectionClose: var e = new Error(args.replyText); e.code = args.replyCode; if (!this.listeners('close').length) { console.log('Unhandled connection error: ' + args.replyText); } this.destroy(e); break; default: throw new Error("Uncaught method '" + method.name + "' with args " + JSON.stringify(args)); } }; Connection.prototype.heartbeat = function () { this.write(new Buffer([8,0,0,0,0,0,0,206])); }; Connection.prototype._outboundHeartbeatTimerReset = function () { if (this._outboundHeartbeatTimer !== null) { clearTimeout(this._outboundHeartbeatTimer); this._outboundHeartbeatTimer = null; } if (this.options.heartbeat) { var self = this; this._outboundHeartbeatTimer = setTimeout(function () { self.heartbeat(); self._outboundHeartbeatTimerReset(); }, 1000 * this.options.heartbeat); } }; Connection.prototype._inboundHeartbeatTimerReset = function () { if (this._inboundHeartbeatTimer !== null) { clearTimeout(this._inboundHeartbeatTimer); this._inboundHeartbeatTimer = null; } if (this.options.heartbeat) { var self = this; var gracePeriod = 2 * this.options.heartbeat; this._inboundHeartbeatTimer = setTimeout(function () { self.emit('error', new Error('no heartbeat or data in last ' + gracePeriod + ' seconds')); }, gracePeriod * 1000); } }; Connection.prototype._sendMethod = function (channel, method, args) { debug(channel + " < " + method.name + " " + JSON.stringify(args)); var b = this._sendBuffer; b.used = 0; b[b.used++] = 1; // constants.frameMethod serializeInt(b, 2, channel); var lengthIndex = b.used; serializeInt(b, 4, 42); // replace with actual length. var startIndex = b.used; serializeInt(b, 2, method.classIndex); // short, classId serializeInt(b, 2, method.methodIndex); // short, methodId serializeFields(b, method.fields, args, true); var endIndex = b.used; // write in the frame length now that we know it. b.used = lengthIndex; serializeInt(b, 4, endIndex - startIndex); b.used = endIndex; b[b.used++] = 206; // constants.frameEnd; var c = b.slice(0, b.used); //debug("sending frame: " + c); this.write(c); this._outboundHeartbeatTimerReset(); }; // connection: the connection // channel: the channel to send this on // size: size in bytes of the following message // properties: an object containing any of the following: // - contentType (default 'application/octet-stream') // - contentEncoding // - headers // - deliveryMode // - priority (0-9) // - correlationId // - replyTo // - experation // - messageId // - timestamp // - userId // - appId // - clusterId function sendHeader (connection, channel, size, properties) { var b = new Buffer(maxFrameBuffer); // FIXME allocating too much. // use freelist? b.used = 0; var classInfo = classes[60]; // always basic class. // 7 OCTET FRAME HEADER b[b.used++] = 2; // constants.frameHeader serializeInt(b, 2, channel); var lengthStart = b.used; serializeInt(b, 4, 0 /*dummy*/); // length var bodyStart = b.used; // HEADER'S BODY serializeInt(b, 2, classInfo.index); // class 60 for Basic serializeInt(b, 2, 0); // weight, always 0 for rabbitmq serializeInt(b, 8, size); // byte size of body // properties - first propertyFlags var props = {'contentType': 'application/octet-stream'}; mixin(props, properties); var propertyFlags = 0; for (var i = 0; i < classInfo.fields.length; i++) { if (props[classInfo.fields[i].name]) propertyFlags |= 1 << (15-i); } serializeInt(b, 2, propertyFlags); // now the actual properties. serializeFields(b, classInfo.fields, props, false); //serializeTable(b, props); var bodyEnd = b.used; // Go back to the header and write in the length now that we know it. b.used = lengthStart; serializeInt(b, 4, bodyEnd - bodyStart); b.used = bodyEnd; // 1 OCTET END b[b.used++] = 206; // constants.frameEnd; var s = b.slice(0, b.used); //debug('header sent: ' + JSON.stringify(s)); connection.write(s); } Connection.prototype._sendBody = function (channel, body, properties) { // Handles 3 cases // - body is utf8 string // - body is instance of Buffer // - body is an object and its JSON representation is sent // Does not handle the case for streaming bodies. // In order to support long frame types we switch our strings into buffers for proper handling if (typeof(body) == 'string') { body = new Buffer(body, 'utf8'); } if (typeof(body) == 'object' && !(body instanceof Buffer)){ properties = mixin({contentType: 'application/json' }, properties); body = new Buffer(JSON.stringify(body), 'utf8'); } if (body instanceof Buffer) { sendHeader(this, channel, body.length, properties); debug('body sent: ' + JSON.stringify(b)); for (var offset = 0; offset < body.length; offset += maxFrameSize){ var remaining = body.length - offset; var fragmentLength = (remaining < maxFrameSize) ? remaining : maxFrameSize; // debug("sending " + offset + " through " + (offset+fragmentLength) + " of " + body.length) var b = new Buffer(7); b.used = 0; b[b.used++] = 3; // constants.frameBody serializeInt(b, 2, channel); serializeInt(b, 4, fragmentLength); this.write(b); this.write(body.slice(offset,offset+fragmentLength)); this.write(new Buffer([206])); // frameEnd } return true; }else{ debug('invalid body sent to _sendBody'); return false; } }; // Options // - passive (boolean) // - durable (boolean) // - exclusive (boolean) // - autoDelete (boolean, default true) Connection.prototype.queue = function (name /* options, openCallback */) { var options, callback; if (typeof arguments[1] == 'object') { options = arguments[1]; callback = arguments[2]; } else { callback = arguments[1]; } this.channelCounter++; var channel = this.channelCounter; var q = new Queue(this, channel, name, options, callback); this.channels[channel] = q; return q; }; // remove a queue when it's closed (called from Queue) Connection.prototype.queueClosed = function (name) { if (this.queues[name]) delete this.queues[name]; }; // remove an exchange when it's closed (called from Exchange) Connection.prototype.exchangeClosed = function (name) { if (this.exchanges[name]) delete this.exchanges[name]; }; // connection.exchange('my-exchange', { type: 'topic' }); // Options // - type 'fanout', 'direct', or 'topic' (default) // - passive (boolean) // - durable (boolean) // - autoDelete (boolean, default true) Connection.prototype.exchange = function (name, options, openCallback) { if (name === undefined) name = this.implOptions.defaultExchangeName; if (!options) options = {}; if (name != '' && options.type === undefined) options.type = 'topic'; this.channelCounter++; var channel = this.channelCounter; var exchange = new Exchange(this, channel, name, options, openCallback); this.channels[channel] = exchange; this.exchanges[name] = exchange; return exchange; }; // Publishes a message to the default exchange. Connection.prototype.publish = function (routingKey, body, options, callback) { if (!this._defaultExchange) this._defaultExchange = this.exchange(); return this._defaultExchange.publish(routingKey, body, options, callback); }; // Properties: // - routingKey // - size // - deliveryTag // // - contentType (default 'application/octet-stream') // - contentEncoding // - headers // - deliveryMode // - priority (0-9) // - correlationId // - replyTo // - experation // - messageId // - timestamp // - userId // - appId // - clusterId function Message (queue, args) { var msgProperties = classes[60].fields; events.EventEmitter.call(this); this.queue = queue; this.deliveryTag = args.deliveryTag; this.redelivered = args.redelivered; this.exchange = args.exchange; this.routingKey = args.routingKey; this.consumerTag = args.consumerTag; for (var i=0, l=msgProperties.length; i<l; i++) { if (args[msgProperties[i].name]) { this[msgProperties[i].name] = args[msgProperties[i].name]; } } } util.inherits(Message, events.EventEmitter); // Acknowledge receipt of message. // Set first arg to 'true' to acknowledge this and all previous messages // received on this queue. Message.prototype.acknowledge = function (all) { this.queue.connection._sendMethod(this.queue.channel, methods.basicAck, { reserved1: 0 , deliveryTag: this.deliveryTag , multiple: all ? true : false }); }; // Reject an incoming message. // Set first arg to 'true' to requeue the message. Message.prototype.reject = function (requeue){ this.queue.connection._sendMethod(this.queue.channel, methods.basicReject, { deliveryTag: this.deliveryTag , requeue: requeue ? true : false }); } // This class is not exposed to the user. Queue and Exchange are subclasses // of Channel. This just provides a task queue. function Channel (connection, channel) { events.EventEmitter.call(this); this.channel = channel; this.connection = connection; this._tasks = []; this.reconnect(); } util.inherits(Channel, events.EventEmitter); Channel.prototype.reconnect = function () { this.connection._sendMethod(this.channel, methods.channelOpen, {reserved1: ""}); }; Channel.prototype._taskPush = function (reply, cb) { var promise = new Promise(); this._tasks.push({ promise: promise , reply: reply , sent: false , cb: cb }); this._tasksFlush(); return promise; }; Channel.prototype._tasksFlush = function () { if (this.state != 'open') return; for (var i = 0; i < this._tasks.length; i++) { var task = this._tasks[i]; if (task.sent) continue; task.cb(); task.sent = true; if (!task.reply) { // if we don't expect a reply, just delete it now this._tasks.splice(i, 1); i = i-1; } } }; Channel.prototype._handleTaskReply = function (channel, method, args) { var task, i; for (i = 0; i < this._tasks.length; i++) { if (this._tasks[i].reply == method) { task = this._tasks[i]; this._tasks.splice(i, 1); task.promise.emitSuccess(args); this._tasksFlush(); return true; } } return false; }; Channel.prototype._onChannelMethod = function(channel, method, args) { switch (method) { case methods.channelCloseOk: delete this.connection.channels[this.channel] this.state = 'closed' default: this._onMethod(channel, method, args); } } Channel.prototype.close = function() { this.state = 'closing'; this.connection._sendMethod(this.channel, methods.channelClose, {'replyText': 'Goodbye from node', 'replyCode': 200, 'classId': 0, 'methodId': 0}); } function Queue (connection, channel, name, options, callback) { Channel.call(this, connection, channel); this.name = name; this.consumerTagListeners = {}; this.consumerTagOptions = {}; var self = this; // route messages to subscribers based on consumerTag this.on('rawMessage', function(message) { if (message.consumerTag && self.consumerTagListeners[message.consumerTag]) { self.consumerTagListeners[message.consumerTag](message); } }); this.options = { autoDelete: true, closeChannelOnUnsubscribe: false }; if (options) mixin(this.options, options); this._openCallback = callback; } util.inherits(Queue, Channel); Queue.prototype.subscribeRaw = function (/* options, messageListener */) { var self = this; var messageListener = arguments[arguments.length-1]; var consumerTag = 'node-amqp-'+process.pid+'-'+Math.random(); this.consumerTagListeners[consumerTag] = messageListener; var options = { }; if (typeof arguments[0] == 'object') { mixin(options, arguments[0]); } options['state'] = 'opening'; this.consumerTagOptions[consumerTag] = options; if (options.prefetchCount) { self.connection._sendMethod(self.channel, methods.basicQos, { reserved1: 0 , prefetchSize: 0 , prefetchCount: options.prefetchCount , global: false }); } return this._taskPush(methods.basicConsumeOk, function () { self.connection._sendMethod(self.channel, methods.basicConsume, { reserved1: 0 , queue: self.name , consumerTag: consumerTag , noLocal: options.noLocal ? true : false , noAck: options.noAck ? true : false , exclusive: options.exclusive ? true : false , noWait: false , "arguments": {} }); self.consumerTagOptions[consumerTag]['state'] = 'open'; }); }; Queue.prototype.unsubscribe = function(consumerTag) { var self = this; return this._taskPush(methods.basicCancelOk, function () { self.connection._sendMethod(self.channel, methods.basicCancel, { reserved1: 0, consumerTag: consumerTag, noWait: false }); }) .addCallback(function () { if(self.options.closeChannelOnUnsubscribe){ self.close(); } delete self.consumerTagListeners[consumerTag]; delete self.consumerTagOptions[consumerTag]; }); }; Queue.prototype.subscribe = function (/* options, messageListener */) { var self = this; var messageListener = arguments[arguments.length-1]; if(typeof(messageListener) !== "function") messageListener = null; var options = { ack: false, prefetchCount: 1, routingKeyInPayload: self.connection.options.routingKeyInPayload, deliveryTagInPayload: self.connection.options.deliveryTagInPayload }; if (typeof arguments[0] == 'object') { if (arguments[0].ack) options.ack = true; if (arguments[0].routingKeyInPayload) options.routingKeyInPayload = arguments[0].routingKeyInPayload; if (arguments[0].deliveryTagInPayload) options.deliveryTagInPayload = arguments[0].deliveryTagInPayload; if (arguments[0].prefetchCount != undefined) options.prefetchCount = arguments[0].prefetchCount; if (arguments[0].exclusive) options.exclusive = arguments[0].exclusive; } // basic consume var rawOptions = { noAck: !options.ack, exclusive: options.exclusive }; if (options.ack) { rawOptions['prefetchCount'] = options.prefetchCount; } return this.subscribeRaw(rawOptions, function (m) { var contentType = m.contentType; if (contentType == null && m.headers && m.headers.properties) { contentType = m.headers.properties.content_type; } var isJSON = (contentType == 'text/json') || (contentType == 'application/json'); var b; if (isJSON) { b = "" } else { b = new Buffer(m.size); b.used = 0; } self._lastMessage = m; m.addListener('data', function (d) { if (isJSON) { b += d.toString(); } else { d.copy(b, b.used); b.used += d.length; } }); m.addListener('end', function () { var json, deliveryInfo = {}, msgProperties = classes[60].fields; if (isJSON) { try { json = JSON.parse(b); } catch (e) { json = null; deliveryInfo.parseError = e; deliveryInfo.rawData = b; } } else { json = { data: b, contentType: m.contentType }; } for (var i=0, l=msgProperties.length; i<l; i++) { if (m[msgProperties[i].name]) { deliveryInfo[msgProperties[i].name] = m[msgProperties[i].name]; } } deliveryInfo.queue = m.queue ? m.queue.name : null; deliveryInfo.deliveryTag = m.deliveryTag; deliveryInfo.redelivered = m.redelivered; deliveryInfo.exchange = m.exchange; deliveryInfo.routingKey = m.routingKey; deliveryInfo.consumerTag = m.consumerTag; if(options.routingKeyInPayload) json._routingKey = m.routingKey; if(options.deliveryTagInPayload) json._deliveryTag = m.deliveryTag; var headers = {}; for (var i in this.headers) { if(this.headers.hasOwnProperty(i)) { if(this.headers[i] instanceof Buffer) headers[i] = this.headers[i].toString(); else headers[i] = this.headers[i]; } } if (messageListener) messageListener(json, headers, deliveryInfo, m); self.emit('message', json, headers, deliveryInfo, m); }); }); }; Queue.prototype.subscribeJSON = Queue.prototype.subscribe; /* Acknowledges the last message */ Queue.prototype.shift = function () { if (this._lastMessage) { this._lastMessage.acknowledge(); } }; Queue.prototype.bind = function (/* [exchange,] routingKey [, bindCallback] */) { var self = this; // The first argument, exchange is optional. // If not supplied the connection will use the 'amq.topic' // exchange. var exchange, routingKey, callback; if(typeof(arguments[arguments.length-1]) == 'function'){ callback = arguments[arguments.length-1]; } // Remove callback from args so rest of bind functionality works as before // Also, defend against cases where a non function callback has been passed as 3rd param if (callback || arguments.length == 3) { delete arguments[arguments.length-1]; arguments.length--; } if (arguments.length == 2) { exchange = arguments[0]; routingKey = arguments[1]; } else { exchange = 'amq.topic'; routingKey = arguments[0]; } if(callback) this._bindCallback = callback; var exchangeName = exchange instanceof Exchange ? exchange.name : exchange; if(exchangeName in self.connection.exchanges) { this.exchange = self.connection.exchanges[exchangeName]; this.exchange.binds++; } self.connection._sendMethod(self.channel, methods.queueBind, { reserved1: 0 , queue: self.name , exchange: exchangeName , routingKey: routingKey , noWait: false , "arguments": {} }); }; Queue.prototype.unbind = function (/* [exchange,] routingKey */) { var self = this; // The first argument, exchange is optional. // If not supplied the connection will use the default 'amq.topic' // exchange. var exchange, routingKey; if (arguments.length == 2) { exchange = arguments[0]; routingKey = arguments[1]; } else { exchange = 'amq.topic'; routingKey = arguments[0]; } return this._taskPush(methods.queueUnbindOk, function () { var exchangeName = exchange instanceof Exchange ? exchange.name : exchange; self.connection._sendMethod(self.channel, methods.queueUnbind, { reserved1: 0 , queue: self.name , exchange: exchangeName , routingKey: routingKey , noWait: false , "arguments": {} }); }); }; Queue.prototype.bind_headers = function (/* [exchange,] matchingPairs */) { var self = this; // The first argument, exchange is optional. // If not supplied the connection will use the default 'amq.headers' // exchange. var exchange, matchingPairs; if (arguments.length == 2) { exchange = arguments[0]; matchingPairs = arguments[1]; } else { exchange = 'amq.headers'; matchingPairs = arguments[0]; } return this._taskPush(methods.queueBindOk, function () { var exchangeName = exchange instanceof Exchange ? exchange.name : exchange; self.connection._sendMethod(self.channel, methods.queueBind, { reserved1: 0 , queue: self.name , exchange: exchangeName , routingKey: '' , noWait: false , "arguments": matchingPairs }); }); }; Queue.prototype.destroy = function (options) { var self = this; options = options || {}; return this._taskPush(methods.queueDeleteOk, function () { self.connection.queueClosed(self.name); if('exchange' in self) { self.exchange.binds--; self.exchange.cleanup(); } self.connection._sendMethod(self.channel, methods.queueDelete, { reserved1: 0 , queue: self.name , ifUnused: options.ifUnused ? true : false , ifEmpty: options.ifEmpty ? true : false , noWait: false , "arguments": {} }); }); }; Queue.prototype.purge = function() { var self = this; return this._taskPush(methods.queuePurgeOk, function () { self.connection._sendMethod(self.channel, methods.queuePurge, { reserved1 : 0, queue: self.name, noWait: false}) }); }; Queue.prototype._onMethod = function (channel, method, args) { this.emit(method.name, args); if (this._handleTaskReply.apply(this, arguments)) return; switch (method) { case methods.channelOpenOk: if (this.options.noDeclare) { this.state = 'open'; if (this._openCallback) { this._openCallback(this); this._openCallback = null; } this.emit('open'); } else { this.connection._sendMethod(channel, methods.queueDeclare, { reserved1: 0 , queue: this.name , passive: this.options.passive ? true : false , durable: this.options.durable ? true : false , exclusive: this.options.exclusive ? true : false , autoDelete: this.options.autoDelete ? true : false , noWait: false , "arguments": this.options.arguments || {} }); this.state = "declare queue"; } break; case methods.queueDeclareOk: this.state = 'open'; this.name = args.queue; this.connection.queues[this.name] = this; if (this._openCallback) { this._openCallback(this); this._openCallback = null; } // TODO this is legacy interface, remove me this.emit('open', args.queue, args.messageCount, args.consumerCount); // If this is a reconnect, we must re-subscribe our queue listeners. var consumerTags = Object.keys(this.consumerTagListeners); for (var index in consumerTags) { if (consumerTags.hasOwnProperty(index)) { if (this.consumerTagOptions[consumerTags[index]]['state'] === 'closed') { this.subscribeRaw(this.consumerTagOptions[consumerTags[index]], this.consumerTagListeners[consumerTags[index]]); // Having called subscribeRaw, we are now a new consumer with a new consumerTag. delete this.consumerTagListeners[consumerTags[index]]; delete this.consumerTagOptions[consumerTags[index]]; } } } break; case methods.basicConsumeOk: debug('basicConsumeOk', util.inspect(args, null)); break; case methods.queueBindOk: if (this._bindCallback) { // setting this._bindCallback to null before calling the callback allows for a subsequent bind within the callback var cb = this._bindCallback; this._bindCallback = null; cb(this); } break; case methods.basicQosOk: break; case methods.confirmSelectOk: this._sequence = 1; this.confirm = true; break; case methods.channelClose: this.state = "closed"; this.connection.queueClosed(this.name); var e = new Error(args.replyText); e.code = args.replyCode; this.emit('error', e); this.emit('close'); break; case methods.channelCloseOk: this.connection.queueClosed(this.name); this.emit('close') break; case methods.basicDeliver: this.currentMessage = new Message(this, args); break; case methods.queueDeleteOk: break; default: throw new Error("Uncaught method '" + method.name + "' with args " + JSON.stringify(args) + "; tasks = " + JSON.stringify(this._tasks)); } this._tasksFlush(); }; Queue.prototype._onContentHeader = function (channel, classInfo, weight, properties, size) { mixin(this.currentMessage, properties); this.currentMessage.read = 0; this.currentMessage.size = size; this.emit('rawMessage', this.currentMessage); }; Queue.prototype._onContent = function (channel, data) { this.currentMessage.read += data.length this.currentMessage.emit('data', data); if (this.currentMessage.read == this.currentMessage.size) { this.currentMessage.emit('end'); } }; Queue.prototype.flow = function(active) { var self = this; return this._taskPush(methods.channelFlowOk, function () { self.connection._sendMethod(self.channel, methods.channelFlow, {'active': active }); }) }; function Exchange (connection, channel, name, options, openCallback) { Channel.call(this, connection, channel); this.name = name; this.binds = 0; // keep track of queues bound this.options = options || { autoDelete: true}; this._openCallback = openCallback; this._sequence = null; this._unAcked = {}; } util.inherits(Exchange, Channel); Exchange.prototype._onMethod = function (channel, method, args) { this.emit(method.name, args); if (this._handleTaskReply.apply(this, arguments)) return true; switch (method) { case methods.channelOpenOk: // Pre-baked exchanges don't need to be declared if (/^$|(amq\.)/.test(this.name)) { this.state = 'open'; // - issue #33 fix if (this._openCallback) { this._openCallback(this); this._openCallback = null; } // -- this.emit('open'); // For if we want to delete a exchange, // we dont care if all of the options match. } else if (this.options.noDeclare){ this.state = 'open'; if (this._openCallback) { this._openCallback(this); this._openCallback = null; } this.emit('open'); } else { this.connection._sendMethod(channel, methods.exchangeDeclare, { reserved1: 0 , reserved2: false , reserved3: false , exchange: this.name , type: this.options.type || 'topic' , passive: this.options.passive ? true : false , durable: this.options.durable ? true : false , autoDelete: this.options.autoDelete ? true : false , internal: this.options.internal ? true : false , noWait: false , "arguments":this.options.arguments || {} }); this.state = 'declaring'; } break; case methods.exchangeDeclareOk: if (this.options.confirm){ this.connection._sendMethod(channel, methods.confirmSelect, { noWait: false }); }else{ this.state = 'open'; this.emit('open'); if (this._openCallback) { this._openCallback(this); this._openCallback = null; } } break; case methods.confirmSelectOk: this._sequence = 1; this.state = 'open'; this.emit('open'); if (this._openCallback) { this._openCallback(this); this._openCallback = null; } break; case methods.channelClose: this.state = "closed"; this.connection.exchangeClosed(this.name); var e = new Error(args.replyText); e.code = args.replyCode; this.emit('error', e); this.emit('close'); break; case methods.channelCloseOk: this.connection.exchangeClosed(this.name); this.emit('close'); break; case methods.basicAck: this.emit('basic-ack', args); if(args.deliveryTag == 0 && args.multiple == true){ // we must ack everything for(var tag in this._unAcked){ this._unAcked[tag].emitAck() delete this._unAcked[tag] } }else if(args.deliveryTag != 0 && args.multiple == true){ // we must ack everything before the delivery tag for(var tag in this._unAcked){ if(tag <= args.deliveryTag){ this._unAcked[tag].emitAck() delete this._unAcked[tag] } } }else if(this._unAcked[args.deliveryTag] && args.multiple == false){ // simple single ack this._unAcked[args.deliveryTag].emitAck() delete this._unAcked[args.deliveryTag] } break; case methods.basicReturn: this.emit('basic-return', args); break; default: throw new Error("Uncaught method '" + method.name + "' with args " + JSON.stringify(args)); } this._tasksFlush(); }; // exchange.publish('routing.key', 'body'); // // the third argument can specify additional options // - mandatory (boolean, default false) // - immediate (boolean, default false) // - contentType (default 'application/octet-stream') // - contentEncoding // - headers // - deliveryMode // - priority (0-9) // - correlationId // - replyTo // - experation // - messageId // - timestamp // - userId // - appId // - clusterId // // the callback is optional and is only used when confirm is turned on for the exchange Exchange.prototype.publish = function (routingKey, data, options, callback) { var self = this; options = options || {}; options.routingKey = routingKey; options.exchange = self.name; options.mandatory = options.mandatory ? true : false; options.immediate = options.immediate ? true : false; options.reserved1 = 0; var task = this._taskPush(null, function () { self.connection._sendMethod(self.channel, methods.basicPublish, options); // This interface is probably not appropriate for streaming large files. // (Of course it's arguable about whether AMQP is the appropriate // transport for large files.) The content header wants to know the size // of the data before sending it - so there's no point in trying to have a // general streaming interface - streaming messages of unknown size simply // isn't possible with AMQP. This is all to say, don't send big messages. // If you need to stream something large, chunk it yourself. self.connection._sendBody(self.channel, data, options); }); if (self.options.confirm){ task.sequence = self._sequence self._unAcked[self._sequence] = task self._sequence++ if(callback != null){ var errorCallback = function(){task.removeAllListeners();callback(true)}; var exchange = this; task.once('ack', function(){exchange.removeListener('error', errorCallback); task.removeAllListeners();callback(false)}); this.once('error', errorCallback); } } return task }; // do any necessary cleanups eg. after queue destruction Exchange.prototype.cleanup = function() { if (this.binds == 0) // don't keep reference open if unused this.connection.exchangeClosed(this.name); }; Exchange.prototype.destroy = function (ifUnused) { var self = this; return this._taskPush(methods.exchangeDeleteOk, function () { self.connection.exchangeClosed(self.name); self.connection._sendMethod(self.channel, methods.exchangeDelete, { reserved1: 0 , exchange: self.name , ifUnused: ifUnused ? true : false , noWait: false }); }); };
amqp.js
var events = require('events'), util = require('util'), net = require('net'), protocol, jspack = require('./jspack').jspack, Buffer = require('buffer').Buffer, Promise = require('./promise').Promise, URL = require('url'), AMQPTypes = require('./constants').AMQPTypes, Indicators = require('./constants').Indicators, FrameType = require('./constants').FrameType; function mixin () { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, source; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !(typeof target === 'function') ) target = {}; // mixin process itself if only one argument is passed if ( length == i ) { target = GLOBAL; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (source = arguments[i]) != null ) { // Extend the base object Object.getOwnPropertyNames(source).forEach(function(k){ var d = Object.getOwnPropertyDescriptor(source, k) || {value: source[k]}; if (d.get) { target.__defineGetter__(k, d.get); if (d.set) { target.__defineSetter__(k, d.set); } } else { // Prevent never-ending loop if (target === d.value) { return; } if (deep && d.value && typeof d.value === "object") { target[k] = mixin(deep, // Never move original objects, clone them source[k] || (d.value.length != null ? [] : {}) , d.value); } else { target[k] = d.value; } } }); } } // Return the modified object return target; } var debugLevel = process.env['NODE_DEBUG_AMQP'] ? 1 : 0; function debug (x) { if (debugLevel > 0) console.error(x + '\n'); } // a look up table for methods recieved // indexed on class id, method id var methodTable = {}; // methods keyed on their name var methods = {}; // classes keyed on their index var classes = {}; (function () { // anon scope for init //debug("initializing amqp methods..."); protocol = require('./amqp-definitions-0-9-1'); for (var i = 0; i < protocol.classes.length; i++) { var classInfo = protocol.classes[i]; classes[classInfo.index] = classInfo; for (var j = 0; j < classInfo.methods.length; j++) { var methodInfo = classInfo.methods[j]; var name = classInfo.name + methodInfo.name[0].toUpperCase() + methodInfo.name.slice(1); //debug(name); var method = { name: name , fields: methodInfo.fields , methodIndex: methodInfo.index , classIndex: classInfo.index }; if (!methodTable[classInfo.index]) methodTable[classInfo.index] = {}; methodTable[classInfo.index][methodInfo.index] = method; methods[name] = method; } } })(); // end anon scope // parser var maxFrameBuffer = 131072; // 128k, same as rabbitmq (which was // copying qpid) var emptyFrameSize = 8; // This is from the javaclient var maxFrameSize = maxFrameBuffer - emptyFrameSize; // An interruptible AMQP parser. // // type is either 'server' or 'client' // version is '0-9-1'. // // Instances of this class have several callbacks // - onMethod(channel, method, args); // - onHeartBeat() // - onContent(channel, buffer); // - onContentHeader(channel, class, weight, properties, size); // // This class does not subclass EventEmitter, in order to reduce the speed // of emitting the callbacks. Since this is an internal class, that should // be fine. function AMQPParser (version, type) { this.isClient = (type == 'client'); this.state = this.isClient ? 'frameHeader' : 'protocolHeader'; if (version != '0-9-1') this.throwError("Unsupported protocol version"); var frameHeader = new Buffer(7); frameHeader.used = 0; var frameBuffer, frameType, frameChannel; var self = this; function header(data) { var fh = frameHeader; var needed = fh.length - fh.used; data.copy(fh, fh.used, 0, data.length); fh.used += data.length; // sloppy if (fh.used >= fh.length) { fh.read = 0; frameType = fh[fh.read++]; frameChannel = parseInt(fh, 2); var frameSize = parseInt(fh, 4); fh.used = 0; // for reuse if (frameSize > maxFrameBuffer) { self.throwError("Oversized frame " + frameSize); } frameBuffer = new Buffer(frameSize); frameBuffer.used = 0; return frame(data.slice(needed)); } else { // need more! return header; } } function frame(data) { var fb = frameBuffer; var needed = fb.length - fb.used; data.copy(fb, fb.used, 0, data.length); fb.used += data.length; if (data.length > needed) { return frameEnd(data.slice(needed)); } else if (data.length == needed) { return frameEnd; } else { return frame; } } function frameEnd(data) { if (data.length > 0) { if (data[0] === Indicators.FRAME_END) { switch (frameType) { case FrameType.METHOD: self._parseMethodFrame(frameChannel, frameBuffer); break; case FrameType.HEADER: self._parseHeaderFrame(frameChannel, frameBuffer); break; case FrameType.BODY: if (self.onContent) { self.onContent(frameChannel, frameBuffer); } break; case FrameType.HEARTBEAT: debug("heartbeat"); if (self.onHeartBeat) self.onHeartBeat(); break; default: self.throwError("Unhandled frame type " + frameType); break; } return header(data.slice(1)); } else { self.throwError("Missing frame end marker"); } } else { return frameEnd; } } self.parse = header; } // If there's an error in the parser, call the onError handler or throw AMQPParser.prototype.throwError = function (error) { if(this.onError) this.onError(error); else throw new Error(error); }; // Everytime data is recieved on the socket, pass it to this function for // parsing. AMQPParser.prototype.execute = function (data) { // This function only deals with dismantling and buffering the frames. // It delegates to other functions for parsing the frame-body. debug('execute: ' + data.toString()); this.parse = this.parse(data); }; // parse Network Byte Order integers. size can be 1,2,4,8 function parseInt (buffer, size) { var int = 0; switch (size) { case 1: return buffer[buffer.read++]; case 2: return (buffer[buffer.read++] << 8) + buffer[buffer.read++]; case 4: return (buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) + (buffer[buffer.read++] << 8) + buffer[buffer.read++]; case 8: return (buffer[buffer.read++] << 56) + (buffer[buffer.read++] << 48) + (buffer[buffer.read++] << 40) + (buffer[buffer.read++] << 32) + (buffer[buffer.read++] << 24) + (buffer[buffer.read++] << 16) + (buffer[buffer.read++] << 8) + buffer[buffer.read++]; default: throw new Error("cannot parse ints of that size"); } } function parseShortString (buffer) { var length = buffer[buffer.read++]; var s = buffer.toString('utf8', buffer.read, buffer.read+length); buffer.read += length; return s; } function parseLongString (buffer) { var length = parseInt(buffer, 4); var s = buffer.slice(buffer.read, buffer.read + length); buffer.read += length; return s.toString(); } function parseSignedInteger (buffer) { var int = parseInt(buffer, 4); if (int & 0x80000000) { int |= 0xEFFFFFFF; int = -int; } return int; } function parseValue (buffer) { switch (buffer[buffer.read++]) { case AMQPTypes.STRING: return parseLongString(buffer); case AMQPTypes.INTEGER: return parseInt(buffer, 4); case AMQPTypes.DECIMAL: var dec = parseInt(buffer, 1); var num = parseInt(buffer, 4); return num / (dec * 10); case AMQPTypes._64BIT_FLOAT: var b = []; for (var i = 0; i < 8; ++i) b[i] = buffer[buffer.read++]; return (new jspack(true)).Unpack('d', b); case AMQPTypes._32BIT_FLOAT: var b = []; for (var i = 0; i < 4; ++i) b[i] = buffer[buffer.read++]; return (new jspack(true)).Unpack('f', b); case AMQPTypes.TIME: var int = parseInt(buffer, 8); return (new Date()).setTime(int * 1000); case AMQPTypes.HASH: return parseTable(buffer); case AMQPTypes.SIGNED_64BIT: return parseInt(buffer, 8); case AMQPTypes.BOOLEAN: return (parseInt(buffer, 1) > 0); case AMQPTypes.BYTE_ARRAY: var len = parseInt(buffer, 4); var buf = new Buffer(len); buffer.copy(buf, 0, buffer.read, buffer.read + len); buffer.read += len; return buf; case AMQPTypes.ARRAY: var len = parseInt(buffer, 4); var end = buffer.read + len; var arr = new Array(); while (buffer.read < end) { arr.push(parseValue(buffer)); } return arr; default: throw new Error("Unknown field value type " + buffer[buffer.read-1]); } } function parseTable (buffer) { var length = buffer.read + parseInt(buffer, 4); var table = {}; while (buffer.read < length) { table[parseShortString(buffer)] = parseValue(buffer); } return table; } function parseFields (buffer, fields) { var args = {}; var bitIndex = 0; var value; for (var i = 0; i < fields.length; i++) { var field = fields[i]; //debug("parsing field " + field.name + " of type " + field.domain); switch (field.domain) { case 'bit': // 8 bits can be packed into one octet. // XXX check if bitIndex greater than 7? value = (buffer[buffer.read] & (1 << bitIndex)) ? true : false; if (fields[i+1] && fields[i+1].domain == 'bit') { bitIndex++; } else { bitIndex = 0; buffer.read++; } break; case 'octet': value = buffer[buffer.read++]; break; case 'short': value = parseInt(buffer, 2); break; case 'long': value = parseInt(buffer, 4); break; case 'timestamp': case 'longlong': value = parseInt(buffer, 8); break; case 'shortstr': value = parseShortString(buffer); break; case 'longstr': value = parseLongString(buffer); break; case 'table': value = parseTable(buffer); break; default: throw new Error("Unhandled parameter type " + field.domain); } //debug("got " + value); args[field.name] = value; } return args; } AMQPParser.prototype._parseMethodFrame = function (channel, buffer) { buffer.read = 0; var classId = parseInt(buffer, 2), methodId = parseInt(buffer, 2); // Make sure that this is a method that we understand. if (!methodTable[classId] || !methodTable[classId][methodId]) { this.throwError("Received unknown [classId, methodId] pair [" + classId + ", " + methodId + "]"); } var method = methodTable[classId][methodId]; if (!method) this.throwError("bad method?"); var args = parseFields(buffer, method.fields); if (this.onMethod) { this.onMethod(channel, method, args); } }; AMQPParser.prototype._parseHeaderFrame = function (channel, buffer) { buffer.read = 0; var classIndex = parseInt(buffer, 2); var weight = parseInt(buffer, 2); var size = parseInt(buffer, 8); var classInfo = classes[classIndex]; if (classInfo.fields.length > 15) { this.throwError("TODO: support more than 15 properties"); } var propertyFlags = parseInt(buffer, 2); var fields = []; for (var i = 0; i < classInfo.fields.length; i++) { var field = classInfo.fields[i]; // groan. if (propertyFlags & (1 << (15-i))) fields.push(field); } var properties = parseFields(buffer, fields); if (this.onContentHeader) { this.onContentHeader(channel, classInfo, weight, properties, size); } }; function serializeFloat(b, size, value, bigEndian) { var jp = new jspack(bigEndian); switch(size) { case 4: var x = jp.Pack('f', [value]); for (var i = 0; i < x.length; ++i) b[b.used++] = x[i]; break; case 8: var x = jp.Pack('d', [value]); for (var i = 0; i < x.length; ++i) b[b.used++] = x[i]; break; default: throw new Error("Unknown floating point size"); } } function serializeInt (b, size, int) { if (b.used + size > b.length) { throw new Error("write out of bounds"); } // Only 4 cases - just going to be explicit instead of looping. switch (size) { // octet case 1: b[b.used++] = int; break; // short case 2: b[b.used++] = (int & 0xFF00) >> 8; b[b.used++] = (int & 0x00FF) >> 0; break; // long case 4: b[b.used++] = (int & 0xFF000000) >> 24; b[b.used++] = (int & 0x00FF0000) >> 16; b[b.used++] = (int & 0x0000FF00) >> 8; b[b.used++] = (int & 0x000000FF) >> 0; break; // long long case 8: b[b.used++] = (int & 0xFF00000000000000) >> 56; b[b.used++] = (int & 0x00FF000000000000) >> 48; b[b.used++] = (int & 0x0000FF0000000000) >> 40; b[b.used++] = (int & 0x000000FF00000000) >> 32; b[b.used++] = (int & 0x00000000FF000000) >> 24; b[b.used++] = (int & 0x0000000000FF0000) >> 16; b[b.used++] = (int & 0x000000000000FF00) >> 8; b[b.used++] = (int & 0x00000000000000FF) >> 0; break; default: throw new Error("Bad size"); } } function serializeShortString (b, string) { if (typeof(string) != "string") { throw new Error("param must be a string"); } var byteLength = Buffer.byteLength(string, 'utf8'); if (byteLength > 0xFF) { throw new Error("String too long for 'shortstr' parameter"); } if (1 + byteLength + b.used >= b.length) { throw new Error("Not enough space in buffer for 'shortstr'"); } b[b.used++] = byteLength; b.write(string, b.used, 'utf8'); b.used += byteLength; } function serializeLongString (b, string) { // we accept string, object, or buffer for this parameter. // in the case of string we serialize it to utf8. if (typeof(string) == 'string') { var byteLength = Buffer.byteLength(string, 'utf8'); serializeInt(b, 4, byteLength); b.write(string, b.used, 'utf8'); b.used += byteLength; } else if (typeof(string) == 'object') { serializeTable(b, string); } else { // data is Buffer var byteLength = string.length; serializeInt(b, 4, byteLength); b.write(string, b.used); // memcpy b.used += byteLength; } } function serializeDate(b, date) { serializeInt(b, 8, date.valueOf() / 1000); } function serializeBuffer(b, buffer) { serializeInt(b, 4, buffer.length); buffer.copy(b, b.used, 0); b.used += buffer.length; } function serializeBase64(b, buffer) { serializeLongString(b, buffer.toString('base64')); } function isBigInt(value) { return value > 0xffffffff; } function getCode(dec) { var hexArray = "0123456789ABCDEF".split(''); var code1 = Math.floor(dec / 16); var code2 = dec - code1 * 16; return hexArray[code2]; } function isFloat(value) { return value === +value && value !== (value|0); } function serializeValue (b, value) { switch (typeof(value)) { case 'string': b[b.used++] = 'S'.charCodeAt(0); serializeLongString(b, value); break; case 'number': if (!isFloat(value)) { if (isBigInt(value)) { // 64-bit uint b[b.used++] = 'l'.charCodeAt(0); serializeInt(b, 8, value); } else { //32-bit uint b[b.used++] = 'I'.charCodeAt(0); serializeInt(b, 4, value); } } else { //64-bit float b[b.used++] = 'd'.charCodeAt(0); serializeFloat(b, 8, value); } break; case 'boolean': b[b.used++] = 't'.charCodeAt(0); b[b.used++] = value; break; default: if (value instanceof Date) { b[b.used++] = 'T'.charCodeAt(0); serializeDate(b, value); } else if (value instanceof Buffer) { b[b.used++] = 'x'.charCodeAt(0); serializeBuffer(b, value); } else if (util.isArray(value)) { b[b.used++] = 'A'.charCodeAt(0); serializeArray(b, value); } else if (typeof(value) === 'object') { b[b.used++] = 'F'.charCodeAt(0); serializeTable(b, value); } else { this.throwError("unsupported type in amqp table: " + typeof(value)); } } } function serializeTable (b, object) { if (typeof(object) != "object") { throw new Error("param must be an object"); } // Save our position so that we can go back and write the length of this table // at the beginning of the packet (once we know how many entries there are). var lengthIndex = b.used; b.used += 4; // sizeof long var startIndex = b.used; for (var key in object) { if (!object.hasOwnProperty(key)) continue; serializeShortString(b, key); serializeValue(b, object[key]); } var endIndex = b.used; b.used = lengthIndex; serializeInt(b, 4, endIndex - startIndex); b.used = endIndex; } function serializeArray (b, arr) { // Save our position so that we can go back and write the byte length of this array // at the beginning of the packet (once we have serialized all elements). var lengthIndex = b.used; b.used += 4; // sizeof long var startIndex = b.used; len = arr.length; for (var i = 0; i < len; i++) { serializeValue(b, arr[i]); } var endIndex = b.used; b.used = lengthIndex; serializeInt(b, 4, endIndex - startIndex); b.used = endIndex; } function serializeFields (buffer, fields, args, strict) { var bitField = 0; var bitIndex = 0; for (var i = 0; i < fields.length; i++) { var field = fields[i]; var domain = field.domain; if (!(field.name in args)) { if (strict) { throw new Error("Missing field '" + field.name + "' of type '" + domain + "' while executing AMQP method '" + arguments.callee.caller.arguments[1].name + "'"); } continue; } var param = args[field.name]; //debug("domain: " + domain + " param: " + param); switch (domain) { case 'bit': if (typeof(param) != "boolean") { throw new Error("Unmatched field " + JSON.stringify(field)); } if (param) bitField |= (1 << bitIndex); bitIndex++; if (!fields[i+1] || fields[i+1].domain != 'bit') { debug('SET bit field ' + field.name + ' 0x' + bitField.toString(16)); buffer[buffer.used++] = bitField; bitField = 0; bitIndex = 0; } break; case 'octet': if (typeof(param) != "number" || param > 0xFF) { throw new Error("Unmatched field " + JSON.stringify(field)); } buffer[buffer.used++] = param; break; case 'short': if (typeof(param) != "number" || param > 0xFFFF) { throw new Error("Unmatched field " + JSON.stringify(field)); } serializeInt(buffer, 2, param); break; case 'long': if (typeof(param) != "number" || param > 0xFFFFFFFF) { throw new Error("Unmatched field " + JSON.stringify(field)); } serializeInt(buffer, 4, param); break; case 'timestamp': case 'longlong': serializeInt(buffer, 8, param); break; case 'shortstr': if (typeof(param) != "string" || param.length > 0xFF) { throw new Error("Unmatched field " + JSON.stringify(field)); } serializeShortString(buffer, param); break; case 'longstr': serializeLongString(buffer, param); break; case 'table': if (typeof(param) != "object") { throw new Error("Unmatched field " + JSON.stringify(field)); } serializeTable(buffer, param); break; default: throw new Error("Unknown domain value type " + domain); } } } function Connection (connectionArgs, options, readyCallback) { net.Stream.call(this); var self = this; this.setOptions(connectionArgs); this.setImplOptions(options); if (typeof readyCallback === 'function') { this._readyCallback = readyCallback; } var parser; var backoffTime = null; this.connectionAttemptScheduled = false; var backoff = function () { if (self._inboundHeartbeatTimer !== null) { clearTimeout(self._inboundHeartbeatTimer); self._inboundHeartbeatTimer = null; } if (self._outboundHeartbeatTimer !== null) { clearTimeout(self._outboundHeartbeatTimer); self._outboundHeartbeatTimer = null; } if (!self.connectionAttemptScheduled) { // Set to true, as we are presently in the process of scheduling one. self.connectionAttemptScheduled = true; // Kill the socket, if it hasn't been killed already. self.end(); // Reset parser state parser = null; // In order for our reconnection to be seamless, we have to notify the // channels that they are no longer connected so that nobody attempts // to send messages which would be doomed to fail. for (var channel in self.channels) { if (channel != 0) { self.channels[channel].state = 'closed'; } } // Queues are channels (so we have already marked them as closed), but // queues have special needs, since the subscriptions will no longer // be known to the server when we reconnect. Mark the subscriptions as // closed so that we can resubscribe them once we are reconnected. for (var queue in self.queues) { for (var index in self.queues[queue].consumerTagOptions) { self.queues[queue].consumerTagOptions[index]['state'] = 'closed'; } } // Begin reconnection attempts if (self.implOptions.reconnect) { // Don't thrash, use a backoff strategy. if (backoffTime === null) { // This is the first time we've failed since a successful connection, // so use the configured backoff time without any modification. backoffTime = self.implOptions.reconnectBackoffTime; } else if (self.implOptions.reconnectBackoffStrategy === 'exponential') { // If you've configured exponential backoff, we'll double the // backoff time each subsequent attempt until success. backoffTime *= 2; // limit the maxium timeout, to avoid potentially unlimited stalls if(backoffTime > self.implOptions.reconnectExponentialLimit){ backoffTime = self.implOptions.reconnectExponentialLimit; } } else if (self.implOptions.reconnectBackoffStrategy === 'linear') { // Linear strategy is the default. In this case, we will retry at a // constant interval, so there's no need to change the backoff time // between attempts. } else { // TODO should we warn people if they picked a nonexistent strategy? } setTimeout(function () { // Set to false, so that if we fail in the reconnect attempt, we can // schedule another one. self.connectionAttemptScheduled = false; self.reconnect(); }, backoffTime); } } }; this._defaultExchange = null; this.channelCounter = 0; this._sendBuffer = new Buffer(maxFrameBuffer); self.addListener('connect', function () { // In the case where this is a reconnection, do not trample on the existing // channels. // For your reference, channel 0 is the control channel. self.channels = (self.implOptions.reconnect ? self.channels : undefined) || {0:self}; self.queues = (self.implOptions.reconnect ? self.queues : undefined) || {}; self.exchanges = (self.implOptions.reconnect ? self.exchanges : undefined) || {}; parser = new AMQPParser('0-9-1', 'client'); parser.onMethod = function (channel, method, args) { self._onMethod(channel, method, args); }; parser.onContent = function (channel, data) { debug(channel + " > content " + data.length); if (self.channels[channel] && self.channels[channel]._onContent) { self.channels[channel]._onContent(channel, data); } else { debug("unhandled content: " + data); } }; parser.onContentHeader = function (channel, classInfo, weight, properties, size) { debug(channel + " > content header " + JSON.stringify([classInfo.name, weight, properties, size])); if (self.channels[channel] && self.channels[channel]._onContentHeader) { self.channels[channel]._onContentHeader(channel, classInfo, weight, properties, size); } else { debug("unhandled content header"); } }; parser.onHeartBeat = function () { self.emit("heartbeat"); debug("heartbeat"); }; parser.onError = function (e) { self.emit("error", e); self.emit("close"); }; //debug("connected..."); // Time to start the AMQP 7-way connection initialization handshake! // 1. The client sends the server a version string self.write("AMQP" + String.fromCharCode(0,0,9,1)); }); self.addListener('data', function (data) { if(parser != null){ parser.execute(data); } self._inboundHeartbeatTimerReset(); }); self.addListener('error', function () { backoff(); }); self.addListener('ready', function () { // Reset the backoff time since we have successfully connected. backoffTime = null; if (self.implOptions.reconnect) { // Reconnect any channels which were open. for (var channel in self.channels) { if (channel != 0) { self.channels[channel].reconnect(); } } } // Restart the heartbeat to the server self._outboundHeartbeatTimerReset(); }) } util.inherits(Connection, net.Stream); exports.Connection = Connection; var defaultPorts = { 'amqp': 5672, 'amqps': 5671 }; var defaultOptions = { host: 'localhost' , port: defaultPorts['amqp'] , login: 'guest' , password: 'guest' , vhost: '/' }; // If the "reconnect" option is true, then the driver will attempt to // reconnect using the configured strategy *any time* the connection // becomes unavailable. // If this is not appropriate for your application, do not set this option. // If you would like this option, you can set parameters controlling how // aggressively the reconnections will be attempted. // Valid strategies are "linear" and "exponential". // Backoff times are in milliseconds. Under the "linear" strategy, the driver // will pause <reconnectBackoffTime> ms before the first attempt, and between // each subsequent attempt. Under the "exponential" strategy, the driver will // pause <reconnectBackoffTime> ms before the first attempt, and will double // the previous pause between each subsequent attempt until a connection is // reestablished. var defaultImplOptions = { defaultExchangeName: '', reconnect: true , reconnectBackoffStrategy: 'linear' , reconnectExponentialLimit: 120000, reconnectBackoffTime: 1000 }; function urlOptions(connectionString) { var opts = {}; var url = URL.parse(connectionString); var scheme = url.protocol.substring(0, url.protocol.lastIndexOf(':')); if (scheme != 'amqp' && scheme != 'amqps') { throw new Error('Connection URI must use amqp or amqps scheme. ' + 'For example, "amqp://bus.megacorp.internal:5766".'); } opts.ssl = ('amqps' === scheme); opts.host = url.hostname; opts.port = url.port || defaultPorts[scheme] if (url.auth) { var auth = url.auth.split(':'); auth[0] && (opts.login = auth[0]); auth[1] && (opts.password = auth[1]); } if (url.pathname) { opts.vhost = unescape(url.pathname.substr(1)); } return opts; } exports.createConnection = function (connectionArgs, options, readyCallback) { var c = new Connection(connectionArgs, options, readyCallback); // c.setOptions(connectionArgs); // c.setImplOptions(options); c.connect(); return c; }; Connection.prototype.setOptions = function (options) { var o = {}; var urlo = (options && options.url) ? urlOptions(options.url) : {}; mixin(o, defaultOptions, urlo, options || {}); this.options = o; }; Connection.prototype.setImplOptions = function (options) { var o = {} mixin(o, defaultImplOptions, options || {}); this.implOptions = o; }; Connection.prototype.reconnect = function () { // Suspend activity on channels for (var channel in this.channels) { this.channels[channel].state = 'closed'; } // Terminate socket activity this.end(); this.connect(); }; Connection.prototype.connect = function () { // If you pass a array of hosts, lets choose a random host, or then next one. var connectToHost = this.options.host; if(Array.isArray(this.options.host) == true){ if(this.hosti == null){ this.hosti = Math.random()*this.options.host.length >> 0; }else{ this.hosti = (this.hosti+1) % this.options.host.length; } connectToHost = this.options.host[this.hosti] } // Connect socket net.Socket.prototype.connect.call(this, this.options.port, connectToHost); }; Connection.prototype._onMethod = function (channel, method, args) { debug(channel + " > " + method.name + " " + JSON.stringify(args)); // Channel 0 is the control channel. If not zero then delegate to // one of the channel objects. if (channel > 0) { if (!this.channels[channel]) { debug("Received message on untracked channel."); return; } if (!this.channels[channel]._onChannelMethod) { throw new Error('Channel ' + channel + ' has no _onChannelMethod method.'); } this.channels[channel]._onChannelMethod(channel, method, args); return; } // channel 0 switch (method) { // 2. The server responds, after the version string, with the // 'connectionStart' method (contains various useless information) case methods.connectionStart: // We check that they're serving us AMQP 0-9 if (args.versionMajor != 0 && args.versionMinor != 9) { this.end(); this.emit('error', new Error("Bad server version")); return; } this.serverProperties = args.serverProperties; // 3. Then we reply with StartOk, containing our useless information. this._sendMethod(0, methods.connectionStartOk, { clientProperties: { version: '0.0.1' , platform: 'node-' + process.version , product: 'node-amqp' } , mechanism: 'AMQPLAIN' , response: { LOGIN: this.options.login , PASSWORD: this.options.password } , locale: 'en_US' }); break; // 4. The server responds with a connectionTune request case methods.connectionTune: // 5. We respond with connectionTuneOk this._sendMethod(0, methods.connectionTuneOk, { channelMax: 0 , frameMax: maxFrameBuffer , heartbeat: this.options.heartbeat || 0 }); // 6. Then we have to send a connectionOpen request this._sendMethod(0, methods.connectionOpen, { virtualHost: this.options.vhost // , capabilities: '' // , insist: true , reserved1: '' , reserved2: true }); break; case methods.connectionOpenOk: // 7. Finally they respond with connectionOpenOk // Whew! That's why they call it the Advanced MQP. if (this._readyCallback) { this._readyCallback(this); this._readyCallback = null; } this.emit('ready'); break; case methods.connectionClose: var e = new Error(args.replyText); e.code = args.replyCode; if (!this.listeners('close').length) { console.log('Unhandled connection error: ' + args.replyText); } this.destroy(e); break; default: throw new Error("Uncaught method '" + method.name + "' with args " + JSON.stringify(args)); } }; Connection.prototype.heartbeat = function () { this.write(new Buffer([8,0,0,0,0,0,0,206])); }; Connection.prototype._outboundHeartbeatTimerReset = function () { if (this._outboundHeartbeatTimer !== null) { clearTimeout(this._outboundHeartbeatTimer); this._outboundHeartbeatTimer = null; } if (this.options.heartbeat) { var self = this; this._outboundHeartbeatTimer = setTimeout(function () { self.heartbeat(); self._outboundHeartbeatTimerReset(); }, 1000 * this.options.heartbeat); } }; Connection.prototype._inboundHeartbeatTimerReset = function () { if (this._inboundHeartbeatTimer !== null) { clearTimeout(this._inboundHeartbeatTimer); this._inboundHeartbeatTimer = null; } if (this.options.heartbeat) { var self = this; var gracePeriod = 2 * this.options.heartbeat; this._inboundHeartbeatTimer = setTimeout(function () { self.emit('error', new Error('no heartbeat or data in last ' + gracePeriod + ' seconds')); }, gracePeriod * 1000); } }; Connection.prototype._sendMethod = function (channel, method, args) { debug(channel + " < " + method.name + " " + JSON.stringify(args)); var b = this._sendBuffer; b.used = 0; b[b.used++] = 1; // constants.frameMethod serializeInt(b, 2, channel); var lengthIndex = b.used; serializeInt(b, 4, 42); // replace with actual length. var startIndex = b.used; serializeInt(b, 2, method.classIndex); // short, classId serializeInt(b, 2, method.methodIndex); // short, methodId serializeFields(b, method.fields, args, true); var endIndex = b.used; // write in the frame length now that we know it. b.used = lengthIndex; serializeInt(b, 4, endIndex - startIndex); b.used = endIndex; b[b.used++] = 206; // constants.frameEnd; var c = b.slice(0, b.used); //debug("sending frame: " + c); this.write(c); this._outboundHeartbeatTimerReset(); }; // connection: the connection // channel: the channel to send this on // size: size in bytes of the following message // properties: an object containing any of the following: // - contentType (default 'application/octet-stream') // - contentEncoding // - headers // - deliveryMode // - priority (0-9) // - correlationId // - replyTo // - experation // - messageId // - timestamp // - userId // - appId // - clusterId function sendHeader (connection, channel, size, properties) { var b = new Buffer(maxFrameBuffer); // FIXME allocating too much. // use freelist? b.used = 0; var classInfo = classes[60]; // always basic class. // 7 OCTET FRAME HEADER b[b.used++] = 2; // constants.frameHeader serializeInt(b, 2, channel); var lengthStart = b.used; serializeInt(b, 4, 0 /*dummy*/); // length var bodyStart = b.used; // HEADER'S BODY serializeInt(b, 2, classInfo.index); // class 60 for Basic serializeInt(b, 2, 0); // weight, always 0 for rabbitmq serializeInt(b, 8, size); // byte size of body // properties - first propertyFlags var props = {'contentType': 'application/octet-stream'}; mixin(props, properties); var propertyFlags = 0; for (var i = 0; i < classInfo.fields.length; i++) { if (props[classInfo.fields[i].name]) propertyFlags |= 1 << (15-i); } serializeInt(b, 2, propertyFlags); // now the actual properties. serializeFields(b, classInfo.fields, props, false); //serializeTable(b, props); var bodyEnd = b.used; // Go back to the header and write in the length now that we know it. b.used = lengthStart; serializeInt(b, 4, bodyEnd - bodyStart); b.used = bodyEnd; // 1 OCTET END b[b.used++] = 206; // constants.frameEnd; var s = b.slice(0, b.used); //debug('header sent: ' + JSON.stringify(s)); connection.write(s); } Connection.prototype._sendBody = function (channel, body, properties) { // Handles 3 cases // - body is utf8 string // - body is instance of Buffer // - body is an object and its JSON representation is sent // Does not handle the case for streaming bodies. // In order to support long frame types we switch our strings into buffers for proper handling if (typeof(body) == 'string') { body = new Buffer(body, 'utf8'); } if (typeof(body) == 'object' && !(body instanceof Buffer)){ properties = mixin({contentType: 'application/json' }, properties); body = new Buffer(JSON.stringify(body), 'utf8'); } if (body instanceof Buffer) { sendHeader(this, channel, body.length, properties); debug('body sent: ' + JSON.stringify(b)); for (var offset = 0; offset < body.length; offset += maxFrameSize){ var remaining = body.length - offset; var fragmentLength = (remaining < maxFrameSize) ? remaining : maxFrameSize; // debug("sending " + offset + " through " + (offset+fragmentLength) + " of " + body.length) var b = new Buffer(7); b.used = 0; b[b.used++] = 3; // constants.frameBody serializeInt(b, 2, channel); serializeInt(b, 4, fragmentLength); this.write(b); this.write(body.slice(offset,offset+fragmentLength)); this.write(new Buffer([206])); // frameEnd } return true; }else{ debug('invalid body sent to _sendBody'); return false; } }; // Options // - passive (boolean) // - durable (boolean) // - exclusive (boolean) // - autoDelete (boolean, default true) Connection.prototype.queue = function (name /* options, openCallback */) { var options, callback; if (typeof arguments[1] == 'object') { options = arguments[1]; callback = arguments[2]; } else { callback = arguments[1]; } this.channelCounter++; var channel = this.channelCounter; var q = new Queue(this, channel, name, options, callback); this.channels[channel] = q; return q; }; // remove a queue when it's closed (called from Queue) Connection.prototype.queueClosed = function (name) { if (this.queues[name]) delete this.queues[name]; }; // remove an exchange when it's closed (called from Exchange) Connection.prototype.exchangeClosed = function (name) { if (this.exchanges[name]) delete this.exchanges[name]; }; // connection.exchange('my-exchange', { type: 'topic' }); // Options // - type 'fanout', 'direct', or 'topic' (default) // - passive (boolean) // - durable (boolean) // - autoDelete (boolean, default true) Connection.prototype.exchange = function (name, options, openCallback) { if (name === undefined) name = this.implOptions.defaultExchangeName; if (!options) options = {}; if (name != '' && options.type === undefined) options.type = 'topic'; this.channelCounter++; var channel = this.channelCounter; var exchange = new Exchange(this, channel, name, options, openCallback); this.channels[channel] = exchange; this.exchanges[name] = exchange; return exchange; }; // Publishes a message to the default exchange. Connection.prototype.publish = function (routingKey, body, options) { if (!this._defaultExchange) this._defaultExchange = this.exchange(); return this._defaultExchange.publish(routingKey, body, options); }; // Properties: // - routingKey // - size // - deliveryTag // // - contentType (default 'application/octet-stream') // - contentEncoding // - headers // - deliveryMode // - priority (0-9) // - correlationId // - replyTo // - experation // - messageId // - timestamp // - userId // - appId // - clusterId function Message (queue, args) { var msgProperties = classes[60].fields; events.EventEmitter.call(this); this.queue = queue; this.deliveryTag = args.deliveryTag; this.redelivered = args.redelivered; this.exchange = args.exchange; this.routingKey = args.routingKey; this.consumerTag = args.consumerTag; for (var i=0, l=msgProperties.length; i<l; i++) { if (args[msgProperties[i].name]) { this[msgProperties[i].name] = args[msgProperties[i].name]; } } } util.inherits(Message, events.EventEmitter); // Acknowledge receipt of message. // Set first arg to 'true' to acknowledge this and all previous messages // received on this queue. Message.prototype.acknowledge = function (all) { this.queue.connection._sendMethod(this.queue.channel, methods.basicAck, { reserved1: 0 , deliveryTag: this.deliveryTag , multiple: all ? true : false }); }; // Reject an incoming message. // Set first arg to 'true' to requeue the message. Message.prototype.reject = function (requeue){ this.queue.connection._sendMethod(this.queue.channel, methods.basicReject, { deliveryTag: this.deliveryTag , requeue: requeue ? true : false }); } // This class is not exposed to the user. Queue and Exchange are subclasses // of Channel. This just provides a task queue. function Channel (connection, channel) { events.EventEmitter.call(this); this.channel = channel; this.connection = connection; this._tasks = []; this.reconnect(); } util.inherits(Channel, events.EventEmitter); Channel.prototype.reconnect = function () { this.connection._sendMethod(this.channel, methods.channelOpen, {reserved1: ""}); }; Channel.prototype._taskPush = function (reply, cb) { var promise = new Promise(); this._tasks.push({ promise: promise , reply: reply , sent: false , cb: cb }); this._tasksFlush(); return promise; }; Channel.prototype._tasksFlush = function () { if (this.state != 'open') return; for (var i = 0; i < this._tasks.length; i++) { var task = this._tasks[i]; if (task.sent) continue; task.cb(); task.sent = true; if (!task.reply) { // if we don't expect a reply, just delete it now this._tasks.splice(i, 1); i = i-1; } } }; Channel.prototype._handleTaskReply = function (channel, method, args) { var task, i; for (i = 0; i < this._tasks.length; i++) { if (this._tasks[i].reply == method) { task = this._tasks[i]; this._tasks.splice(i, 1); task.promise.emitSuccess(args); this._tasksFlush(); return true; } } return false; }; Channel.prototype._onChannelMethod = function(channel, method, args) { switch (method) { case methods.channelCloseOk: delete this.connection.channels[this.channel] this.state = 'closed' default: this._onMethod(channel, method, args); } } Channel.prototype.close = function() { this.state = 'closing'; this.connection._sendMethod(this.channel, methods.channelClose, {'replyText': 'Goodbye from node', 'replyCode': 200, 'classId': 0, 'methodId': 0}); } function Queue (connection, channel, name, options, callback) { Channel.call(this, connection, channel); this.name = name; this.consumerTagListeners = {}; this.consumerTagOptions = {}; var self = this; // route messages to subscribers based on consumerTag this.on('rawMessage', function(message) { if (message.consumerTag && self.consumerTagListeners[message.consumerTag]) { self.consumerTagListeners[message.consumerTag](message); } }); this.options = { autoDelete: true, closeChannelOnUnsubscribe: false }; if (options) mixin(this.options, options); this._openCallback = callback; } util.inherits(Queue, Channel); Queue.prototype.subscribeRaw = function (/* options, messageListener */) { var self = this; var messageListener = arguments[arguments.length-1]; var consumerTag = 'node-amqp-'+process.pid+'-'+Math.random(); this.consumerTagListeners[consumerTag] = messageListener; var options = { }; if (typeof arguments[0] == 'object') { mixin(options, arguments[0]); } options['state'] = 'opening'; this.consumerTagOptions[consumerTag] = options; if (options.prefetchCount) { self.connection._sendMethod(self.channel, methods.basicQos, { reserved1: 0 , prefetchSize: 0 , prefetchCount: options.prefetchCount , global: false }); } return this._taskPush(methods.basicConsumeOk, function () { self.connection._sendMethod(self.channel, methods.basicConsume, { reserved1: 0 , queue: self.name , consumerTag: consumerTag , noLocal: options.noLocal ? true : false , noAck: options.noAck ? true : false , exclusive: options.exclusive ? true : false , noWait: false , "arguments": {} }); self.consumerTagOptions[consumerTag]['state'] = 'open'; }); }; Queue.prototype.unsubscribe = function(consumerTag) { var self = this; return this._taskPush(methods.basicCancelOk, function () { self.connection._sendMethod(self.channel, methods.basicCancel, { reserved1: 0, consumerTag: consumerTag, noWait: false }); }) .addCallback(function () { if(self.options.closeChannelOnUnsubscribe){ self.close(); } delete self.consumerTagListeners[consumerTag]; delete self.consumerTagOptions[consumerTag]; }); }; Queue.prototype.subscribe = function (/* options, messageListener */) { var self = this; var messageListener = arguments[arguments.length-1]; if(typeof(messageListener) !== "function") messageListener = null; var options = { ack: false, prefetchCount: 1, routingKeyInPayload: self.connection.options.routingKeyInPayload, deliveryTagInPayload: self.connection.options.deliveryTagInPayload }; if (typeof arguments[0] == 'object') { if (arguments[0].ack) options.ack = true; if (arguments[0].routingKeyInPayload) options.routingKeyInPayload = arguments[0].routingKeyInPayload; if (arguments[0].deliveryTagInPayload) options.deliveryTagInPayload = arguments[0].deliveryTagInPayload; if (arguments[0].prefetchCount != undefined) options.prefetchCount = arguments[0].prefetchCount; if (arguments[0].exclusive) options.exclusive = arguments[0].exclusive; } // basic consume var rawOptions = { noAck: !options.ack, exclusive: options.exclusive }; if (options.ack) { rawOptions['prefetchCount'] = options.prefetchCount; } return this.subscribeRaw(rawOptions, function (m) { var contentType = m.contentType; if (contentType == null && m.headers && m.headers.properties) { contentType = m.headers.properties.content_type; } var isJSON = (contentType == 'text/json') || (contentType == 'application/json'); var b; if (isJSON) { b = "" } else { b = new Buffer(m.size); b.used = 0; } self._lastMessage = m; m.addListener('data', function (d) { if (isJSON) { b += d.toString(); } else { d.copy(b, b.used); b.used += d.length; } }); m.addListener('end', function () { var json, deliveryInfo = {}, msgProperties = classes[60].fields; if (isJSON) { try { json = JSON.parse(b); } catch (e) { json = null; deliveryInfo.parseError = e; deliveryInfo.rawData = b; } } else { json = { data: b, contentType: m.contentType }; } for (var i=0, l=msgProperties.length; i<l; i++) { if (m[msgProperties[i].name]) { deliveryInfo[msgProperties[i].name] = m[msgProperties[i].name]; } } deliveryInfo.queue = m.queue ? m.queue.name : null; deliveryInfo.deliveryTag = m.deliveryTag; deliveryInfo.redelivered = m.redelivered; deliveryInfo.exchange = m.exchange; deliveryInfo.routingKey = m.routingKey; deliveryInfo.consumerTag = m.consumerTag; if(options.routingKeyInPayload) json._routingKey = m.routingKey; if(options.deliveryTagInPayload) json._deliveryTag = m.deliveryTag; var headers = {}; for (var i in this.headers) { if(this.headers.hasOwnProperty(i)) { if(this.headers[i] instanceof Buffer) headers[i] = this.headers[i].toString(); else headers[i] = this.headers[i]; } } if (messageListener) messageListener(json, headers, deliveryInfo, m); self.emit('message', json, headers, deliveryInfo, m); }); }); }; Queue.prototype.subscribeJSON = Queue.prototype.subscribe; /* Acknowledges the last message */ Queue.prototype.shift = function () { if (this._lastMessage) { this._lastMessage.acknowledge(); } }; Queue.prototype.bind = function (/* [exchange,] routingKey [, bindCallback] */) { var self = this; // The first argument, exchange is optional. // If not supplied the connection will use the 'amq.topic' // exchange. var exchange, routingKey, callback; if(typeof(arguments[arguments.length-1]) == 'function'){ callback = arguments[arguments.length-1]; } // Remove callback from args so rest of bind functionality works as before // Also, defend against cases where a non function callback has been passed as 3rd param if (callback || arguments.length == 3) { delete arguments[arguments.length-1]; arguments.length--; } if (arguments.length == 2) { exchange = arguments[0]; routingKey = arguments[1]; } else { exchange = 'amq.topic'; routingKey = arguments[0]; } if(callback) this._bindCallback = callback; var exchangeName = exchange instanceof Exchange ? exchange.name : exchange; if(exchangeName in self.connection.exchanges) { this.exchange = self.connection.exchanges[exchangeName]; this.exchange.binds++; } self.connection._sendMethod(self.channel, methods.queueBind, { reserved1: 0 , queue: self.name , exchange: exchangeName , routingKey: routingKey , noWait: false , "arguments": {} }); }; Queue.prototype.unbind = function (/* [exchange,] routingKey */) { var self = this; // The first argument, exchange is optional. // If not supplied the connection will use the default 'amq.topic' // exchange. var exchange, routingKey; if (arguments.length == 2) { exchange = arguments[0]; routingKey = arguments[1]; } else { exchange = 'amq.topic'; routingKey = arguments[0]; } return this._taskPush(methods.queueUnbindOk, function () { var exchangeName = exchange instanceof Exchange ? exchange.name : exchange; self.connection._sendMethod(self.channel, methods.queueUnbind, { reserved1: 0 , queue: self.name , exchange: exchangeName , routingKey: routingKey , noWait: false , "arguments": {} }); }); }; Queue.prototype.bind_headers = function (/* [exchange,] matchingPairs */) { var self = this; // The first argument, exchange is optional. // If not supplied the connection will use the default 'amq.headers' // exchange. var exchange, matchingPairs; if (arguments.length == 2) { exchange = arguments[0]; matchingPairs = arguments[1]; } else { exchange = 'amq.headers'; matchingPairs = arguments[0]; } return this._taskPush(methods.queueBindOk, function () { var exchangeName = exchange instanceof Exchange ? exchange.name : exchange; self.connection._sendMethod(self.channel, methods.queueBind, { reserved1: 0 , queue: self.name , exchange: exchangeName , routingKey: '' , noWait: false , "arguments": matchingPairs }); }); }; Queue.prototype.destroy = function (options) { var self = this; options = options || {}; return this._taskPush(methods.queueDeleteOk, function () { self.connection.queueClosed(self.name); if('exchange' in self) { self.exchange.binds--; self.exchange.cleanup(); } self.connection._sendMethod(self.channel, methods.queueDelete, { reserved1: 0 , queue: self.name , ifUnused: options.ifUnused ? true : false , ifEmpty: options.ifEmpty ? true : false , noWait: false , "arguments": {} }); }); }; Queue.prototype.purge = function() { var self = this; return this._taskPush(methods.queuePurgeOk, function () { self.connection._sendMethod(self.channel, methods.queuePurge, { reserved1 : 0, queue: self.name, noWait: false}) }); }; Queue.prototype._onMethod = function (channel, method, args) { this.emit(method.name, args); if (this._handleTaskReply.apply(this, arguments)) return; switch (method) { case methods.channelOpenOk: if (this.options.noDeclare) { this.state = 'open'; if (this._openCallback) { this._openCallback(this); this._openCallback = null; } this.emit('open'); } else { this.connection._sendMethod(channel, methods.queueDeclare, { reserved1: 0 , queue: this.name , passive: this.options.passive ? true : false , durable: this.options.durable ? true : false , exclusive: this.options.exclusive ? true : false , autoDelete: this.options.autoDelete ? true : false , noWait: false , "arguments": this.options.arguments || {} }); this.state = "declare queue"; } break; case methods.queueDeclareOk: this.state = 'open'; this.name = args.queue; this.connection.queues[this.name] = this; if (this._openCallback) { this._openCallback(this); this._openCallback = null; } // TODO this is legacy interface, remove me this.emit('open', args.queue, args.messageCount, args.consumerCount); // If this is a reconnect, we must re-subscribe our queue listeners. var consumerTags = Object.keys(this.consumerTagListeners); for (var index in consumerTags) { if (consumerTags.hasOwnProperty(index)) { if (this.consumerTagOptions[consumerTags[index]]['state'] === 'closed') { this.subscribeRaw(this.consumerTagOptions[consumerTags[index]], this.consumerTagListeners[consumerTags[index]]); // Having called subscribeRaw, we are now a new consumer with a new consumerTag. delete this.consumerTagListeners[consumerTags[index]]; delete this.consumerTagOptions[consumerTags[index]]; } } } break; case methods.basicConsumeOk: debug('basicConsumeOk', util.inspect(args, null)); break; case methods.queueBindOk: if (this._bindCallback) { // setting this._bindCallback to null before calling the callback allows for a subsequent bind within the callback var cb = this._bindCallback; this._bindCallback = null; cb(this); } break; case methods.basicQosOk: break; case methods.confirmSelectOk: this._sequence = 1; this.confirm = true; break; case methods.channelClose: this.state = "closed"; this.connection.queueClosed(this.name); var e = new Error(args.replyText); e.code = args.replyCode; this.emit('error', e); this.emit('close'); break; case methods.channelCloseOk: this.connection.queueClosed(this.name); this.emit('close') break; case methods.basicDeliver: this.currentMessage = new Message(this, args); break; case methods.queueDeleteOk: break; default: throw new Error("Uncaught method '" + method.name + "' with args " + JSON.stringify(args) + "; tasks = " + JSON.stringify(this._tasks)); } this._tasksFlush(); }; Queue.prototype._onContentHeader = function (channel, classInfo, weight, properties, size) { mixin(this.currentMessage, properties); this.currentMessage.read = 0; this.currentMessage.size = size; this.emit('rawMessage', this.currentMessage); }; Queue.prototype._onContent = function (channel, data) { this.currentMessage.read += data.length this.currentMessage.emit('data', data); if (this.currentMessage.read == this.currentMessage.size) { this.currentMessage.emit('end'); } }; Queue.prototype.flow = function(active) { var self = this; return this._taskPush(methods.channelFlowOk, function () { self.connection._sendMethod(self.channel, methods.channelFlow, {'active': active }); }) }; function Exchange (connection, channel, name, options, openCallback) { Channel.call(this, connection, channel); this.name = name; this.binds = 0; // keep track of queues bound this.options = options || { autoDelete: true}; this._openCallback = openCallback; this._sequence = null; this._unAcked = {}; } util.inherits(Exchange, Channel); Exchange.prototype._onMethod = function (channel, method, args) { this.emit(method.name, args); if (this._handleTaskReply.apply(this, arguments)) return true; switch (method) { case methods.channelOpenOk: // Pre-baked exchanges don't need to be declared if (/^$|(amq\.)/.test(this.name)) { this.state = 'open'; // - issue #33 fix if (this._openCallback) { this._openCallback(this); this._openCallback = null; } // -- this.emit('open'); // For if we want to delete a exchange, // we dont care if all of the options match. } else if (this.options.noDeclare){ this.state = 'open'; if (this._openCallback) { this._openCallback(this); this._openCallback = null; } this.emit('open'); } else { this.connection._sendMethod(channel, methods.exchangeDeclare, { reserved1: 0 , reserved2: false , reserved3: false , exchange: this.name , type: this.options.type || 'topic' , passive: this.options.passive ? true : false , durable: this.options.durable ? true : false , autoDelete: this.options.autoDelete ? true : false , internal: this.options.internal ? true : false , noWait: false , "arguments":this.options.arguments || {} }); this.state = 'declaring'; } break; case methods.exchangeDeclareOk: if (this.options.confirm){ this.connection._sendMethod(channel, methods.confirmSelect, { noWait: false }); }else{ this.state = 'open'; this.emit('open'); if (this._openCallback) { this._openCallback(this); this._openCallback = null; } } break; case methods.confirmSelectOk: this._sequence = 1; this.state = 'open'; this.emit('open'); if (this._openCallback) { this._openCallback(this); this._openCallback = null; } break; case methods.channelClose: this.state = "closed"; this.connection.exchangeClosed(this.name); var e = new Error(args.replyText); e.code = args.replyCode; this.emit('error', e); this.emit('close'); break; case methods.channelCloseOk: this.connection.exchangeClosed(this.name); this.emit('close'); break; case methods.basicAck: this.emit('basic-ack', args); if(args.deliveryTag == 0 && args.multiple == true){ // we must ack everything for(var tag in this._unAcked){ this._unAcked[tag].emitAck() delete this._unAcked[tag] } }else if(args.deliveryTag != 0 && args.multiple == true){ // we must ack everything before the delivery tag for(var tag in this._unAcked){ if(tag <= args.deliveryTag){ this._unAcked[tag].emitAck() delete this._unAcked[tag] } } }else if(this._unAcked[args.deliveryTag] && args.multiple == false){ // simple single ack this._unAcked[args.deliveryTag].emitAck() delete this._unAcked[args.deliveryTag] } break; case methods.basicReturn: this.emit('basic-return', args); break; default: throw new Error("Uncaught method '" + method.name + "' with args " + JSON.stringify(args)); } this._tasksFlush(); }; // exchange.publish('routing.key', 'body'); // // the third argument can specify additional options // - mandatory (boolean, default false) // - immediate (boolean, default false) // - contentType (default 'application/octet-stream') // - contentEncoding // - headers // - deliveryMode // - priority (0-9) // - correlationId // - replyTo // - experation // - messageId // - timestamp // - userId // - appId // - clusterId // // the callback is optional and is only used when confirm is turned on for the exchange Exchange.prototype.publish = function (routingKey, data, options, callback) { var self = this; options = options || {}; options.routingKey = routingKey; options.exchange = self.name; options.mandatory = options.mandatory ? true : false; options.immediate = options.immediate ? true : false; options.reserved1 = 0; var task = this._taskPush(null, function () { self.connection._sendMethod(self.channel, methods.basicPublish, options); // This interface is probably not appropriate for streaming large files. // (Of course it's arguable about whether AMQP is the appropriate // transport for large files.) The content header wants to know the size // of the data before sending it - so there's no point in trying to have a // general streaming interface - streaming messages of unknown size simply // isn't possible with AMQP. This is all to say, don't send big messages. // If you need to stream something large, chunk it yourself. self.connection._sendBody(self.channel, data, options); }); if (self.options.confirm){ task.sequence = self._sequence self._unAcked[self._sequence] = task self._sequence++ if(callback != null){ var errorCallback = function(){task.removeAllListeners();callback(true)}; var exchange = this; task.once('ack', function(){exchange.removeListener('error', errorCallback); task.removeAllListeners();callback(false)}); this.once('error', errorCallback); } } return task }; // do any necessary cleanups eg. after queue destruction Exchange.prototype.cleanup = function() { if (this.binds == 0) // don't keep reference open if unused this.connection.exchangeClosed(this.name); }; Exchange.prototype.destroy = function (ifUnused) { var self = this; return this._taskPush(methods.exchangeDeleteOk, function () { self.connection.exchangeClosed(self.name); self.connection._sendMethod(self.channel, methods.exchangeDelete, { reserved1: 0 , exchange: self.name , ifUnused: ifUnused ? true : false , noWait: false }); }); };
Add callback to Connection.publish
amqp.js
Add callback to Connection.publish
<ide><path>mqp.js <ide> }; <ide> <ide> // Publishes a message to the default exchange. <del>Connection.prototype.publish = function (routingKey, body, options) { <add>Connection.prototype.publish = function (routingKey, body, options, callback) { <ide> if (!this._defaultExchange) this._defaultExchange = this.exchange(); <del> return this._defaultExchange.publish(routingKey, body, options); <del>}; <del> <add> return this._defaultExchange.publish(routingKey, body, options, callback); <add>}; <ide> <ide> <ide> // Properties:
Java
mit
6b89008f0a4fa8ddff9704bb85e0f98ef26b6ae1
0
Realiserad/kex15,Realiserad/kex15
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; /** * Verify a solution to The Monk problem using an EL-system. The solution should contain a * directed graph G consisting of one component, and a set of solution vectors describing the * movement of the pursuers. * * The solution to be checked is read from stdin and the program answers YES or NO to stdout * followed by the states produced in sequence by the solution vectors. * * * Input format: * Row Data * 0 Should contain the number of rows "r" in the neighbour matrix for G. * 1 to r Should contain the data (separated by space) for the neighbour matrix. * r+1 Should contain two integers separated by space; the number of pursuers "p" * and the length of a solution vector. * r+2 to r+2+p Should contain the movement of the pursuers (solution vectors for G). * The vertices of G are assumed to be labeled from 1 and up (see the * example below). * * Example: * 5 * 0 1 0 0 0 * 1 0 1 0 0 * 0 1 0 1 0 * 0 0 1 0 1 * 0 0 0 1 0 * 1 6 * 2 3 4 4 3 2 * * The example describes a solution to the original version of The Monk Problem * stated by Dilian Gurov, in which a monk is to be found by one pursuer, in a * "chained graph" with 5 vertices as shown below. * (1) <--> (2) <--> (3) <--> (4) <--> (5) * * Run the verifier with javac Verify.java && cat solution.txt | java Verify * * @author Realiserad */ public class Verify { private final int ROWS; private int[][] graph; private int[] w; public static void main(String[] args) { new Verify(); } /** * Constructor suitable for reading graph from System.in. */ public Verify() { Kattio io = new Kattio(System.in); /* Read neighbour matrix */ ROWS = io.getInt(); graph = new int[ROWS][ROWS]; w = new int[ROWS]; for (int row = 0; row < ROWS; row++) { for (int col = 0; col < ROWS; col++) { graph[row][col] = io.getInt() == 0 ? 0 : 1; // 1 means "has edge (col -> row)" if (graph[row][col] == 1) w[row]++; // w[i] should contain Hamming weight for row i } } /* Read solution vectors */ final int P = io.getInt(); final int LEN = io.getInt(); int[][] seed = new int[LEN][P]; for (int col = 0; col < P; col++) { for (int row = 0; row < LEN; row++) { seed[row][col] = io.getInt()-1; // use 0-indexing internally } } /* Save the states for debugging, i.e. can check by hand */ List<int[]> states = new LinkedList<int[]>(); /* Verify solution by iterating the formula s_{n+1}=graph*s_{n}+seed with s_{0} = 0 */ int[] s = expand(seed[0], ROWS); // s_{1} states.add(s); for (int i = 1; i < LEN; i++) { s = radd(rmul(graph, s, w), expand(seed[i], ROWS)); states.add(s); } if (onesOnly(s)) { io.println("YES"); } else { io.println("NO"); } /* Print states */ for (int i = 0; i < states.size(); i++) { io.println("State "+(i+1)+": "); int[] state = states.get(i); for (int j = 0; j < state.length; j++) { io.print(state[j] + " "); } } io.close(); } /** * This constructor is used for repeated verification of different solutions but on the same graph. * Suitable for brute-force solution. * @param g Graph, exception if null */ public Verify(Graph g) { ROWS = g.getVertexCount(); graph = g.getAdjacencyMatrix(); w = new int[ROWS]; for (int row = 0; row < ROWS; row++) { for (int col = 0; col < ROWS; col++) { if (graph[row][col] == 1) w[row]++; // w[i] should contain Hamming weight for row i } } } /** * */ public boolean verify(int p, int len, int[][] seed) { /* Verify solution by iterating the formula s_{n+1}=graph*s_{n}+seed with s_{0} = 0 */ int[] s = expand(seed[0], ROWS); // s_{1} for (int i = 1; i < len; i++) { s = radd(rmul(graph, s, w), expand(seed[i], ROWS)); } return (onesOnly(s)); } /** * Create a binary array with 1 on position p iff seed contains p. */ private int[] expand(int[] seed, int len) { int[] a = new int[len]; for (int i = 0; i < seed.length; i++) a[seed[i]] = 1; return a; } /** * Reduced addition of two column vectors "a" and "b". */ private int[] radd(int[] a, int[] b) { int[] c = new int[a.length]; for (int i = 0; i < a.length; i++) { c[i] = a[i]+b[i]; if (c[i] > 1) c[i] = 1; } return c; } /** * Reduced multiplication of an N x N-matrix "a" with a column vector "b". */ private int[] rmul(int[][] a, int[] b, int[] w) { int[] c = new int[b.length]; for (int row = 0; row < b.length; row++) { for (int i = 0; i < b.length; i++) { c[row] += a[row][i]*b[i]; } if (c[row] > 0) { c[row] = c[row] == w[row] ? 1 : 0; } } return c; } /** * Returns true if all elements in the array are ones. */ private boolean onesOnly(int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] != 1) return false; } return true; } }
src/Verify.java
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Verify a solution to The Monk problem using an EL-system. The solution should contain a * directed graph G consisting of one component, and a set of solution vectors describing the * movement of the pursuers. * * The solution to be checked is read from stdin and the program answers YES or NO to stdout. * * Input format: * Row Data * 0 Should contain the number of rows "r" in the neighbour matrix for G. * 1 to r Should contain the data (separated by space) for the neighbour matrix. * r+1 Should contain two integers separated by space; the number of pursuers "p" * and the length of a solution vector. * r+2 to r+2+p Should contain the movement of the pursuers (solution vectors for G). * The vertices of G are assumed to be labeled from 1 and up (see the * example below). * * Example: * 5 * 0 1 0 0 0 * 1 0 1 0 0 * 0 1 0 1 0 * 0 0 1 0 1 * 0 0 0 1 0 * 1 6 * 2 3 4 4 3 2 * * The example describes a solution to the original version of The Monk Problem * stated by Dilian Gurov, in which a monk is to be found by one pursuer, in a * "chained graph" with 5 vertices as shown below. * (1) <--> (2) <--> (3) <--> (4) <--> (5) * * Run the verifier with javac Verify.java && cat solution.txt | java Verify * * @author Realiserad */ public class Verify { private final int ROWS; private int[][] graph; private int[] w; public static void main(String[] args) { new Verify(); } /** * Constructor suitable for reading graph from System.in. */ public Verify() { Kattio io = new Kattio(System.in); /* Read neighbour matrix */ ROWS = io.getInt(); graph = new int[ROWS][ROWS]; w = new int[ROWS]; for (int row = 0; row < ROWS; row++) { for (int col = 0; col < ROWS; col++) { graph[row][col] = io.getInt() == 0 ? 0 : 1; // 1 means "has edge (col -> row)" if (graph[row][col] == 1) w[row]++; // w[i] should contain Hamming weight for row i } } /* Read solution vectors */ final int P = io.getInt(); final int LEN = io.getInt(); int[][] seed = new int[LEN][P]; for (int col = 0; col < P; col++) { for (int row = 0; row < LEN; row++) { seed[row][col] = io.getInt()-1; // use 0-indexing internally } } /* Verify solution by iterating the formula s_{n+1}=graph*s_{n}+seed with s_{0} = 0 */ int[] s = expand(seed[0], ROWS); // s_{1} for (int i = 1; i < LEN; i++) { s = radd(rmul(graph, s, w), expand(seed[i], ROWS)); } if (onesOnly(s)) { System.out.println("YES"); } else { System.out.println("NO"); } io.close(); } /** * This constructor is used for repeated verification of different solutions but on the same graph. * Suitable for brute-force solution. * @param g Graph, exception if null */ public Verify(Graph g) { ROWS = g.getVertexCount(); graph = g.getAdjacencyMatrix(); w = new int[ROWS]; for (int row = 0; row < ROWS; row++) { for (int col = 0; col < ROWS; col++) { if (graph[row][col] == 1) w[row]++; // w[i] should contain Hamming weight for row i } } } /** * */ public boolean verify(int p, int len, int[][] seed) { /* Verify solution by iterating the formula s_{n+1}=graph*s_{n}+seed with s_{0} = 0 */ int[] s = expand(seed[0], ROWS); // s_{1} for (int i = 1; i < len; i++) { s = radd(rmul(graph, s, w), expand(seed[i], ROWS)); } return (onesOnly(s)); } /** * Create a binary array with 1 on position p iff seed contains p. */ private int[] expand(int[] seed, int len) { int[] a = new int[len]; for (int i = 0; i < seed.length; i++) a[seed[i]] = 1; return a; } /** * Reduced addition of two column vectors "a" and "b". */ private int[] radd(int[] a, int[] b) { int[] c = new int[a.length]; for (int i = 0; i < a.length; i++) { c[i] = a[i]+b[i]; if (c[i] > 1) c[i] = 1; } return c; } /** * Reduced multiplication of an N x N-matrix "a" with a column vector "b". */ private int[] rmul(int[][] a, int[] b, int[] w) { int[] c = new int[b.length]; for (int row = 0; row < b.length; row++) { for (int i = 0; i < b.length; i++) { c[row] += a[row][i]*b[i]; } if (c[row] > 0) { c[row] = c[row] == w[row] ? 1 : 0; } } return c; } /** * Returns true if all elements in the array are ones. */ private boolean onesOnly(int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] != 1) return false; } return true; } }
Saving states and printing in sequence after outputting "YES" or "NO".
src/Verify.java
Saving states and printing in sequence after outputting "YES" or "NO".
<ide><path>rc/Verify.java <ide> import java.io.InputStream; <ide> import java.io.InputStreamReader; <ide> import java.io.PrintWriter; <add>import java.util.LinkedList; <add>import java.util.List; <ide> import java.util.StringTokenizer; <ide> <ide> /** <ide> * directed graph G consisting of one component, and a set of solution vectors describing the <ide> * movement of the pursuers. <ide> * <del> * The solution to be checked is read from stdin and the program answers YES or NO to stdout. <add> * The solution to be checked is read from stdin and the program answers YES or NO to stdout <add> * followed by the states produced in sequence by the solution vectors. <add> * <ide> * <ide> * Input format: <ide> * Row Data <ide> } <ide> } <ide> <add> /* Save the states for debugging, i.e. can check by hand */ <add> List<int[]> states = new LinkedList<int[]>(); <ide> /* Verify solution by iterating the formula s_{n+1}=graph*s_{n}+seed with s_{0} = 0 */ <ide> int[] s = expand(seed[0], ROWS); // s_{1} <add> states.add(s); <ide> for (int i = 1; i < LEN; i++) { <ide> s = radd(rmul(graph, s, w), expand(seed[i], ROWS)); <add> states.add(s); <ide> } <ide> <ide> if (onesOnly(s)) { <del> System.out.println("YES"); <add> io.println("YES"); <ide> } else { <del> System.out.println("NO"); <add> io.println("NO"); <add> } <add> /* Print states */ <add> for (int i = 0; i < states.size(); i++) { <add> io.println("State "+(i+1)+": "); <add> int[] state = states.get(i); <add> for (int j = 0; j < state.length; j++) { <add> io.print(state[j] + " "); <add> } <ide> } <ide> <ide> io.close();
Java
apache-2.0
ea9886395880df963d8a5c78b1d111dacabff4b1
0
ceylon/ceylon-spec,jvasileff/ceylon-spec,jvasileff/ceylon-spec,jvasileff/ceylon-spec,ceylon/ceylon-spec,ceylon/ceylon-spec
package com.redhat.ceylon.compiler.typechecker.analyzer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.cmr.api.VersionComparator; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.ModuleImport; /** * Validate module dependency: * - make sure all modules are available * - get modules from local or remote repos if necessary * - parse and process external modules * * @author Emmanuel Bernard <[email protected]> */ public class ModuleValidator { private final Context context; private List<PhasedUnits> phasedUnitsOfDependencies; private final ModuleManager moduleManager; private Map<Module, ArtifactResult> searchedArtifacts = new HashMap<Module, ArtifactResult>(); public static interface ProgressListener { void retrievingModuleArtifact(Module module, ArtifactContext artifactContext); void resolvingModuleArtifact(Module module, ArtifactResult artifactResult); } private ProgressListener listener = new ProgressListener() { @Override public void resolvingModuleArtifact(Module module, ArtifactResult artifactResult) { } @Override public void retrievingModuleArtifact(Module module, ArtifactContext artifactContext) { } }; public ModuleValidator(Context context, PhasedUnits phasedUnits) { this.context = context; this.moduleManager = phasedUnits.getModuleManager(); } public void setListener (ProgressListener listener) { this.listener = listener; } public List<PhasedUnits> getPhasedUnitsOfDependencies() { return phasedUnitsOfDependencies; } /** * At this stage we need to * - resolve all non local modules (recursively) * - build the object model of these compiled modules * - declare a missing module as an error * - detect circular dependencies * - detect module version conflicts */ public void verifyModuleDependencyTree() { phasedUnitsOfDependencies = new ArrayList<PhasedUnits>(); LinkedList<Module> dependencyTree = new LinkedList<Module>(); // only verify modules we compile (and default/language), as that makes us traverse their dependencies anyways Set<Module> compiledModules = moduleManager.getCompiledModules(); List<Module> modules = new ArrayList<Module>(compiledModules.size()+2); // we must resolve the language module first because it contains definitions that must be in the classpath // before any other JVM class is loaded, including the module descriptor annotations themselves modules.add(context.getModules().getLanguageModule()); modules.add(context.getModules().getDefaultModule()); modules.addAll(compiledModules); for (Module module : modules) { dependencyTree.addLast(module); //we don't care about propagated dependency here as top modules are independent from one another verifyModuleDependencyTree(module.getImports(), dependencyTree, new ArrayList<Module>(), ImportDepth.First, searchedArtifacts); dependencyTree.pollLast(); } moduleManager.addImplicitImports(); executeExternalModulePhases(); } public final long numberOfModulesNotAlreadySearched() { long result = 0; for (Module m : context.getModules().getListOfModules()) { if (! m.isAvailable() && !searchedArtifacts.containsKey(m)) { result ++; } } return result; } public final long numberOfModulesAlreadySearched() { return searchedArtifacts.size(); } /** * Used to represent import links with compiled modules */ private enum ImportDepth { /** * Represents a module directly imported by a compiled module */ First { @Override public ImportDepth forModuleImport(ModuleImport moduleImport) { return Required; } @Override public boolean isVisibleToCompiledModules() { return true; } }, /** * Represents a module indirectly imported by a compiled module, through a chain of exported/shared * modules imported by a module imported directly by a compiled module */ Required { @Override public ImportDepth forModuleImport(ModuleImport moduleImport) { return moduleImport.isExport() ? Required : Transitive; } @Override public boolean isVisibleToCompiledModules() { return true; } }, /** * Represents a module indirectly imported by a compiled module, but not visible to it because * it was not shared/exported to it */ Transitive { @Override public ImportDepth forModuleImport(ModuleImport moduleImport) { return Transitive; } @Override public boolean isVisibleToCompiledModules() { return false; } }; /** * Returns a new ImportDepth for the given module import */ public abstract ImportDepth forModuleImport(ModuleImport moduleImport); /** * Returns true if this import is visible to the compiled modules */ public abstract boolean isVisibleToCompiledModules(); } private void verifyModuleDependencyTree( Collection<ModuleImport> moduleImports, LinkedList<Module> dependencyTree, List<Module> propagatedDependencies, ImportDepth importDepth, Map<Module, ArtifactResult> alreadySearchedArtifacts) { List<Module> visibleDependencies = new ArrayList<Module>(); visibleDependencies.add(dependencyTree.getLast()); //first addition => no possible conflict for (ModuleImport moduleImport : moduleImports) { Module module = moduleImport.getModule(); if (moduleManager.findModule(module, dependencyTree, true) != null) { //circular dependency: stop right here return; } Iterable<String> searchedArtifactExtensions = moduleManager.getSearchedArtifactExtensions(); ImportDepth newImportDepth = importDepth.forModuleImport(moduleImport); if ( ! module.isAvailable()) { ArtifactResult artifact = null; if (alreadySearchedArtifacts.containsKey(module)) { artifact = alreadySearchedArtifacts.get(module); } else { //try and load the module from the repository RepositoryManager repositoryManager = context.getRepositoryManager(); Exception exceptionOnGetArtifact = null; ArtifactContext artifactContext = new ArtifactContext(module.getNameAsString(), module.getVersion(), getArtifactSuffixes(searchedArtifactExtensions)); listener.retrievingModuleArtifact(module, artifactContext); try { artifact = repositoryManager.getArtifactResult(artifactContext); } catch (Exception e) { exceptionOnGetArtifact = catchIfPossible(e); } if (artifact == null) { //not there => error ModuleHelper.buildErrorOnMissingArtifact(artifactContext, module, moduleImport, dependencyTree, exceptionOnGetArtifact, moduleManager); } alreadySearchedArtifacts.put(module, artifact); } if (artifact != null) { //parse module units and build module dependency and carry on boolean forCompiledModule = newImportDepth.isVisibleToCompiledModules(); listener.resolvingModuleArtifact(module, artifact); moduleManager.resolveModule(artifact, module, moduleImport, dependencyTree, phasedUnitsOfDependencies, forCompiledModule); } } dependencyTree.addLast(module); List<Module> subModulePropagatedDependencies = new ArrayList<Module>(); verifyModuleDependencyTree( module.getImports(), dependencyTree, subModulePropagatedDependencies, newImportDepth, alreadySearchedArtifacts); //visible dependency += subModule + subModulePropagatedDependencies checkAndAddDependency(visibleDependencies, module, dependencyTree); for (Module submodule : subModulePropagatedDependencies) { checkAndAddDependency(visibleDependencies, submodule, dependencyTree); } //propagated dependency += if subModule.export then subModule + subModulePropagatedDependencies if (moduleImport.isExport()) { checkAndAddDependency(propagatedDependencies, module, dependencyTree); for (Module submodule : subModulePropagatedDependencies) { checkAndAddDependency(propagatedDependencies, submodule, dependencyTree); } } dependencyTree.pollLast(); } } protected Exception catchIfPossible(Exception e) { return e; } private String[] getArtifactSuffixes(Iterable<String> extensions) { ArrayList<String> suffixes = new ArrayList<String>(); for (String ext : extensions) { suffixes.add("." + ext); } return suffixes.toArray(new String[suffixes.size()]); } private void checkAndAddDependency(List<Module> dependencies, Module module, LinkedList<Module> dependencyTree) { Module dupe = moduleManager.findModule(module, dependencies, false); if (dupe != null && !isSameVersion(module, dupe)) { //TODO improve by giving the dependency string leading to these two conflicting modules StringBuilder error = new StringBuilder("module (transitively) imports conflicting versions of dependency '"); error.append(module.getNameAsString()).append("': "); String[] versions = VersionComparator.orderVersions(module.getVersion(), dupe.getVersion()); error.append("version '").append(versions[0]).append("' and version '").append(versions[1]).append("'"); moduleManager.addErrorToModule(dependencyTree.getFirst(), error.toString()); } else { dependencies.add(module); } } private boolean isSameVersion(Module module, Module dupe) { if (module == null || dupe == null) return false; if (dupe.getVersion() == null) { System.err.println("TypeChecker assertion failure: version should not be null in " + "ModuleValidator.isSameVersion. Please report the issue with a test case"); return false; } return dupe.getVersion().equals(module.getVersion()); } protected void executeExternalModulePhases() { //moduleimport phase already done //Already called from within verifyModuleDependencyTree for (PhasedUnits units : phasedUnitsOfDependencies) { for (PhasedUnit pu : units.getPhasedUnits()) { pu.scanDeclarations(); } } for (PhasedUnits units : phasedUnitsOfDependencies) { for (PhasedUnit pu : units.getPhasedUnits()) { pu.scanTypeDeclarations(); } } for (PhasedUnits units : phasedUnitsOfDependencies) { for (PhasedUnit pu : units.getPhasedUnits()) { pu.validateRefinement(); } } } }
src/com/redhat/ceylon/compiler/typechecker/analyzer/ModuleValidator.java
package com.redhat.ceylon.compiler.typechecker.analyzer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.cmr.api.VersionComparator; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.ModuleImport; /** * Validate module dependency: * - make sure all modules are available * - get modules from local or remote repos if necessary * - parse and process external modules * * @author Emmanuel Bernard <[email protected]> */ public class ModuleValidator { private final Context context; private List<PhasedUnits> phasedUnitsOfDependencies; private final ModuleManager moduleManager; private Map<Module, ArtifactResult> searchedArtifacts = new HashMap<Module, ArtifactResult>(); public static interface ProgressListener { void retrievingModuleArtifact(Module module, ArtifactContext artifactContext); void resolvingModuleArtifact(Module module, ArtifactResult artifactResult); } private ProgressListener listener = new ProgressListener() { @Override public void resolvingModuleArtifact(Module module, ArtifactResult artifactResult) { } @Override public void retrievingModuleArtifact(Module module, ArtifactContext artifactContext) { } }; public ModuleValidator(Context context, PhasedUnits phasedUnits) { this.context = context; this.moduleManager = phasedUnits.getModuleManager(); } public void setListener (ProgressListener listener) { this.listener = listener; } public List<PhasedUnits> getPhasedUnitsOfDependencies() { return phasedUnitsOfDependencies; } /** * At this stage we need to * - resolve all non local modules (recursively) * - build the object model of these compiled modules * - declare a missing module as an error * - detect circular dependencies * - detect module version conflicts */ public void verifyModuleDependencyTree() { phasedUnitsOfDependencies = new ArrayList<PhasedUnits>(); LinkedList<Module> dependencyTree = new LinkedList<Module>(); // only verify modules we compile (and default/language), as that makes us traverse their dependencies anyways Set<Module> compiledModules = moduleManager.getCompiledModules(); List<Module> modules = new ArrayList<Module>(compiledModules.size()+2); modules.addAll(compiledModules); modules.add(context.getModules().getDefaultModule()); modules.add(context.getModules().getLanguageModule()); for (Module module : modules) { dependencyTree.addLast(module); //we don't care about propagated dependency here as top modules are independent from one another verifyModuleDependencyTree(module.getImports(), dependencyTree, new ArrayList<Module>(), ImportDepth.First, searchedArtifacts); dependencyTree.pollLast(); } moduleManager.addImplicitImports(); executeExternalModulePhases(); } public final long numberOfModulesNotAlreadySearched() { long result = 0; for (Module m : context.getModules().getListOfModules()) { if (! m.isAvailable() && !searchedArtifacts.containsKey(m)) { result ++; } } return result; } public final long numberOfModulesAlreadySearched() { return searchedArtifacts.size(); } /** * Used to represent import links with compiled modules */ private enum ImportDepth { /** * Represents a module directly imported by a compiled module */ First { @Override public ImportDepth forModuleImport(ModuleImport moduleImport) { return Required; } @Override public boolean isVisibleToCompiledModules() { return true; } }, /** * Represents a module indirectly imported by a compiled module, through a chain of exported/shared * modules imported by a module imported directly by a compiled module */ Required { @Override public ImportDepth forModuleImport(ModuleImport moduleImport) { return moduleImport.isExport() ? Required : Transitive; } @Override public boolean isVisibleToCompiledModules() { return true; } }, /** * Represents a module indirectly imported by a compiled module, but not visible to it because * it was not shared/exported to it */ Transitive { @Override public ImportDepth forModuleImport(ModuleImport moduleImport) { return Transitive; } @Override public boolean isVisibleToCompiledModules() { return false; } }; /** * Returns a new ImportDepth for the given module import */ public abstract ImportDepth forModuleImport(ModuleImport moduleImport); /** * Returns true if this import is visible to the compiled modules */ public abstract boolean isVisibleToCompiledModules(); } private void verifyModuleDependencyTree( Collection<ModuleImport> moduleImports, LinkedList<Module> dependencyTree, List<Module> propagatedDependencies, ImportDepth importDepth, Map<Module, ArtifactResult> alreadySearchedArtifacts) { List<Module> visibleDependencies = new ArrayList<Module>(); visibleDependencies.add(dependencyTree.getLast()); //first addition => no possible conflict for (ModuleImport moduleImport : moduleImports) { Module module = moduleImport.getModule(); if (moduleManager.findModule(module, dependencyTree, true) != null) { //circular dependency: stop right here return; } Iterable<String> searchedArtifactExtensions = moduleManager.getSearchedArtifactExtensions(); ImportDepth newImportDepth = importDepth.forModuleImport(moduleImport); if ( ! module.isAvailable()) { ArtifactResult artifact = null; if (alreadySearchedArtifacts.containsKey(module)) { artifact = alreadySearchedArtifacts.get(module); } else { //try and load the module from the repository RepositoryManager repositoryManager = context.getRepositoryManager(); Exception exceptionOnGetArtifact = null; ArtifactContext artifactContext = new ArtifactContext(module.getNameAsString(), module.getVersion(), getArtifactSuffixes(searchedArtifactExtensions)); listener.retrievingModuleArtifact(module, artifactContext); try { artifact = repositoryManager.getArtifactResult(artifactContext); } catch (Exception e) { exceptionOnGetArtifact = catchIfPossible(e); } if (artifact == null) { //not there => error ModuleHelper.buildErrorOnMissingArtifact(artifactContext, module, moduleImport, dependencyTree, exceptionOnGetArtifact, moduleManager); } alreadySearchedArtifacts.put(module, artifact); } if (artifact != null) { //parse module units and build module dependency and carry on boolean forCompiledModule = newImportDepth.isVisibleToCompiledModules(); listener.resolvingModuleArtifact(module, artifact); moduleManager.resolveModule(artifact, module, moduleImport, dependencyTree, phasedUnitsOfDependencies, forCompiledModule); } } dependencyTree.addLast(module); List<Module> subModulePropagatedDependencies = new ArrayList<Module>(); verifyModuleDependencyTree( module.getImports(), dependencyTree, subModulePropagatedDependencies, newImportDepth, alreadySearchedArtifacts); //visible dependency += subModule + subModulePropagatedDependencies checkAndAddDependency(visibleDependencies, module, dependencyTree); for (Module submodule : subModulePropagatedDependencies) { checkAndAddDependency(visibleDependencies, submodule, dependencyTree); } //propagated dependency += if subModule.export then subModule + subModulePropagatedDependencies if (moduleImport.isExport()) { checkAndAddDependency(propagatedDependencies, module, dependencyTree); for (Module submodule : subModulePropagatedDependencies) { checkAndAddDependency(propagatedDependencies, submodule, dependencyTree); } } dependencyTree.pollLast(); } } protected Exception catchIfPossible(Exception e) { return e; } private String[] getArtifactSuffixes(Iterable<String> extensions) { ArrayList<String> suffixes = new ArrayList<String>(); for (String ext : extensions) { suffixes.add("." + ext); } return suffixes.toArray(new String[suffixes.size()]); } private void checkAndAddDependency(List<Module> dependencies, Module module, LinkedList<Module> dependencyTree) { Module dupe = moduleManager.findModule(module, dependencies, false); if (dupe != null && !isSameVersion(module, dupe)) { //TODO improve by giving the dependency string leading to these two conflicting modules StringBuilder error = new StringBuilder("module (transitively) imports conflicting versions of dependency '"); error.append(module.getNameAsString()).append("': "); String[] versions = VersionComparator.orderVersions(module.getVersion(), dupe.getVersion()); error.append("version '").append(versions[0]).append("' and version '").append(versions[1]).append("'"); moduleManager.addErrorToModule(dependencyTree.getFirst(), error.toString()); } else { dependencies.add(module); } } private boolean isSameVersion(Module module, Module dupe) { if (module == null || dupe == null) return false; if (dupe.getVersion() == null) { System.err.println("TypeChecker assertion failure: version should not be null in " + "ModuleValidator.isSameVersion. Please report the issue with a test case"); return false; } return dupe.getVersion().equals(module.getVersion()); } protected void executeExternalModulePhases() { //moduleimport phase already done //Already called from within verifyModuleDependencyTree for (PhasedUnits units : phasedUnitsOfDependencies) { for (PhasedUnit pu : units.getPhasedUnits()) { pu.scanDeclarations(); } } for (PhasedUnits units : phasedUnitsOfDependencies) { for (PhasedUnit pu : units.getPhasedUnits()) { pu.scanTypeDeclarations(); } } for (PhasedUnits units : phasedUnitsOfDependencies) { for (PhasedUnit pu : units.getPhasedUnits()) { pu.validateRefinement(); } } } }
ModuleValidator: change the order of module resolving for ceylon/ceylon-compiler#1797 So that the module descriptor annotations are in the classpath before we load any module descriptor
src/com/redhat/ceylon/compiler/typechecker/analyzer/ModuleValidator.java
ModuleValidator: change the order of module resolving for ceylon/ceylon-compiler#1797
<ide><path>rc/com/redhat/ceylon/compiler/typechecker/analyzer/ModuleValidator.java <ide> // only verify modules we compile (and default/language), as that makes us traverse their dependencies anyways <ide> Set<Module> compiledModules = moduleManager.getCompiledModules(); <ide> List<Module> modules = new ArrayList<Module>(compiledModules.size()+2); <add> // we must resolve the language module first because it contains definitions that must be in the classpath <add> // before any other JVM class is loaded, including the module descriptor annotations themselves <add> modules.add(context.getModules().getLanguageModule()); <add> modules.add(context.getModules().getDefaultModule()); <ide> modules.addAll(compiledModules); <del> modules.add(context.getModules().getDefaultModule()); <del> modules.add(context.getModules().getLanguageModule()); <ide> for (Module module : modules) { <ide> dependencyTree.addLast(module); <ide> //we don't care about propagated dependency here as top modules are independent from one another
Java
agpl-3.0
70a0771af68cb6b7772a0cc45e9e26fd3372fb3c
0
bitsquare/bitsquare,bitsquare/bitsquare,bisq-network/exchange,bisq-network/exchange
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.filter; import bisq.network.p2p.storage.payload.ExpirablePayload; import bisq.network.p2p.storage.payload.ProtectedStoragePayload; import bisq.common.crypto.Sig; import bisq.common.proto.ProtoUtil; import bisq.common.util.CollectionUtils; import bisq.common.util.ExtraDataMapValidator; import bisq.common.util.Utilities; import com.google.protobuf.ByteString; import com.google.common.annotations.VisibleForTesting; import java.security.PublicKey; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import lombok.Value; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; @Slf4j @Value public final class Filter implements ProtectedStoragePayload, ExpirablePayload { private final List<String> bannedOfferIds; private final List<String> bannedNodeAddress; private final List<PaymentAccountFilter> bannedPaymentAccounts; private final List<String> bannedCurrencies; private final List<String> bannedPaymentMethods; private final List<String> arbitrators; private final List<String> seedNodes; private final List<String> priceRelayNodes; private final boolean preventPublicBtcNetwork; private final List<String> btcNodes; // SignatureAsBase64 is not set initially as we use the serialized data for signing. We set it after signature is // created by cloning the object with a non-null sig. @Nullable private final String signatureAsBase64; // The pub EC key from the dev who has signed and published the filter (different to ownerPubKeyBytes) private final String signerPubKeyAsHex; // The pub key used for the data protection in the p2p storage private final byte[] ownerPubKeyBytes; private final boolean disableDao; private final String disableDaoBelowVersion; private final String disableTradeBelowVersion; private final List<String> mediators; private final List<String> refundAgents; private final List<String> bannedAccountWitnessSignerPubKeys; private final List<String> btcFeeReceiverAddresses; private final long creationDate; private final List<String> bannedPrivilegedDevPubKeys; // Should be only used in emergency case if we need to add data but do not want to break backward compatibility // at the P2P network storage checks. The hash of the object will be used to verify if the data is valid. Any new // field in a class would break that hash and therefore break the storage mechanism. @Nullable private Map<String, String> extraDataMap; private transient PublicKey ownerPubKey; // added at v1.3.8 private final boolean disableAutoConf; // After we have created the signature from the filter data we clone it and apply the signature static Filter cloneWithSig(Filter filter, String signatureAsBase64) { return new Filter(filter.getBannedOfferIds(), filter.getBannedNodeAddress(), filter.getBannedPaymentAccounts(), filter.getBannedCurrencies(), filter.getBannedPaymentMethods(), filter.getArbitrators(), filter.getSeedNodes(), filter.getPriceRelayNodes(), filter.isPreventPublicBtcNetwork(), filter.getBtcNodes(), filter.isDisableDao(), filter.getDisableDaoBelowVersion(), filter.getDisableTradeBelowVersion(), filter.getMediators(), filter.getRefundAgents(), filter.getBannedAccountWitnessSignerPubKeys(), filter.getBtcFeeReceiverAddresses(), filter.getOwnerPubKeyBytes(), filter.getCreationDate(), filter.getExtraDataMap(), signatureAsBase64, filter.getSignerPubKeyAsHex(), filter.getBannedPrivilegedDevPubKeys(), filter.isDisableAutoConf()); } // Used for signature verification as we created the sig without the signatureAsBase64 field we set it to null again static Filter cloneWithoutSig(Filter filter) { return new Filter(filter.getBannedOfferIds(), filter.getBannedNodeAddress(), filter.getBannedPaymentAccounts(), filter.getBannedCurrencies(), filter.getBannedPaymentMethods(), filter.getArbitrators(), filter.getSeedNodes(), filter.getPriceRelayNodes(), filter.isPreventPublicBtcNetwork(), filter.getBtcNodes(), filter.isDisableDao(), filter.getDisableDaoBelowVersion(), filter.getDisableTradeBelowVersion(), filter.getMediators(), filter.getRefundAgents(), filter.getBannedAccountWitnessSignerPubKeys(), filter.getBtcFeeReceiverAddresses(), filter.getOwnerPubKeyBytes(), filter.getCreationDate(), filter.getExtraDataMap(), null, filter.getSignerPubKeyAsHex(), filter.getBannedPrivilegedDevPubKeys(), filter.isDisableAutoConf()); } public Filter(List<String> bannedOfferIds, List<String> bannedNodeAddress, List<PaymentAccountFilter> bannedPaymentAccounts, List<String> bannedCurrencies, List<String> bannedPaymentMethods, List<String> arbitrators, List<String> seedNodes, List<String> priceRelayNodes, boolean preventPublicBtcNetwork, List<String> btcNodes, boolean disableDao, String disableDaoBelowVersion, String disableTradeBelowVersion, List<String> mediators, List<String> refundAgents, List<String> bannedAccountWitnessSignerPubKeys, List<String> btcFeeReceiverAddresses, PublicKey ownerPubKey, String signerPubKeyAsHex, List<String> bannedPrivilegedDevPubKeys, boolean disableAutoConf) { this(bannedOfferIds, bannedNodeAddress, bannedPaymentAccounts, bannedCurrencies, bannedPaymentMethods, arbitrators, seedNodes, priceRelayNodes, preventPublicBtcNetwork, btcNodes, disableDao, disableDaoBelowVersion, disableTradeBelowVersion, mediators, refundAgents, bannedAccountWitnessSignerPubKeys, btcFeeReceiverAddresses, Sig.getPublicKeyBytes(ownerPubKey), System.currentTimeMillis(), null, null, signerPubKeyAsHex, bannedPrivilegedDevPubKeys, disableAutoConf); } /////////////////////////////////////////////////////////////////////////////////////////// // PROTO BUFFER /////////////////////////////////////////////////////////////////////////////////////////// @VisibleForTesting public Filter(List<String> bannedOfferIds, List<String> bannedNodeAddress, List<PaymentAccountFilter> bannedPaymentAccounts, List<String> bannedCurrencies, List<String> bannedPaymentMethods, List<String> arbitrators, List<String> seedNodes, List<String> priceRelayNodes, boolean preventPublicBtcNetwork, List<String> btcNodes, boolean disableDao, String disableDaoBelowVersion, String disableTradeBelowVersion, List<String> mediators, List<String> refundAgents, List<String> bannedAccountWitnessSignerPubKeys, List<String> btcFeeReceiverAddresses, byte[] ownerPubKeyBytes, long creationDate, @Nullable Map<String, String> extraDataMap, @Nullable String signatureAsBase64, String signerPubKeyAsHex, List<String> bannedPrivilegedDevPubKeys, boolean disableAutoConf) { this.bannedOfferIds = bannedOfferIds; this.bannedNodeAddress = bannedNodeAddress; this.bannedPaymentAccounts = bannedPaymentAccounts; this.bannedCurrencies = bannedCurrencies; this.bannedPaymentMethods = bannedPaymentMethods; this.arbitrators = arbitrators; this.seedNodes = seedNodes; this.priceRelayNodes = priceRelayNodes; this.preventPublicBtcNetwork = preventPublicBtcNetwork; this.btcNodes = btcNodes; this.disableDao = disableDao; this.disableDaoBelowVersion = disableDaoBelowVersion; this.disableTradeBelowVersion = disableTradeBelowVersion; this.mediators = mediators; this.refundAgents = refundAgents; this.bannedAccountWitnessSignerPubKeys = bannedAccountWitnessSignerPubKeys; this.btcFeeReceiverAddresses = btcFeeReceiverAddresses; this.ownerPubKeyBytes = ownerPubKeyBytes; this.creationDate = creationDate; this.extraDataMap = ExtraDataMapValidator.getValidatedExtraDataMap(extraDataMap); this.signatureAsBase64 = signatureAsBase64; this.signerPubKeyAsHex = signerPubKeyAsHex; this.bannedPrivilegedDevPubKeys = bannedPrivilegedDevPubKeys; this.disableAutoConf = disableAutoConf; // ownerPubKeyBytes can be null when called from tests if (ownerPubKeyBytes != null) { ownerPubKey = Sig.getPublicKeyFromBytes(ownerPubKeyBytes); } else { ownerPubKey = null; } } @Override public protobuf.StoragePayload toProtoMessage() { List<protobuf.PaymentAccountFilter> paymentAccountFilterList = bannedPaymentAccounts.stream() .map(PaymentAccountFilter::toProtoMessage) .collect(Collectors.toList()); protobuf.Filter.Builder builder = protobuf.Filter.newBuilder().addAllBannedOfferIds(bannedOfferIds) .addAllBannedNodeAddress(bannedNodeAddress) .addAllBannedPaymentAccounts(paymentAccountFilterList) .addAllBannedCurrencies(bannedCurrencies) .addAllBannedPaymentMethods(bannedPaymentMethods) .addAllArbitrators(arbitrators) .addAllSeedNodes(seedNodes) .addAllPriceRelayNodes(priceRelayNodes) .setPreventPublicBtcNetwork(preventPublicBtcNetwork) .addAllBtcNodes(btcNodes) .setDisableDao(disableDao) .setDisableDaoBelowVersion(disableDaoBelowVersion) .setDisableTradeBelowVersion(disableTradeBelowVersion) .addAllMediators(mediators) .addAllRefundAgents(refundAgents) .addAllBannedSignerPubKeys(bannedAccountWitnessSignerPubKeys) .addAllBtcFeeReceiverAddresses(btcFeeReceiverAddresses) .setOwnerPubKeyBytes(ByteString.copyFrom(ownerPubKeyBytes)) .setSignerPubKeyAsHex(signerPubKeyAsHex) .setCreationDate(creationDate) .addAllBannedPrivilegedDevPubKeys(bannedPrivilegedDevPubKeys) .setDisableAutoConf(disableAutoConf); Optional.ofNullable(signatureAsBase64).ifPresent(builder::setSignatureAsBase64); Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData); return protobuf.StoragePayload.newBuilder().setFilter(builder).build(); } public static Filter fromProto(protobuf.Filter proto) { List<PaymentAccountFilter> bannedPaymentAccountsList = proto.getBannedPaymentAccountsList().stream() .map(PaymentAccountFilter::fromProto) .collect(Collectors.toList()); return new Filter(ProtoUtil.protocolStringListToList(proto.getBannedOfferIdsList()), ProtoUtil.protocolStringListToList(proto.getBannedNodeAddressList()), bannedPaymentAccountsList, ProtoUtil.protocolStringListToList(proto.getBannedCurrenciesList()), ProtoUtil.protocolStringListToList(proto.getBannedPaymentMethodsList()), ProtoUtil.protocolStringListToList(proto.getArbitratorsList()), ProtoUtil.protocolStringListToList(proto.getSeedNodesList()), ProtoUtil.protocolStringListToList(proto.getPriceRelayNodesList()), proto.getPreventPublicBtcNetwork(), ProtoUtil.protocolStringListToList(proto.getBtcNodesList()), proto.getDisableDao(), proto.getDisableDaoBelowVersion(), proto.getDisableTradeBelowVersion(), ProtoUtil.protocolStringListToList(proto.getMediatorsList()), ProtoUtil.protocolStringListToList(proto.getRefundAgentsList()), ProtoUtil.protocolStringListToList(proto.getBannedSignerPubKeysList()), ProtoUtil.protocolStringListToList(proto.getBtcFeeReceiverAddressesList()), proto.getOwnerPubKeyBytes().toByteArray(), proto.getCreationDate(), CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap(), proto.getSignatureAsBase64(), proto.getSignerPubKeyAsHex(), ProtoUtil.protocolStringListToList(proto.getBannedPrivilegedDevPubKeysList()), proto.getDisableAutoConf() ); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// @Override public long getTTL() { return TimeUnit.DAYS.toMillis(180); } @Override public String toString() { return "Filter{" + "\n bannedOfferIds=" + bannedOfferIds + ",\n bannedNodeAddress=" + bannedNodeAddress + ",\n bannedPaymentAccounts=" + bannedPaymentAccounts + ",\n bannedCurrencies=" + bannedCurrencies + ",\n bannedPaymentMethods=" + bannedPaymentMethods + ",\n arbitrators=" + arbitrators + ",\n seedNodes=" + seedNodes + ",\n priceRelayNodes=" + priceRelayNodes + ",\n preventPublicBtcNetwork=" + preventPublicBtcNetwork + ",\n btcNodes=" + btcNodes + ",\n signatureAsBase64='" + signatureAsBase64 + '\'' + ",\n signerPubKeyAsHex='" + signerPubKeyAsHex + '\'' + ",\n ownerPubKeyBytes=" + Utilities.bytesAsHexString(ownerPubKeyBytes) + ",\n disableDao=" + disableDao + ",\n disableDaoBelowVersion='" + disableDaoBelowVersion + '\'' + ",\n disableTradeBelowVersion='" + disableTradeBelowVersion + '\'' + ",\n mediators=" + mediators + ",\n refundAgents=" + refundAgents + ",\n bannedAccountWitnessSignerPubKeys=" + bannedAccountWitnessSignerPubKeys + ",\n bannedPrivilegedDevPubKeys=" + bannedPrivilegedDevPubKeys + ",\n btcFeeReceiverAddresses=" + btcFeeReceiverAddresses + ",\n creationDate=" + creationDate + ",\n extraDataMap=" + extraDataMap + ",\n disableAutoConf=" + disableAutoConf + "\n}"; } }
core/src/main/java/bisq/core/filter/Filter.java
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.filter; import bisq.network.p2p.storage.payload.ExpirablePayload; import bisq.network.p2p.storage.payload.ProtectedStoragePayload; import bisq.common.crypto.Sig; import bisq.common.proto.ProtoUtil; import bisq.common.util.CollectionUtils; import bisq.common.util.ExtraDataMapValidator; import bisq.common.util.Utilities; import com.google.protobuf.ByteString; import com.google.common.annotations.VisibleForTesting; import java.security.PublicKey; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import lombok.Value; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; @Slf4j @Value public final class Filter implements ProtectedStoragePayload, ExpirablePayload { private final List<String> bannedOfferIds; private final List<String> bannedNodeAddress; private final List<PaymentAccountFilter> bannedPaymentAccounts; private final List<String> bannedCurrencies; private final List<String> bannedPaymentMethods; private final List<String> arbitrators; private final List<String> seedNodes; private final List<String> priceRelayNodes; private final boolean preventPublicBtcNetwork; private final List<String> btcNodes; // SignatureAsBase64 is not set initially as we use the serialized data for signing. We set it after signature is // created by cloning the object with a non-null sig. @Nullable private final String signatureAsBase64; // The pub EC key from the dev who has signed and published the filter (different to ownerPubKeyBytes) private final String signerPubKeyAsHex; // The pub key used for the data protection in the p2p storage private final byte[] ownerPubKeyBytes; private final boolean disableDao; private final String disableDaoBelowVersion; private final String disableTradeBelowVersion; private final List<String> mediators; private final List<String> refundAgents; private final List<String> bannedAccountWitnessSignerPubKeys; private final List<String> btcFeeReceiverAddresses; private final long creationDate; private final List<String> bannedPrivilegedDevPubKeys; // Should be only used in emergency case if we need to add data but do not want to break backward compatibility // at the P2P network storage checks. The hash of the object will be used to verify if the data is valid. Any new // field in a class would break that hash and therefore break the storage mechanism. @Nullable private Map<String, String> extraDataMap; private transient PublicKey ownerPubKey; // added at v1.3.8 private final boolean disableAutoConf; // After we have created the signature from the filter data we clone it and apply the signature static Filter cloneWithSig(Filter filter, String signatureAsBase64) { return new Filter(filter.getBannedOfferIds(), filter.getBannedNodeAddress(), filter.getBannedPaymentAccounts(), filter.getBannedCurrencies(), filter.getBannedPaymentMethods(), filter.getArbitrators(), filter.getSeedNodes(), filter.getPriceRelayNodes(), filter.isPreventPublicBtcNetwork(), filter.getBtcNodes(), filter.isDisableDao(), filter.getDisableDaoBelowVersion(), filter.getDisableTradeBelowVersion(), filter.getMediators(), filter.getRefundAgents(), filter.getBannedAccountWitnessSignerPubKeys(), filter.getBtcFeeReceiverAddresses(), filter.getOwnerPubKeyBytes(), filter.getCreationDate(), filter.getExtraDataMap(), signatureAsBase64, filter.getSignerPubKeyAsHex(), filter.getBannedPrivilegedDevPubKeys(), filter.isDisableAutoConf()); } // Used for signature verification as we created the sig without the signatureAsBase64 field we set it to null again static Filter cloneWithoutSig(Filter filter) { return new Filter(filter.getBannedOfferIds(), filter.getBannedNodeAddress(), filter.getBannedPaymentAccounts(), filter.getBannedCurrencies(), filter.getBannedPaymentMethods(), filter.getArbitrators(), filter.getSeedNodes(), filter.getPriceRelayNodes(), filter.isPreventPublicBtcNetwork(), filter.getBtcNodes(), filter.isDisableDao(), filter.getDisableDaoBelowVersion(), filter.getDisableTradeBelowVersion(), filter.getMediators(), filter.getRefundAgents(), filter.getBannedAccountWitnessSignerPubKeys(), filter.getBtcFeeReceiverAddresses(), filter.getOwnerPubKeyBytes(), filter.getCreationDate(), filter.getExtraDataMap(), null, filter.getSignerPubKeyAsHex(), filter.getBannedPrivilegedDevPubKeys(), filter.isDisableAutoConf()); } public Filter(List<String> bannedOfferIds, List<String> bannedNodeAddress, List<PaymentAccountFilter> bannedPaymentAccounts, List<String> bannedCurrencies, List<String> bannedPaymentMethods, List<String> arbitrators, List<String> seedNodes, List<String> priceRelayNodes, boolean preventPublicBtcNetwork, List<String> btcNodes, boolean disableDao, String disableDaoBelowVersion, String disableTradeBelowVersion, List<String> mediators, List<String> refundAgents, List<String> bannedAccountWitnessSignerPubKeys, List<String> btcFeeReceiverAddresses, PublicKey ownerPubKey, String signerPubKeyAsHex, List<String> bannedPrivilegedDevPubKeys, boolean disableAutoConf) { this(bannedOfferIds, bannedNodeAddress, bannedPaymentAccounts, bannedCurrencies, bannedPaymentMethods, arbitrators, seedNodes, priceRelayNodes, preventPublicBtcNetwork, btcNodes, disableDao, disableDaoBelowVersion, disableTradeBelowVersion, mediators, refundAgents, bannedAccountWitnessSignerPubKeys, btcFeeReceiverAddresses, Sig.getPublicKeyBytes(ownerPubKey), System.currentTimeMillis(), null, null, signerPubKeyAsHex, bannedPrivilegedDevPubKeys, disableAutoConf); } /////////////////////////////////////////////////////////////////////////////////////////// // PROTO BUFFER /////////////////////////////////////////////////////////////////////////////////////////// @VisibleForTesting public Filter(List<String> bannedOfferIds, List<String> bannedNodeAddress, List<PaymentAccountFilter> bannedPaymentAccounts, List<String> bannedCurrencies, List<String> bannedPaymentMethods, List<String> arbitrators, List<String> seedNodes, List<String> priceRelayNodes, boolean preventPublicBtcNetwork, List<String> btcNodes, boolean disableDao, String disableDaoBelowVersion, String disableTradeBelowVersion, List<String> mediators, List<String> refundAgents, List<String> bannedAccountWitnessSignerPubKeys, List<String> btcFeeReceiverAddresses, byte[] ownerPubKeyBytes, long creationDate, @Nullable Map<String, String> extraDataMap, @Nullable String signatureAsBase64, String signerPubKeyAsHex, List<String> bannedPrivilegedDevPubKeys, boolean disableAutoConf) { this.bannedOfferIds = bannedOfferIds; this.bannedNodeAddress = bannedNodeAddress; this.bannedPaymentAccounts = bannedPaymentAccounts; this.bannedCurrencies = bannedCurrencies; this.bannedPaymentMethods = bannedPaymentMethods; this.arbitrators = arbitrators; this.seedNodes = seedNodes; this.priceRelayNodes = priceRelayNodes; this.preventPublicBtcNetwork = preventPublicBtcNetwork; this.btcNodes = btcNodes; this.disableDao = disableDao; this.disableDaoBelowVersion = disableDaoBelowVersion; this.disableTradeBelowVersion = disableTradeBelowVersion; this.mediators = mediators; this.refundAgents = refundAgents; this.bannedAccountWitnessSignerPubKeys = bannedAccountWitnessSignerPubKeys; this.btcFeeReceiverAddresses = btcFeeReceiverAddresses; this.disableAutoConf = disableAutoConf; this.ownerPubKeyBytes = ownerPubKeyBytes; this.creationDate = creationDate; this.extraDataMap = ExtraDataMapValidator.getValidatedExtraDataMap(extraDataMap); this.signatureAsBase64 = signatureAsBase64; this.signerPubKeyAsHex = signerPubKeyAsHex; this.bannedPrivilegedDevPubKeys = bannedPrivilegedDevPubKeys; // ownerPubKeyBytes can be null when called from tests if (ownerPubKeyBytes != null) { ownerPubKey = Sig.getPublicKeyFromBytes(ownerPubKeyBytes); } else { ownerPubKey = null; } } @Override public protobuf.StoragePayload toProtoMessage() { List<protobuf.PaymentAccountFilter> paymentAccountFilterList = bannedPaymentAccounts.stream() .map(PaymentAccountFilter::toProtoMessage) .collect(Collectors.toList()); protobuf.Filter.Builder builder = protobuf.Filter.newBuilder().addAllBannedOfferIds(bannedOfferIds) .addAllBannedNodeAddress(bannedNodeAddress) .addAllBannedPaymentAccounts(paymentAccountFilterList) .addAllBannedCurrencies(bannedCurrencies) .addAllBannedPaymentMethods(bannedPaymentMethods) .addAllArbitrators(arbitrators) .addAllSeedNodes(seedNodes) .addAllPriceRelayNodes(priceRelayNodes) .setPreventPublicBtcNetwork(preventPublicBtcNetwork) .addAllBtcNodes(btcNodes) .setDisableDao(disableDao) .setDisableDaoBelowVersion(disableDaoBelowVersion) .setDisableTradeBelowVersion(disableTradeBelowVersion) .addAllMediators(mediators) .addAllRefundAgents(refundAgents) .addAllBannedSignerPubKeys(bannedAccountWitnessSignerPubKeys) .addAllBtcFeeReceiverAddresses(btcFeeReceiverAddresses) .setOwnerPubKeyBytes(ByteString.copyFrom(ownerPubKeyBytes)) .setSignerPubKeyAsHex(signerPubKeyAsHex) .setCreationDate(creationDate) .addAllBannedPrivilegedDevPubKeys(bannedPrivilegedDevPubKeys) .setDisableAutoConf(disableAutoConf); Optional.ofNullable(signatureAsBase64).ifPresent(builder::setSignatureAsBase64); Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData); return protobuf.StoragePayload.newBuilder().setFilter(builder).build(); } public static Filter fromProto(protobuf.Filter proto) { List<PaymentAccountFilter> bannedPaymentAccountsList = proto.getBannedPaymentAccountsList().stream() .map(PaymentAccountFilter::fromProto) .collect(Collectors.toList()); return new Filter(ProtoUtil.protocolStringListToList(proto.getBannedOfferIdsList()), ProtoUtil.protocolStringListToList(proto.getBannedNodeAddressList()), bannedPaymentAccountsList, ProtoUtil.protocolStringListToList(proto.getBannedCurrenciesList()), ProtoUtil.protocolStringListToList(proto.getBannedPaymentMethodsList()), ProtoUtil.protocolStringListToList(proto.getArbitratorsList()), ProtoUtil.protocolStringListToList(proto.getSeedNodesList()), ProtoUtil.protocolStringListToList(proto.getPriceRelayNodesList()), proto.getPreventPublicBtcNetwork(), ProtoUtil.protocolStringListToList(proto.getBtcNodesList()), proto.getDisableDao(), proto.getDisableDaoBelowVersion(), proto.getDisableTradeBelowVersion(), ProtoUtil.protocolStringListToList(proto.getMediatorsList()), ProtoUtil.protocolStringListToList(proto.getRefundAgentsList()), ProtoUtil.protocolStringListToList(proto.getBannedSignerPubKeysList()), ProtoUtil.protocolStringListToList(proto.getBtcFeeReceiverAddressesList()), proto.getOwnerPubKeyBytes().toByteArray(), proto.getCreationDate(), CollectionUtils.isEmpty(proto.getExtraDataMap()) ? null : proto.getExtraDataMap(), proto.getSignatureAsBase64(), proto.getSignerPubKeyAsHex(), ProtoUtil.protocolStringListToList(proto.getBannedPrivilegedDevPubKeysList()), proto.getDisableAutoConf() ); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// @Override public long getTTL() { return TimeUnit.DAYS.toMillis(180); } @Override public String toString() { return "Filter{" + "\n bannedOfferIds=" + bannedOfferIds + ",\n bannedNodeAddress=" + bannedNodeAddress + ",\n bannedPaymentAccounts=" + bannedPaymentAccounts + ",\n bannedCurrencies=" + bannedCurrencies + ",\n bannedPaymentMethods=" + bannedPaymentMethods + ",\n arbitrators=" + arbitrators + ",\n seedNodes=" + seedNodes + ",\n priceRelayNodes=" + priceRelayNodes + ",\n preventPublicBtcNetwork=" + preventPublicBtcNetwork + ",\n btcNodes=" + btcNodes + ",\n signatureAsBase64='" + signatureAsBase64 + '\'' + ",\n signerPubKeyAsHex='" + signerPubKeyAsHex + '\'' + ",\n ownerPubKeyBytes=" + Utilities.bytesAsHexString(ownerPubKeyBytes) + ",\n disableDao=" + disableDao + ",\n disableDaoBelowVersion='" + disableDaoBelowVersion + '\'' + ",\n disableTradeBelowVersion='" + disableTradeBelowVersion + '\'' + ",\n mediators=" + mediators + ",\n refundAgents=" + refundAgents + ",\n bannedAccountWitnessSignerPubKeys=" + bannedAccountWitnessSignerPubKeys + ",\n bannedPrivilegedDevPubKeys=" + bannedPrivilegedDevPubKeys + ",\n btcFeeReceiverAddresses=" + btcFeeReceiverAddresses + ",\n disableAutoConf=" + disableAutoConf + ",\n creationDate=" + creationDate + ",\n extraDataMap=" + extraDataMap + "\n}"; } }
Code style: Improve order of fields
core/src/main/java/bisq/core/filter/Filter.java
Code style: Improve order of fields
<ide><path>ore/src/main/java/bisq/core/filter/Filter.java <ide> this.refundAgents = refundAgents; <ide> this.bannedAccountWitnessSignerPubKeys = bannedAccountWitnessSignerPubKeys; <ide> this.btcFeeReceiverAddresses = btcFeeReceiverAddresses; <del> this.disableAutoConf = disableAutoConf; <ide> this.ownerPubKeyBytes = ownerPubKeyBytes; <ide> this.creationDate = creationDate; <ide> this.extraDataMap = ExtraDataMapValidator.getValidatedExtraDataMap(extraDataMap); <ide> this.signatureAsBase64 = signatureAsBase64; <ide> this.signerPubKeyAsHex = signerPubKeyAsHex; <ide> this.bannedPrivilegedDevPubKeys = bannedPrivilegedDevPubKeys; <add> this.disableAutoConf = disableAutoConf; <ide> <ide> // ownerPubKeyBytes can be null when called from tests <ide> if (ownerPubKeyBytes != null) { <ide> ",\n bannedAccountWitnessSignerPubKeys=" + bannedAccountWitnessSignerPubKeys + <ide> ",\n bannedPrivilegedDevPubKeys=" + bannedPrivilegedDevPubKeys + <ide> ",\n btcFeeReceiverAddresses=" + btcFeeReceiverAddresses + <del> ",\n disableAutoConf=" + disableAutoConf + <ide> ",\n creationDate=" + creationDate + <ide> ",\n extraDataMap=" + extraDataMap + <add> ",\n disableAutoConf=" + disableAutoConf + <ide> "\n}"; <ide> } <ide> }
JavaScript
mit
3f6e7d785bcad99d30017b593a873766011e00d1
0
6pac/SlickGrid,6pac/SlickGrid
/** * @license * (c) 2009-2016 Michael Leibman * michael{dot}leibman{at}gmail{dot}com * http://github.com/mleibman/slickgrid * * Distributed under MIT license. * All rights reserved. * * SlickGrid v2.4 * * NOTES: * Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods. * This increases the speed dramatically, but can only be done safely because there are no event handlers * or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy() * and do proper cleanup. */ // make sure required JavaScript modules are loaded if (typeof jQuery === "undefined") { throw new Error("SlickGrid requires jquery module to be loaded"); } if (!jQuery.fn.drag) { throw new Error("SlickGrid requires jquery.event.drag module to be loaded"); } if (typeof Slick === "undefined") { throw new Error("slick.core.js not loaded"); } (function ($) { "use strict"; // shared across all grids on the page var scrollbarDimensions; var maxSupportedCssHeight; // browser's breaking point ////////////////////////////////////////////////////////////////////////////////////////////// // SlickGrid class implementation (available as Slick.Grid) /** * Creates a new instance of the grid. * @class SlickGrid * @constructor * @param {Node} container Container node to create the grid in. * @param {Array,Object} data An array of objects for databinding. * @param {Array} columns An array of column definitions. * @param {Object} options Grid options. **/ function SlickGrid(container, data, columns, options) { // settings var defaults = { alwaysShowVerticalScroll: false, alwaysAllowHorizontalScroll: false, explicitInitialization: false, rowHeight: 25, defaultColumnWidth: 80, enableAddRow: false, leaveSpaceForNewRows: false, editable: false, autoEdit: true, suppressActiveCellChangeOnEdit: false, enableCellNavigation: true, enableColumnReorder: true, asyncEditorLoading: false, asyncEditorLoadDelay: 100, forceFitColumns: false, enableAsyncPostRender: false, asyncPostRenderDelay: 50, enableAsyncPostRenderCleanup: false, asyncPostRenderCleanupDelay: 40, autoHeight: false, editorLock: Slick.GlobalEditorLock, showColumnHeader: true, showHeaderRow: false, headerRowHeight: 25, createFooterRow: false, showFooterRow: false, footerRowHeight: 25, createPreHeaderPanel: false, showPreHeaderPanel: false, preHeaderPanelHeight: 25, showTopPanel: false, topPanelHeight: 25, formatterFactory: null, editorFactory: null, cellFlashingCssClass: "flashing", selectedCellCssClass: "selected", multiSelect: true, enableTextSelectionOnCells: false, dataItemColumnValueExtractor: null, frozenBottom: false, frozenColumn: -1, frozenRow: -1, fullWidthRows: false, multiColumnSort: false, numberedMultiColumnSort: false, tristateMultiColumnSort: false, sortColNumberInSeparateSpan: false, defaultFormatter: defaultFormatter, forceSyncScrolling: false, addNewRowCssClass: "new-row", preserveCopiedSelectionOnPaste: false, showCellSelection: true, viewportClass: null, minRowBuffer: 3, emulatePagingWhenScrolling: true, // when scrolling off bottom of viewport, place new row at top of viewport editorCellNavOnLRKeys: false, enableMouseWheelScrollHandler: true, doPaging: true, autosizeColsMode: Slick.GridAutosizeColsMode.LegacyOff, autosizeColPaddingPx: 4, autosizeTextAvgToMWidthRatio: 0.75, viewportSwitchToScrollModeWidthPercent: undefined, viewportMinWidthPx: undefined, viewportMaxWidthPx: undefined, suppressCssChangesOnHiddenInit: false }; var columnDefaults = { name: "", resizable: true, sortable: false, minWidth: 30, maxWidth: undefined, rerenderOnResize: false, headerCssClass: null, defaultSortAsc: true, focusable: true, selectable: true, }; var columnAutosizeDefaults = { ignoreHeaderText: false, colValueArray: undefined, allowAddlPercent: undefined, formatterOverride: undefined, autosizeMode: Slick.ColAutosizeMode.ContentIntelligent, rowSelectionModeOnInit: undefined, rowSelectionMode: Slick.RowSelectionMode.FirstNRows, rowSelectionCount: 100, valueFilterMode: Slick.ValueFilterMode.None, widthEvalMode: Slick.WidthEvalMode.CanvasTextSize, sizeToRemaining: undefined, widthPx: undefined, colDataTypeOf: undefined }; // scroller var th; // virtual height var h; // real scrollable height var ph; // page height var n; // number of pages var cj; // "jumpiness" coefficient var page = 0; // current page var offset = 0; // current page offset var vScrollDir = 1; // private var initialized = false; var $container; var uid = "slickgrid_" + Math.round(1000000 * Math.random()); var self = this; var $focusSink, $focusSink2; var $groupHeaders = $(); var $headerScroller; var $headers; var $headerRow, $headerRowScroller, $headerRowSpacerL, $headerRowSpacerR; var $footerRow, $footerRowScroller, $footerRowSpacerL, $footerRowSpacerR; var $preHeaderPanel, $preHeaderPanelScroller, $preHeaderPanelSpacer; var $preHeaderPanelR, $preHeaderPanelScrollerR, $preHeaderPanelSpacerR; var $topPanelScroller; var $topPanel; var $viewport; var $canvas; var $style; var $boundAncestors; var treeColumns; var stylesheet, columnCssRulesL, columnCssRulesR; var viewportH, viewportW; var canvasWidth, canvasWidthL, canvasWidthR; var headersWidth, headersWidthL, headersWidthR; var viewportHasHScroll, viewportHasVScroll; var headerColumnWidthDiff = 0, headerColumnHeightDiff = 0, // border+padding cellWidthDiff = 0, cellHeightDiff = 0, jQueryNewWidthBehaviour = false; var absoluteColumnMinWidth; var hasFrozenRows = false; var frozenRowsHeight = 0; var actualFrozenRow = -1; var paneTopH = 0; var paneBottomH = 0; var viewportTopH = 0; var viewportBottomH = 0; var topPanelH = 0; var headerRowH = 0; var footerRowH = 0; var tabbingDirection = 1; var $activeCanvasNode; var $activeViewportNode; var activePosX; var activeRow, activeCell; var activeCellNode = null; var currentEditor = null; var serializedEditorValue; var editController; var rowsCache = {}; var renderedRows = 0; var numVisibleRows = 0; var prevScrollTop = 0; var scrollTop = 0; var lastRenderedScrollTop = 0; var lastRenderedScrollLeft = 0; var prevScrollLeft = 0; var scrollLeft = 0; var selectionModel; var selectedRows = []; var plugins = []; var cellCssClasses = {}; var columnsById = {}; var sortColumns = []; var columnPosLeft = []; var columnPosRight = []; var pagingActive = false; var pagingIsLastPage = false; var scrollThrottle = ActionThrottle(render, 50); // async call handles var h_editorLoader = null; var h_render = null; var h_postrender = null; var h_postrenderCleanup = null; var postProcessedRows = {}; var postProcessToRow = null; var postProcessFromRow = null; var postProcessedCleanupQueue = []; var postProcessgroupId = 0; // perf counters var counter_rows_rendered = 0; var counter_rows_removed = 0; // These two variables work around a bug with inertial scrolling in Webkit/Blink on Mac. // See http://crbug.com/312427. var rowNodeFromLastMouseWheelEvent; // this node must not be deleted while inertial scrolling var zombieRowNodeFromLastMouseWheelEvent; // node that was hidden instead of getting deleted var zombieRowCacheFromLastMouseWheelEvent; // row cache for above node var zombieRowPostProcessedFromLastMouseWheelEvent; // post processing references for above node var $paneHeaderL; var $paneHeaderR; var $paneTopL; var $paneTopR; var $paneBottomL; var $paneBottomR; var $headerScrollerL; var $headerScrollerR; var $headerL; var $headerR; var $groupHeadersL; var $groupHeadersR; var $headerRowScrollerL; var $headerRowScrollerR; var $footerRowScrollerL; var $footerRowScrollerR; var $headerRowL; var $headerRowR; var $footerRowL; var $footerRowR; var $topPanelScrollerL; var $topPanelScrollerR; var $topPanelL; var $topPanelR; var $viewportTopL; var $viewportTopR; var $viewportBottomL; var $viewportBottomR; var $canvasTopL; var $canvasTopR; var $canvasBottomL; var $canvasBottomR; var $viewportScrollContainerX; var $viewportScrollContainerY; var $headerScrollContainer; var $headerRowScrollContainer; var $footerRowScrollContainer; // store css attributes if display:none is active in container or parent var cssShow = { position: 'absolute', visibility: 'hidden', display: 'block' }; var $hiddenParents; var oldProps = []; var columnResizeDragging = false; ////////////////////////////////////////////////////////////////////////////////////////////// // Initialization function init() { if (container instanceof jQuery) { $container = container; } else { $container = $(container); } if ($container.length < 1) { throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM."); } if (!options.suppressCssChangesOnHiddenInit) { cacheCssForHiddenInit(); } // calculate these only once and share between grid instances maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight(); options = $.extend({}, defaults, options); validateAndEnforceOptions(); columnDefaults.width = options.defaultColumnWidth; treeColumns = new Slick.TreeColumns(columns); columns = treeColumns.extractColumns(); updateColumnProps(); // validate loaded JavaScript modules against requested options if (options.enableColumnReorder && !$.fn.sortable) { throw new Error("SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded"); } editController = { "commitCurrentEdit": commitCurrentEdit, "cancelCurrentEdit": cancelCurrentEdit }; $container .empty() .css("overflow", "hidden") .css("outline", 0) .addClass(uid) .addClass("ui-widget"); // set up a positioning container if needed if (!(/relative|absolute|fixed/).test($container.css("position"))) { $container.css("position", "relative"); } $focusSink = $("<div tabIndex='0' hideFocus style='position:fixed;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container); // Containers used for scrolling frozen columns and rows $paneHeaderL = $("<div class='slick-pane slick-pane-header slick-pane-left' tabIndex='0' />").appendTo($container); $paneHeaderR = $("<div class='slick-pane slick-pane-header slick-pane-right' tabIndex='0' />").appendTo($container); $paneTopL = $("<div class='slick-pane slick-pane-top slick-pane-left' tabIndex='0' />").appendTo($container); $paneTopR = $("<div class='slick-pane slick-pane-top slick-pane-right' tabIndex='0' />").appendTo($container); $paneBottomL = $("<div class='slick-pane slick-pane-bottom slick-pane-left' tabIndex='0' />").appendTo($container); $paneBottomR = $("<div class='slick-pane slick-pane-bottom slick-pane-right' tabIndex='0' />").appendTo($container); if (options.createPreHeaderPanel) { $preHeaderPanelScroller = $("<div class='slick-preheader-panel ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($paneHeaderL); $preHeaderPanel = $("<div />").appendTo($preHeaderPanelScroller); $preHeaderPanelSpacer = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($preHeaderPanelScroller); $preHeaderPanelScrollerR = $("<div class='slick-preheader-panel ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($paneHeaderR); $preHeaderPanelR = $("<div />").appendTo($preHeaderPanelScrollerR); $preHeaderPanelSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($preHeaderPanelScrollerR); if (!options.showPreHeaderPanel) { $preHeaderPanelScroller.hide(); $preHeaderPanelScrollerR.hide(); } } // Append the header scroller containers $headerScrollerL = $("<div class='slick-header ui-state-default slick-header-left' />").appendTo($paneHeaderL); $headerScrollerR = $("<div class='slick-header ui-state-default slick-header-right' />").appendTo($paneHeaderR); // Cache the header scroller containers $headerScroller = $().add($headerScrollerL).add($headerScrollerR); if (treeColumns.hasDepth()) { $groupHeadersL = []; $groupHeadersR = []; for (var index = 0; index < treeColumns.getDepth() - 1; index++) { $groupHeadersL[index] = $("<div class='slick-group-header-columns slick-group-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL); $groupHeadersR[index] = $("<div class='slick-group-header-columns slick-group-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR); } $groupHeaders = $().add($groupHeadersL).add($groupHeadersR); } // Append the columnn containers to the headers $headerL = $("<div class='slick-header-columns slick-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL); $headerR = $("<div class='slick-header-columns slick-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR); // Cache the header columns $headers = $().add($headerL).add($headerR); $headerRowScrollerL = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopL); $headerRowScrollerR = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopR); $headerRowScroller = $().add($headerRowScrollerL).add($headerRowScrollerR); $headerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($headerRowScrollerL); $headerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($headerRowScrollerR); $headerRowL = $("<div class='slick-headerrow-columns slick-headerrow-columns-left' />").appendTo($headerRowScrollerL); $headerRowR = $("<div class='slick-headerrow-columns slick-headerrow-columns-right' />").appendTo($headerRowScrollerR); $headerRow = $().add($headerRowL).add($headerRowR); // Append the top panel scroller $topPanelScrollerL = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopL); $topPanelScrollerR = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopR); $topPanelScroller = $().add($topPanelScrollerL).add($topPanelScrollerR); // Append the top panel $topPanelL = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerL); $topPanelR = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerR); $topPanel = $().add($topPanelL).add($topPanelR); if (!options.showColumnHeader) { $headerScroller.hide(); } if (!options.showTopPanel) { $topPanelScroller.hide(); } if (!options.showHeaderRow) { $headerRowScroller.hide(); } // Append the viewport containers $viewportTopL = $("<div class='slick-viewport slick-viewport-top slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneTopL); $viewportTopR = $("<div class='slick-viewport slick-viewport-top slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneTopR); $viewportBottomL = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneBottomL); $viewportBottomR = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneBottomR); // Cache the viewports $viewport = $().add($viewportTopL).add($viewportTopR).add($viewportBottomL).add($viewportBottomR); // Default the active viewport to the top left $activeViewportNode = $viewportTopL; // Append the canvas containers $canvasTopL = $("<div class='grid-canvas grid-canvas-top grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportTopL); $canvasTopR = $("<div class='grid-canvas grid-canvas-top grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportTopR); $canvasBottomL = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportBottomL); $canvasBottomR = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportBottomR); if (options.viewportClass) $viewport.toggleClass(options.viewportClass, true); // Cache the canvases $canvas = $().add($canvasTopL).add($canvasTopR).add($canvasBottomL).add($canvasBottomR); scrollbarDimensions = scrollbarDimensions || measureScrollbar(); // Default the active canvas to the top left $activeCanvasNode = $canvasTopL; // pre-header if ($preHeaderPanelSpacer) $preHeaderPanelSpacer.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); $headers.width(getHeadersWidth()); $headerRowSpacerL.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); $headerRowSpacerR.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); // footer Row if (options.createFooterRow) { $footerRowScrollerR = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopR); $footerRowScrollerL = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopL); $footerRowScroller = $().add($footerRowScrollerL).add($footerRowScrollerR); $footerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($footerRowScrollerL); $footerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($footerRowScrollerR); $footerRowL = $("<div class='slick-footerrow-columns slick-footerrow-columns-left' />").appendTo($footerRowScrollerL); $footerRowR = $("<div class='slick-footerrow-columns slick-footerrow-columns-right' />").appendTo($footerRowScrollerR); $footerRow = $().add($footerRowL).add($footerRowR); if (!options.showFooterRow) { $footerRowScroller.hide(); } } $focusSink2 = $focusSink.clone().appendTo($container); if (!options.explicitInitialization) { finishInitialization(); } } function finishInitialization() { if (!initialized) { initialized = true; getViewportWidth(); getViewportHeight(); // header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?) // calculate the diff so we can set consistent sizes measureCellPaddingAndBorder(); // for usability reasons, all text selection in SlickGrid is disabled // with the exception of input and textarea elements (selection must // be enabled there so that editors work as expected); note that // selection in grid cells (grid body) is already unavailable in // all browsers except IE disableSelection($headers); // disable all text selection in header (including input and textarea) if (!options.enableTextSelectionOnCells) { // disable text selection in grid cells except in input and textarea elements // (this is IE-specific, because selectstart event will only fire in IE) $viewport.on("selectstart.ui", function (event) { return $(event.target).is("input,textarea"); }); } setFrozenOptions(); setPaneVisibility(); setScroller(); setOverflow(); updateColumnCaches(); createColumnHeaders(); createColumnGroupHeaders(); createColumnFooter(); setupColumnSort(); createCssRules(); resizeCanvas(); bindAncestorScrollEvents(); $container .on("resize.slickgrid", resizeCanvas); $viewport .on("scroll", handleScroll); if (jQuery.fn.mousewheel && options.enableMouseWheelScrollHandler) { $viewport.on("mousewheel", handleMouseWheel); } $headerScroller //.on("scroll", handleHeaderScroll) .on("contextmenu", handleHeaderContextMenu) .on("click", handleHeaderClick) .on("mouseenter", ".slick-header-column", handleHeaderMouseEnter) .on("mouseleave", ".slick-header-column", handleHeaderMouseLeave); $headerRowScroller .on("scroll", handleHeaderRowScroll); if (options.createFooterRow) { $footerRow .on("contextmenu", handleFooterContextMenu) .on("click", handleFooterClick); $footerRowScroller .on("scroll", handleFooterRowScroll); } if (options.createPreHeaderPanel) { $preHeaderPanelScroller .on("scroll", handlePreHeaderPanelScroll); } $focusSink.add($focusSink2) .on("keydown", handleKeyDown); $canvas .on("keydown", handleKeyDown) .on("click", handleClick) .on("dblclick", handleDblClick) .on("contextmenu", handleContextMenu) .on("draginit", handleDragInit) .on("dragstart", {distance: 3}, handleDragStart) .on("drag", handleDrag) .on("dragend", handleDragEnd) .on("mouseenter", ".slick-cell", handleMouseEnter) .on("mouseleave", ".slick-cell", handleMouseLeave); if (!options.suppressCssChangesOnHiddenInit) { restoreCssFromHiddenInit(); } } } function cacheCssForHiddenInit() { // handle display:none on container or container parents $hiddenParents = $container.parents().addBack().not(':visible'); $hiddenParents.each(function() { var old = {}; for ( var name in cssShow ) { old[ name ] = this.style[ name ]; this.style[ name ] = cssShow[ name ]; } oldProps.push(old); }); } function restoreCssFromHiddenInit() { // finish handle display:none on container or container parents // - put values back the way they were $hiddenParents.each(function(i) { var old = oldProps[i]; for ( var name in cssShow ) { this.style[ name ] = old[ name ]; } }); } function hasFrozenColumns() { return options.frozenColumn > -1; } function registerPlugin(plugin) { plugins.unshift(plugin); plugin.init(self); } function unregisterPlugin(plugin) { for (var i = plugins.length; i >= 0; i--) { if (plugins[i] === plugin) { if (plugins[i].destroy) { plugins[i].destroy(); } plugins.splice(i, 1); break; } } } function getPluginByName(name) { for (var i = plugins.length-1; i >= 0; i--) { if (plugins[i].pluginName === name) { return plugins[i]; } } return undefined; } function setSelectionModel(model) { if (selectionModel) { selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged); if (selectionModel.destroy) { selectionModel.destroy(); } } selectionModel = model; if (selectionModel) { selectionModel.init(self); selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged); } } function getSelectionModel() { return selectionModel; } function getCanvasNode(columnIdOrIdx, rowIndex) { if (!columnIdOrIdx) { columnIdOrIdx = 0; } if (!rowIndex) { rowIndex = 0; } var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); return (hasFrozenRows && rowIndex >= actualFrozenRow + (options.frozenBottom ? 0 : 1) ) ? ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasBottomR[0] : $canvasBottomL[0]) : ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasTopR[0] : $canvasTopL[0]) ; } function getActiveCanvasNode(element) { setActiveCanvasNode(element); return $activeCanvasNode[0]; } function getCanvases() { return $canvas; } function setActiveCanvasNode(element) { if (element) { $activeCanvasNode = $(element.target).closest('.grid-canvas'); } } function getViewportNode() { return $viewport[0]; } function getActiveViewportNode(element) { setActiveViewPortNode(element); return $activeViewportNode[0]; } function setActiveViewportNode(element) { if (element) { $activeViewportNode = $(element.target).closest('.slick-viewport'); } } function measureScrollbar() { var $outerdiv = $('<div class="' + $viewport.className + '" style="position:absolute; top:-10000px; left:-10000px; overflow:auto; width:100px; height:100px;"></div>').appendTo('body'); var $innerdiv = $('<div style="width:200px; height:200px; overflow:auto;"></div>').appendTo($outerdiv); var dim = { width: $outerdiv[0].offsetWidth - $outerdiv[0].clientWidth, height: $outerdiv[0].offsetHeight - $outerdiv[0].clientHeight }; $innerdiv.remove(); $outerdiv.remove(); return dim; } function getHeadersWidth() { headersWidth = headersWidthL = headersWidthR = 0; var includeScrollbar = !options.autoHeight; for (var i = 0, ii = columns.length; i < ii; i++) { var width = columns[ i ].width; if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) { headersWidthR += width; } else { headersWidthL += width; } } if (includeScrollbar) { if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) { headersWidthR += scrollbarDimensions.width; } else { headersWidthL += scrollbarDimensions.width; } } if (hasFrozenColumns()) { headersWidthL = headersWidthL + 1000; headersWidthR = Math.max(headersWidthR, viewportW) + headersWidthL; headersWidthR += scrollbarDimensions.width; } else { headersWidthL += scrollbarDimensions.width; headersWidthL = Math.max(headersWidthL, viewportW) + 1000; } headersWidth = headersWidthL + headersWidthR; return Math.max(headersWidth, viewportW) + 1000; } function getHeadersWidthL() { headersWidthL =0; columns.forEach(function(column, i) { if (!(( options.frozenColumn ) > -1 && ( i > options.frozenColumn ))) headersWidthL += column.width; }); if (hasFrozenColumns()) { headersWidthL += 1000; } else { headersWidthL += scrollbarDimensions.width; headersWidthL = Math.max(headersWidthL, viewportW) + 1000; } return headersWidthL; } function getHeadersWidthR() { headersWidthR =0; columns.forEach(function(column, i) { if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) headersWidthR += column.width; }); if (hasFrozenColumns()) { headersWidthR = Math.max(headersWidthR, viewportW) + getHeadersWidthL(); headersWidthR += scrollbarDimensions.width; } return headersWidthR; } function getCanvasWidth() { var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; var i = columns.length; canvasWidthL = canvasWidthR = 0; while (i--) { if (hasFrozenColumns() && (i > options.frozenColumn)) { canvasWidthR += columns[i].width; } else { canvasWidthL += columns[i].width; } } var totalRowWidth = canvasWidthL + canvasWidthR; return options.fullWidthRows ? Math.max(totalRowWidth, availableWidth) : totalRowWidth; } function updateCanvasWidth(forceColumnWidthsUpdate) { var oldCanvasWidth = canvasWidth; var oldCanvasWidthL = canvasWidthL; var oldCanvasWidthR = canvasWidthR; var widthChanged; canvasWidth = getCanvasWidth(); widthChanged = canvasWidth !== oldCanvasWidth || canvasWidthL !== oldCanvasWidthL || canvasWidthR !== oldCanvasWidthR; if (widthChanged || hasFrozenColumns() || hasFrozenRows) { $canvasTopL.width(canvasWidthL); getHeadersWidth(); $headerL.width(headersWidthL); $headerR.width(headersWidthR); if (hasFrozenColumns()) { $canvasTopR.width(canvasWidthR); $paneHeaderL.width(canvasWidthL); $paneHeaderR.css('left', canvasWidthL); $paneHeaderR.css('width', viewportW - canvasWidthL); $paneTopL.width(canvasWidthL); $paneTopR.css('left', canvasWidthL); $paneTopR.css('width', viewportW - canvasWidthL); $headerRowScrollerL.width(canvasWidthL); $headerRowScrollerR.width(viewportW - canvasWidthL); $headerRowL.width(canvasWidthL); $headerRowR.width(canvasWidthR); if (options.createFooterRow) { $footerRowScrollerL.width(canvasWidthL); $footerRowScrollerR.width(viewportW - canvasWidthL); $footerRowL.width(canvasWidthL); $footerRowR.width(canvasWidthR); } if (options.createPreHeaderPanel) { $preHeaderPanel.width(canvasWidth); } $viewportTopL.width(canvasWidthL); $viewportTopR.width(viewportW - canvasWidthL); if (hasFrozenRows) { $paneBottomL.width(canvasWidthL); $paneBottomR.css('left', canvasWidthL); $viewportBottomL.width(canvasWidthL); $viewportBottomR.width(viewportW - canvasWidthL); $canvasBottomL.width(canvasWidthL); $canvasBottomR.width(canvasWidthR); } } else { $paneHeaderL.width('100%'); $paneTopL.width('100%'); $headerRowScrollerL.width('100%'); $headerRowL.width(canvasWidth); if (options.createFooterRow) { $footerRowScrollerL.width('100%'); $footerRowL.width(canvasWidth); } if (options.createPreHeaderPanel) { $preHeaderPanel.width('100%'); $preHeaderPanel.width(canvasWidth); } $viewportTopL.width('100%'); if (hasFrozenRows) { $viewportBottomL.width('100%'); $canvasBottomL.width(canvasWidthL); } } viewportHasHScroll = (canvasWidth >= viewportW - scrollbarDimensions.width); } $headerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); $headerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); if (options.createFooterRow) { $footerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); $footerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); } if (widthChanged || forceColumnWidthsUpdate) { applyColumnWidths(); } } function disableSelection($target) { if ($target && $target.jquery) { $target .attr("unselectable", "on") .css("MozUserSelect", "none") .on("selectstart.ui", function () { return false; }); // from jquery:ui.core.js 1.7.2 } } function getMaxSupportedCssHeight() { var supportedHeight = 1000000; // FF reports the height back but still renders blank after ~6M px var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000; var div = $("<div style='display:none' />").appendTo(document.body); while (true) { var test = supportedHeight * 2; div.css("height", test); if (test > testUpTo || div.height() !== test) { break; } else { supportedHeight = test; } } div.remove(); return supportedHeight; } function getUID() { return uid; } function getHeaderColumnWidthDiff() { return headerColumnWidthDiff; } function getScrollbarDimensions() { return scrollbarDimensions; } // TODO: this is static. need to handle page mutation. function bindAncestorScrollEvents() { var elem = (hasFrozenRows && !options.frozenBottom) ? $canvasBottomL[0] : $canvasTopL[0]; while ((elem = elem.parentNode) != document.body && elem != null) { // bind to scroll containers only if (elem == $viewportTopL[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) { var $elem = $(elem); if (!$boundAncestors) { $boundAncestors = $elem; } else { $boundAncestors = $boundAncestors.add($elem); } $elem.on("scroll." + uid, handleActiveCellPositionChange); } } } function unbindAncestorScrollEvents() { if (!$boundAncestors) { return; } $boundAncestors.off("scroll." + uid); $boundAncestors = null; } function updateColumnHeader(columnId, title, toolTip) { if (!initialized) { return; } var idx = getColumnIndex(columnId); if (idx == null) { return; } var columnDef = columns[idx]; var $header = $headers.children().eq(idx); if ($header) { if (title !== undefined) { columns[idx].name = title; } if (toolTip !== undefined) { columns[idx].toolTip = toolTip; } trigger(self.onBeforeHeaderCellDestroy, { "node": $header[0], "column": columnDef, "grid": self }); $header .attr("title", toolTip || "") .children().eq(0).html(title); trigger(self.onHeaderCellRendered, { "node": $header[0], "column": columnDef, "grid": self }); } } function getHeader(columnDef) { if (!columnDef) { return hasFrozenColumns() ? $headers : $headerL; } var idx = getColumnIndex(columnDef.id); return hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL; } function getHeaderColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var targetHeader = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL; var targetIndex = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? idx : idx - options.frozenColumn - 1) : idx; var $rtn = targetHeader.children().eq(targetIndex); return $rtn && $rtn[0]; } function getHeaderRow() { return hasFrozenColumns() ? $headerRow : $headerRow[0]; } function getFooterRow() { return hasFrozenColumns() ? $footerRow : $footerRow[0]; } function getPreHeaderPanel() { return $preHeaderPanel[0]; } function getPreHeaderPanelRight() { return $preHeaderPanelR[0]; } function getHeaderRowColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var $headerRowTarget; if (hasFrozenColumns()) { if (idx <= options.frozenColumn) { $headerRowTarget = $headerRowL; } else { $headerRowTarget = $headerRowR; idx -= options.frozenColumn + 1; } } else { $headerRowTarget = $headerRowL; } var $header = $headerRowTarget.children().eq(idx); return $header && $header[0]; } function getFooterRowColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var $footerRowTarget; if (hasFrozenColumns()) { if (idx <= options.frozenColumn) { $footerRowTarget = $footerRowL; } else { $footerRowTarget = $footerRowR; idx -= options.frozenColumn + 1; } } else { $footerRowTarget = $footerRowL; } var $footer = $footerRowTarget && $footerRowTarget.children().eq(idx); return $footer && $footer[0]; } function createColumnFooter() { if (options.createFooterRow) { $footerRow.find(".slick-footerrow-column") .each(function () { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowL.empty(); $footerRowR.empty(); for (var i = 0; i < columns.length; i++) { var m = columns[i]; var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo(hasFrozenColumns() && (i > options.frozenColumn)? $footerRowR: $footerRowL); trigger(self.onFooterRowCellRendered, { "node": footerRowCell[0], "column": m, "grid": self }); } } } function createColumnGroupHeaders() { var columnsLength = 0; var frozenColumnsValid = false; if (!treeColumns.hasDepth()) return; for (var index = 0; index < $groupHeadersL.length; index++) { $groupHeadersL[index].empty(); $groupHeadersR[index].empty(); var groupColumns = treeColumns.getColumnsInDepth(index); for (var indexGroup in groupColumns) { var m = groupColumns[indexGroup]; columnsLength += m.extractColumns().length; if (hasFrozenColumns() && index === 0 && (columnsLength-1) === options.frozenColumn) frozenColumnsValid = true; $("<div class='ui-state-default slick-group-header-column' />") .html("<span class='slick-column-name'>" + m.name + "</span>") .attr("id", "" + uid + m.id) .attr("title", m.toolTip || "") .data("column", m) .addClass(m.headerCssClass || "") .addClass(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? 'frozen': '') .appendTo(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? $groupHeadersR[index]: $groupHeadersL[index]); } if (hasFrozenColumns() && index === 0 && !frozenColumnsValid) { $groupHeadersL[index].empty(); $groupHeadersR[index].empty(); alert("All columns of group should to be grouped!"); break; } } applyColumnGroupHeaderWidths(); } function createColumnHeaders() { function onMouseEnter() { $(this).addClass("ui-state-hover"); } function onMouseLeave() { $(this).removeClass("ui-state-hover"); } $headers.find(".slick-header-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headerL.empty(); $headerR.empty(); getHeadersWidth(); $headerL.width(headersWidthL); $headerR.width(headersWidthR); $headerRow.find(".slick-headerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headerRowL.empty(); $headerRowR.empty(); if (options.createFooterRow) { $footerRowL.find(".slick-footerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowL.empty(); if (hasFrozenColumns()) { $footerRowR.find(".slick-footerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowR.empty(); } } for (var i = 0; i < columns.length; i++) { var m = columns[i]; var $headerTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerL : $headerR) : $headerL; var $headerRowTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerRowL : $headerRowR) : $headerRowL; var header = $("<div class='ui-state-default slick-header-column' />") .html("<span class='slick-column-name'>" + m.name + "</span>") .width(m.width - headerColumnWidthDiff) .attr("id", "" + uid + m.id) .attr("title", m.toolTip || "") .data("column", m) .addClass(m.headerCssClass || "") .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo($headerTarget); if (options.enableColumnReorder || m.sortable) { header .on('mouseenter', onMouseEnter) .on('mouseleave', onMouseLeave); } if(m.hasOwnProperty('headerCellAttrs') && m.headerCellAttrs instanceof Object) { for (var key in m.headerCellAttrs) { if (m.headerCellAttrs.hasOwnProperty(key)) { header.attr(key, m.headerCellAttrs[key]); } } } if (m.sortable) { header.addClass("slick-header-sortable"); header.append("<span class='slick-sort-indicator" + (options.numberedMultiColumnSort && !options.sortColNumberInSeparateSpan ? " slick-sort-indicator-numbered" : "" ) + "' />"); if (options.numberedMultiColumnSort && options.sortColNumberInSeparateSpan) { header.append("<span class='slick-sort-indicator-numbered' />"); } } trigger(self.onHeaderCellRendered, { "node": header[0], "column": m, "grid": self }); if (options.showHeaderRow) { var headerRowCell = $("<div class='ui-state-default slick-headerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo($headerRowTarget); trigger(self.onHeaderRowCellRendered, { "node": headerRowCell[0], "column": m, "grid": self }); } if (options.createFooterRow && options.showFooterRow) { var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .appendTo($footerRow); trigger(self.onFooterRowCellRendered, { "node": footerRowCell[0], "column": m, "grid": self }); } } setSortColumns(sortColumns); setupColumnResize(); if (options.enableColumnReorder) { if (typeof options.enableColumnReorder == 'function') { options.enableColumnReorder(self, $headers, headerColumnWidthDiff, setColumns, setupColumnResize, columns, getColumnIndex, uid, trigger); } else { setupColumnReorder(); } } } function setupColumnSort() { $headers.click(function (e) { if (columnResizeDragging) return; // temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328) e.metaKey = e.metaKey || e.ctrlKey; if ($(e.target).hasClass("slick-resizable-handle")) { return; } var $col = $(e.target).closest(".slick-header-column"); if (!$col.length) { return; } var column = $col.data("column"); if (column.sortable) { if (!getEditorLock().commitCurrentEdit()) { return; } var sortColumn = null; var i = 0; for (; i < sortColumns.length; i++) { if (sortColumns[i].columnId == column.id) { sortColumn = sortColumns[i]; sortColumn.sortAsc = !sortColumn.sortAsc; break; } } var hadSortCol = !!sortColumn; if (options.tristateMultiColumnSort) { if (!sortColumn) { sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc }; } if (hadSortCol && sortColumn.sortAsc) { // three state: remove sort rather than go back to ASC sortColumns.splice(i, 1); sortColumn = null; } if (!options.multiColumnSort) { sortColumns = []; } if (sortColumn && (!hadSortCol || !options.multiColumnSort)) { sortColumns.push(sortColumn); } } else { // legacy behaviour if (e.metaKey && options.multiColumnSort) { if (sortColumn) { sortColumns.splice(i, 1); } } else { if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) { sortColumns = []; } if (!sortColumn) { sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc }; sortColumns.push(sortColumn); } else if (sortColumns.length === 0) { sortColumns.push(sortColumn); } } } setSortColumns(sortColumns); if (!options.multiColumnSort) { trigger(self.onSort, { multiColumnSort: false, columnId: (sortColumns.length > 0 ? column.id : null), sortCol: (sortColumns.length > 0 ? column : null), sortAsc: (sortColumns.length > 0 ? sortColumns[0].sortAsc : true) }, e); } else { trigger(self.onSort, { multiColumnSort: true, sortCols: $.map(sortColumns, function(col) { return {columnId: columns[getColumnIndex(col.columnId)].id, sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc }; }) }, e); } } }); } function currentPositionInHeader(id) { var currentPosition = 0; $headers.find('.slick-header-column').each(function (i) { if (this.id == id) { currentPosition = i; return false; } }); return currentPosition; } function limitPositionInGroup(idColumn) { var groupColumnOfPreviousPosition, startLimit = 0, endLimit = 0; treeColumns .getColumnsInDepth($groupHeadersL.length - 1) .some(function (groupColumn) { startLimit = endLimit; endLimit += groupColumn.columns.length; groupColumn.columns.some(function (column) { if (column.id === idColumn) groupColumnOfPreviousPosition = groupColumn; return groupColumnOfPreviousPosition; }); return groupColumnOfPreviousPosition; }); endLimit--; return { start: startLimit, end: endLimit, group: groupColumnOfPreviousPosition }; } function remove(arr, elem) { var index = arr.lastIndexOf(elem); if(index > -1) { arr.splice(index, 1); remove(arr, elem); } } function columnPositionValidInGroup($item) { var currentPosition = currentPositionInHeader($item[0].id); var limit = limitPositionInGroup($item.data('column').id); var positionValid = limit.start <= currentPosition && currentPosition <= limit.end; return { limit: limit, valid: positionValid, message: positionValid? '': 'Column "'.concat($item.text(), '" can be reordered only within the "', limit.group.name, '" group!') }; } function setupColumnReorder() { $headers.filter(":ui-sortable").sortable("destroy"); var columnScrollTimer = null; function scrollColumnsRight() { $viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft + 10; } function scrollColumnsLeft() { $viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft - 10; } var canDragScroll; $headers.sortable({ containment: "parent", distance: 3, axis: "x", cursor: "default", tolerance: "intersection", helper: "clone", placeholder: "slick-sortable-placeholder ui-state-default slick-header-column", start: function (e, ui) { ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff); canDragScroll = !hasFrozenColumns() || (ui.placeholder.offset().left + ui.placeholder.width()) > $viewportScrollContainerX.offset().left; $(ui.helper).addClass("slick-header-column-active"); }, beforeStop: function (e, ui) { $(ui.helper).removeClass("slick-header-column-active"); }, sort: function (e, ui) { if (canDragScroll && e.originalEvent.pageX > $container[0].clientWidth) { if (!(columnScrollTimer)) { columnScrollTimer = setInterval( scrollColumnsRight, 100); } } else if (canDragScroll && e.originalEvent.pageX < $viewportScrollContainerX.offset().left) { if (!(columnScrollTimer)) { columnScrollTimer = setInterval( scrollColumnsLeft, 100); } } else { clearInterval(columnScrollTimer); columnScrollTimer = null; } }, stop: function (e, ui) { var cancel = false; clearInterval(columnScrollTimer); columnScrollTimer = null; var limit = null; if (treeColumns.hasDepth()) { var validPositionInGroup = columnPositionValidInGroup(ui.item); limit = validPositionInGroup.limit; cancel = !validPositionInGroup.valid; if (cancel) alert(validPositionInGroup.message); } if (cancel || !getEditorLock().commitCurrentEdit()) { $(this).sortable("cancel"); return; } var reorderedIds = $headerL.sortable("toArray"); reorderedIds = reorderedIds.concat($headerR.sortable("toArray")); var reorderedColumns = []; for (var i = 0; i < reorderedIds.length; i++) { reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]); } setColumns(reorderedColumns); trigger(self.onColumnsReordered, { impactedColumns : getImpactedColumns( limit ) }); e.stopPropagation(); setupColumnResize(); } }); } function getImpactedColumns( limit ) { var impactedColumns = []; if( limit ) { for( var i = limit.start; i <= limit.end; i++ ) { impactedColumns.push( columns[i] ); } } else { impactedColumns = columns; } return impactedColumns; } function setupColumnResize() { var $col, j, k, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable; columnElements = $headers.children(); columnElements.find(".slick-resizable-handle").remove(); columnElements.each(function (i, e) { if (i >= columns.length) { return; } if (columns[i].resizable) { if (firstResizable === undefined) { firstResizable = i; } lastResizable = i; } }); if (firstResizable === undefined) { return; } columnElements.each(function (i, e) { if (i >= columns.length) { return; } if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) { return; } $col = $(e); $("<div class='slick-resizable-handle' />") .appendTo(e) .on("dragstart", function (e, dd) { if (!getEditorLock().commitCurrentEdit()) { return false; } pageX = e.pageX; $(this).parent().addClass("slick-header-column-active"); var shrinkLeewayOnRight = null, stretchLeewayOnRight = null; // lock each column's width option to current width columnElements.each(function (i, e) { if (i >= columns.length) { return; } columns[i].previousWidth = $(e).outerWidth(); }); if (options.forceFitColumns) { shrinkLeewayOnRight = 0; stretchLeewayOnRight = 0; // colums on right affect maxPageX/minPageX for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (stretchLeewayOnRight !== null) { if (c.maxWidth) { stretchLeewayOnRight += c.maxWidth - c.previousWidth; } else { stretchLeewayOnRight = null; } } shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } } var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0; for (j = 0; j <= i; j++) { // columns on left only affect minPageX c = columns[j]; if (c.resizable) { if (stretchLeewayOnLeft !== null) { if (c.maxWidth) { stretchLeewayOnLeft += c.maxWidth - c.previousWidth; } else { stretchLeewayOnLeft = null; } } shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } if (shrinkLeewayOnRight === null) { shrinkLeewayOnRight = 100000; } if (shrinkLeewayOnLeft === null) { shrinkLeewayOnLeft = 100000; } if (stretchLeewayOnRight === null) { stretchLeewayOnRight = 100000; } if (stretchLeewayOnLeft === null) { stretchLeewayOnLeft = 100000; } maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft); minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight); }) .on("drag", function (e, dd) { columnResizeDragging = true; var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x; var newCanvasWidthL = 0, newCanvasWidthR = 0; if (d < 0) { // shrink column x = d; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } } } for (k = 0; k <= i; k++) { c = columns[k]; if (hasFrozenColumns() && (k > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } else { for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } } } else { // stretch column x = d; newCanvasWidthL = 0; newCanvasWidthR = 0; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } for (k = 0; k <= i; k++) { c = columns[k]; if (hasFrozenColumns() && (k > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } else { for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } if (hasFrozenColumns() && newCanvasWidthL != canvasWidthL) { $headerL.width(newCanvasWidthL + 1000); $paneHeaderR.css('left', newCanvasWidthL); } applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); if (options.syncColumnCellResize) { applyColumnWidths(); } trigger(self.onColumnsDrag, { triggeredByColumn: $(this).parent().attr("id").replace(uid, ""), resizeHandle: $(this) }); }) .on("dragend", function (e, dd) { $(this).parent().removeClass("slick-header-column-active"); var triggeredByColumn = $(this).parent().attr("id").replace(uid, ""); if (trigger(self.onBeforeColumnsResize, { triggeredByColumn: triggeredByColumn }) === true) { applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); } var newWidth; for (j = 0; j < columns.length; j++) { c = columns[j]; newWidth = $(columnElements[j]).outerWidth(); if (c.previousWidth !== newWidth && c.rerenderOnResize) { invalidateAllRows(); } } updateCanvasWidth(true); render(); trigger(self.onColumnsResized, { triggeredByColumn: triggeredByColumn }); setTimeout(function () { columnResizeDragging = false; }, 300); }); }); } function getVBoxDelta($el) { var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; var delta = 0; if ($el && typeof $el.css === 'function') { $.each(p, function (n, val) { delta += parseFloat($el.css(val)) || 0; }); } return delta; } function setFrozenOptions() { options.frozenColumn = (options.frozenColumn >= 0 && options.frozenColumn < columns.length) ? parseInt(options.frozenColumn) : -1; if (options.frozenRow > -1) { hasFrozenRows = true; frozenRowsHeight = ( options.frozenRow ) * options.rowHeight; var dataLength = getDataLength(); actualFrozenRow = ( options.frozenBottom ) ? ( dataLength - options.frozenRow ) : options.frozenRow; } else { hasFrozenRows = false; } } function setPaneVisibility() { if (hasFrozenColumns()) { $paneHeaderR.show(); $paneTopR.show(); if (hasFrozenRows) { $paneBottomL.show(); $paneBottomR.show(); } else { $paneBottomR.hide(); $paneBottomL.hide(); } } else { $paneHeaderR.hide(); $paneTopR.hide(); $paneBottomR.hide(); if (hasFrozenRows) { $paneBottomL.show(); } else { $paneBottomR.hide(); $paneBottomL.hide(); } } } function setOverflow() { $viewportTopL.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ), 'overflow-y': (!hasFrozenColumns() && options.alwaysShowVerticalScroll) ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ) : ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportTopR.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'scroll' : 'auto' ) : ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportBottomL.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ): ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ), 'overflow-y': (!hasFrozenColumns() && options.alwaysShowVerticalScroll) ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ): ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportBottomR.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'auto' : 'auto' ) : ( hasFrozenRows ? 'auto' : 'auto' )) }); if (options.viewportClass) { $viewportTopL.toggleClass(options.viewportClass, true); $viewportTopR.toggleClass(options.viewportClass, true); $viewportBottomL.toggleClass(options.viewportClass, true); $viewportBottomR.toggleClass(options.viewportClass, true); } } function setScroller() { if (hasFrozenColumns()) { $headerScrollContainer = $headerScrollerR; $headerRowScrollContainer = $headerRowScrollerR; $footerRowScrollContainer = $footerRowScrollerR; if (hasFrozenRows) { if (options.frozenBottom) { $viewportScrollContainerX = $viewportBottomR; $viewportScrollContainerY = $viewportTopR; } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomR; } } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportTopR; } } else { $headerScrollContainer = $headerScrollerL; $headerRowScrollContainer = $headerRowScrollerL; $footerRowScrollContainer = $footerRowScrollerL; if (hasFrozenRows) { if (options.frozenBottom) { $viewportScrollContainerX = $viewportBottomL; $viewportScrollContainerY = $viewportTopL; } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomL; } } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportTopL; } } } function measureCellPaddingAndBorder() { var el; var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"]; var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; // jquery prior to version 1.8 handles .width setter/getter as a direct css write/read // jquery 1.8 changed .width to read the true inner element width if box-sizing is set to border-box, and introduced a setter for .outerWidth // so for equivalent functionality, prior to 1.8 use .width, and after use .outerWidth var verArray = $.fn.jquery.split('.'); jQueryNewWidthBehaviour = (verArray[0]==1 && verArray[1]>=8) || verArray[0] >=2; el = $("<div class='ui-state-default slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers); headerColumnWidthDiff = headerColumnHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { headerColumnWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { headerColumnHeightDiff += parseFloat(el.css(val)) || 0; }); } el.remove(); var r = $("<div class='slick-row' />").appendTo($canvas); el = $("<div class='slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r); cellWidthDiff = cellHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { cellWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { cellHeightDiff += parseFloat(el.css(val)) || 0; }); } r.remove(); absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff); } function createCssRules() { $style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head")); var rowHeight = (options.rowHeight - cellHeightDiff); var rules = [ "." + uid + " .slick-group-header-column { left: 1000px; }", "." + uid + " .slick-header-column { left: 1000px; }", "." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }", "." + uid + " .slick-preheader-panel { height:" + options.preHeaderPanelHeight + "px; }", "." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }", "." + uid + " .slick-footerrow-columns { height:" + options.footerRowHeight + "px; }", "." + uid + " .slick-cell { height:" + rowHeight + "px; }", "." + uid + " .slick-row { height:" + options.rowHeight + "px; }" ]; for (var i = 0; i < columns.length; i++) { rules.push("." + uid + " .l" + i + " { }"); rules.push("." + uid + " .r" + i + " { }"); } if ($style[0].styleSheet) { // IE $style[0].styleSheet.cssText = rules.join(" "); } else { $style[0].appendChild(document.createTextNode(rules.join(" "))); } } function getColumnCssRules(idx) { var i; if (!stylesheet) { var sheets = document.styleSheets; for (i = 0; i < sheets.length; i++) { if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) { stylesheet = sheets[i]; break; } } if (!stylesheet) { throw new Error("Cannot find stylesheet."); } // find and cache column CSS rules columnCssRulesL = []; columnCssRulesR = []; var cssRules = (stylesheet.cssRules || stylesheet.rules); var matches, columnIdx; for (i = 0; i < cssRules.length; i++) { var selector = cssRules[i].selectorText; if (matches = /\.l\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesL[columnIdx] = cssRules[i]; } else if (matches = /\.r\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesR[columnIdx] = cssRules[i]; } } } return { "left": columnCssRulesL[idx], "right": columnCssRulesR[idx] }; } function removeCssRules() { $style.remove(); stylesheet = null; } function destroy(shouldDestroyAllElements) { getEditorLock().cancelCurrentEdit(); trigger(self.onBeforeDestroy, {}); var i = plugins.length; while(i--) { unregisterPlugin(plugins[i]); } if (options.enableColumnReorder) { $headers.filter(":ui-sortable").sortable("destroy"); } unbindAncestorScrollEvents(); $container.off(".slickgrid"); removeCssRules(); $canvas.off(); $viewport.off(); $headerScroller.off(); $headerRowScroller.off(); if ($footerRow) { $footerRow.off(); } if ($footerRowScroller) { $footerRowScroller.off(); } if ($preHeaderPanelScroller) { $preHeaderPanelScroller.off(); } $focusSink.off(); $(".slick-resizable-handle").off(); $(".slick-header-column").off(); $container.empty().removeClass(uid); if (shouldDestroyAllElements) { destroyAllElements(); } } function destroyAllElements() { $activeCanvasNode = null; $activeViewportNode = null; $boundAncestors = null; $canvas = null; $canvasTopL = null; $canvasTopR = null; $canvasBottomL = null; $canvasBottomR = null; $container = null; $focusSink = null; $focusSink2 = null; $groupHeaders = null; $groupHeadersL = null; $groupHeadersR = null; $headerL = null; $headerR = null; $headers = null; $headerRow = null; $headerRowL = null; $headerRowR = null; $headerRowSpacerL = null; $headerRowSpacerR = null; $headerRowScrollContainer = null; $headerRowScroller = null; $headerRowScrollerL = null; $headerRowScrollerR = null; $headerScrollContainer = null; $headerScroller = null; $headerScrollerL = null; $headerScrollerR = null; $hiddenParents = null; $footerRow = null; $footerRowL = null; $footerRowR = null; $footerRowSpacerL = null; $footerRowSpacerR = null; $footerRowScroller = null; $footerRowScrollerL = null; $footerRowScrollerR = null; $footerRowScrollContainer = null; $preHeaderPanel = null; $preHeaderPanelR = null; $preHeaderPanelScroller = null; $preHeaderPanelScrollerR = null; $preHeaderPanelSpacer = null; $preHeaderPanelSpacerR = null; $topPanel = null; $topPanelScroller = null; $style = null; $topPanelScrollerL = null; $topPanelScrollerR = null; $topPanelL = null; $topPanelR = null; $paneHeaderL = null; $paneHeaderR = null; $paneTopL = null; $paneTopR = null; $paneBottomL = null; $paneBottomR = null; $viewport = null; $viewportTopL = null; $viewportTopR = null; $viewportBottomL = null; $viewportBottomR = null; $viewportScrollContainerX = null; $viewportScrollContainerY = null; } ////////////////////////////////////////////////////////////////////////////////////////////// // Column Autosizing ////////////////////////////////////////////////////////////////////////////////////////////// var canvas = null; var canvas_context = null; function autosizeColumn(columnOrIndexOrId, isInit) { var c = columnOrIndexOrId; if (typeof columnOrIndexOrId === 'number') { c = columns[columnOrIndexOrId]; } else if (typeof columnOrIndexOrId === 'string') { for (var i = 0; i < columns.length; i++) { if (columns[i].Id === columnOrIndexOrId) { c = columns[i]; } } } var $gridCanvas = $(getCanvasNode(0, 0)); getColAutosizeWidth(c, $gridCanvas, isInit); } function autosizeColumns(autosizeMode, isInit) { //LogColWidths(); autosizeMode = autosizeMode || options.autosizeColsMode; if (autosizeMode === Slick.GridAutosizeColsMode.LegacyForceFit || autosizeMode === Slick.GridAutosizeColsMode.LegacyOff) { legacyAutosizeColumns(); return; } if (autosizeMode === Slick.GridAutosizeColsMode.None) { return; } // test for brower canvas support, canvas_context!=null if supported canvas = document.createElement("canvas"); if (canvas && canvas.getContext) { canvas_context = canvas.getContext("2d"); } // pass in the grid canvas var $gridCanvas = $(getCanvasNode(0, 0)); var viewportWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; // iterate columns to get autosizes var i, c, colWidth, reRender, totalWidth = 0, totalWidthLessSTR = 0, strColsMinWidth = 0, totalMinWidth = 0, totalLockedColWidth = 0; for (i = 0; i < columns.length; i++) { c = columns[i]; getColAutosizeWidth(c, $gridCanvas, isInit); totalLockedColWidth += (c.autoSize.autosizeMode === Slick.ColAutosizeMode.Locked ? c.width : 0); totalMinWidth += (c.autoSize.autosizeMode === Slick.ColAutosizeMode.Locked ? c.width : c.minWidth); totalWidth += c.autoSize.widthPx; totalWidthLessSTR += (c.autoSize.sizeToRemaining ? 0 : c.autoSize.widthPx); strColsMinWidth += (c.autoSize.sizeToRemaining ? c.minWidth || 0 : 0); } var strColTotalGuideWidth = totalWidth - totalWidthLessSTR; if (autosizeMode === Slick.GridAutosizeColsMode.FitViewportToCols) { // - if viewport with is outside MinViewportWidthPx and MaxViewportWidthPx, then the viewport is set to // MinViewportWidthPx or MaxViewportWidthPx and the FitColsToViewport algorithm is used // - viewport is resized to fit columns var setWidth = totalWidth + scrollbarDimensions.width; autosizeMode = Slick.GridAutosizeColsMode.IgnoreViewport; if (options.viewportMaxWidthPx && setWidth > options.viewportMaxWidthPx) { setWidth = options.viewportMaxWidthPx; autosizeMode = Slick.GridAutosizeColsMode.FitColsToViewport; } else if (options.viewportMinWidthPx && setWidth < options.viewportMinWidthPx) { setWidth = options.viewportMinWidthPx; autosizeMode = Slick.GridAutosizeColsMode.FitColsToViewport; } else { // falling back to IgnoreViewport will size the columns as-is, with render checking //for (i = 0; i < columns.length; i++) { columns[i].width = columns[i].autoSize.widthPx; } } $container.width(setWidth); } if (autosizeMode === Slick.GridAutosizeColsMode.FitColsToViewport) { if (strColTotalGuideWidth > 0 && totalWidthLessSTR < viewportWidth - strColsMinWidth) { // if addl space remains in the viewport and there are SizeToRemaining cols, just the SizeToRemaining cols expand proportionally to fill viewport for (i = 0; i < columns.length; i++) { c = columns[i]; var totalSTRViewportWidth = viewportWidth - totalWidthLessSTR; if (c.autoSize.sizeToRemaining) { colWidth = totalSTRViewportWidth * c.autoSize.widthPx / strColTotalGuideWidth; } else { colWidth = c.autoSize.widthPx; } if (c.rerenderOnResize && c.width != colWidth) { reRender = true; } c.width = colWidth; } } else if ((options.viewportSwitchToScrollModeWidthPercent && totalWidthLessSTR + strColsMinWidth > viewportWidth * options.viewportSwitchToScrollModeWidthPercent / 100) || (totalMinWidth > viewportWidth)) { // if the total columns width is wider than the viewport by switchToScrollModeWidthPercent, switch to IgnoreViewport mode autosizeMode = Slick.GridAutosizeColsMode.IgnoreViewport; } else { // otherwise (ie. no SizeToRemaining cols or viewport smaller than columns) all cols other than 'Locked' scale in proportion to fill viewport // and SizeToRemaining get minWidth var unallocatedColWidth = totalWidthLessSTR - totalLockedColWidth; var unallocatedViewportWidth = viewportWidth - totalLockedColWidth - strColsMinWidth; for (i = 0; i < columns.length; i++) { c = columns[i]; colWidth = c.width; if (c.autoSize.autosizeMode !== Slick.ColAutosizeMode.Locked) { if (c.autoSize.sizeToRemaining) { colWidth = c.minWidth; } else { // size width proportionally to free space (we know we have enough room due to the earlier calculations) colWidth = unallocatedViewportWidth / unallocatedColWidth * c.autoSize.widthPx; if (colWidth < c.minWidth) { colWidth = c.minWidth; } // remove the just allocated widths from the allocation pool unallocatedColWidth -= c.autoSize.widthPx; unallocatedViewportWidth -= colWidth; } } if (c.rerenderOnResize && c.width != colWidth) { reRender = true; } c.width = colWidth; } } } if (autosizeMode === Slick.GridAutosizeColsMode.IgnoreViewport) { // just size columns as-is for (i = 0; i < columns.length; i++) { colWidth = columns[i].autoSize.widthPx; if (columns[i].rerenderOnResize && columns[i].width != colWidth) { reRender = true; } columns[i].width = colWidth; } } //LogColWidths(); reRenderColumns(reRender); } function LogColWidths () { var s = "Col Widths:"; for (var i = 0; i < columns.length; i++) { s += ' ' + columns[i].width; } console.log(s); } function getColAutosizeWidth(columnDef, $gridCanvas, isInit) { var autoSize = columnDef.autoSize; // set to width as default autoSize.widthPx = columnDef.width; if (autoSize.autosizeMode === Slick.ColAutosizeMode.Locked || autoSize.autosizeMode === Slick.ColAutosizeMode.Guide) { return; } var dl = getDataLength(); //getDataItem(); // ContentIntelligent takes settings from column data type if (autoSize.autosizeMode === Slick.ColAutosizeMode.ContentIntelligent) { // default to column colDataTypeOf (can be used if initially there are no data rows) var colDataTypeOf = autoSize.colDataTypeOf; var colDataItem; if (dl > 0) { var tempRow = getDataItem(0); if (tempRow) { colDataItem = tempRow[columnDef.field]; colDataTypeOf = typeof colDataItem; if (colDataTypeOf === 'object') { if (colDataItem instanceof Date) { colDataTypeOf = "date"; } if (typeof moment!=='undefined' && colDataItem instanceof moment) { colDataTypeOf = "moment"; } } } } if (colDataTypeOf === 'boolean') { autoSize.colValueArray = [ true, false ]; } if (colDataTypeOf === 'number') { autoSize.valueFilterMode = Slick.ValueFilterMode.GetGreatestAndSub; autoSize.rowSelectionMode = Slick.RowSelectionMode.AllRows; } if (colDataTypeOf === 'string') { autoSize.valueFilterMode = Slick.ValueFilterMode.GetLongestText; autoSize.rowSelectionMode = Slick.RowSelectionMode.AllRows; autoSize.allowAddlPercent = 5; } if (colDataTypeOf === 'date') { autoSize.colValueArray = [ new Date(2009, 8, 30, 12, 20, 20) ]; // Sep 30th 2009, 12:20:20 AM } if (colDataTypeOf === 'moment' && typeof moment!=='undefined') { autoSize.colValueArray = [ moment([2009, 8, 30, 12, 20, 20]) ]; // Sep 30th 2009, 12:20:20 AM } } // at this point, the autosizeMode is effectively 'Content', so proceed to get size var colWidth = getColContentSize(columnDef, $gridCanvas, isInit); var addlPercentMultiplier = (autoSize.allowAddlPercent ? (1 + autoSize.allowAddlPercent/100) : 1); colWidth = colWidth * addlPercentMultiplier + options.autosizeColPaddingPx; if (columnDef.minWidth && colWidth < columnDef.minWidth) { colWidth = columnDef.minWidth; } if (columnDef.maxWidth && colWidth > columnDef.maxWidth) { colWidth = columnDef.maxWidth; } autoSize.widthPx = colWidth; } function getColContentSize(columnDef, $gridCanvas, isInit) { var autoSize = columnDef.autoSize; var widthAdjustRatio = 1; // at this point, the autosizeMode is effectively 'Content', so proceed to get size // get header width, if we are taking notice of it var i, ii; var maxColWidth = 0; var headerWidth = 0; if (!autoSize.ignoreHeaderText) { headerWidth = getColHeaderWidth(columnDef); } if (autoSize.colValueArray) { // if an array of values are specified, just pass them in instead of data maxColWidth = getColWidth(columnDef, $gridCanvas, autoSize.colValueArray); return Math.max(headerWidth, maxColWidth); } // select rows to evaluate using rowSelectionMode and rowSelectionCount var rows = getData(); if (rows.getItems) { rows = rows.getItems(); } var rowSelectionMode = (isInit ? autoSize.rowSelectionModeOnInit : undefined) || autoSize.rowSelectionMode; if (rowSelectionMode === Slick.RowSelectionMode.FirstRow) { rows = rows.slice(0,1); } if (rowSelectionMode === Slick.RowSelectionMode.LastRow) { rows = rows.slice(rows.length -1, rows.length); } if (rowSelectionMode === Slick.RowSelectionMode.FirstNRows) { rows = rows.slice(0, autoSize.rowSelectionCount); } // now use valueFilterMode to further filter selected rows if (autoSize.valueFilterMode === Slick.ValueFilterMode.DeDuplicate) { var rowsDict = {}; for (i = 0, ii = rows.length; i < ii; i++) { rowsDict[rows[i][columnDef.field]] = true; } if (Object.keys) { rows = Object.keys(rowsDict); } else { rows = []; for (var i in rowsDict) rows.push(i); } } if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetGreatestAndSub) { // get greatest abs value in data var tempVal, maxVal, maxAbsVal = 0; for (i = 0, ii = rows.length; i < ii; i++) { tempVal = rows[i][columnDef.field]; if (Math.abs(tempVal) > maxAbsVal) { maxVal = tempVal; maxAbsVal = Math.abs(tempVal); } } // now substitute a '9' for all characters (to get widest width) and convert back to a number maxVal = '' + maxVal; maxVal = Array(maxVal.length + 1).join("9"); maxVal = +maxVal; rows = [ maxVal ]; } if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetLongestTextAndSub) { // get greatest abs value in data var tempVal, maxLen = 0; for (i = 0, ii = rows.length; i < ii; i++) { tempVal = rows[i][columnDef.field]; if ((tempVal || '').length > maxLen) { maxLen = tempVal.length; } } // now substitute a 'c' for all characters tempVal = Array(maxLen + 1).join("m"); widthAdjustRatio = options.autosizeTextAvgToMWidthRatio; rows = [ tempVal ]; } if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetLongestText) { // get greatest abs value in data var tempVal, maxLen = 0, maxIndex = 0; for (i = 0, ii = rows.length; i < ii; i++) { tempVal = rows[i][columnDef.field]; if ((tempVal || '').length > maxLen) { maxLen = tempVal.length; maxIndex = i; } } // now substitute a 'c' for all characters tempVal = rows[maxIndex][columnDef.field]; rows = [ tempVal ]; } maxColWidth = getColWidth(columnDef, $gridCanvas, rows) * widthAdjustRatio; return Math.max(headerWidth, maxColWidth); } function getColWidth(columnDef, $gridCanvas, data) { var colIndex = getColumnIndex(columnDef.id); var $rowEl = $('<div class="slick-row ui-widget-content"></div>'); var $cellEl = $('<div class="slick-cell"></div>'); $cellEl.css({ "position": "absolute", "visibility": "hidden", "text-overflow": "initial", "white-space": "nowrap" }); $rowEl.append($cellEl); $gridCanvas.append($rowEl); var len, max = 0, text, maxText, formatterResult, maxWidth = 0, val; // use canvas - very fast, but text-only if (canvas_context && columnDef.autoSize.widthEvalMode === Slick.WidthEvalMode.CanvasTextSize) { canvas_context.font = $cellEl.css("font-size") + " " + $cellEl.css("font-family"); $(data).each(function (index, row) { // row is either an array or values or a single value val = (Array.isArray(row) ? row[columnDef.field] : row); text = '' + val; len = text ? canvas_context.measureText(text).width : 0; if (len > max) { max = len; maxText = text; } }); $cellEl.html(maxText); len = $cellEl.outerWidth(); $rowEl.remove(); $cellEl = null; return len; } $(data).each(function (index, row) { val = (Array.isArray(row) ? row[columnDef.field] : row); if (columnDef.formatterOverride) { // use formatterOverride as first preference formatterResult = columnDef.formatterOverride(index, colIndex, val, columnDef, row, self); } else if (columnDef.formatter) { // otherwise, use formatter formatterResult = columnDef.formatter(index, colIndex, val, columnDef, row, self); } else { // otherwise, use plain text formatterResult = '' + val; } applyFormatResultToCellNode(formatterResult, $cellEl[0]); len = $cellEl.outerWidth(); if (len > max) { max = len; } }); $rowEl.remove(); $cellEl = null; return max; } function getColHeaderWidth(columnDef) { var width = 0; //if (columnDef && (!columnDef.resizable || columnDef._autoCalcWidth === true)) return; var headerColElId = getUID() + columnDef.id; var headerColEl = document.getElementById(headerColElId); var dummyHeaderColElId = headerColElId + "_"; if (headerColEl) { // headers have been created, use clone technique var clone = headerColEl.cloneNode(true); clone.id = dummyHeaderColElId; clone.style.cssText = 'position: absolute; visibility: hidden;right: auto;text-overflow: initial;white-space: nowrap;'; headerColEl.parentNode.insertBefore(clone, headerColEl); width = clone.offsetWidth; clone.parentNode.removeChild(clone); } else { // headers have not yet been created, create a new node var header = getHeader(columnDef); headerColEl = $("<div class='ui-state-default slick-header-column' />") .html("<span class='slick-column-name'>" + columnDef.name + "</span>") .attr("id", dummyHeaderColElId) .css({ "position": "absolute", "visibility": "hidden", "right": "auto", "text-overflow:": "initial", "white-space": "nowrap" }) .addClass(columnDef.headerCssClass || "") .appendTo(header); width = headerColEl[0].offsetWidth; header[0].removeChild(headerColEl[0]); } return width; } function legacyAutosizeColumns() { var i, c, widths = [], shrinkLeeway = 0, total = 0, prevTotal, availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; for (i = 0; i < columns.length; i++) { c = columns[i]; widths.push(c.width); total += c.width; if (c.resizable) { shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth); } } // shrink prevTotal = total; while (total > availWidth && shrinkLeeway) { var shrinkProportion = (total - availWidth) / shrinkLeeway; for (i = 0; i < columns.length && total > availWidth; i++) { c = columns[i]; var width = widths[i]; if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) { continue; } var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth); var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1; shrinkSize = Math.min(shrinkSize, width - absMinWidth); total -= shrinkSize; shrinkLeeway -= shrinkSize; widths[i] -= shrinkSize; } if (prevTotal <= total) { // avoid infinite loop break; } prevTotal = total; } // grow prevTotal = total; while (total < availWidth) { var growProportion = availWidth / total; for (i = 0; i < columns.length && total < availWidth; i++) { c = columns[i]; var currentWidth = widths[i]; var growSize; if (!c.resizable || c.maxWidth <= currentWidth) { growSize = 0; } else { growSize = Math.min(Math.floor(growProportion * currentWidth) - currentWidth, (c.maxWidth - currentWidth) || 1000000) || 1; } total += growSize; widths[i] += (total <= availWidth ? growSize : 0); } if (prevTotal >= total) { // avoid infinite loop break; } prevTotal = total; } var reRender = false; for (i = 0; i < columns.length; i++) { if (columns[i].rerenderOnResize && columns[i].width != widths[i]) { reRender = true; } columns[i].width = widths[i]; } reRenderColumns(reRender); } function reRenderColumns(reRender) { applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); updateCanvasWidth(true); trigger(self.onAutosizeColumns, { "columns": columns}); if (reRender) { invalidateAllRows(); render(); } } ////////////////////////////////////////////////////////////////////////////////////////////// // General ////////////////////////////////////////////////////////////////////////////////////////////// function trigger(evt, args, e) { e = e || new Slick.EventData(); args = args || {}; args.grid = self; return evt.notify(args, e, self); } function getEditorLock() { return options.editorLock; } function getEditController() { return editController; } function getColumnIndex(id) { return columnsById[id]; } function applyColumnGroupHeaderWidths() { if (!treeColumns.hasDepth()) return; for (var depth = $groupHeadersL.length - 1; depth >= 0; depth--) { var groupColumns = treeColumns.getColumnsInDepth(depth); $().add($groupHeadersL[depth]).add($groupHeadersR[depth]).each(function(i) { var $groupHeader = $(this), currentColumnIndex = 0; $groupHeader.width(i === 0? getHeadersWidthL(): getHeadersWidthR()); $groupHeader.children().each(function() { var $groupHeaderColumn = $(this); var m = $(this).data('column'); m.width = 0; m.columns.forEach(function() { var $headerColumn = $groupHeader.next().children(':eq(' + (currentColumnIndex++) + ')'); m.width += $headerColumn.outerWidth(); }); $groupHeaderColumn.width(m.width - headerColumnWidthDiff); }); }); } } function applyColumnHeaderWidths() { if (!initialized) { return; } var h; for (var i = 0, headers = $headers.children(), ii = columns.length; i < ii; i++) { h = $(headers[i]); if (jQueryNewWidthBehaviour) { if (h.outerWidth() !== columns[i].width) { h.outerWidth(columns[i].width); } } else { if (h.width() !== columns[i].width - headerColumnWidthDiff) { h.width(columns[i].width - headerColumnWidthDiff); } } } updateColumnCaches(); } function applyColumnWidths() { var x = 0, w, rule; for (var i = 0; i < columns.length; i++) { w = columns[i].width; rule = getColumnCssRules(i); rule.left.style.left = x + "px"; rule.right.style.right = (((options.frozenColumn != -1 && i > options.frozenColumn) ? canvasWidthR : canvasWidthL) - x - w) + "px"; // If this column is frozen, reset the css left value since the // column starts in a new viewport. if (options.frozenColumn == i) { x = 0; } else { x += columns[i].width; } } } function setSortColumn(columnId, ascending) { setSortColumns([{ columnId: columnId, sortAsc: ascending}]); } function setSortColumns(cols) { sortColumns = cols; var numberCols = options.numberedMultiColumnSort && sortColumns.length > 1; var headerColumnEls = $headers.children(); headerColumnEls .removeClass("slick-header-column-sorted") .find(".slick-sort-indicator") .removeClass("slick-sort-indicator-asc slick-sort-indicator-desc"); headerColumnEls .find(".slick-sort-indicator-numbered") .text(''); $.each(sortColumns, function(i, col) { if (col.sortAsc == null) { col.sortAsc = true; } var columnIndex = getColumnIndex(col.columnId); if (columnIndex != null) { headerColumnEls.eq(columnIndex) .addClass("slick-header-column-sorted") .find(".slick-sort-indicator") .addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc"); if (numberCols) { headerColumnEls.eq(columnIndex) .find(".slick-sort-indicator-numbered") .text(i+1); } } }); } function getSortColumns() { return sortColumns; } function handleSelectedRangesChanged(e, ranges) { var previousSelectedRows = selectedRows.slice(0); // shallow copy previously selected rows for later comparison selectedRows = []; var hash = {}; for (var i = 0; i < ranges.length; i++) { for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) { if (!hash[j]) { // prevent duplicates selectedRows.push(j); hash[j] = {}; } for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) { if (canCellBeSelected(j, k)) { hash[j][columns[k].id] = options.selectedCellCssClass; } } } } setCellCssStyles(options.selectedCellCssClass, hash); if (simpleArrayEquals(previousSelectedRows, selectedRows)) { trigger(self.onSelectedRowsChanged, {rows: getSelectedRows(), previousSelectedRows: previousSelectedRows}, e); } } // compare 2 simple arrays (integers or strings only, do not use to compare object arrays) function simpleArrayEquals(arr1, arr2) { return Array.isArray(arr1) && Array.isArray(arr2) && arr2.sort().toString() !== arr1.sort().toString(); } function getColumns() { return columns; } function updateColumnCaches() { // Pre-calculate cell boundaries. columnPosLeft = []; columnPosRight = []; var x = 0; for (var i = 0, ii = columns.length; i < ii; i++) { columnPosLeft[i] = x; columnPosRight[i] = x + columns[i].width; if (options.frozenColumn == i) { x = 0; } else { x += columns[i].width; } } } function updateColumnProps() { columnsById = {}; for (var i = 0; i < columns.length; i++) { if (columns[i].width) { columns[i].widthRequest = columns[i].width; } var m = columns[i] = $.extend({}, columnDefaults, columns[i]); m.autoSize = $.extend({}, columnAutosizeDefaults, m.autoSize); columnsById[m.id] = i; if (m.minWidth && m.width < m.minWidth) { m.width = m.minWidth; } if (m.maxWidth && m.width > m.maxWidth) { m.width = m.maxWidth; } if (!m.resizable) { // there is difference between user resizable and autoWidth resizable //m.autoSize.autosizeMode = Slick.ColAutosizeMode.Locked; } } } function setColumns(columnDefinitions) { var _treeColumns = new Slick.TreeColumns(columnDefinitions); if (_treeColumns.hasDepth()) { treeColumns = _treeColumns; columns = treeColumns.extractColumns(); } else { columns = columnDefinitions; } updateColumnProps(); updateColumnCaches(); if (initialized) { setPaneVisibility(); setOverflow(); invalidateAllRows(); createColumnHeaders(); createColumnGroupHeaders(); createColumnFooter(); removeCssRules(); createCssRules(); resizeCanvas(); updateCanvasWidth(); applyColumnHeaderWidths(); applyColumnWidths(); handleScroll(); } } function getOptions() { return options; } function setOptions(args, suppressRender, suppressColumnSet) { if (!getEditorLock().commitCurrentEdit()) { return; } makeActiveCellNormal(); if (args.showColumnHeader !== undefined) { setColumnHeaderVisibility(args.showColumnHeader); } if (options.enableAddRow !== args.enableAddRow) { invalidateRow(getDataLength()); } var originalOptions = $.extend(true, {}, options); options = $.extend(options, args); trigger(self.onSetOptions, { "optionsBefore": originalOptions, "optionsAfter": options }); validateAndEnforceOptions(); $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto"); if (!suppressRender) { render(); } setFrozenOptions(); setScroller(); zombieRowNodeFromLastMouseWheelEvent = null; if (!suppressColumnSet) { setColumns(treeColumns.extractColumns()); } if (options.enableMouseWheelScrollHandler && $viewport && jQuery.fn.mousewheel) { var viewportEvents = $._data($viewport[0], "events"); if (!viewportEvents || !viewportEvents.mousewheel) { $viewport.on("mousewheel", handleMouseWheel); } } else if (options.enableMouseWheelScrollHandler === false) { $viewport.off("mousewheel"); // remove scroll handler when option is disable } } function validateAndEnforceOptions() { if (options.autoHeight) { options.leaveSpaceForNewRows = false; } if (options.forceFitColumns) { options.autosizeColsMode = Slick.GridAutosizeColsMode.LegacyForceFit; console.log("forceFitColumns option is deprecated - use autosizeColsMode"); } } function setData(newData, scrollToTop) { data = newData; invalidateAllRows(); updateRowCount(); if (scrollToTop) { scrollTo(0); } } function getData() { return data; } function getDataLength() { if (data.getLength) { return data.getLength(); } else { return data && data.length || 0; } } function getDataLengthIncludingAddNew() { return getDataLength() + (!options.enableAddRow ? 0 : (!pagingActive || pagingIsLastPage ? 1 : 0) ); } function getDataItem(i) { if (data.getItem) { return data.getItem(i); } else { return data[i]; } } function getTopPanel() { return $topPanel[0]; } function setTopPanelVisibility(visible, animate) { var animated = (animate === false) ? false : true; if (options.showTopPanel != visible) { options.showTopPanel = visible; if (visible) { if (animated) { $topPanelScroller.slideDown("fast", resizeCanvas); } else { $topPanelScroller.show(); resizeCanvas(); } } else { if (animated) { $topPanelScroller.slideUp("fast", resizeCanvas); } else { $topPanelScroller.hide(); resizeCanvas(); } } } } function setHeaderRowVisibility(visible, animate) { var animated = (animate === false) ? false : true; if (options.showHeaderRow != visible) { options.showHeaderRow = visible; if (visible) { if (animated) { $headerRowScroller.slideDown("fast", resizeCanvas); } else { $headerRowScroller.show(); resizeCanvas(); } } else { if (animated) { $headerRowScroller.slideUp("fast", resizeCanvas); } else { $headerRowScroller.hide(); resizeCanvas(); } } } } function setColumnHeaderVisibility(visible, animate) { if (options.showColumnHeader != visible) { options.showColumnHeader = visible; if (visible) { if (animate) { $headerScroller.slideDown("fast", resizeCanvas); } else { $headerScroller.show(); resizeCanvas(); } } else { if (animate) { $headerScroller.slideUp("fast", resizeCanvas); } else { $headerScroller.hide(); resizeCanvas(); } } } } function setFooterRowVisibility(visible, animate) { var animated = (animate === false) ? false : true; if (options.showFooterRow != visible) { options.showFooterRow = visible; if (visible) { if (animated) { $footerRowScroller.slideDown("fast", resizeCanvas); } else { $footerRowScroller.show(); resizeCanvas(); } } else { if (animated) { $footerRowScroller.slideUp("fast", resizeCanvas); } else { $footerRowScroller.hide(); resizeCanvas(); } } } } function setPreHeaderPanelVisibility(visible, animate) { var animated = (animate === false) ? false : true; if (options.showPreHeaderPanel != visible) { options.showPreHeaderPanel = visible; if (visible) { if (animated) { $preHeaderPanelScroller.slideDown("fast", resizeCanvas); } else { $preHeaderPanelScroller.show(); resizeCanvas(); } } else { if (animated) { $preHeaderPanelScroller.slideUp("fast", resizeCanvas); } else { $preHeaderPanelScroller.hide(); resizeCanvas(); } } } } function getContainerNode() { return $container.get(0); } ////////////////////////////////////////////////////////////////////////////////////////////// // Rendering / Scrolling function getRowTop(row) { return options.rowHeight * row - offset; } function getRowFromPosition(y) { return Math.floor((y + offset) / options.rowHeight); } function scrollTo(y) { y = Math.max(y, 0); y = Math.min(y, th - $viewportScrollContainerY.height() + ((viewportHasHScroll || hasFrozenColumns()) ? scrollbarDimensions.height : 0)); var oldOffset = offset; page = Math.min(n - 1, Math.floor(y / ph)); offset = Math.round(page * cj); var newScrollTop = y - offset; if (offset != oldOffset) { var range = getVisibleRange(newScrollTop); cleanupRows(range); updateRowPositions(); } if (prevScrollTop != newScrollTop) { vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1; lastRenderedScrollTop = ( scrollTop = prevScrollTop = newScrollTop ); if (hasFrozenColumns()) { $viewportTopL[0].scrollTop = newScrollTop; } if (hasFrozenRows) { $viewportBottomL[0].scrollTop = $viewportBottomR[0].scrollTop = newScrollTop; } $viewportScrollContainerY[0].scrollTop = newScrollTop; trigger(self.onViewportChanged, {}); } } function defaultFormatter(row, cell, value, columnDef, dataContext, grid) { if (value == null) { return ""; } else { return (value + "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); } } function getFormatter(row, column) { var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); // look up by id, then index var columnOverrides = rowMetadata && rowMetadata.columns && (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]); return (columnOverrides && columnOverrides.formatter) || (rowMetadata && rowMetadata.formatter) || column.formatter || (options.formatterFactory && options.formatterFactory.getFormatter(column)) || options.defaultFormatter; } function getEditor(row, cell) { var column = columns[cell]; var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) { return columnMetadata[column.id].editor; } if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) { return columnMetadata[cell].editor; } return column.editor || (options.editorFactory && options.editorFactory.getEditor(column)); } function getDataItemValueForColumn(item, columnDef) { if (options.dataItemColumnValueExtractor) { return options.dataItemColumnValueExtractor(item, columnDef); } return item[columnDef.field]; } function appendRowHtml(stringArrayL, stringArrayR, row, range, dataLength) { var d = getDataItem(row); var dataLoading = row < dataLength && !d; var rowCss = "slick-row" + (hasFrozenRows && row <= options.frozenRow? ' frozen': '') + (dataLoading ? " loading" : "") + (row === activeRow && options.showCellSelection ? " active" : "") + (row % 2 == 1 ? " odd" : " even"); if (!d) { rowCss += " " + options.addNewRowCssClass; } var metadata = data.getItemMetadata && data.getItemMetadata(row); if (metadata && metadata.cssClasses) { rowCss += " " + metadata.cssClasses; } var frozenRowOffset = getFrozenRowOffset(row); var rowHtml = "<div class='ui-widget-content " + rowCss + "' style='top:" + (getRowTop(row) - frozenRowOffset ) + "px'>"; stringArrayL.push(rowHtml); if (hasFrozenColumns()) { stringArrayR.push(rowHtml); } var colspan, m; for (var i = 0, ii = columns.length; i < ii; i++) { m = columns[i]; colspan = 1; if (metadata && metadata.columns) { var columnData = metadata.columns[m.id] || metadata.columns[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } // Do not render cells outside of the viewport. if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { if (!m.alwaysRenderColumn && columnPosLeft[i] > range.rightPx) { // All columns to the right are outside the range. break; } if (hasFrozenColumns() && ( i > options.frozenColumn )) { appendCellHtml(stringArrayR, row, i, colspan, d); } else { appendCellHtml(stringArrayL, row, i, colspan, d); } } else if (m.alwaysRenderColumn || (hasFrozenColumns() && i <= options.frozenColumn)) { appendCellHtml(stringArrayL, row, i, colspan, d); } if (colspan > 1) { i += (colspan - 1); } } stringArrayL.push("</div>"); if (hasFrozenColumns()) { stringArrayR.push("</div>"); } } function appendCellHtml(stringArray, row, cell, colspan, item) { // stringArray: stringBuilder containing the HTML parts // row, cell: row and column index // colspan: HTML colspan // item: grid data for row var m = columns[cell]; var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1) + (m.cssClass ? " " + m.cssClass : ""); if (hasFrozenColumns() && cell <= options.frozenColumn) { cellCss += (" frozen"); } if (row === activeRow && cell === activeCell && options.showCellSelection) { cellCss += (" active"); } // TODO: merge them together in the setter for (var key in cellCssClasses) { if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) { cellCss += (" " + cellCssClasses[key][row][m.id]); } } var value = null, formatterResult = ''; if (item) { value = getDataItemValueForColumn(item, m); formatterResult = getFormatter(row, m)(row, cell, value, m, item, self); if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; } } // get addl css class names from object type formatter return and from string type return of onBeforeAppendCell var addlCssClasses = trigger(self.onBeforeAppendCell, { row: row, cell: cell, value: value, dataContext: item }) || ''; addlCssClasses += (formatterResult && formatterResult.addClasses ? (addlCssClasses ? ' ' : '') + formatterResult.addClasses : ''); var toolTip = formatterResult && formatterResult.toolTip ? "title='" + formatterResult.toolTip + "'" : ''; var customAttrStr = ''; if(m.hasOwnProperty('cellAttrs') && m.cellAttrs instanceof Object) { for (var key in m.cellAttrs) { if (m.cellAttrs.hasOwnProperty(key)) { customAttrStr += ' ' + key + '="' + m.cellAttrs[key] + '" '; } } } stringArray.push("<div class='" + cellCss + (addlCssClasses ? ' ' + addlCssClasses : '') + "' " + toolTip + customAttrStr + ">"); // if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet) if (item) { stringArray.push(Object.prototype.toString.call(formatterResult) !== '[object Object]' ? formatterResult : formatterResult.text); } stringArray.push("</div>"); rowsCache[row].cellRenderQueue.push(cell); rowsCache[row].cellColSpans[cell] = colspan; } function cleanupRows(rangeToKeep) { for (var i in rowsCache) { var removeFrozenRow = true; if (hasFrozenRows && ( ( options.frozenBottom && i >= actualFrozenRow ) // Frozen bottom rows || ( !options.frozenBottom && i <= actualFrozenRow ) // Frozen top rows ) ) { removeFrozenRow = false; } if (( ( i = parseInt(i, 10)) !== activeRow ) && ( i < rangeToKeep.top || i > rangeToKeep.bottom ) && ( removeFrozenRow ) ) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidate() { updateRowCount(); invalidateAllRows(); render(); } function invalidateAllRows() { if (currentEditor) { makeActiveCellNormal(); } for (var row in rowsCache) { removeRowFromCache(row); } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function queuePostProcessedRowForCleanup(cacheEntry, postProcessedRow, rowIdx) { postProcessgroupId++; // store and detach node for later async cleanup for (var columnIdx in postProcessedRow) { if (postProcessedRow.hasOwnProperty(columnIdx)) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cacheEntry.cellNodesByColumnIdx[ columnIdx | 0], columnIdx: columnIdx | 0, rowIdx: rowIdx }); } } postProcessedCleanupQueue.push({ actionType: 'R', groupId: postProcessgroupId, node: cacheEntry.rowNode }); $(cacheEntry.rowNode).detach(); } function queuePostProcessedCellForCleanup(cellnode, columnIdx, rowIdx) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cellnode, columnIdx: columnIdx, rowIdx: rowIdx }); $(cellnode).detach(); } function removeRowFromCache(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } if (rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[0] || (hasFrozenColumns() && rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[1])) { cacheEntry.rowNode.hide(); zombieRowNodeFromLastMouseWheelEvent = cacheEntry.rowNode; } else { cacheEntry.rowNode.each(function() { this.parentElement.removeChild(this); }); } delete rowsCache[row]; delete postProcessedRows[row]; renderedRows--; counter_rows_removed++; } function invalidateRows(rows) { var i, rl; if (!rows || !rows.length) { return; } vScrollDir = 0; rl = rows.length; for (i = 0; i < rl; i++) { if (currentEditor && activeRow === rows[i]) { makeActiveCellNormal(); } if (rowsCache[rows[i]]) { removeRowFromCache(rows[i]); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidateRow(row) { if (!row && row !== 0) { return; } invalidateRows([row]); } function applyFormatResultToCellNode(formatterResult, cellNode, suppressRemove) { if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; } if (Object.prototype.toString.call(formatterResult) !== '[object Object]') { cellNode.innerHTML = formatterResult; return; } cellNode.innerHTML = formatterResult.text; if (formatterResult.removeClasses && !suppressRemove) { $(cellNode).removeClass(formatterResult.removeClasses); } if (formatterResult.addClasses) { $(cellNode).addClass(formatterResult.addClasses); } if (formatterResult.toolTip) { $(cellNode).attr("title", formatterResult.toolTip); } } function updateCell(row, cell) { var cellNode = getCellNode(row, cell); if (!cellNode) { return; } var m = columns[cell], d = getDataItem(row); if (currentEditor && activeRow === row && activeCell === cell) { currentEditor.loadValue(d); } else { var formatterResult = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d, self) : ""; applyFormatResultToCellNode(formatterResult, cellNode); invalidatePostProcessingResults(row); } } function updateRow(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } ensureCellNodesInRowsCache(row); var formatterResult, d = getDataItem(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx], node = cacheEntry.cellNodesByColumnIdx[columnIdx][0]; if (row === activeRow && columnIdx === activeCell && currentEditor) { currentEditor.loadValue(d); } else if (d) { formatterResult = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d, self); applyFormatResultToCellNode(formatterResult, node); } else { node.innerHTML = ""; } } invalidatePostProcessingResults(row); } function getViewportHeight() { if (!options.autoHeight || options.frozenColumn != -1) { topPanelH = ( options.showTopPanel ) ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0; headerRowH = ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0; footerRowH = ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0; } if (options.autoHeight) { var fullHeight = $paneHeaderL.outerHeight(); fullHeight += ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0; fullHeight += ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0; fullHeight += (getCanvasWidth() > viewportW) ? scrollbarDimensions.height : 0; viewportH = options.rowHeight * getDataLengthIncludingAddNew() + ( ( options.frozenColumn == -1 ) ? fullHeight : 0 ); } else { var columnNamesH = ( options.showColumnHeader ) ? parseFloat($.css($headerScroller[0], "height")) + getVBoxDelta($headerScroller) : 0; var preHeaderH = (options.createPreHeaderPanel && options.showPreHeaderPanel) ? options.preHeaderPanelHeight + getVBoxDelta($preHeaderPanelScroller) : 0; viewportH = parseFloat($.css($container[0], "height", true)) - parseFloat($.css($container[0], "paddingTop", true)) - parseFloat($.css($container[0], "paddingBottom", true)) - columnNamesH - topPanelH - headerRowH - footerRowH - preHeaderH; } numVisibleRows = Math.ceil(viewportH / options.rowHeight); return viewportH; } function getViewportWidth() { viewportW = parseFloat($container.width()); } function resizeCanvas() { if (!initialized) { return; } paneTopH = 0; paneBottomH = 0; viewportTopH = 0; viewportBottomH = 0; getViewportWidth(); getViewportHeight(); // Account for Frozen Rows if (hasFrozenRows) { if (options.frozenBottom) { paneTopH = viewportH - frozenRowsHeight - scrollbarDimensions.height; paneBottomH = frozenRowsHeight + scrollbarDimensions.height; } else { paneTopH = frozenRowsHeight; paneBottomH = viewportH - frozenRowsHeight; } } else { paneTopH = viewportH; } // The top pane includes the top panel and the header row paneTopH += topPanelH + headerRowH + footerRowH; if (hasFrozenColumns() && options.autoHeight) { paneTopH += scrollbarDimensions.height; } // The top viewport does not contain the top panel or header row viewportTopH = paneTopH - topPanelH - headerRowH - footerRowH; if (options.autoHeight) { if (hasFrozenColumns()) { $container.height( paneTopH + parseFloat($.css($headerScrollerL[0], "height")) ); } $paneTopL.css('position', 'relative'); } $paneTopL.css({ 'top': $paneHeaderL.height(), 'height': paneTopH }); var paneBottomTop = $paneTopL.position().top + paneTopH; if (!options.autoHeight) { $viewportTopL.height(viewportTopH); } if (hasFrozenColumns()) { $paneTopR.css({ 'top': $paneHeaderL.height(), 'height': paneTopH }); $viewportTopR.height(viewportTopH); if (hasFrozenRows) { $paneBottomL.css({ 'top': paneBottomTop, 'height': paneBottomH }); $paneBottomR.css({ 'top': paneBottomTop, 'height': paneBottomH }); $viewportBottomR.height(paneBottomH); } } else { if (hasFrozenRows) { $paneBottomL.css({ 'width': '100%', 'height': paneBottomH }); $paneBottomL.css('top', paneBottomTop); } } if (hasFrozenRows) { $viewportBottomL.height(paneBottomH); if (options.frozenBottom) { $canvasBottomL.height(frozenRowsHeight); if (hasFrozenColumns()) { $canvasBottomR.height(frozenRowsHeight); } } else { $canvasTopL.height(frozenRowsHeight); if (hasFrozenColumns()) { $canvasTopR.height(frozenRowsHeight); } } } else { $viewportTopR.height(viewportTopH); } if (!scrollbarDimensions || !scrollbarDimensions.width) { scrollbarDimensions = measureScrollbar(); } if (options.autosizeColsMode === Slick.GridAutosizeColsMode.LegacyForceFit) { autosizeColumns(); } updateRowCount(); handleScroll(); // Since the width has changed, force the render() to reevaluate virtually rendered cells. lastRenderedScrollLeft = -1; render(); } function updatePagingStatusFromView( pagingInfo ) { pagingActive = (pagingInfo.pageSize !== 0); pagingIsLastPage = (pagingInfo.pageNum == pagingInfo.totalPages - 1); } function updateRowCount() { if (!initialized) { return; } var dataLength = getDataLength(); var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); var numberOfRows = 0; var oldH = ( hasFrozenRows && !options.frozenBottom ) ? $canvasBottomL.height() : $canvasTopL.height(); if (hasFrozenRows ) { var numberOfRows = getDataLength() - options.frozenRow; } else { var numberOfRows = dataLengthIncludingAddNew + (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0); } var tempViewportH = $viewportScrollContainerY.height(); var oldViewportHasVScroll = viewportHasVScroll; // with autoHeight, we do not need to accommodate the vertical scroll bar viewportHasVScroll = options.alwaysShowVerticalScroll || !options.autoHeight && (numberOfRows * options.rowHeight > tempViewportH); makeActiveCellNormal(); // remove the rows that are now outside of the data range // this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows var r1 = dataLength - 1; for (var i in rowsCache) { if (i > r1) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } if (activeCellNode && activeRow > r1) { resetActiveCell(); } var oldH = h; if (options.autoHeight) { h = options.rowHeight * numberOfRows; } else { th = Math.max(options.rowHeight * numberOfRows, tempViewportH - scrollbarDimensions.height); if (th < maxSupportedCssHeight) { // just one page h = ph = th; n = 1; cj = 0; } else { // break into pages h = maxSupportedCssHeight; ph = h / 100; n = Math.floor(th / ph); cj = (th - h) / (n - 1); } } if (h !== oldH) { if (hasFrozenRows && !options.frozenBottom) { $canvasBottomL.css("height", h); if (hasFrozenColumns()) { $canvasBottomR.css("height", h); } } else { $canvasTopL.css("height", h); $canvasTopR.css("height", h); } scrollTop = $viewportScrollContainerY[0].scrollTop; } var oldScrollTopInRange = (scrollTop + offset <= th - tempViewportH); if (th == 0 || scrollTop == 0) { page = offset = 0; } else if (oldScrollTopInRange) { // maintain virtual position scrollTo(scrollTop + offset); } else { // scroll to bottom scrollTo(th - tempViewportH); } if (h != oldH && options.autoHeight) { resizeCanvas(); } if (options.autosizeColsMode === Slick.GridAutosizeColsMode.LegacyForceFit && oldViewportHasVScroll != viewportHasVScroll) { autosizeColumns(); } updateCanvasWidth(false); } function getVisibleRange(viewportTop, viewportLeft) { if (viewportTop == null) { viewportTop = scrollTop; } if (viewportLeft == null) { viewportLeft = scrollLeft; } return { top: getRowFromPosition(viewportTop), bottom: getRowFromPosition(viewportTop + viewportH) + 1, leftPx: viewportLeft, rightPx: viewportLeft + viewportW }; } function getRenderedRange(viewportTop, viewportLeft) { var range = getVisibleRange(viewportTop, viewportLeft); var buffer = Math.round(viewportH / options.rowHeight); var minBuffer = options.minRowBuffer; if (vScrollDir == -1) { range.top -= buffer; range.bottom += minBuffer; } else if (vScrollDir == 1) { range.top -= minBuffer; range.bottom += buffer; } else { range.top -= minBuffer; range.bottom += minBuffer; } range.top = Math.max(0, range.top); range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom); range.leftPx -= viewportW; range.rightPx += viewportW; range.leftPx = Math.max(0, range.leftPx); range.rightPx = Math.min(canvasWidth, range.rightPx); return range; } function ensureCellNodesInRowsCache(row) { var cacheEntry = rowsCache[row]; if (cacheEntry) { if (cacheEntry.cellRenderQueue.length) { var $lastNode = cacheEntry.rowNode.children().last(); while (cacheEntry.cellRenderQueue.length) { var columnIdx = cacheEntry.cellRenderQueue.pop(); cacheEntry.cellNodesByColumnIdx[columnIdx] = $lastNode; $lastNode = $lastNode.prev(); // Hack to retrieve the frozen columns because if ($lastNode.length === 0) { $lastNode = $(cacheEntry.rowNode[0]).children().last(); } } } } } function cleanUpCells(range, row) { // Ignore frozen rows if (hasFrozenRows && ( ( options.frozenBottom && row > actualFrozenRow ) // Frozen bottom rows || ( row <= actualFrozenRow ) // Frozen top rows ) ) { return; } var totalCellsRemoved = 0; var cacheEntry = rowsCache[row]; // Remove cells outside the range. var cellsToRemove = []; for (var i in cacheEntry.cellNodesByColumnIdx) { // I really hate it when people mess with Array.prototype. if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) { continue; } // This is a string, so it needs to be cast back to a number. i = i | 0; // Ignore frozen columns if (i <= options.frozenColumn) { continue; } // Ignore alwaysRenderedColumns if (Array.isArray(columns) && columns[i] && columns[i].alwaysRenderColumn){ continue; } var colspan = cacheEntry.cellColSpans[i]; if (columnPosLeft[i] > range.rightPx || columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) { if (!(row == activeRow && i == activeCell)) { cellsToRemove.push(i); } } } var cellToRemove; while ((cellToRemove = cellsToRemove.pop()) != null) { cacheEntry.cellNodesByColumnIdx[cellToRemove][0].parentElement.removeChild(cacheEntry.cellNodesByColumnIdx[cellToRemove][0]); delete cacheEntry.cellColSpans[cellToRemove]; delete cacheEntry.cellNodesByColumnIdx[cellToRemove]; if (postProcessedRows[row]) { delete postProcessedRows[row][cellToRemove]; } totalCellsRemoved++; } } function cleanUpAndRenderCells(range) { var cacheEntry; var stringArray = []; var processedRows = []; var cellsAdded; var totalCellsAdded = 0; var colspan; for (var row = range.top, btm = range.bottom; row <= btm; row++) { cacheEntry = rowsCache[row]; if (!cacheEntry) { continue; } // cellRenderQueue populated in renderRows() needs to be cleared first ensureCellNodesInRowsCache(row); cleanUpCells(range, row); // Render missing cells. cellsAdded = 0; var metadata = data.getItemMetadata && data.getItemMetadata(row); metadata = metadata && metadata.columns; var d = getDataItem(row); // TODO: shorten this loop (index? heuristics? binary search?) for (var i = 0, ii = columns.length; i < ii; i++) { // Cells to the right are outside the range. if (columnPosLeft[i] > range.rightPx) { break; } // Already rendered. if ((colspan = cacheEntry.cellColSpans[i]) != null) { i += (colspan > 1 ? colspan - 1 : 0); continue; } colspan = 1; if (metadata) { var columnData = metadata[columns[i].id] || metadata[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { appendCellHtml(stringArray, row, i, colspan, d); cellsAdded++; } i += (colspan > 1 ? colspan - 1 : 0); } if (cellsAdded) { totalCellsAdded += cellsAdded; processedRows.push(row); } } if (!stringArray.length) { return; } var x = document.createElement("div"); x.innerHTML = stringArray.join(""); var processedRow; var node; while ((processedRow = processedRows.pop()) != null) { cacheEntry = rowsCache[processedRow]; var columnIdx; while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) { node = x.lastChild; if (hasFrozenColumns() && (columnIdx > options.frozenColumn)) { cacheEntry.rowNode[1].appendChild(node); } else { cacheEntry.rowNode[0].appendChild(node); } cacheEntry.cellNodesByColumnIdx[columnIdx] = $(node); } } } function renderRows(range) { var stringArrayL = [], stringArrayR = [], rows = [], needToReselectCell = false, dataLength = getDataLength(); for (var i = range.top, ii = range.bottom; i <= ii; i++) { if (rowsCache[i] || ( hasFrozenRows && options.frozenBottom && i == getDataLength() )) { continue; } renderedRows++; rows.push(i); // Create an entry right away so that appendRowHtml() can // start populatating it. rowsCache[i] = { "rowNode": null, // ColSpans of rendered cells (by column idx). // Can also be used for checking whether a cell has been rendered. "cellColSpans": [], // Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache(). "cellNodesByColumnIdx": [], // Column indices of cell nodes that have been rendered, but not yet indexed in // cellNodesByColumnIdx. These are in the same order as cell nodes added at the // end of the row. "cellRenderQueue": [] }; appendRowHtml(stringArrayL, stringArrayR, i, range, dataLength); if (activeCellNode && activeRow === i) { needToReselectCell = true; } counter_rows_rendered++; } if (!rows.length) { return; } var x = document.createElement("div"), xRight = document.createElement("div"); x.innerHTML = stringArrayL.join(""); xRight.innerHTML = stringArrayR.join(""); for (var i = 0, ii = rows.length; i < ii; i++) { if (( hasFrozenRows ) && ( rows[i] >= actualFrozenRow )) { if (hasFrozenColumns()) { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasBottomL)) .add($(xRight.firstChild).appendTo($canvasBottomR)); } else { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasBottomL)); } } else if (hasFrozenColumns()) { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasTopL)) .add($(xRight.firstChild).appendTo($canvasTopR)); } else { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasTopL)); } } if (needToReselectCell) { activeCellNode = getCellNode(activeRow, activeCell); } } function startPostProcessing() { if (!options.enableAsyncPostRender) { return; } clearTimeout(h_postrender); h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); } function startPostProcessingCleanup() { if (!options.enableAsyncPostRenderCleanup) { return; } clearTimeout(h_postrenderCleanup); h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } function invalidatePostProcessingResults(row) { // change status of columns to be re-rendered for (var columnIdx in postProcessedRows[row]) { if (postProcessedRows[row].hasOwnProperty(columnIdx)) { postProcessedRows[row][columnIdx] = 'C'; } } postProcessFromRow = Math.min(postProcessFromRow, row); postProcessToRow = Math.max(postProcessToRow, row); startPostProcessing(); } function updateRowPositions() { for (var row in rowsCache) { var rowNumber = row ? parseInt(row) : 0; rowsCache[rowNumber].rowNode[0].style.top = getRowTop(rowNumber) + "px"; } } function render() { if (!initialized) { return; } scrollThrottle.dequeue(); var visible = getVisibleRange(); var rendered = getRenderedRange(); // remove rows no longer in the viewport cleanupRows(rendered); // add new rows & missing cells in existing rows if (lastRenderedScrollLeft != scrollLeft) { if ( hasFrozenRows ) { var renderedFrozenRows = jQuery.extend(true, {}, rendered); if (options.frozenBottom) { renderedFrozenRows.top=actualFrozenRow; renderedFrozenRows.bottom=getDataLength(); } else { renderedFrozenRows.top=0; renderedFrozenRows.bottom=options.frozenRow; } cleanUpAndRenderCells(renderedFrozenRows); } cleanUpAndRenderCells(rendered); } // render missing rows renderRows(rendered); // Render frozen rows if (hasFrozenRows) { if (options.frozenBottom) { renderRows({ top: actualFrozenRow, bottom: getDataLength() - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx }); } else { renderRows({ top: 0, bottom: options.frozenRow - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx }); } } postProcessFromRow = visible.top; postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom); startPostProcessing(); lastRenderedScrollTop = scrollTop; lastRenderedScrollLeft = scrollLeft; h_render = null; trigger(self.onRendered, { startRow: visible.top, endRow: visible.bottom, grid: self }); } function handleHeaderScroll() { handleElementScroll($headerScrollContainer[0]); } function handleHeaderRowScroll() { var scrollLeft = $headerRowScrollContainer[0].scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handleFooterRowScroll() { var scrollLeft = $footerRowScrollContainer[0].scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handlePreHeaderPanelScroll() { handleElementScroll($preHeaderPanelScroller[0]); } function handleElementScroll(element) { var scrollLeft = element.scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handleScroll() { scrollTop = $viewportScrollContainerY[0].scrollTop; scrollLeft = $viewportScrollContainerX[0].scrollLeft; return _handleScroll(false); } function _handleScroll(isMouseWheel) { var maxScrollDistanceY = $viewportScrollContainerY[0].scrollHeight - $viewportScrollContainerY[0].clientHeight; var maxScrollDistanceX = $viewportScrollContainerY[0].scrollWidth - $viewportScrollContainerY[0].clientWidth; // Protect against erroneous clientHeight/Width greater than scrollHeight/Width. // Sometimes seen in Chrome. maxScrollDistanceY = Math.max(0, maxScrollDistanceY); maxScrollDistanceX = Math.max(0, maxScrollDistanceX); // Ceiling the max scroll values if (scrollTop > maxScrollDistanceY) { scrollTop = maxScrollDistanceY; } if (scrollLeft > maxScrollDistanceX) { scrollLeft = maxScrollDistanceX; } var vScrollDist = Math.abs(scrollTop - prevScrollTop); var hScrollDist = Math.abs(scrollLeft - prevScrollLeft); if (hScrollDist) { prevScrollLeft = scrollLeft; $viewportScrollContainerX[0].scrollLeft = scrollLeft; $headerScrollContainer[0].scrollLeft = scrollLeft; $topPanelScroller[0].scrollLeft = scrollLeft; $headerRowScrollContainer[0].scrollLeft = scrollLeft; if (options.createFooterRow) { $footerRowScrollContainer[0].scrollLeft = scrollLeft; } if (options.createPreHeaderPanel) { if (hasFrozenColumns()) { $preHeaderPanelScrollerR[0].scrollLeft = scrollLeft; } else { $preHeaderPanelScroller[0].scrollLeft = scrollLeft; } } if (hasFrozenColumns()) { if (hasFrozenRows) { $viewportTopR[0].scrollLeft = scrollLeft; } } else { if (hasFrozenRows) { $viewportTopL[0].scrollLeft = scrollLeft; } } } if (vScrollDist) { vScrollDir = prevScrollTop < scrollTop ? 1 : -1; prevScrollTop = scrollTop; if (isMouseWheel) { $viewportScrollContainerY[0].scrollTop = scrollTop; } if (hasFrozenColumns()) { if (hasFrozenRows && !options.frozenBottom) { $viewportBottomL[0].scrollTop = scrollTop; } else { $viewportTopL[0].scrollTop = scrollTop; } } // switch virtual pages if needed if (vScrollDist < viewportH) { scrollTo(scrollTop + offset); } else { var oldOffset = offset; if (h == viewportH) { page = 0; } else { page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph))); } offset = Math.round(page * cj); if (oldOffset != offset) { invalidateAllRows(); } } } if (hScrollDist || vScrollDist) { var dx = Math.abs(lastRenderedScrollLeft - scrollLeft); var dy = Math.abs(lastRenderedScrollTop - scrollTop); if (dx > 20 || dy > 20) { // if rendering is forced or scrolling is small enough to be "easy", just render if (options.forceSyncScrolling || (dy < viewportH && dx < viewportW)) { render(); } else { // otherwise, perform "difficult" renders at a capped frequency scrollThrottle.enqueue(); } trigger(self.onViewportChanged, {}); } } trigger(self.onScroll, {scrollLeft: scrollLeft, scrollTop: scrollTop}); if (hScrollDist || vScrollDist) return true; return false; } /* limits the frequency at which the provided action is executed. call enqueue to execute the action - it will execute either immediately or, if it was executed less than minPeriod_ms in the past, as soon as minPeriod_ms has expired. call dequeue to cancel any pending action. */ function ActionThrottle(action, minPeriod_ms) { var blocked = false; var queued = false; function enqueue() { if (!blocked) { blockAndExecute(); } else { queued = true; } } function dequeue() { queued = false; } function blockAndExecute() { blocked = true; setTimeout(unblock, minPeriod_ms); action(); } function unblock() { if (queued) { dequeue(); blockAndExecute(); } else { blocked = false; } } return { enqueue: enqueue, dequeue: dequeue }; } function asyncPostProcessRows() { var dataLength = getDataLength(); while (postProcessFromRow <= postProcessToRow) { var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--; var cacheEntry = rowsCache[row]; if (!cacheEntry || row >= dataLength) { continue; } if (!postProcessedRows[row]) { postProcessedRows[row] = {}; } ensureCellNodesInRowsCache(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx]; var processedStatus = postProcessedRows[row][columnIdx]; // C=cleanup and re-render, R=rendered if (m.asyncPostRender && processedStatus !== 'R') { var node = cacheEntry.cellNodesByColumnIdx[columnIdx]; if (node) { m.asyncPostRender(node, row, getDataItem(row), m, (processedStatus === 'C')); } postProcessedRows[row][columnIdx] = 'R'; } } h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); return; } } function asyncPostProcessCleanupRows() { if (postProcessedCleanupQueue.length > 0) { var groupId = postProcessedCleanupQueue[0].groupId; // loop through all queue members with this groupID while (postProcessedCleanupQueue.length > 0 && postProcessedCleanupQueue[0].groupId == groupId) { var entry = postProcessedCleanupQueue.shift(); if (entry.actionType == 'R') { $(entry.node).remove(); } if (entry.actionType == 'C') { var column = columns[entry.columnIdx]; if (column.asyncPostRenderCleanup && entry.node) { // cleanup must also remove element column.asyncPostRenderCleanup(entry.node, entry.rowIdx, column); } } } // call this function again after the specified delay h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } } function updateCellCssStylesOnRenderedRows(addedHash, removedHash) { var node, columnId, addedRowHash, removedRowHash; for (var row in rowsCache) { removedRowHash = removedHash && removedHash[row]; addedRowHash = addedHash && addedHash[row]; if (removedRowHash) { for (columnId in removedRowHash) { if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).removeClass(removedRowHash[columnId]); } } } } if (addedRowHash) { for (columnId in addedRowHash) { if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).addClass(addedRowHash[columnId]); } } } } } } function addCellCssStyles(key, hash) { if (cellCssClasses[key]) { throw new Error("addCellCssStyles: cell CSS hash with key '" + key + "' already exists."); } cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, null); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function removeCellCssStyles(key) { if (!cellCssClasses[key]) { return; } updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]); delete cellCssClasses[key]; trigger(self.onCellCssStylesChanged, { "key": key, "hash": null, "grid": self }); } function setCellCssStyles(key, hash) { var prevHash = cellCssClasses[key]; cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, prevHash); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function getCellCssStyles(key) { return cellCssClasses[key]; } function flashCell(row, cell, speed) { speed = speed || 100; function toggleCellClass($cell, times) { if (!times) { return; } setTimeout(function () { $cell.queue(function () { $cell.toggleClass(options.cellFlashingCssClass).dequeue(); toggleCellClass($cell, times - 1); }); }, speed); } if (rowsCache[row]) { var $cell = $(getCellNode(row, cell)); toggleCellClass($cell, 4); } } ////////////////////////////////////////////////////////////////////////////////////////////// // Interactivity function handleMouseWheel(e, delta, deltaX, deltaY) { var $rowNode = $(e.target).closest(".slick-row"); var rowNode = $rowNode[0]; if (rowNode != rowNodeFromLastMouseWheelEvent) { var $gridCanvas = $rowNode.parents('.grid-canvas'); var left = $gridCanvas.hasClass('grid-canvas-left'); if (zombieRowNodeFromLastMouseWheelEvent && zombieRowNodeFromLastMouseWheelEvent[left? 0:1] != rowNode) { var zombieRow = zombieRowNodeFromLastMouseWheelEvent[left || zombieRowNodeFromLastMouseWheelEvent.length == 1? 0:1]; zombieRow.parentElement.removeChild(zombieRow); zombieRowNodeFromLastMouseWheelEvent = null; } rowNodeFromLastMouseWheelEvent = rowNode; } scrollTop = Math.max(0, $viewportScrollContainerY[0].scrollTop - (deltaY * options.rowHeight)); scrollLeft = $viewportScrollContainerX[0].scrollLeft + (deltaX * 10); var handled = _handleScroll(true); if (handled) e.preventDefault(); } function handleDragInit(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragInit, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } // if nobody claims to be handling drag'n'drop by stopping immediate propagation, // cancel out of it return false; } function handleDragStart(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragStart, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } return false; } function handleDrag(e, dd) { return trigger(self.onDrag, dd, e); } function handleDragEnd(e, dd) { trigger(self.onDragEnd, dd, e); } function handleKeyDown(e) { trigger(self.onKeyDown, {row: activeRow, cell: activeCell}, e); var handled = e.isImmediatePropagationStopped(); var keyCode = Slick.keyCode; if (!handled) { if (!e.shiftKey && !e.altKey) { if (options.editable && currentEditor && currentEditor.keyCaptureList) { if (currentEditor.keyCaptureList.indexOf(e.which) > -1) { return; } } if (e.which == keyCode.HOME) { handled = (e.ctrlKey) ? navigateTop() : navigateRowStart(); } else if (e.which == keyCode.END) { handled = (e.ctrlKey) ? navigateBottom() : navigateRowEnd(); } } } if (!handled) { if (!e.shiftKey && !e.altKey && !e.ctrlKey) { // editor may specify an array of keys to bubble if (options.editable && currentEditor && currentEditor.keyCaptureList) { if (currentEditor.keyCaptureList.indexOf( e.which ) > -1) { return; } } if (e.which == keyCode.ESCAPE) { if (!getEditorLock().isActive()) { return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event) } cancelEditAndSetFocus(); } else if (e.which == keyCode.PAGE_DOWN) { navigatePageDown(); handled = true; } else if (e.which == keyCode.PAGE_UP) { navigatePageUp(); handled = true; } else if (e.which == keyCode.LEFT) { handled = navigateLeft(); } else if (e.which == keyCode.RIGHT) { handled = navigateRight(); } else if (e.which == keyCode.UP) { handled = navigateUp(); } else if (e.which == keyCode.DOWN) { handled = navigateDown(); } else if (e.which == keyCode.TAB) { handled = navigateNext(); } else if (e.which == keyCode.ENTER) { if (options.editable) { if (currentEditor) { // adding new row if (activeRow === getDataLength()) { navigateDown(); } else { commitEditAndSetFocus(); } } else { if (getEditorLock().commitCurrentEdit()) { makeActiveCellEditable(undefined, undefined, e); } } } handled = true; } } else if (e.which == keyCode.TAB && e.shiftKey && !e.ctrlKey && !e.altKey) { handled = navigatePrev(); } } if (handled) { // the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it e.stopPropagation(); e.preventDefault(); try { e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.) } // ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl" // (hitting control key only, nothing else), "Shift" (maybe others) catch (error) { } } } function handleClick(e) { if (!currentEditor) { // if this click resulted in some cell child node getting focus, // don't steal it back - keyboard events will still bubble up // IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly. if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) { setFocus(); } } var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onClick, {row: cell.row, cell: cell.cell}, e); if (e.isImmediatePropagationStopped()) { return; } // this optimisation causes trouble - MLeibman #329 //if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) { if (canCellBeActive(cell.row, cell.cell)) { if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) { scrollRowIntoView(cell.row, false); var preClickModeOn = (e.target && e.target.className === Slick.preClickClassName); var column = columns[cell.cell]; var suppressActiveCellChangedEvent = !!(options.editable && column && column.editor && options.suppressActiveCellChangeOnEdit); setActiveCellInternal(getCellNode(cell.row, cell.cell), null, preClickModeOn, suppressActiveCellChangedEvent, e); } } } function handleContextMenu(e) { var $cell = $(e.target).closest(".slick-cell", $canvas); if ($cell.length === 0) { return; } // are we editing this cell? if (activeCellNode === $cell[0] && currentEditor !== null) { return; } trigger(self.onContextMenu, {}, e); } function handleDblClick(e) { var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onDblClick, {row: cell.row, cell: cell.cell}, e); if (e.isImmediatePropagationStopped()) { return; } if (options.editable) { gotoCell(cell.row, cell.cell, true, e); } } function handleHeaderMouseEnter(e) { trigger(self.onHeaderMouseEnter, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderMouseLeave(e) { trigger(self.onHeaderMouseLeave, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderContextMenu(e) { var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); trigger(self.onHeaderContextMenu, {column: column}, e); } function handleHeaderClick(e) { if (columnResizeDragging) return; var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); if (column) { trigger(self.onHeaderClick, {column: column}, e); } } function handleFooterContextMenu(e) { var $footer = $(e.target).closest(".slick-footerrow-column", ".slick-footerrow-columns"); var column = $footer && $footer.data("column"); trigger(self.onFooterContextMenu, {column: column}, e); } function handleFooterClick(e) { var $footer = $(e.target).closest(".slick-footerrow-column", ".slick-footerrow-columns"); var column = $footer && $footer.data("column"); trigger(self.onFooterClick, {column: column}, e); } function handleMouseEnter(e) { trigger(self.onMouseEnter, {}, e); } function handleMouseLeave(e) { trigger(self.onMouseLeave, {}, e); } function cellExists(row, cell) { return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length); } function getCellFromPoint(x, y) { var row = getRowFromPosition(y); var cell = 0; var w = 0; for (var i = 0; i < columns.length && w < x; i++) { w += columns[i].width; cell++; } if (cell < 0) { cell = 0; } return {row: row, cell: cell - 1}; } function getCellFromNode(cellNode) { // read column number from .l<columnNumber> CSS class var cls = /l\d+/.exec(cellNode.className); if (!cls) { throw new Error("getCellFromNode: cannot get cell - " + cellNode.className); } return parseInt(cls[0].substr(1, cls[0].length - 1), 10); } function getRowFromNode(rowNode) { for (var row in rowsCache) { for (var i in rowsCache[row].rowNode) { if (rowsCache[row].rowNode[i] === rowNode) return (row ? parseInt(row) : 0); } } return null; } function getFrozenRowOffset(row) { var offset = ( hasFrozenRows ) ? ( options.frozenBottom ) ? ( row >= actualFrozenRow ) ? ( h < viewportTopH ) ? ( actualFrozenRow * options.rowHeight ) : h : 0 : ( row >= actualFrozenRow ) ? frozenRowsHeight : 0 : 0; return offset; } function getCellFromEvent(e) { var row, cell; var $cell = $(e.target).closest(".slick-cell", $canvas); if (!$cell.length) { return null; } row = getRowFromNode($cell[0].parentNode); if (hasFrozenRows) { var c = $cell.parents('.grid-canvas').offset(); var rowOffset = 0; var isBottom = $cell.parents('.grid-canvas-bottom').length; if (isBottom) { rowOffset = ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight; } row = getCellFromPoint(e.clientX - c.left, e.clientY - c.top + rowOffset + $(document).scrollTop()).row; } cell = getCellFromNode($cell[0]); if (row == null || cell == null) { return null; } else { return { "row": row, "cell": cell }; } } function getCellNodeBox(row, cell) { if (!cellExists(row, cell)) { return null; } var frozenRowOffset = getFrozenRowOffset(row); var y1 = getRowTop(row) - frozenRowOffset; var y2 = y1 + options.rowHeight - 1; var x1 = 0; for (var i = 0; i < cell; i++) { x1 += columns[i].width; if (options.frozenColumn == i) { x1 = 0; } } var x2 = x1 + columns[cell].width; return { top: y1, left: x1, bottom: y2, right: x2 }; } ////////////////////////////////////////////////////////////////////////////////////////////// // Cell switching function resetActiveCell() { setActiveCellInternal(null, false); } function setFocus() { if (tabbingDirection == -1) { $focusSink[0].focus(); } else { $focusSink2[0].focus(); } } function scrollCellIntoView(row, cell, doPaging) { scrollRowIntoView(row, doPaging); if (cell <= options.frozenColumn) { return; } var colspan = getColspan(row, cell); internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)]); } function internalScrollColumnIntoView(left, right) { var scrollRight = scrollLeft + $viewportScrollContainerX.width(); if (left < scrollLeft) { $viewportScrollContainerX.scrollLeft(left); handleScroll(); render(); } else if (right > scrollRight) { $viewportScrollContainerX.scrollLeft(Math.min(left, right - $viewportScrollContainerX[0].clientWidth)); handleScroll(); render(); } } function scrollColumnIntoView(cell) { internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell]); } function setActiveCellInternal(newCell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent, e) { if (activeCellNode !== null) { makeActiveCellNormal(); $(activeCellNode).removeClass("active"); if (rowsCache[activeRow]) { $(rowsCache[activeRow].rowNode).removeClass("active"); } } var activeCellChanged = (activeCellNode !== newCell); activeCellNode = newCell; if (activeCellNode != null) { var $activeCellNode = $(activeCellNode); var $activeCellOffset = $activeCellNode.offset(); var rowOffset = Math.floor($activeCellNode.parents('.grid-canvas').offset().top); var isBottom = $activeCellNode.parents('.grid-canvas-bottom').length; if (hasFrozenRows && isBottom) { rowOffset -= ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight; } var cell = getCellFromPoint($activeCellOffset.left, Math.ceil($activeCellOffset.top) - rowOffset); activeRow = cell.row; activeCell = activePosX = activeCell = activePosX = getCellFromNode(activeCellNode); if (opt_editMode == null) { opt_editMode = (activeRow == getDataLength()) || options.autoEdit; } if (options.showCellSelection) { $activeCellNode.addClass("active"); if (rowsCache[activeRow]) { $(rowsCache[activeRow].rowNode).addClass("active"); } } if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) { clearTimeout(h_editorLoader); if (options.asyncEditorLoading) { h_editorLoader = setTimeout(function () { makeActiveCellEditable(undefined, preClickModeOn, e); }, options.asyncEditorLoadDelay); } else { makeActiveCellEditable(undefined, preClickModeOn, e); } } } else { activeRow = activeCell = null; } // this optimisation causes trouble - MLeibman #329 //if (activeCellChanged) { if (!suppressActiveCellChangedEvent) { trigger(self.onActiveCellChanged, getActiveCell()); } //} } function clearTextSelection() { if (document.selection && document.selection.empty) { try { //IE fails here if selected element is not in dom document.selection.empty(); } catch (e) { } } else if (window.getSelection) { var sel = window.getSelection(); if (sel && sel.removeAllRanges) { sel.removeAllRanges(); } } } function isCellPotentiallyEditable(row, cell) { var dataLength = getDataLength(); // is the data for this row loaded? if (row < dataLength && !getDataItem(row)) { return false; } // are we in the Add New row? can we create new from this cell? if (columns[cell].cannotTriggerInsert && row >= dataLength) { return false; } // does this cell have an editor? if (!getEditor(row, cell)) { return false; } return true; } function makeActiveCellNormal() { if (!currentEditor) { return; } trigger(self.onBeforeCellEditorDestroy, {editor: currentEditor}); currentEditor.destroy(); currentEditor = null; if (activeCellNode) { var d = getDataItem(activeRow); $(activeCellNode).removeClass("editable invalid"); if (d) { var column = columns[activeCell]; var formatter = getFormatter(activeRow, column); var formatterResult = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d, self); applyFormatResultToCellNode(formatterResult, activeCellNode); invalidatePostProcessingResults(activeRow); } } // if there previously was text selected on a page (such as selected text in the edit cell just removed), // IE can't set focus to anything else correctly if (navigator.userAgent.toLowerCase().match(/msie/)) { clearTextSelection(); } getEditorLock().deactivate(editController); } function makeActiveCellEditable(editor, preClickModeOn, e) { if (!activeCellNode) { return; } if (!options.editable) { throw new Error("Grid : makeActiveCellEditable : should never get called when options.editable is false"); } // cancel pending async call if there is one clearTimeout(h_editorLoader); if (!isCellPotentiallyEditable(activeRow, activeCell)) { return; } var columnDef = columns[activeCell]; var item = getDataItem(activeRow); if (trigger(self.onBeforeEditCell, {row: activeRow, cell: activeCell, item: item, column: columnDef}) === false) { setFocus(); return; } getEditorLock().activate(editController); $(activeCellNode).addClass("editable"); var useEditor = editor || getEditor(activeRow, activeCell); // don't clear the cell if a custom editor is passed through if (!editor && !useEditor.suppressClearOnEdit) { activeCellNode.innerHTML = ""; } var metadata = data.getItemMetadata && data.getItemMetadata(activeRow); metadata = metadata && metadata.columns; var columnMetaData = metadata && ( metadata[columnDef.id] || metadata[activeCell] ); currentEditor = new useEditor({ grid: self, gridPosition: absBox($container[0]), position: absBox(activeCellNode), container: activeCellNode, column: columnDef, columnMetaData: columnMetaData, item: item || {}, event: e, commitChanges: commitEditAndSetFocus, cancelChanges: cancelEditAndSetFocus }); if (item) { currentEditor.loadValue(item); if (preClickModeOn && currentEditor.preClick) { currentEditor.preClick(); } } serializedEditorValue = currentEditor.serializeValue(); if (currentEditor.position) { handleActiveCellPositionChange(); } } function commitEditAndSetFocus() { // if the commit fails, it would do so due to a validation error // if so, do not steal the focus from the editor if (getEditorLock().commitCurrentEdit()) { setFocus(); if (options.autoEdit) { navigateDown(); } } } function cancelEditAndSetFocus() { if (getEditorLock().cancelCurrentEdit()) { setFocus(); } } function absBox(elem) { var box = { top: elem.offsetTop, left: elem.offsetLeft, bottom: 0, right: 0, width: $(elem).outerWidth(), height: $(elem).outerHeight(), visible: true }; box.bottom = box.top + box.height; box.right = box.left + box.width; // walk up the tree var offsetParent = elem.offsetParent; while ((elem = elem.parentNode) != document.body) { if (elem == null) break; if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") { box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight; } if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") { box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth; } box.left -= elem.scrollLeft; box.top -= elem.scrollTop; if (elem === offsetParent) { box.left += elem.offsetLeft; box.top += elem.offsetTop; offsetParent = elem.offsetParent; } box.bottom = box.top + box.height; box.right = box.left + box.width; } return box; } function getActiveCellPosition() { return absBox(activeCellNode); } function getGridPosition() { return absBox($container[0]); } function handleActiveCellPositionChange() { if (!activeCellNode) { return; } trigger(self.onActiveCellPositionChanged, {}); if (currentEditor) { var cellBox = getActiveCellPosition(); if (currentEditor.show && currentEditor.hide) { if (!cellBox.visible) { currentEditor.hide(); } else { currentEditor.show(); } } if (currentEditor.position) { currentEditor.position(cellBox); } } } function getCellEditor() { return currentEditor; } function getActiveCell() { if (!activeCellNode) { return null; } else { return {row: activeRow, cell: activeCell}; } } function getActiveCellNode() { return activeCellNode; } function scrollRowIntoView(row, doPaging) { if (!hasFrozenRows || ( !options.frozenBottom && row > actualFrozenRow - 1 ) || ( options.frozenBottom && row < actualFrozenRow - 1 ) ) { var viewportScrollH = $viewportScrollContainerY.height(); // if frozen row on top // subtract number of frozen row var rowNumber = ( hasFrozenRows && !options.frozenBottom ? row - options.frozenRow : row ); var rowAtTop = rowNumber * options.rowHeight; var rowAtBottom = (rowNumber + 1) * options.rowHeight - viewportScrollH + (viewportHasHScroll ? scrollbarDimensions.height : 0); // need to page down? if ((rowNumber + 1) * options.rowHeight > scrollTop + viewportScrollH + offset) { scrollTo(doPaging ? rowAtTop : rowAtBottom); render(); } // or page up? else if (rowNumber * options.rowHeight < scrollTop + offset) { scrollTo(doPaging ? rowAtBottom : rowAtTop); render(); } } } function scrollRowToTop(row) { scrollTo(row * options.rowHeight); render(); } function scrollPage(dir) { var deltaRows = dir * numVisibleRows; /// First fully visible row crosses the line with /// y == bottomOfTopmostFullyVisibleRow var bottomOfTopmostFullyVisibleRow = scrollTop + options.rowHeight - 1; scrollTo((getRowFromPosition(bottomOfTopmostFullyVisibleRow) + deltaRows) * options.rowHeight); render(); if (options.enableCellNavigation && activeRow != null) { var row = activeRow + deltaRows; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); if (row >= dataLengthIncludingAddNew) { row = dataLengthIncludingAddNew - 1; } if (row < 0) { row = 0; } var cell = 0, prevCell = null; var prevActivePosX = activePosX; while (cell <= activePosX) { if (canCellBeActive(row, cell)) { prevCell = cell; } cell += getColspan(row, cell); } if (prevCell !== null) { setActiveCellInternal(getCellNode(row, prevCell)); activePosX = prevActivePosX; } else { resetActiveCell(); } } } function navigatePageDown() { scrollPage(1); } function navigatePageUp() { scrollPage(-1); } function navigateTop() { navigateToRow(0); } function navigateBottom() { navigateToRow(getDataLength()-1); } function navigateToRow(row) { var num_rows = getDataLength(); if (!num_rows) return true; if (row < 0) row = 0; else if (row >= num_rows) row = num_rows - 1; scrollCellIntoView(row, 0, true); if (options.enableCellNavigation && activeRow != null) { var cell = 0, prevCell = null; var prevActivePosX = activePosX; while (cell <= activePosX) { if (canCellBeActive(row, cell)) { prevCell = cell; } cell += getColspan(row, cell); } if (prevCell !== null) { setActiveCellInternal(getCellNode(row, prevCell)); activePosX = prevActivePosX; } else { resetActiveCell(); } } return true; } function getColspan(row, cell) { var metadata = data.getItemMetadata && data.getItemMetadata(row); if (!metadata || !metadata.columns) { return 1; } var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell]; var colspan = (columnData && columnData.colspan); if (colspan === "*") { colspan = columns.length - cell; } else { colspan = colspan || 1; } return colspan; } function findFirstFocusableCell(row) { var cell = 0; while (cell < columns.length) { if (canCellBeActive(row, cell)) { return cell; } cell += getColspan(row, cell); } return null; } function findLastFocusableCell(row) { var cell = 0; var lastFocusableCell = null; while (cell < columns.length) { if (canCellBeActive(row, cell)) { lastFocusableCell = cell; } cell += getColspan(row, cell); } return lastFocusableCell; } function gotoRight(row, cell, posX) { if (cell >= columns.length) { return null; } do { cell += getColspan(row, cell); } while (cell < columns.length && !canCellBeActive(row, cell)); if (cell < columns.length) { return { "row": row, "cell": cell, "posX": cell }; } return null; } function gotoLeft(row, cell, posX) { if (cell <= 0) { return null; } var firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell === null || firstFocusableCell >= cell) { return null; } var prev = { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; var pos; while (true) { pos = gotoRight(prev.row, prev.cell, prev.posX); if (!pos) { return null; } if (pos.cell >= cell) { return prev; } prev = pos; } } function gotoDown(row, cell, posX) { var prevCell; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); while (true) { if (++row >= dataLengthIncludingAddNew) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoUp(row, cell, posX) { var prevCell; while (true) { if (--row < 0) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoNext(row, cell, posX) { if (row == null && cell == null) { row = cell = posX = 0; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos = gotoRight(row, cell, posX); if (pos) { return pos; } var firstFocusableCell = null; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); // if at last row, cycle through columns rather than get stuck in the last one if (row === dataLengthIncludingAddNew - 1) { row--; } while (++row < dataLengthIncludingAddNew) { firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell !== null) { return { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; } } return null; } function gotoPrev(row, cell, posX) { if (row == null && cell == null) { row = getDataLengthIncludingAddNew() - 1; cell = posX = columns.length - 1; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos; var lastSelectableCell; while (!pos) { pos = gotoLeft(row, cell, posX); if (pos) { break; } if (--row < 0) { return null; } cell = 0; lastSelectableCell = findLastFocusableCell(row); if (lastSelectableCell !== null) { pos = { "row": row, "cell": lastSelectableCell, "posX": lastSelectableCell }; } } return pos; } function gotoRowStart(row, cell, posX) { var newCell = findFirstFocusableCell(row); if (newCell === null) return null; return { "row": row, "cell": newCell, "posX": newCell }; } function gotoRowEnd(row, cell, posX) { var newCell = findLastFocusableCell(row); if (newCell === null) return null; return { "row": row, "cell": newCell, "posX": newCell }; } function navigateRight() { return navigate("right"); } function navigateLeft() { return navigate("left"); } function navigateDown() { return navigate("down"); } function navigateUp() { return navigate("up"); } function navigateNext() { return navigate("next"); } function navigatePrev() { return navigate("prev"); } function navigateRowStart() { return navigate("home"); } function navigateRowEnd() { return navigate("end"); } /** * @param {string} dir Navigation direction. * @return {boolean} Whether navigation resulted in a change of active cell. */ function navigate(dir) { if (!options.enableCellNavigation) { return false; } if (!activeCellNode && dir != "prev" && dir != "next") { return false; } if (!getEditorLock().commitCurrentEdit()) { return true; } setFocus(); var tabbingDirections = { "up": -1, "down": 1, "left": -1, "right": 1, "prev": -1, "next": 1, "home": -1, "end": 1 }; tabbingDirection = tabbingDirections[dir]; var stepFunctions = { "up": gotoUp, "down": gotoDown, "left": gotoLeft, "right": gotoRight, "prev": gotoPrev, "next": gotoNext, "home": gotoRowStart, "end": gotoRowEnd }; var stepFn = stepFunctions[dir]; var pos = stepFn(activeRow, activeCell, activePosX); if (pos) { if (hasFrozenRows && options.frozenBottom & pos.row == getDataLength()) { return; } var isAddNewRow = (pos.row == getDataLength()); if (( !options.frozenBottom && pos.row >= actualFrozenRow ) || ( options.frozenBottom && pos.row < actualFrozenRow ) ) { scrollCellIntoView(pos.row, pos.cell, !isAddNewRow && options.emulatePagingWhenScrolling); } setActiveCellInternal(getCellNode(pos.row, pos.cell)); activePosX = pos.posX; return true; } else { setActiveCellInternal(getCellNode(activeRow, activeCell)); return false; } } function getCellNode(row, cell) { if (rowsCache[row]) { ensureCellNodesInRowsCache(row); try { if (rowsCache[row].cellNodesByColumnIdx.length > cell) { return rowsCache[row].cellNodesByColumnIdx[cell][0]; } else { return null; } } catch (e) { return rowsCache[row].cellNodesByColumnIdx[cell]; } } return null; } function setActiveCell(row, cell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent) { if (!initialized) { return; } if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return; } if (!options.enableCellNavigation) { return; } scrollCellIntoView(row, cell, false); setActiveCellInternal(getCellNode(row, cell), opt_editMode, preClickModeOn, suppressActiveCellChangedEvent); } function setActiveRow(row, cell, suppressScrollIntoView) { if (!initialized) { return; } if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return; } activeRow = row; if (!suppressScrollIntoView) { scrollCellIntoView(row, cell || 0, false); } } function canCellBeActive(row, cell) { if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.focusable !== "undefined") { return !!rowMetadata.focusable; } var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable !== "undefined") { return !!columnMetadata[columns[cell].id].focusable; } if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable !== "undefined") { return !!columnMetadata[cell].focusable; } return !!columns[cell].focusable; } function canCellBeSelected(row, cell) { if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.selectable !== "undefined") { return !!rowMetadata.selectable; } var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]); if (columnMetadata && typeof columnMetadata.selectable !== "undefined") { return !!columnMetadata.selectable; } return !!columns[cell].selectable; } function gotoCell(row, cell, forceEdit, e) { if (!initialized) { return; } if (!canCellBeActive(row, cell)) { return; } if (!getEditorLock().commitCurrentEdit()) { return; } scrollCellIntoView(row, cell, false); var newCell = getCellNode(row, cell); // if selecting the 'add new' row, start editing right away var column = columns[cell]; var suppressActiveCellChangedEvent = !!(options.editable && column && column.editor && options.suppressActiveCellChangeOnEdit); setActiveCellInternal(newCell, (forceEdit || (row === getDataLength()) || options.autoEdit), null, suppressActiveCellChangedEvent, e); // if no editor was created, set the focus back on the grid if (!currentEditor) { setFocus(); } } ////////////////////////////////////////////////////////////////////////////////////////////// // IEditor implementation for the editor lock function commitCurrentEdit() { var item = getDataItem(activeRow); var column = columns[activeCell]; if (currentEditor) { if (currentEditor.isValueChanged()) { var validationResults = currentEditor.validate(); if (validationResults.valid) { if (activeRow < getDataLength()) { var editCommand = { row: activeRow, cell: activeCell, editor: currentEditor, serializedValue: currentEditor.serializeValue(), prevSerializedValue: serializedEditorValue, execute: function () { this.editor.applyValue(item, this.serializedValue); updateRow(this.row); trigger(self.onCellChange, { row: this.row, cell: this.cell, item: item, column: column }); }, undo: function () { this.editor.applyValue(item, this.prevSerializedValue); updateRow(this.row); trigger(self.onCellChange, { row: this.row, cell: this.cell, item: item, column: column }); } }; if (options.editCommandHandler) { makeActiveCellNormal(); options.editCommandHandler(item, column, editCommand); } else { editCommand.execute(); makeActiveCellNormal(); } } else { var newItem = {}; currentEditor.applyValue(newItem, currentEditor.serializeValue()); makeActiveCellNormal(); trigger(self.onAddNewRow, {item: newItem, column: column}); } // check whether the lock has been re-acquired by event handlers return !getEditorLock().isActive(); } else { // Re-add the CSS class to trigger transitions, if any. $(activeCellNode).removeClass("invalid"); $(activeCellNode).width(); // force layout $(activeCellNode).addClass("invalid"); trigger(self.onValidationError, { editor: currentEditor, cellNode: activeCellNode, validationResults: validationResults, row: activeRow, cell: activeCell, column: column }); currentEditor.focus(); return false; } } makeActiveCellNormal(); } return true; } function cancelCurrentEdit() { makeActiveCellNormal(); return true; } function rowsToRanges(rows) { var ranges = []; var lastCell = columns.length - 1; for (var i = 0; i < rows.length; i++) { ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell)); } return ranges; } function getSelectedRows() { if (!selectionModel) { throw new Error("Selection model is not set"); } return selectedRows.slice(0); } function setSelectedRows(rows) { if (!selectionModel) { throw new Error("Selection model is not set"); } if (self && self.getEditorLock && !self.getEditorLock().isActive()) { selectionModel.setSelectedRanges(rowsToRanges(rows)); } } ////////////////////////////////////////////////////////////////////////////////////////////// // Debug this.debug = function () { var s = ""; s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered); s += ("\n" + "counter_rows_removed: " + counter_rows_removed); s += ("\n" + "renderedRows: " + renderedRows); s += ("\n" + "numVisibleRows: " + numVisibleRows); s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight); s += ("\n" + "n(umber of pages): " + n); s += ("\n" + "(current) page: " + page); s += ("\n" + "page height (ph): " + ph); s += ("\n" + "vScrollDir: " + vScrollDir); alert(s); }; // a debug helper to be able to access private members this.eval = function (expr) { return eval(expr); }; ////////////////////////////////////////////////////////////////////////////////////////////// // Public API $.extend(this, { "slickGridVersion": "2.4.33", // Events "onScroll": new Slick.Event(), "onSort": new Slick.Event(), "onHeaderMouseEnter": new Slick.Event(), "onHeaderMouseLeave": new Slick.Event(), "onHeaderContextMenu": new Slick.Event(), "onHeaderClick": new Slick.Event(), "onHeaderCellRendered": new Slick.Event(), "onBeforeHeaderCellDestroy": new Slick.Event(), "onHeaderRowCellRendered": new Slick.Event(), "onFooterRowCellRendered": new Slick.Event(), "onFooterContextMenu": new Slick.Event(), "onFooterClick": new Slick.Event(), "onBeforeHeaderRowCellDestroy": new Slick.Event(), "onBeforeFooterRowCellDestroy": new Slick.Event(), "onMouseEnter": new Slick.Event(), "onMouseLeave": new Slick.Event(), "onClick": new Slick.Event(), "onDblClick": new Slick.Event(), "onContextMenu": new Slick.Event(), "onKeyDown": new Slick.Event(), "onAddNewRow": new Slick.Event(), "onBeforeAppendCell": new Slick.Event(), "onValidationError": new Slick.Event(), "onViewportChanged": new Slick.Event(), "onColumnsReordered": new Slick.Event(), "onColumnsDrag": new Slick.Event(), "onColumnsResized": new Slick.Event(), "onBeforeColumnsResize": new Slick.Event(), "onCellChange": new Slick.Event(), "onCompositeEditorChange": new Slick.Event(), "onBeforeEditCell": new Slick.Event(), "onBeforeCellEditorDestroy": new Slick.Event(), "onBeforeDestroy": new Slick.Event(), "onActiveCellChanged": new Slick.Event(), "onActiveCellPositionChanged": new Slick.Event(), "onDragInit": new Slick.Event(), "onDragStart": new Slick.Event(), "onDrag": new Slick.Event(), "onDragEnd": new Slick.Event(), "onSelectedRowsChanged": new Slick.Event(), "onCellCssStylesChanged": new Slick.Event(), "onAutosizeColumns": new Slick.Event(), "onRendered": new Slick.Event(), "onSetOptions": new Slick.Event(), // Methods "registerPlugin": registerPlugin, "unregisterPlugin": unregisterPlugin, "getPluginByName": getPluginByName, "getColumns": getColumns, "setColumns": setColumns, "getColumnIndex": getColumnIndex, "updateColumnHeader": updateColumnHeader, "setSortColumn": setSortColumn, "setSortColumns": setSortColumns, "getSortColumns": getSortColumns, "autosizeColumns": autosizeColumns, "autosizeColumn": autosizeColumn, "getOptions": getOptions, "setOptions": setOptions, "getData": getData, "getDataLength": getDataLength, "getDataItem": getDataItem, "setData": setData, "getSelectionModel": getSelectionModel, "setSelectionModel": setSelectionModel, "getSelectedRows": getSelectedRows, "setSelectedRows": setSelectedRows, "getContainerNode": getContainerNode, "updatePagingStatusFromView": updatePagingStatusFromView, "applyFormatResultToCellNode": applyFormatResultToCellNode, "render": render, "reRenderColumns": reRenderColumns, "invalidate": invalidate, "invalidateRow": invalidateRow, "invalidateRows": invalidateRows, "invalidateAllRows": invalidateAllRows, "updateCell": updateCell, "updateRow": updateRow, "getViewport": getVisibleRange, "getRenderedRange": getRenderedRange, "resizeCanvas": resizeCanvas, "updateRowCount": updateRowCount, "scrollRowIntoView": scrollRowIntoView, "scrollRowToTop": scrollRowToTop, "scrollCellIntoView": scrollCellIntoView, "scrollColumnIntoView": scrollColumnIntoView, "getCanvasNode": getCanvasNode, "getUID": getUID, "getHeaderColumnWidthDiff": getHeaderColumnWidthDiff, "getScrollbarDimensions": getScrollbarDimensions, "getHeadersWidth": getHeadersWidth, "getCanvasWidth": getCanvasWidth, "getCanvases": getCanvases, "getActiveCanvasNode": getActiveCanvasNode, "setActiveCanvasNode": setActiveCanvasNode, "getViewportNode": getViewportNode, "getActiveViewportNode": getActiveViewportNode, "setActiveViewportNode": setActiveViewportNode, "focus": setFocus, "scrollTo": scrollTo, "cacheCssForHiddenInit": cacheCssForHiddenInit, "restoreCssFromHiddenInit": restoreCssFromHiddenInit, "getCellFromPoint": getCellFromPoint, "getCellFromEvent": getCellFromEvent, "getActiveCell": getActiveCell, "setActiveCell": setActiveCell, "setActiveRow": setActiveRow, "getActiveCellNode": getActiveCellNode, "getActiveCellPosition": getActiveCellPosition, "resetActiveCell": resetActiveCell, "editActiveCell": makeActiveCellEditable, "getCellEditor": getCellEditor, "getCellNode": getCellNode, "getCellNodeBox": getCellNodeBox, "canCellBeSelected": canCellBeSelected, "canCellBeActive": canCellBeActive, "navigatePrev": navigatePrev, "navigateNext": navigateNext, "navigateUp": navigateUp, "navigateDown": navigateDown, "navigateLeft": navigateLeft, "navigateRight": navigateRight, "navigatePageUp": navigatePageUp, "navigatePageDown": navigatePageDown, "navigateTop": navigateTop, "navigateBottom": navigateBottom, "navigateRowStart": navigateRowStart, "navigateRowEnd": navigateRowEnd, "gotoCell": gotoCell, "getTopPanel": getTopPanel, "setTopPanelVisibility": setTopPanelVisibility, "getPreHeaderPanel": getPreHeaderPanel, "getPreHeaderPanelLeft": getPreHeaderPanel, "getPreHeaderPanelRight": getPreHeaderPanelRight, "setPreHeaderPanelVisibility": setPreHeaderPanelVisibility, "getHeader": getHeader, "getHeaderColumn": getHeaderColumn, "setHeaderRowVisibility": setHeaderRowVisibility, "getHeaderRow": getHeaderRow, "getHeaderRowColumn": getHeaderRowColumn, "setFooterRowVisibility": setFooterRowVisibility, "getFooterRow": getFooterRow, "getFooterRowColumn": getFooterRowColumn, "getGridPosition": getGridPosition, "flashCell": flashCell, "addCellCssStyles": addCellCssStyles, "setCellCssStyles": setCellCssStyles, "removeCellCssStyles": removeCellCssStyles, "getCellCssStyles": getCellCssStyles, "getFrozenRowOffset": getFrozenRowOffset, "setColumnHeaderVisibility": setColumnHeaderVisibility, "init": finishInitialization, "destroy": destroy, // IEditor implementation "getEditorLock": getEditorLock, "getEditController": getEditController }); init(); } // exports $.extend(true, window, { Slick: { Grid: SlickGrid } }); }(jQuery));
slick.grid.js
/** * @license * (c) 2009-2016 Michael Leibman * michael{dot}leibman{at}gmail{dot}com * http://github.com/mleibman/slickgrid * * Distributed under MIT license. * All rights reserved. * * SlickGrid v2.4 * * NOTES: * Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods. * This increases the speed dramatically, but can only be done safely because there are no event handlers * or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy() * and do proper cleanup. */ // make sure required JavaScript modules are loaded if (typeof jQuery === "undefined") { throw new Error("SlickGrid requires jquery module to be loaded"); } if (!jQuery.fn.drag) { throw new Error("SlickGrid requires jquery.event.drag module to be loaded"); } if (typeof Slick === "undefined") { throw new Error("slick.core.js not loaded"); } (function ($) { "use strict"; // shared across all grids on the page var scrollbarDimensions; var maxSupportedCssHeight; // browser's breaking point ////////////////////////////////////////////////////////////////////////////////////////////// // SlickGrid class implementation (available as Slick.Grid) /** * Creates a new instance of the grid. * @class SlickGrid * @constructor * @param {Node} container Container node to create the grid in. * @param {Array,Object} data An array of objects for databinding. * @param {Array} columns An array of column definitions. * @param {Object} options Grid options. **/ function SlickGrid(container, data, columns, options) { // settings var defaults = { alwaysShowVerticalScroll: false, alwaysAllowHorizontalScroll: false, explicitInitialization: false, rowHeight: 25, defaultColumnWidth: 80, enableAddRow: false, leaveSpaceForNewRows: false, editable: false, autoEdit: true, suppressActiveCellChangeOnEdit: false, enableCellNavigation: true, enableColumnReorder: true, asyncEditorLoading: false, asyncEditorLoadDelay: 100, forceFitColumns: false, enableAsyncPostRender: false, asyncPostRenderDelay: 50, enableAsyncPostRenderCleanup: false, asyncPostRenderCleanupDelay: 40, autoHeight: false, editorLock: Slick.GlobalEditorLock, showColumnHeader: true, showHeaderRow: false, headerRowHeight: 25, createFooterRow: false, showFooterRow: false, footerRowHeight: 25, createPreHeaderPanel: false, showPreHeaderPanel: false, preHeaderPanelHeight: 25, showTopPanel: false, topPanelHeight: 25, formatterFactory: null, editorFactory: null, cellFlashingCssClass: "flashing", selectedCellCssClass: "selected", multiSelect: true, enableTextSelectionOnCells: false, dataItemColumnValueExtractor: null, frozenBottom: false, frozenColumn: -1, frozenRow: -1, fullWidthRows: false, multiColumnSort: false, numberedMultiColumnSort: false, tristateMultiColumnSort: false, sortColNumberInSeparateSpan: false, defaultFormatter: defaultFormatter, forceSyncScrolling: false, addNewRowCssClass: "new-row", preserveCopiedSelectionOnPaste: false, showCellSelection: true, viewportClass: null, minRowBuffer: 3, emulatePagingWhenScrolling: true, // when scrolling off bottom of viewport, place new row at top of viewport editorCellNavOnLRKeys: false, enableMouseWheelScrollHandler: true, doPaging: true, autosizeColsMode: Slick.GridAutosizeColsMode.LegacyOff, autosizeColPaddingPx: 4, autosizeTextAvgToMWidthRatio: 0.75, viewportSwitchToScrollModeWidthPercent: undefined, viewportMinWidthPx: undefined, viewportMaxWidthPx: undefined, suppressCssChangesOnHiddenInit: false }; var columnDefaults = { name: "", resizable: true, sortable: false, minWidth: 30, maxWidth: undefined, rerenderOnResize: false, headerCssClass: null, defaultSortAsc: true, focusable: true, selectable: true, }; var columnAutosizeDefaults = { ignoreHeaderText: false, colValueArray: undefined, allowAddlPercent: undefined, formatterOverride: undefined, autosizeMode: Slick.ColAutosizeMode.ContentIntelligent, rowSelectionModeOnInit: undefined, rowSelectionMode: Slick.RowSelectionMode.FirstNRows, rowSelectionCount: 100, valueFilterMode: Slick.ValueFilterMode.None, widthEvalMode: Slick.WidthEvalMode.CanvasTextSize, sizeToRemaining: undefined, widthPx: undefined, colDataTypeOf: undefined }; // scroller var th; // virtual height var h; // real scrollable height var ph; // page height var n; // number of pages var cj; // "jumpiness" coefficient var page = 0; // current page var offset = 0; // current page offset var vScrollDir = 1; // private var initialized = false; var $container; var uid = "slickgrid_" + Math.round(1000000 * Math.random()); var self = this; var $focusSink, $focusSink2; var $groupHeaders = $(); var $headerScroller; var $headers; var $headerRow, $headerRowScroller, $headerRowSpacerL, $headerRowSpacerR; var $footerRow, $footerRowScroller, $footerRowSpacerL, $footerRowSpacerR; var $preHeaderPanel, $preHeaderPanelScroller, $preHeaderPanelSpacer; var $preHeaderPanelR, $preHeaderPanelScrollerR, $preHeaderPanelSpacerR; var $topPanelScroller; var $topPanel; var $viewport; var $canvas; var $style; var $boundAncestors; var treeColumns; var stylesheet, columnCssRulesL, columnCssRulesR; var viewportH, viewportW; var canvasWidth, canvasWidthL, canvasWidthR; var headersWidth, headersWidthL, headersWidthR; var viewportHasHScroll, viewportHasVScroll; var headerColumnWidthDiff = 0, headerColumnHeightDiff = 0, // border+padding cellWidthDiff = 0, cellHeightDiff = 0, jQueryNewWidthBehaviour = false; var absoluteColumnMinWidth; var hasFrozenRows = false; var frozenRowsHeight = 0; var actualFrozenRow = -1; var paneTopH = 0; var paneBottomH = 0; var viewportTopH = 0; var viewportBottomH = 0; var topPanelH = 0; var headerRowH = 0; var footerRowH = 0; var tabbingDirection = 1; var $activeCanvasNode; var $activeViewportNode; var activePosX; var activeRow, activeCell; var activeCellNode = null; var currentEditor = null; var serializedEditorValue; var editController; var rowsCache = {}; var renderedRows = 0; var numVisibleRows = 0; var prevScrollTop = 0; var scrollTop = 0; var lastRenderedScrollTop = 0; var lastRenderedScrollLeft = 0; var prevScrollLeft = 0; var scrollLeft = 0; var selectionModel; var selectedRows = []; var plugins = []; var cellCssClasses = {}; var columnsById = {}; var sortColumns = []; var columnPosLeft = []; var columnPosRight = []; var pagingActive = false; var pagingIsLastPage = false; var scrollThrottle = ActionThrottle(render, 50); // async call handles var h_editorLoader = null; var h_render = null; var h_postrender = null; var h_postrenderCleanup = null; var postProcessedRows = {}; var postProcessToRow = null; var postProcessFromRow = null; var postProcessedCleanupQueue = []; var postProcessgroupId = 0; // perf counters var counter_rows_rendered = 0; var counter_rows_removed = 0; // These two variables work around a bug with inertial scrolling in Webkit/Blink on Mac. // See http://crbug.com/312427. var rowNodeFromLastMouseWheelEvent; // this node must not be deleted while inertial scrolling var zombieRowNodeFromLastMouseWheelEvent; // node that was hidden instead of getting deleted var zombieRowCacheFromLastMouseWheelEvent; // row cache for above node var zombieRowPostProcessedFromLastMouseWheelEvent; // post processing references for above node var $paneHeaderL; var $paneHeaderR; var $paneTopL; var $paneTopR; var $paneBottomL; var $paneBottomR; var $headerScrollerL; var $headerScrollerR; var $headerL; var $headerR; var $groupHeadersL; var $groupHeadersR; var $headerRowScrollerL; var $headerRowScrollerR; var $footerRowScrollerL; var $footerRowScrollerR; var $headerRowL; var $headerRowR; var $footerRowL; var $footerRowR; var $topPanelScrollerL; var $topPanelScrollerR; var $topPanelL; var $topPanelR; var $viewportTopL; var $viewportTopR; var $viewportBottomL; var $viewportBottomR; var $canvasTopL; var $canvasTopR; var $canvasBottomL; var $canvasBottomR; var $viewportScrollContainerX; var $viewportScrollContainerY; var $headerScrollContainer; var $headerRowScrollContainer; var $footerRowScrollContainer; // store css attributes if display:none is active in container or parent var cssShow = { position: 'absolute', visibility: 'hidden', display: 'block' }; var $hiddenParents; var oldProps = []; var columnResizeDragging = false; ////////////////////////////////////////////////////////////////////////////////////////////// // Initialization function init() { if (container instanceof jQuery) { $container = container; } else { $container = $(container); } if ($container.length < 1) { throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM."); } if (!options.suppressCssChangesOnHiddenInit) { cacheCssForHiddenInit(); } // calculate these only once and share between grid instances maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight(); options = $.extend({}, defaults, options); validateAndEnforceOptions(); columnDefaults.width = options.defaultColumnWidth; treeColumns = new Slick.TreeColumns(columns); columns = treeColumns.extractColumns(); updateColumnProps(); // validate loaded JavaScript modules against requested options if (options.enableColumnReorder && !$.fn.sortable) { throw new Error("SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded"); } editController = { "commitCurrentEdit": commitCurrentEdit, "cancelCurrentEdit": cancelCurrentEdit }; $container .empty() .css("overflow", "hidden") .css("outline", 0) .addClass(uid) .addClass("ui-widget"); // set up a positioning container if needed if (!(/relative|absolute|fixed/).test($container.css("position"))) { $container.css("position", "relative"); } $focusSink = $("<div tabIndex='0' hideFocus style='position:fixed;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container); // Containers used for scrolling frozen columns and rows $paneHeaderL = $("<div class='slick-pane slick-pane-header slick-pane-left' tabIndex='0' />").appendTo($container); $paneHeaderR = $("<div class='slick-pane slick-pane-header slick-pane-right' tabIndex='0' />").appendTo($container); $paneTopL = $("<div class='slick-pane slick-pane-top slick-pane-left' tabIndex='0' />").appendTo($container); $paneTopR = $("<div class='slick-pane slick-pane-top slick-pane-right' tabIndex='0' />").appendTo($container); $paneBottomL = $("<div class='slick-pane slick-pane-bottom slick-pane-left' tabIndex='0' />").appendTo($container); $paneBottomR = $("<div class='slick-pane slick-pane-bottom slick-pane-right' tabIndex='0' />").appendTo($container); if (options.createPreHeaderPanel) { $preHeaderPanelScroller = $("<div class='slick-preheader-panel ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($paneHeaderL); $preHeaderPanel = $("<div />").appendTo($preHeaderPanelScroller); $preHeaderPanelSpacer = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($preHeaderPanelScroller); $preHeaderPanelScrollerR = $("<div class='slick-preheader-panel ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($paneHeaderR); $preHeaderPanelR = $("<div />").appendTo($preHeaderPanelScrollerR); $preHeaderPanelSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($preHeaderPanelScrollerR); if (!options.showPreHeaderPanel) { $preHeaderPanelScroller.hide(); $preHeaderPanelScrollerR.hide(); } } // Append the header scroller containers $headerScrollerL = $("<div class='slick-header ui-state-default slick-header-left' />").appendTo($paneHeaderL); $headerScrollerR = $("<div class='slick-header ui-state-default slick-header-right' />").appendTo($paneHeaderR); // Cache the header scroller containers $headerScroller = $().add($headerScrollerL).add($headerScrollerR); if (treeColumns.hasDepth()) { $groupHeadersL = []; $groupHeadersR = []; for (var index = 0; index < treeColumns.getDepth() - 1; index++) { $groupHeadersL[index] = $("<div class='slick-group-header-columns slick-group-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL); $groupHeadersR[index] = $("<div class='slick-group-header-columns slick-group-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR); } $groupHeaders = $().add($groupHeadersL).add($groupHeadersR); } // Append the columnn containers to the headers $headerL = $("<div class='slick-header-columns slick-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL); $headerR = $("<div class='slick-header-columns slick-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR); // Cache the header columns $headers = $().add($headerL).add($headerR); $headerRowScrollerL = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopL); $headerRowScrollerR = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopR); $headerRowScroller = $().add($headerRowScrollerL).add($headerRowScrollerR); $headerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($headerRowScrollerL); $headerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($headerRowScrollerR); $headerRowL = $("<div class='slick-headerrow-columns slick-headerrow-columns-left' />").appendTo($headerRowScrollerL); $headerRowR = $("<div class='slick-headerrow-columns slick-headerrow-columns-right' />").appendTo($headerRowScrollerR); $headerRow = $().add($headerRowL).add($headerRowR); // Append the top panel scroller $topPanelScrollerL = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopL); $topPanelScrollerR = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopR); $topPanelScroller = $().add($topPanelScrollerL).add($topPanelScrollerR); // Append the top panel $topPanelL = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerL); $topPanelR = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerR); $topPanel = $().add($topPanelL).add($topPanelR); if (!options.showColumnHeader) { $headerScroller.hide(); } if (!options.showTopPanel) { $topPanelScroller.hide(); } if (!options.showHeaderRow) { $headerRowScroller.hide(); } // Append the viewport containers $viewportTopL = $("<div class='slick-viewport slick-viewport-top slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneTopL); $viewportTopR = $("<div class='slick-viewport slick-viewport-top slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneTopR); $viewportBottomL = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneBottomL); $viewportBottomR = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneBottomR); // Cache the viewports $viewport = $().add($viewportTopL).add($viewportTopR).add($viewportBottomL).add($viewportBottomR); // Default the active viewport to the top left $activeViewportNode = $viewportTopL; // Append the canvas containers $canvasTopL = $("<div class='grid-canvas grid-canvas-top grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportTopL); $canvasTopR = $("<div class='grid-canvas grid-canvas-top grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportTopR); $canvasBottomL = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportBottomL); $canvasBottomR = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportBottomR); if (options.viewportClass) $viewport.toggleClass(options.viewportClass, true); // Cache the canvases $canvas = $().add($canvasTopL).add($canvasTopR).add($canvasBottomL).add($canvasBottomR); scrollbarDimensions = scrollbarDimensions || measureScrollbar(); // Default the active canvas to the top left $activeCanvasNode = $canvasTopL; // pre-header if ($preHeaderPanelSpacer) $preHeaderPanelSpacer.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); $headers.width(getHeadersWidth()); $headerRowSpacerL.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); $headerRowSpacerR.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); // footer Row if (options.createFooterRow) { $footerRowScrollerR = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopR); $footerRowScrollerL = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopL); $footerRowScroller = $().add($footerRowScrollerL).add($footerRowScrollerR); $footerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($footerRowScrollerL); $footerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($footerRowScrollerR); $footerRowL = $("<div class='slick-footerrow-columns slick-footerrow-columns-left' />").appendTo($footerRowScrollerL); $footerRowR = $("<div class='slick-footerrow-columns slick-footerrow-columns-right' />").appendTo($footerRowScrollerR); $footerRow = $().add($footerRowL).add($footerRowR); if (!options.showFooterRow) { $footerRowScroller.hide(); } } $focusSink2 = $focusSink.clone().appendTo($container); if (!options.explicitInitialization) { finishInitialization(); } } function finishInitialization() { if (!initialized) { initialized = true; getViewportWidth(); getViewportHeight(); // header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?) // calculate the diff so we can set consistent sizes measureCellPaddingAndBorder(); // for usability reasons, all text selection in SlickGrid is disabled // with the exception of input and textarea elements (selection must // be enabled there so that editors work as expected); note that // selection in grid cells (grid body) is already unavailable in // all browsers except IE disableSelection($headers); // disable all text selection in header (including input and textarea) if (!options.enableTextSelectionOnCells) { // disable text selection in grid cells except in input and textarea elements // (this is IE-specific, because selectstart event will only fire in IE) $viewport.on("selectstart.ui", function (event) { return $(event.target).is("input,textarea"); }); } setFrozenOptions(); setPaneVisibility(); setScroller(); setOverflow(); updateColumnCaches(); createColumnHeaders(); createColumnGroupHeaders(); createColumnFooter(); setupColumnSort(); createCssRules(); resizeCanvas(); bindAncestorScrollEvents(); $container .on("resize.slickgrid", resizeCanvas); $viewport .on("scroll", handleScroll); if (jQuery.fn.mousewheel && options.enableMouseWheelScrollHandler) { $viewport.on("mousewheel", handleMouseWheel); } $headerScroller //.on("scroll", handleHeaderScroll) .on("contextmenu", handleHeaderContextMenu) .on("click", handleHeaderClick) .on("mouseenter", ".slick-header-column", handleHeaderMouseEnter) .on("mouseleave", ".slick-header-column", handleHeaderMouseLeave); $headerRowScroller .on("scroll", handleHeaderRowScroll); if (options.createFooterRow) { $footerRow .on("contextmenu", handleFooterContextMenu) .on("click", handleFooterClick); $footerRowScroller .on("scroll", handleFooterRowScroll); } if (options.createPreHeaderPanel) { $preHeaderPanelScroller .on("scroll", handlePreHeaderPanelScroll); } $focusSink.add($focusSink2) .on("keydown", handleKeyDown); $canvas .on("keydown", handleKeyDown) .on("click", handleClick) .on("dblclick", handleDblClick) .on("contextmenu", handleContextMenu) .on("draginit", handleDragInit) .on("dragstart", {distance: 3}, handleDragStart) .on("drag", handleDrag) .on("dragend", handleDragEnd) .on("mouseenter", ".slick-cell", handleMouseEnter) .on("mouseleave", ".slick-cell", handleMouseLeave); if (!options.suppressCssChangesOnHiddenInit) { restoreCssFromHiddenInit(); } } } function cacheCssForHiddenInit() { // handle display:none on container or container parents $hiddenParents = $container.parents().addBack().not(':visible'); $hiddenParents.each(function() { var old = {}; for ( var name in cssShow ) { old[ name ] = this.style[ name ]; this.style[ name ] = cssShow[ name ]; } oldProps.push(old); }); } function restoreCssFromHiddenInit() { // finish handle display:none on container or container parents // - put values back the way they were $hiddenParents.each(function(i) { var old = oldProps[i]; for ( var name in cssShow ) { this.style[ name ] = old[ name ]; } }); } function hasFrozenColumns() { return options.frozenColumn > -1; } function registerPlugin(plugin) { plugins.unshift(plugin); plugin.init(self); } function unregisterPlugin(plugin) { for (var i = plugins.length; i >= 0; i--) { if (plugins[i] === plugin) { if (plugins[i].destroy) { plugins[i].destroy(); } plugins.splice(i, 1); break; } } } function getPluginByName(name) { for (var i = plugins.length-1; i >= 0; i--) { if (plugins[i].pluginName === name) { return plugins[i]; } } return undefined; } function setSelectionModel(model) { if (selectionModel) { selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged); if (selectionModel.destroy) { selectionModel.destroy(); } } selectionModel = model; if (selectionModel) { selectionModel.init(self); selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged); } } function getSelectionModel() { return selectionModel; } function getCanvasNode(columnIdOrIdx, rowIndex) { if (!columnIdOrIdx) { columnIdOrIdx = 0; } if (!rowIndex) { rowIndex = 0; } var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); return (hasFrozenRows && rowIndex >= actualFrozenRow + (options.frozenBottom ? 0 : 1) ) ? ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasBottomR[0] : $canvasBottomL[0]) : ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasTopR[0] : $canvasTopL[0]) ; } function getActiveCanvasNode(element) { setActiveCanvasNode(element); return $activeCanvasNode[0]; } function getCanvases() { return $canvas; } function setActiveCanvasNode(element) { if (element) { $activeCanvasNode = $(element.target).closest('.grid-canvas'); } } function getViewportNode() { return $viewport[0]; } function getActiveViewportNode(element) { setActiveViewPortNode(element); return $activeViewportNode[0]; } function setActiveViewportNode(element) { if (element) { $activeViewportNode = $(element.target).closest('.slick-viewport'); } } function measureScrollbar() { var $outerdiv = $('<div class="' + $viewport.className + '" style="position:absolute; top:-10000px; left:-10000px; overflow:auto; width:100px; height:100px;"></div>').appendTo('body'); var $innerdiv = $('<div style="width:200px; height:200px; overflow:auto;"></div>').appendTo($outerdiv); var dim = { width: $outerdiv[0].offsetWidth - $outerdiv[0].clientWidth, height: $outerdiv[0].offsetHeight - $outerdiv[0].clientHeight }; $innerdiv.remove(); $outerdiv.remove(); return dim; } function getHeadersWidth() { headersWidth = headersWidthL = headersWidthR = 0; var includeScrollbar = !options.autoHeight; for (var i = 0, ii = columns.length; i < ii; i++) { var width = columns[ i ].width; if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) { headersWidthR += width; } else { headersWidthL += width; } } if (includeScrollbar) { if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) { headersWidthR += scrollbarDimensions.width; } else { headersWidthL += scrollbarDimensions.width; } } if (hasFrozenColumns()) { headersWidthL = headersWidthL + 1000; headersWidthR = Math.max(headersWidthR, viewportW) + headersWidthL; headersWidthR += scrollbarDimensions.width; } else { headersWidthL += scrollbarDimensions.width; headersWidthL = Math.max(headersWidthL, viewportW) + 1000; } headersWidth = headersWidthL + headersWidthR; return Math.max(headersWidth, viewportW) + 1000; } function getHeadersWidthL() { headersWidthL =0; columns.forEach(function(column, i) { if (!(( options.frozenColumn ) > -1 && ( i > options.frozenColumn ))) headersWidthL += column.width; }); if (hasFrozenColumns()) { headersWidthL += 1000; } else { headersWidthL += scrollbarDimensions.width; headersWidthL = Math.max(headersWidthL, viewportW) + 1000; } return headersWidthL; } function getHeadersWidthR() { headersWidthR =0; columns.forEach(function(column, i) { if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) headersWidthR += column.width; }); if (hasFrozenColumns()) { headersWidthR = Math.max(headersWidthR, viewportW) + getHeadersWidthL(); headersWidthR += scrollbarDimensions.width; } return headersWidthR; } function getCanvasWidth() { var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; var i = columns.length; canvasWidthL = canvasWidthR = 0; while (i--) { if (hasFrozenColumns() && (i > options.frozenColumn)) { canvasWidthR += columns[i].width; } else { canvasWidthL += columns[i].width; } } var totalRowWidth = canvasWidthL + canvasWidthR; return options.fullWidthRows ? Math.max(totalRowWidth, availableWidth) : totalRowWidth; } function updateCanvasWidth(forceColumnWidthsUpdate) { var oldCanvasWidth = canvasWidth; var oldCanvasWidthL = canvasWidthL; var oldCanvasWidthR = canvasWidthR; var widthChanged; canvasWidth = getCanvasWidth(); widthChanged = canvasWidth !== oldCanvasWidth || canvasWidthL !== oldCanvasWidthL || canvasWidthR !== oldCanvasWidthR; if (widthChanged || hasFrozenColumns() || hasFrozenRows) { $canvasTopL.width(canvasWidthL); getHeadersWidth(); $headerL.width(headersWidthL); $headerR.width(headersWidthR); if (hasFrozenColumns()) { $canvasTopR.width(canvasWidthR); $paneHeaderL.width(canvasWidthL); $paneHeaderR.css('left', canvasWidthL); $paneHeaderR.css('width', viewportW - canvasWidthL); $paneTopL.width(canvasWidthL); $paneTopR.css('left', canvasWidthL); $paneTopR.css('width', viewportW - canvasWidthL); $headerRowScrollerL.width(canvasWidthL); $headerRowScrollerR.width(viewportW - canvasWidthL); $headerRowL.width(canvasWidthL); $headerRowR.width(canvasWidthR); if (options.createFooterRow) { $footerRowScrollerL.width(canvasWidthL); $footerRowScrollerR.width(viewportW - canvasWidthL); $footerRowL.width(canvasWidthL); $footerRowR.width(canvasWidthR); } if (options.createPreHeaderPanel) { $preHeaderPanel.width(canvasWidth); } $viewportTopL.width(canvasWidthL); $viewportTopR.width(viewportW - canvasWidthL); if (hasFrozenRows) { $paneBottomL.width(canvasWidthL); $paneBottomR.css('left', canvasWidthL); $viewportBottomL.width(canvasWidthL); $viewportBottomR.width(viewportW - canvasWidthL); $canvasBottomL.width(canvasWidthL); $canvasBottomR.width(canvasWidthR); } } else { $paneHeaderL.width('100%'); $paneTopL.width('100%'); $headerRowScrollerL.width('100%'); $headerRowL.width(canvasWidth); if (options.createFooterRow) { $footerRowScrollerL.width('100%'); $footerRowL.width(canvasWidth); } if (options.createPreHeaderPanel) { $preHeaderPanel.width('100%'); $preHeaderPanel.width(canvasWidth); } $viewportTopL.width('100%'); if (hasFrozenRows) { $viewportBottomL.width('100%'); $canvasBottomL.width(canvasWidthL); } } viewportHasHScroll = (canvasWidth >= viewportW - scrollbarDimensions.width); } $headerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); $headerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); if (options.createFooterRow) { $footerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); $footerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); } if (widthChanged || forceColumnWidthsUpdate) { applyColumnWidths(); } } function disableSelection($target) { if ($target && $target.jquery) { $target .attr("unselectable", "on") .css("MozUserSelect", "none") .on("selectstart.ui", function () { return false; }); // from jquery:ui.core.js 1.7.2 } } function getMaxSupportedCssHeight() { var supportedHeight = 1000000; // FF reports the height back but still renders blank after ~6M px var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000; var div = $("<div style='display:none' />").appendTo(document.body); while (true) { var test = supportedHeight * 2; div.css("height", test); if (test > testUpTo || div.height() !== test) { break; } else { supportedHeight = test; } } div.remove(); return supportedHeight; } function getUID() { return uid; } function getHeaderColumnWidthDiff() { return headerColumnWidthDiff; } function getScrollbarDimensions() { return scrollbarDimensions; } // TODO: this is static. need to handle page mutation. function bindAncestorScrollEvents() { var elem = (hasFrozenRows && !options.frozenBottom) ? $canvasBottomL[0] : $canvasTopL[0]; while ((elem = elem.parentNode) != document.body && elem != null) { // bind to scroll containers only if (elem == $viewportTopL[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) { var $elem = $(elem); if (!$boundAncestors) { $boundAncestors = $elem; } else { $boundAncestors = $boundAncestors.add($elem); } $elem.on("scroll." + uid, handleActiveCellPositionChange); } } } function unbindAncestorScrollEvents() { if (!$boundAncestors) { return; } $boundAncestors.off("scroll." + uid); $boundAncestors = null; } function updateColumnHeader(columnId, title, toolTip) { if (!initialized) { return; } var idx = getColumnIndex(columnId); if (idx == null) { return; } var columnDef = columns[idx]; var $header = $headers.children().eq(idx); if ($header) { if (title !== undefined) { columns[idx].name = title; } if (toolTip !== undefined) { columns[idx].toolTip = toolTip; } trigger(self.onBeforeHeaderCellDestroy, { "node": $header[0], "column": columnDef, "grid": self }); $header .attr("title", toolTip || "") .children().eq(0).html(title); trigger(self.onHeaderCellRendered, { "node": $header[0], "column": columnDef, "grid": self }); } } function getHeader(columnDef) { if (!columnDef) { return hasFrozenColumns() ? $headers : $headerL; } var idx = getColumnIndex(columnDef.id); return hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL; } function getHeaderColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var targetHeader = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL; var targetIndex = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? idx : idx - options.frozenColumn - 1) : idx; var $rtn = targetHeader.children().eq(targetIndex); return $rtn && $rtn[0]; } function getHeaderRow() { return hasFrozenColumns() ? $headerRow : $headerRow[0]; } function getFooterRow() { return hasFrozenColumns() ? $footerRow : $footerRow[0]; } function getPreHeaderPanel() { return $preHeaderPanel[0]; } function getPreHeaderPanelRight() { return $preHeaderPanelR[0]; } function getHeaderRowColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var $headerRowTarget; if (hasFrozenColumns()) { if (idx <= options.frozenColumn) { $headerRowTarget = $headerRowL; } else { $headerRowTarget = $headerRowR; idx -= options.frozenColumn + 1; } } else { $headerRowTarget = $headerRowL; } var $header = $headerRowTarget.children().eq(idx); return $header && $header[0]; } function getFooterRowColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var $footerRowTarget; if (hasFrozenColumns()) { if (idx <= options.frozenColumn) { $footerRowTarget = $footerRowL; } else { $footerRowTarget = $footerRowR; idx -= options.frozenColumn + 1; } } else { $footerRowTarget = $footerRowL; } var $footer = $footerRowTarget && $footerRowTarget.children().eq(idx); return $footer && $footer[0]; } function createColumnFooter() { if (options.createFooterRow) { $footerRow.find(".slick-footerrow-column") .each(function () { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowL.empty(); $footerRowR.empty(); for (var i = 0; i < columns.length; i++) { var m = columns[i]; var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo(hasFrozenColumns() && (i > options.frozenColumn)? $footerRowR: $footerRowL); trigger(self.onFooterRowCellRendered, { "node": footerRowCell[0], "column": m, "grid": self }); } } } function createColumnGroupHeaders() { var columnsLength = 0; var frozenColumnsValid = false; if (!treeColumns.hasDepth()) return; for (var index = 0; index < $groupHeadersL.length; index++) { $groupHeadersL[index].empty(); $groupHeadersR[index].empty(); var groupColumns = treeColumns.getColumnsInDepth(index); for (var indexGroup in groupColumns) { var m = groupColumns[indexGroup]; columnsLength += m.extractColumns().length; if (hasFrozenColumns() && index === 0 && (columnsLength-1) === options.frozenColumn) frozenColumnsValid = true; $("<div class='ui-state-default slick-group-header-column' />") .html("<span class='slick-column-name'>" + m.name + "</span>") .attr("id", "" + uid + m.id) .attr("title", m.toolTip || "") .data("column", m) .addClass(m.headerCssClass || "") .addClass(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? 'frozen': '') .appendTo(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? $groupHeadersR[index]: $groupHeadersL[index]); } if (hasFrozenColumns() && index === 0 && !frozenColumnsValid) { $groupHeadersL[index].empty(); $groupHeadersR[index].empty(); alert("All columns of group should to be grouped!"); break; } } applyColumnGroupHeaderWidths(); } function createColumnHeaders() { function onMouseEnter() { $(this).addClass("ui-state-hover"); } function onMouseLeave() { $(this).removeClass("ui-state-hover"); } $headers.find(".slick-header-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headerL.empty(); $headerR.empty(); getHeadersWidth(); $headerL.width(headersWidthL); $headerR.width(headersWidthR); $headerRow.find(".slick-headerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headerRowL.empty(); $headerRowR.empty(); if (options.createFooterRow) { $footerRowL.find(".slick-footerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowL.empty(); if (hasFrozenColumns()) { $footerRowR.find(".slick-footerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowR.empty(); } } for (var i = 0; i < columns.length; i++) { var m = columns[i]; var $headerTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerL : $headerR) : $headerL; var $headerRowTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerRowL : $headerRowR) : $headerRowL; var header = $("<div class='ui-state-default slick-header-column' />") .html("<span class='slick-column-name'>" + m.name + "</span>") .width(m.width - headerColumnWidthDiff) .attr("id", "" + uid + m.id) .attr("title", m.toolTip || "") .data("column", m) .addClass(m.headerCssClass || "") .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo($headerTarget); if (options.enableColumnReorder || m.sortable) { header .on('mouseenter', onMouseEnter) .on('mouseleave', onMouseLeave); } if(m.hasOwnProperty('headerCellAttrs') && m.headerCellAttrs instanceof Object) { for (var key in m.headerCellAttrs) { if (m.headerCellAttrs.hasOwnProperty(key)) { header.attr(key, m.headerCellAttrs[key]); } } } if (m.sortable) { header.addClass("slick-header-sortable"); header.append("<span class='slick-sort-indicator" + (options.numberedMultiColumnSort && !options.sortColNumberInSeparateSpan ? " slick-sort-indicator-numbered" : "" ) + "' />"); if (options.numberedMultiColumnSort && options.sortColNumberInSeparateSpan) { header.append("<span class='slick-sort-indicator-numbered' />"); } } trigger(self.onHeaderCellRendered, { "node": header[0], "column": m, "grid": self }); if (options.showHeaderRow) { var headerRowCell = $("<div class='ui-state-default slick-headerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo($headerRowTarget); trigger(self.onHeaderRowCellRendered, { "node": headerRowCell[0], "column": m, "grid": self }); } if (options.createFooterRow && options.showFooterRow) { var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .appendTo($footerRow); trigger(self.onFooterRowCellRendered, { "node": footerRowCell[0], "column": m, "grid": self }); } } setSortColumns(sortColumns); setupColumnResize(); if (options.enableColumnReorder) { if (typeof options.enableColumnReorder == 'function') { options.enableColumnReorder(self, $headers, headerColumnWidthDiff, setColumns, setupColumnResize, columns, getColumnIndex, uid, trigger); } else { setupColumnReorder(); } } } function setupColumnSort() { $headers.click(function (e) { if (columnResizeDragging) return; // temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328) e.metaKey = e.metaKey || e.ctrlKey; if ($(e.target).hasClass("slick-resizable-handle")) { return; } var $col = $(e.target).closest(".slick-header-column"); if (!$col.length) { return; } var column = $col.data("column"); if (column.sortable) { if (!getEditorLock().commitCurrentEdit()) { return; } var sortColumn = null; var i = 0; for (; i < sortColumns.length; i++) { if (sortColumns[i].columnId == column.id) { sortColumn = sortColumns[i]; sortColumn.sortAsc = !sortColumn.sortAsc; break; } } var hadSortCol = !!sortColumn; if (options.tristateMultiColumnSort) { if (!sortColumn) { sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc }; } if (hadSortCol && sortColumn.sortAsc) { // three state: remove sort rather than go back to ASC sortColumns.splice(i, 1); sortColumn = null; } if (!options.multiColumnSort) { sortColumns = []; } if (sortColumn && (!hadSortCol || !options.multiColumnSort)) { sortColumns.push(sortColumn); } } else { // legacy behaviour if (e.metaKey && options.multiColumnSort) { if (sortColumn) { sortColumns.splice(i, 1); } } else { if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) { sortColumns = []; } if (!sortColumn) { sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc }; sortColumns.push(sortColumn); } else if (sortColumns.length === 0) { sortColumns.push(sortColumn); } } } setSortColumns(sortColumns); if (!options.multiColumnSort) { trigger(self.onSort, { multiColumnSort: false, columnId: (sortColumns.length > 0 ? column.id : null), sortCol: (sortColumns.length > 0 ? column : null), sortAsc: (sortColumns.length > 0 ? sortColumns[0].sortAsc : true) }, e); } else { trigger(self.onSort, { multiColumnSort: true, sortCols: $.map(sortColumns, function(col) { return {columnId: columns[getColumnIndex(col.columnId)].id, sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc }; }) }, e); } } }); } function currentPositionInHeader(id) { var currentPosition = 0; $headers.find('.slick-header-column').each(function (i) { if (this.id == id) { currentPosition = i; return false; } }); return currentPosition; } function limitPositionInGroup(idColumn) { var groupColumnOfPreviousPosition, startLimit = 0, endLimit = 0; treeColumns .getColumnsInDepth($groupHeadersL.length - 1) .some(function (groupColumn) { startLimit = endLimit; endLimit += groupColumn.columns.length; groupColumn.columns.some(function (column) { if (column.id === idColumn) groupColumnOfPreviousPosition = groupColumn; return groupColumnOfPreviousPosition; }); return groupColumnOfPreviousPosition; }); endLimit--; return { start: startLimit, end: endLimit, group: groupColumnOfPreviousPosition }; } function remove(arr, elem) { var index = arr.lastIndexOf(elem); if(index > -1) { arr.splice(index, 1); remove(arr, elem); } } function columnPositionValidInGroup($item) { var currentPosition = currentPositionInHeader($item[0].id); var limit = limitPositionInGroup($item.data('column').id); var positionValid = limit.start <= currentPosition && currentPosition <= limit.end; return { limit: limit, valid: positionValid, message: positionValid? '': 'Column "'.concat($item.text(), '" can be reordered only within the "', limit.group.name, '" group!') }; } function setupColumnReorder() { $headers.filter(":ui-sortable").sortable("destroy"); var columnScrollTimer = null; function scrollColumnsRight() { $viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft + 10; } function scrollColumnsLeft() { $viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft - 10; } var canDragScroll; $headers.sortable({ containment: "parent", distance: 3, axis: "x", cursor: "default", tolerance: "intersection", helper: "clone", placeholder: "slick-sortable-placeholder ui-state-default slick-header-column", start: function (e, ui) { ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff); canDragScroll = !hasFrozenColumns() || (ui.placeholder.offset().left + ui.placeholder.width()) > $viewportScrollContainerX.offset().left; $(ui.helper).addClass("slick-header-column-active"); }, beforeStop: function (e, ui) { $(ui.helper).removeClass("slick-header-column-active"); }, sort: function (e, ui) { if (canDragScroll && e.originalEvent.pageX > $container[0].clientWidth) { if (!(columnScrollTimer)) { columnScrollTimer = setInterval( scrollColumnsRight, 100); } } else if (canDragScroll && e.originalEvent.pageX < $viewportScrollContainerX.offset().left) { if (!(columnScrollTimer)) { columnScrollTimer = setInterval( scrollColumnsLeft, 100); } } else { clearInterval(columnScrollTimer); columnScrollTimer = null; } }, stop: function (e, ui) { var cancel = false; clearInterval(columnScrollTimer); columnScrollTimer = null; var limit = null; if (treeColumns.hasDepth()) { var validPositionInGroup = columnPositionValidInGroup(ui.item); limit = validPositionInGroup.limit; cancel = !validPositionInGroup.valid; if (cancel) alert(validPositionInGroup.message); } if (cancel || !getEditorLock().commitCurrentEdit()) { $(this).sortable("cancel"); return; } var reorderedIds = $headerL.sortable("toArray"); reorderedIds = reorderedIds.concat($headerR.sortable("toArray")); var reorderedColumns = []; for (var i = 0; i < reorderedIds.length; i++) { reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]); } setColumns(reorderedColumns); trigger(self.onColumnsReordered, { impactedColumns : getImpactedColumns( limit ) }); e.stopPropagation(); setupColumnResize(); } }); } function getImpactedColumns( limit ) { var impactedColumns = []; if( limit ) { for( var i = limit.start; i <= limit.end; i++ ) { impactedColumns.push( columns[i] ); } } else { impactedColumns = columns; } return impactedColumns; } function setupColumnResize() { var $col, j, k, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable; columnElements = $headers.children(); columnElements.find(".slick-resizable-handle").remove(); columnElements.each(function (i, e) { if (i >= columns.length) { return; } if (columns[i].resizable) { if (firstResizable === undefined) { firstResizable = i; } lastResizable = i; } }); if (firstResizable === undefined) { return; } columnElements.each(function (i, e) { if (i >= columns.length) { return; } if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) { return; } $col = $(e); $("<div class='slick-resizable-handle' />") .appendTo(e) .on("dragstart", function (e, dd) { if (!getEditorLock().commitCurrentEdit()) { return false; } pageX = e.pageX; $(this).parent().addClass("slick-header-column-active"); var shrinkLeewayOnRight = null, stretchLeewayOnRight = null; // lock each column's width option to current width columnElements.each(function (i, e) { if (i >= columns.length) { return; } columns[i].previousWidth = $(e).outerWidth(); }); if (options.forceFitColumns) { shrinkLeewayOnRight = 0; stretchLeewayOnRight = 0; // colums on right affect maxPageX/minPageX for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (stretchLeewayOnRight !== null) { if (c.maxWidth) { stretchLeewayOnRight += c.maxWidth - c.previousWidth; } else { stretchLeewayOnRight = null; } } shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } } var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0; for (j = 0; j <= i; j++) { // columns on left only affect minPageX c = columns[j]; if (c.resizable) { if (stretchLeewayOnLeft !== null) { if (c.maxWidth) { stretchLeewayOnLeft += c.maxWidth - c.previousWidth; } else { stretchLeewayOnLeft = null; } } shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } if (shrinkLeewayOnRight === null) { shrinkLeewayOnRight = 100000; } if (shrinkLeewayOnLeft === null) { shrinkLeewayOnLeft = 100000; } if (stretchLeewayOnRight === null) { stretchLeewayOnRight = 100000; } if (stretchLeewayOnLeft === null) { stretchLeewayOnLeft = 100000; } maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft); minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight); }) .on("drag", function (e, dd) { columnResizeDragging = true; var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x; var newCanvasWidthL = 0, newCanvasWidthR = 0; if (d < 0) { // shrink column x = d; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } } } for (k = 0; k <= i; k++) { c = columns[k]; if (hasFrozenColumns() && (k > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } else { for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } } } else { // stretch column x = d; newCanvasWidthL = 0; newCanvasWidthR = 0; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } for (k = 0; k <= i; k++) { c = columns[k]; if (hasFrozenColumns() && (k > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } else { for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } if (hasFrozenColumns() && newCanvasWidthL != canvasWidthL) { $headerL.width(newCanvasWidthL + 1000); $paneHeaderR.css('left', newCanvasWidthL); } applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); if (options.syncColumnCellResize) { applyColumnWidths(); } trigger(self.onColumnsDrag, { triggeredByColumn: $(this).parent().attr("id").replace(uid, ""), resizeHandle: $(this) }); }) .on("dragend", function (e, dd) { $(this).parent().removeClass("slick-header-column-active"); var triggeredByColumn = $(this).parent().attr("id").replace(uid, ""); if (trigger(self.onBeforeColumnsResize, { triggeredByColumn: triggeredByColumn }) === true) { applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); } var newWidth; for (j = 0; j < columns.length; j++) { c = columns[j]; newWidth = $(columnElements[j]).outerWidth(); if (c.previousWidth !== newWidth && c.rerenderOnResize) { invalidateAllRows(); } } updateCanvasWidth(true); render(); trigger(self.onColumnsResized, { triggeredByColumn: triggeredByColumn }); setTimeout(function () { columnResizeDragging = false; }, 300); }); }); } function getVBoxDelta($el) { var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; var delta = 0; if ($el && typeof $el.css === 'function') { $.each(p, function (n, val) { delta += parseFloat($el.css(val)) || 0; }); } return delta; } function setFrozenOptions() { options.frozenColumn = (options.frozenColumn >= 0 && options.frozenColumn < columns.length) ? parseInt(options.frozenColumn) : -1; if (options.frozenRow > -1) { hasFrozenRows = true; frozenRowsHeight = ( options.frozenRow ) * options.rowHeight; var dataLength = getDataLength(); actualFrozenRow = ( options.frozenBottom ) ? ( dataLength - options.frozenRow ) : options.frozenRow; } else { hasFrozenRows = false; } } function setPaneVisibility() { if (hasFrozenColumns()) { $paneHeaderR.show(); $paneTopR.show(); if (hasFrozenRows) { $paneBottomL.show(); $paneBottomR.show(); } else { $paneBottomR.hide(); $paneBottomL.hide(); } } else { $paneHeaderR.hide(); $paneTopR.hide(); $paneBottomR.hide(); if (hasFrozenRows) { $paneBottomL.show(); } else { $paneBottomR.hide(); $paneBottomL.hide(); } } } function setOverflow() { $viewportTopL.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ), 'overflow-y': (!hasFrozenColumns() && options.alwaysShowVerticalScroll) ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ) : ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportTopR.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'scroll' : 'auto' ) : ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportBottomL.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ): ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ), 'overflow-y': (!hasFrozenColumns() && options.alwaysShowVerticalScroll) ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ): ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportBottomR.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'auto' : 'auto' ) : ( hasFrozenRows ? 'auto' : 'auto' )) }); if (options.viewportClass) { $viewportTopL.toggleClass(options.viewportClass, true); $viewportTopR.toggleClass(options.viewportClass, true); $viewportBottomL.toggleClass(options.viewportClass, true); $viewportBottomR.toggleClass(options.viewportClass, true); } } function setScroller() { if (hasFrozenColumns()) { $headerScrollContainer = $headerScrollerR; $headerRowScrollContainer = $headerRowScrollerR; $footerRowScrollContainer = $footerRowScrollerR; if (hasFrozenRows) { if (options.frozenBottom) { $viewportScrollContainerX = $viewportBottomR; $viewportScrollContainerY = $viewportTopR; } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomR; } } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportTopR; } } else { $headerScrollContainer = $headerScrollerL; $headerRowScrollContainer = $headerRowScrollerL; $footerRowScrollContainer = $footerRowScrollerL; if (hasFrozenRows) { if (options.frozenBottom) { $viewportScrollContainerX = $viewportBottomL; $viewportScrollContainerY = $viewportTopL; } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomL; } } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportTopL; } } } function measureCellPaddingAndBorder() { var el; var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"]; var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; // jquery prior to version 1.8 handles .width setter/getter as a direct css write/read // jquery 1.8 changed .width to read the true inner element width if box-sizing is set to border-box, and introduced a setter for .outerWidth // so for equivalent functionality, prior to 1.8 use .width, and after use .outerWidth var verArray = $.fn.jquery.split('.'); jQueryNewWidthBehaviour = (verArray[0]==1 && verArray[1]>=8) || verArray[0] >=2; el = $("<div class='ui-state-default slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers); headerColumnWidthDiff = headerColumnHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { headerColumnWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { headerColumnHeightDiff += parseFloat(el.css(val)) || 0; }); } el.remove(); var r = $("<div class='slick-row' />").appendTo($canvas); el = $("<div class='slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r); cellWidthDiff = cellHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { cellWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { cellHeightDiff += parseFloat(el.css(val)) || 0; }); } r.remove(); absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff); } function createCssRules() { $style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head")); var rowHeight = (options.rowHeight - cellHeightDiff); var rules = [ "." + uid + " .slick-group-header-column { left: 1000px; }", "." + uid + " .slick-header-column { left: 1000px; }", "." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }", "." + uid + " .slick-preheader-panel { height:" + options.preHeaderPanelHeight + "px; }", "." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }", "." + uid + " .slick-footerrow-columns { height:" + options.footerRowHeight + "px; }", "." + uid + " .slick-cell { height:" + rowHeight + "px; }", "." + uid + " .slick-row { height:" + options.rowHeight + "px; }" ]; for (var i = 0; i < columns.length; i++) { rules.push("." + uid + " .l" + i + " { }"); rules.push("." + uid + " .r" + i + " { }"); } if ($style[0].styleSheet) { // IE $style[0].styleSheet.cssText = rules.join(" "); } else { $style[0].appendChild(document.createTextNode(rules.join(" "))); } } function getColumnCssRules(idx) { var i; if (!stylesheet) { var sheets = document.styleSheets; for (i = 0; i < sheets.length; i++) { if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) { stylesheet = sheets[i]; break; } } if (!stylesheet) { throw new Error("Cannot find stylesheet."); } // find and cache column CSS rules columnCssRulesL = []; columnCssRulesR = []; var cssRules = (stylesheet.cssRules || stylesheet.rules); var matches, columnIdx; for (i = 0; i < cssRules.length; i++) { var selector = cssRules[i].selectorText; if (matches = /\.l\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesL[columnIdx] = cssRules[i]; } else if (matches = /\.r\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesR[columnIdx] = cssRules[i]; } } } return { "left": columnCssRulesL[idx], "right": columnCssRulesR[idx] }; } function removeCssRules() { $style.remove(); stylesheet = null; } function destroy(shouldDestroyAllElements) { getEditorLock().cancelCurrentEdit(); trigger(self.onBeforeDestroy, {}); var i = plugins.length; while(i--) { unregisterPlugin(plugins[i]); } if (options.enableColumnReorder) { $headers.filter(":ui-sortable").sortable("destroy"); } unbindAncestorScrollEvents(); $container.off(".slickgrid"); removeCssRules(); $canvas.off(); $viewport.off(); $headerScroller.off(); $headerRowScroller.off(); if ($footerRow) { $footerRow.off(); } if ($footerRowScroller) { $footerRowScroller.off(); } if ($preHeaderPanelScroller) { $preHeaderPanelScroller.off(); } $focusSink.off(); $(".slick-resizable-handle").off(); $(".slick-header-column").off(); $container.empty().removeClass(uid); if (shouldDestroyAllElements) { destroyAllElements(); } } function destroyAllElements() { $activeCanvasNode = null; $activeViewportNode = null; $boundAncestors = null; $canvas = null; $canvasTopL = null; $canvasTopR = null; $canvasBottomL = null; $canvasBottomR = null; $container = null; $focusSink = null; $focusSink2 = null; $groupHeaders = null; $groupHeadersL = null; $groupHeadersR = null; $headerL = null; $headerR = null; $headers = null; $headerRow = null; $headerRowL = null; $headerRowR = null; $headerRowSpacerL = null; $headerRowSpacerR = null; $headerRowScrollContainer = null; $headerRowScroller = null; $headerRowScrollerL = null; $headerRowScrollerR = null; $headerScrollContainer = null; $headerScroller = null; $headerScrollerL = null; $headerScrollerR = null; $hiddenParents = null; $footerRow = null; $footerRowL = null; $footerRowR = null; $footerRowSpacerL = null; $footerRowSpacerR = null; $footerRowScroller = null; $footerRowScrollerL = null; $footerRowScrollerR = null; $footerRowScrollContainer = null; $preHeaderPanel = null; $preHeaderPanelR = null; $preHeaderPanelScroller = null; $preHeaderPanelScrollerR = null; $preHeaderPanelSpacer = null; $preHeaderPanelSpacerR = null; $topPanel = null; $topPanelScroller = null; $style = null; $topPanelScrollerL = null; $topPanelScrollerR = null; $topPanelL = null; $topPanelR = null; $paneHeaderL = null; $paneHeaderR = null; $paneTopL = null; $paneTopR = null; $paneBottomL = null; $paneBottomR = null; $viewport = null; $viewportTopL = null; $viewportTopR = null; $viewportBottomL = null; $viewportBottomR = null; $viewportScrollContainerX = null; $viewportScrollContainerY = null; } ////////////////////////////////////////////////////////////////////////////////////////////// // Column Autosizing ////////////////////////////////////////////////////////////////////////////////////////////// var canvas = null; var canvas_context = null; function autosizeColumn(columnOrIndexOrId, isInit) { var c = columnOrIndexOrId; if (typeof columnOrIndexOrId === 'number') { c = columns[columnOrIndexOrId]; } else if (typeof columnOrIndexOrId === 'string') { for (var i = 0; i < columns.length; i++) { if (columns[i].Id === columnOrIndexOrId) { c = columns[i]; } } } var $gridCanvas = $(getCanvasNode(0, 0)); getColAutosizeWidth(c, $gridCanvas, isInit); } function autosizeColumns(autosizeMode, isInit) { //LogColWidths(); autosizeMode = autosizeMode || options.autosizeColsMode; if (autosizeMode === Slick.GridAutosizeColsMode.LegacyForceFit || autosizeMode === Slick.GridAutosizeColsMode.LegacyOff) { legacyAutosizeColumns(); return; } if (autosizeMode === Slick.GridAutosizeColsMode.None) { return; } // test for brower canvas support, canvas_context!=null if supported canvas = document.createElement("canvas"); if (canvas && canvas.getContext) { canvas_context = canvas.getContext("2d"); } // pass in the grid canvas var $gridCanvas = $(getCanvasNode(0, 0)); var viewportWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; // iterate columns to get autosizes var i, c, colWidth, reRender, totalWidth = 0, totalWidthLessSTR = 0, strColsMinWidth = 0, totalMinWidth = 0, totalLockedColWidth = 0; for (i = 0; i < columns.length; i++) { c = columns[i]; getColAutosizeWidth(c, $gridCanvas, isInit); totalLockedColWidth += (c.autoSize.autosizeMode === Slick.ColAutosizeMode.Locked ? c.width : 0); totalMinWidth += (c.autoSize.autosizeMode === Slick.ColAutosizeMode.Locked ? c.width : c.minWidth); totalWidth += c.autoSize.widthPx; totalWidthLessSTR += (c.autoSize.sizeToRemaining ? 0 : c.autoSize.widthPx); strColsMinWidth += (c.autoSize.sizeToRemaining ? c.minWidth || 0 : 0); } var strColTotalGuideWidth = totalWidth - totalWidthLessSTR; if (autosizeMode === Slick.GridAutosizeColsMode.FitViewportToCols) { // - if viewport with is outside MinViewportWidthPx and MaxViewportWidthPx, then the viewport is set to // MinViewportWidthPx or MaxViewportWidthPx and the FitColsToViewport algorithm is used // - viewport is resized to fit columns var setWidth = totalWidth + scrollbarDimensions.width; autosizeMode = Slick.GridAutosizeColsMode.IgnoreViewport; if (options.viewportMaxWidthPx && setWidth > options.viewportMaxWidthPx) { setWidth = options.viewportMaxWidthPx; autosizeMode = Slick.GridAutosizeColsMode.FitColsToViewport; } else if (options.viewportMinWidthPx && setWidth < options.viewportMinWidthPx) { setWidth = options.viewportMinWidthPx; autosizeMode = Slick.GridAutosizeColsMode.FitColsToViewport; } else { // falling back to IgnoreViewport will size the columns as-is, with render checking //for (i = 0; i < columns.length; i++) { columns[i].width = columns[i].autoSize.widthPx; } } $container.width(setWidth); } if (autosizeMode === Slick.GridAutosizeColsMode.FitColsToViewport) { if (strColTotalGuideWidth > 0 && totalWidthLessSTR < viewportWidth - strColsMinWidth) { // if addl space remains in the viewport and there are SizeToRemaining cols, just the SizeToRemaining cols expand proportionally to fill viewport for (i = 0; i < columns.length; i++) { c = columns[i]; var totalSTRViewportWidth = viewportWidth - totalWidthLessSTR; if (c.autoSize.sizeToRemaining) { colWidth = totalSTRViewportWidth * c.autoSize.widthPx / strColTotalGuideWidth; } else { colWidth = c.autoSize.widthPx; } if (c.rerenderOnResize && c.width != colWidth) { reRender = true; } c.width = colWidth; } } else if ((options.viewportSwitchToScrollModeWidthPercent && totalWidthLessSTR + strColsMinWidth > viewportWidth * options.viewportSwitchToScrollModeWidthPercent / 100) || (totalMinWidth > viewportWidth)) { // if the total columns width is wider than the viewport by switchToScrollModeWidthPercent, switch to IgnoreViewport mode autosizeMode = Slick.GridAutosizeColsMode.IgnoreViewport; } else { // otherwise (ie. no SizeToRemaining cols or viewport smaller than columns) all cols other than 'Locked' scale in proportion to fill viewport // and SizeToRemaining get minWidth var unallocatedColWidth = totalWidthLessSTR - totalLockedColWidth; var unallocatedViewportWidth = viewportWidth - totalLockedColWidth - strColsMinWidth; for (i = 0; i < columns.length; i++) { c = columns[i]; colWidth = c.width; if (c.autoSize.autosizeMode !== Slick.ColAutosizeMode.Locked) { if (c.autoSize.sizeToRemaining) { colWidth = c.minWidth; } else { // size width proportionally to free space (we know we have enough room due to the earlier calculations) colWidth = unallocatedViewportWidth / unallocatedColWidth * c.autoSize.widthPx; if (colWidth < c.minWidth) { colWidth = c.minWidth; } // remove the just allocated widths from the allocation pool unallocatedColWidth -= c.autoSize.widthPx; unallocatedViewportWidth -= colWidth; } } if (c.rerenderOnResize && c.width != colWidth) { reRender = true; } c.width = colWidth; } } } if (autosizeMode === Slick.GridAutosizeColsMode.IgnoreViewport) { // just size columns as-is for (i = 0; i < columns.length; i++) { colWidth = columns[i].autoSize.widthPx; if (columns[i].rerenderOnResize && columns[i].width != colWidth) { reRender = true; } columns[i].width = colWidth; } } //LogColWidths(); reRenderColumns(reRender); } function LogColWidths () { var s = "Col Widths:"; for (var i = 0; i < columns.length; i++) { s += ' ' + columns[i].width; } console.log(s); } function getColAutosizeWidth(columnDef, $gridCanvas, isInit) { var autoSize = columnDef.autoSize; // set to width as default autoSize.widthPx = columnDef.width; if (autoSize.autosizeMode === Slick.ColAutosizeMode.Locked || autoSize.autosizeMode === Slick.ColAutosizeMode.Guide) { return; } var dl = getDataLength(); //getDataItem(); // ContentIntelligent takes settings from column data type if (autoSize.autosizeMode === Slick.ColAutosizeMode.ContentIntelligent) { // default to column colDataTypeOf (can be used if initially there are no data rows) var colDataTypeOf = autoSize.colDataTypeOf; var colDataItem; if (dl > 0) { var tempRow = getDataItem(0); if (tempRow) { colDataItem = tempRow[columnDef.field]; colDataTypeOf = typeof colDataItem; if (colDataTypeOf === 'object') { if (colDataItem instanceof Date) { colDataTypeOf = "date"; } if (typeof moment!=='undefined' && colDataItem instanceof moment) { colDataTypeOf = "moment"; } } } } if (colDataTypeOf === 'boolean') { autoSize.colValueArray = [ true, false ]; } if (colDataTypeOf === 'number') { autoSize.valueFilterMode = Slick.ValueFilterMode.GetGreatestAndSub; autoSize.rowSelectionMode = Slick.RowSelectionMode.AllRows; } if (colDataTypeOf === 'string') { autoSize.valueFilterMode = Slick.ValueFilterMode.GetLongestText; autoSize.rowSelectionMode = Slick.RowSelectionMode.AllRows; autoSize.allowAddlPercent = 5; } if (colDataTypeOf === 'date') { autoSize.colValueArray = [ new Date(2009, 8, 30, 12, 20, 20) ]; // Sep 30th 2009, 12:20:20 AM } if (colDataTypeOf === 'moment' && typeof moment!=='undefined') { autoSize.colValueArray = [ moment([2009, 8, 30, 12, 20, 20]) ]; // Sep 30th 2009, 12:20:20 AM } } // at this point, the autosizeMode is effectively 'Content', so proceed to get size var colWidth = getColContentSize(columnDef, $gridCanvas, isInit); var addlPercentMultiplier = (autoSize.allowAddlPercent ? (1 + autoSize.allowAddlPercent/100) : 1); colWidth = colWidth * addlPercentMultiplier + options.autosizeColPaddingPx; if (columnDef.minWidth && colWidth < columnDef.minWidth) { colWidth = columnDef.minWidth; } if (columnDef.maxWidth && colWidth > columnDef.maxWidth) { colWidth = columnDef.maxWidth; } autoSize.widthPx = colWidth; } function getColContentSize(columnDef, $gridCanvas, isInit) { var autoSize = columnDef.autoSize; var widthAdjustRatio = 1; // at this point, the autosizeMode is effectively 'Content', so proceed to get size // get header width, if we are taking notice of it var i, ii; var maxColWidth = 0; var headerWidth = 0; if (!autoSize.ignoreHeaderText) { headerWidth = getColHeaderWidth(columnDef); } if (autoSize.colValueArray) { // if an array of values are specified, just pass them in instead of data maxColWidth = getColWidth(columnDef, $gridCanvas, autoSize.colValueArray); return Math.max(headerWidth, maxColWidth); } // select rows to evaluate using rowSelectionMode and rowSelectionCount var rows = getData(); if (rows.getItems) { rows = rows.getItems(); } var rowSelectionMode = (isInit ? autoSize.rowSelectionModeOnInit : undefined) || autoSize.rowSelectionMode; if (rowSelectionMode === Slick.RowSelectionMode.FirstRow) { rows = rows.slice(0,1); } if (rowSelectionMode === Slick.RowSelectionMode.LastRow) { rows = rows.slice(rows.length -1, rows.length); } if (rowSelectionMode === Slick.RowSelectionMode.FirstNRows) { rows = rows.slice(0, autoSize.rowSelectionCount); } // now use valueFilterMode to further filter selected rows if (autoSize.valueFilterMode === Slick.ValueFilterMode.DeDuplicate) { var rowsDict = {}; for (i = 0, ii = rows.length; i < ii; i++) { rowsDict[rows[i][columnDef.field]] = true; } if (Object.keys) { rows = Object.keys(rowsDict); } else { rows = []; for (var i in rowsDict) rows.push(i); } } if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetGreatestAndSub) { // get greatest abs value in data var tempVal, maxVal, maxAbsVal = 0; for (i = 0, ii = rows.length; i < ii; i++) { tempVal = rows[i][columnDef.field]; if (Math.abs(tempVal) > maxAbsVal) { maxVal = tempVal; maxAbsVal = Math.abs(tempVal); } } // now substitute a '9' for all characters (to get widest width) and convert back to a number maxVal = '' + maxVal; maxVal = Array(maxVal.length + 1).join("9"); maxVal = +maxVal; rows = [ maxVal ]; } if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetLongestTextAndSub) { // get greatest abs value in data var tempVal, maxLen = 0; for (i = 0, ii = rows.length; i < ii; i++) { tempVal = rows[i][columnDef.field]; if ((tempVal || '').length > maxLen) { maxLen = tempVal.length; } } // now substitute a 'c' for all characters tempVal = Array(maxLen + 1).join("m"); widthAdjustRatio = options.autosizeTextAvgToMWidthRatio; rows = [ tempVal ]; } if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetLongestText) { // get greatest abs value in data var tempVal, maxLen = 0, maxIndex = 0; for (i = 0, ii = rows.length; i < ii; i++) { tempVal = rows[i][columnDef.field]; if ((tempVal || '').length > maxLen) { maxLen = tempVal.length; maxIndex = i; } } // now substitute a 'c' for all characters tempVal = rows[maxIndex][columnDef.field]; rows = [ tempVal ]; } maxColWidth = getColWidth(columnDef, $gridCanvas, rows) * widthAdjustRatio; return Math.max(headerWidth, maxColWidth); } function getColWidth(columnDef, $gridCanvas, data) { var colIndex = getColumnIndex(columnDef.id); var $rowEl = $('<div class="slick-row ui-widget-content"></div>'); var $cellEl = $('<div class="slick-cell"></div>'); $cellEl.css({ "position": "absolute", "visibility": "hidden", "text-overflow": "initial", "white-space": "nowrap" }); $rowEl.append($cellEl); $gridCanvas.append($rowEl); var len, max = 0, text, maxText, formatterResult, maxWidth = 0, val; // use canvas - very fast, but text-only if (canvas_context && columnDef.autoSize.widthEvalMode === Slick.WidthEvalMode.CanvasTextSize) { canvas_context.font = $cellEl.css("font-size") + " " + $cellEl.css("font-family"); $(data).each(function (index, row) { // row is either an array or values or a single value val = (Array.isArray(row) ? row[columnDef.field] : row); text = '' + val; len = text ? canvas_context.measureText(text).width : 0; if (len > max) { max = len; maxText = text; } }); $cellEl.html(maxText); len = $cellEl.outerWidth(); $rowEl.remove(); $cellEl = null; return len; } $(data).each(function (index, row) { val = (Array.isArray(row) ? row[columnDef.field] : row); if (columnDef.formatterOverride) { // use formatterOverride as first preference formatterResult = columnDef.formatterOverride(index, colIndex, val, columnDef, row, self); } else if (columnDef.formatter) { // otherwise, use formatter formatterResult = columnDef.formatter(index, colIndex, val, columnDef, row, self); } else { // otherwise, use plain text formatterResult = '' + val; } applyFormatResultToCellNode(formatterResult, $cellEl[0]); len = $cellEl.outerWidth(); if (len > max) { max = len; } }); $rowEl.remove(); $cellEl = null; return max; } function getColHeaderWidth(columnDef) { var width = 0; //if (columnDef && (!columnDef.resizable || columnDef._autoCalcWidth === true)) return; var headerColElId = getUID() + columnDef.id; var headerColEl = document.getElementById(headerColElId); var dummyHeaderColElId = headerColElId + "_"; if (headerColEl) { // headers have been created, use clone technique var clone = headerColEl.cloneNode(true); clone.id = dummyHeaderColElId; clone.style.cssText = 'position: absolute; visibility: hidden;right: auto;text-overflow: initial;white-space: nowrap;'; headerColEl.parentNode.insertBefore(clone, headerColEl); width = clone.offsetWidth; clone.parentNode.removeChild(clone); } else { // headers have not yet been created, create a new node var header = getHeader(columnDef); headerColEl = $("<div class='ui-state-default slick-header-column' />") .html("<span class='slick-column-name'>" + columnDef.name + "</span>") .attr("id", dummyHeaderColElId) .css({ "position": "absolute", "visibility": "hidden", "right": "auto", "text-overflow:": "initial", "white-space": "nowrap" }) .addClass(columnDef.headerCssClass || "") .appendTo(header); width = headerColEl[0].offsetWidth; header[0].removeChild(headerColEl[0]); } return width; } function legacyAutosizeColumns() { var i, c, widths = [], shrinkLeeway = 0, total = 0, prevTotal, availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; for (i = 0; i < columns.length; i++) { c = columns[i]; widths.push(c.width); total += c.width; if (c.resizable) { shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth); } } // shrink prevTotal = total; while (total > availWidth && shrinkLeeway) { var shrinkProportion = (total - availWidth) / shrinkLeeway; for (i = 0; i < columns.length && total > availWidth; i++) { c = columns[i]; var width = widths[i]; if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) { continue; } var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth); var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1; shrinkSize = Math.min(shrinkSize, width - absMinWidth); total -= shrinkSize; shrinkLeeway -= shrinkSize; widths[i] -= shrinkSize; } if (prevTotal <= total) { // avoid infinite loop break; } prevTotal = total; } // grow prevTotal = total; while (total < availWidth) { var growProportion = availWidth / total; for (i = 0; i < columns.length && total < availWidth; i++) { c = columns[i]; var currentWidth = widths[i]; var growSize; if (!c.resizable || c.maxWidth <= currentWidth) { growSize = 0; } else { growSize = Math.min(Math.floor(growProportion * currentWidth) - currentWidth, (c.maxWidth - currentWidth) || 1000000) || 1; } total += growSize; widths[i] += (total <= availWidth ? growSize : 0); } if (prevTotal >= total) { // avoid infinite loop break; } prevTotal = total; } var reRender = false; for (i = 0; i < columns.length; i++) { if (columns[i].rerenderOnResize && columns[i].width != widths[i]) { reRender = true; } columns[i].width = widths[i]; } reRenderColumns(reRender); } function reRenderColumns(reRender) { applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); updateCanvasWidth(true); trigger(self.onAutosizeColumns, { "columns": columns}); if (reRender) { invalidateAllRows(); render(); } } ////////////////////////////////////////////////////////////////////////////////////////////// // General ////////////////////////////////////////////////////////////////////////////////////////////// function trigger(evt, args, e) { e = e || new Slick.EventData(); args = args || {}; args.grid = self; return evt.notify(args, e, self); } function getEditorLock() { return options.editorLock; } function getEditController() { return editController; } function getColumnIndex(id) { return columnsById[id]; } function applyColumnGroupHeaderWidths() { if (!treeColumns.hasDepth()) return; for (var depth = $groupHeadersL.length - 1; depth >= 0; depth--) { var groupColumns = treeColumns.getColumnsInDepth(depth); $().add($groupHeadersL[depth]).add($groupHeadersR[depth]).each(function(i) { var $groupHeader = $(this), currentColumnIndex = 0; $groupHeader.width(i === 0? getHeadersWidthL(): getHeadersWidthR()); $groupHeader.children().each(function() { var $groupHeaderColumn = $(this); var m = $(this).data('column'); m.width = 0; m.columns.forEach(function() { var $headerColumn = $groupHeader.next().children(':eq(' + (currentColumnIndex++) + ')'); m.width += $headerColumn.outerWidth(); }); $groupHeaderColumn.width(m.width - headerColumnWidthDiff); }); }); } } function applyColumnHeaderWidths() { if (!initialized) { return; } var h; for (var i = 0, headers = $headers.children(), ii = columns.length; i < ii; i++) { h = $(headers[i]); if (jQueryNewWidthBehaviour) { if (h.outerWidth() !== columns[i].width) { h.outerWidth(columns[i].width); } } else { if (h.width() !== columns[i].width - headerColumnWidthDiff) { h.width(columns[i].width - headerColumnWidthDiff); } } } updateColumnCaches(); } function applyColumnWidths() { var x = 0, w, rule; for (var i = 0; i < columns.length; i++) { w = columns[i].width; rule = getColumnCssRules(i); rule.left.style.left = x + "px"; rule.right.style.right = (((options.frozenColumn != -1 && i > options.frozenColumn) ? canvasWidthR : canvasWidthL) - x - w) + "px"; // If this column is frozen, reset the css left value since the // column starts in a new viewport. if (options.frozenColumn == i) { x = 0; } else { x += columns[i].width; } } } function setSortColumn(columnId, ascending) { setSortColumns([{ columnId: columnId, sortAsc: ascending}]); } function setSortColumns(cols) { sortColumns = cols; var numberCols = options.numberedMultiColumnSort && sortColumns.length > 1; var headerColumnEls = $headers.children(); headerColumnEls .removeClass("slick-header-column-sorted") .find(".slick-sort-indicator") .removeClass("slick-sort-indicator-asc slick-sort-indicator-desc"); headerColumnEls .find(".slick-sort-indicator-numbered") .text(''); $.each(sortColumns, function(i, col) { if (col.sortAsc == null) { col.sortAsc = true; } var columnIndex = getColumnIndex(col.columnId); if (columnIndex != null) { headerColumnEls.eq(columnIndex) .addClass("slick-header-column-sorted") .find(".slick-sort-indicator") .addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc"); if (numberCols) { headerColumnEls.eq(columnIndex) .find(".slick-sort-indicator-numbered") .text(i+1); } } }); } function getSortColumns() { return sortColumns; } function handleSelectedRangesChanged(e, ranges) { var previousSelectedRows = selectedRows.slice(0); // shallow copy previously selected rows for later comparison selectedRows = []; var hash = {}; for (var i = 0; i < ranges.length; i++) { for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) { if (!hash[j]) { // prevent duplicates selectedRows.push(j); hash[j] = {}; } for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) { if (canCellBeSelected(j, k)) { hash[j][columns[k].id] = options.selectedCellCssClass; } } } } setCellCssStyles(options.selectedCellCssClass, hash); if (simpleArrayEquals(previousSelectedRows, selectedRows)) { trigger(self.onSelectedRowsChanged, {rows: getSelectedRows(), previousSelectedRows: previousSelectedRows}, e); } } // compare 2 simple arrays (integers or strings only, do not use to compare object arrays) function simpleArrayEquals(arr1, arr2) { return Array.isArray(arr1) && Array.isArray(arr2) && arr2.sort().toString() !== arr1.sort().toString(); } function getColumns() { return columns; } function updateColumnCaches() { // Pre-calculate cell boundaries. columnPosLeft = []; columnPosRight = []; var x = 0; for (var i = 0, ii = columns.length; i < ii; i++) { columnPosLeft[i] = x; columnPosRight[i] = x + columns[i].width; if (options.frozenColumn == i) { x = 0; } else { x += columns[i].width; } } } function updateColumnProps() { columnsById = {}; for (var i = 0; i < columns.length; i++) { if (columns[i].width) { columns[i].widthRequest = columns[i].width; } var m = columns[i] = $.extend({}, columnDefaults, columns[i]); m.autoSize = $.extend({}, columnAutosizeDefaults, m.autoSize); columnsById[m.id] = i; if (m.minWidth && m.width < m.minWidth) { m.width = m.minWidth; } if (m.maxWidth && m.width > m.maxWidth) { m.width = m.maxWidth; } if (!m.resizable) { // there is difference between user resizable and autoWidth resizable //m.autoSize.autosizeMode = Slick.ColAutosizeMode.Locked; } } } function setColumns(columnDefinitions) { var _treeColumns = new Slick.TreeColumns(columnDefinitions); if (_treeColumns.hasDepth()) { treeColumns = _treeColumns; columns = treeColumns.extractColumns(); } else { columns = columnDefinitions; } updateColumnProps(); updateColumnCaches(); if (initialized) { setPaneVisibility(); setOverflow(); invalidateAllRows(); createColumnHeaders(); createColumnGroupHeaders(); createColumnFooter(); removeCssRules(); createCssRules(); resizeCanvas(); updateCanvasWidth(); applyColumnHeaderWidths(); applyColumnWidths(); handleScroll(); } } function getOptions() { return options; } function setOptions(args, suppressRender, suppressColumnSet) { if (!getEditorLock().commitCurrentEdit()) { return; } makeActiveCellNormal(); if (args.showColumnHeader !== undefined) { setColumnHeaderVisibility(args.showColumnHeader); } if (options.enableAddRow !== args.enableAddRow) { invalidateRow(getDataLength()); } var originalOptions = $.extend(true, {}, options); options = $.extend(options, args); trigger(self.onSetOptions, { "optionsBefore": originalOptions, "optionsAfter": options }); validateAndEnforceOptions(); $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto"); if (!suppressRender) { render(); } setFrozenOptions(); setScroller(); zombieRowNodeFromLastMouseWheelEvent = null; if (!suppressColumnSet) { setColumns(treeColumns.extractColumns()); } if (options.enableMouseWheelScrollHandler && $viewport && jQuery.fn.mousewheel) { var viewportEvents = $._data($viewport[0], "events"); if (!viewportEvents || !viewportEvents.mousewheel) { $viewport.on("mousewheel", handleMouseWheel); } } else if (options.enableMouseWheelScrollHandler === false) { $viewport.off("mousewheel"); // remove scroll handler when option is disable } } function validateAndEnforceOptions() { if (options.autoHeight) { options.leaveSpaceForNewRows = false; } if (options.forceFitColumns) { options.autosizeColsMode = Slick.GridAutosizeColsMode.LegacyForceFit; console.log("forceFitColumns option is deprecated - use autosizeColsMode"); } } function setData(newData, scrollToTop) { data = newData; invalidateAllRows(); updateRowCount(); if (scrollToTop) { scrollTo(0); } } function getData() { return data; } function getDataLength() { if (data.getLength) { return data.getLength(); } else { return data && data.length || 0; } } function getDataLengthIncludingAddNew() { return getDataLength() + (!options.enableAddRow ? 0 : (!pagingActive || pagingIsLastPage ? 1 : 0) ); } function getDataItem(i) { if (data.getItem) { return data.getItem(i); } else { return data[i]; } } function getTopPanel() { return $topPanel[0]; } function setTopPanelVisibility(visible, animate) { var animated = (animate === false) ? false : true; if (options.showTopPanel != visible) { options.showTopPanel = visible; if (visible) { if (animated) { $topPanelScroller.slideDown("fast", resizeCanvas); } else { $topPanelScroller.show(); resizeCanvas(); } } else { if (animated) { $topPanelScroller.slideUp("fast", resizeCanvas); } else { $topPanelScroller.hide(); resizeCanvas(); } } } } function setHeaderRowVisibility(visible, animate) { var animated = (animate === false) ? false : true; if (options.showHeaderRow != visible) { options.showHeaderRow = visible; if (visible) { if (animated) { $headerRowScroller.slideDown("fast", resizeCanvas); } else { $headerRowScroller.show(); resizeCanvas(); } } else { if (animated) { $headerRowScroller.slideUp("fast", resizeCanvas); } else { $headerRowScroller.hide(); resizeCanvas(); } } } } function setColumnHeaderVisibility(visible, animate) { if (options.showColumnHeader != visible) { options.showColumnHeader = visible; if (visible) { if (animate) { $headerScroller.slideDown("fast", resizeCanvas); } else { $headerScroller.show(); resizeCanvas(); } } else { if (animate) { $headerScroller.slideUp("fast", resizeCanvas); } else { $headerScroller.hide(); resizeCanvas(); } } } } function setFooterRowVisibility(visible, animate) { var animated = (animate === false) ? false : true; if (options.showFooterRow != visible) { options.showFooterRow = visible; if (visible) { if (animated) { $footerRowScroller.slideDown("fast", resizeCanvas); } else { $footerRowScroller.show(); resizeCanvas(); } } else { if (animated) { $footerRowScroller.slideUp("fast", resizeCanvas); } else { $footerRowScroller.hide(); resizeCanvas(); } } } } function setPreHeaderPanelVisibility(visible, animate) { var animated = (animate === false) ? false : true; if (options.showPreHeaderPanel != visible) { options.showPreHeaderPanel = visible; if (visible) { if (animated) { $preHeaderPanelScroller.slideDown("fast", resizeCanvas); } else { $preHeaderPanelScroller.show(); resizeCanvas(); } } else { if (animated) { $preHeaderPanelScroller.slideUp("fast", resizeCanvas); } else { $preHeaderPanelScroller.hide(); resizeCanvas(); } } } } function getContainerNode() { return $container.get(0); } ////////////////////////////////////////////////////////////////////////////////////////////// // Rendering / Scrolling function getRowTop(row) { return options.rowHeight * row - offset; } function getRowFromPosition(y) { return Math.floor((y + offset) / options.rowHeight); } function scrollTo(y) { y = Math.max(y, 0); y = Math.min(y, th - $viewportScrollContainerY.height() + ((viewportHasHScroll || hasFrozenColumns()) ? scrollbarDimensions.height : 0)); var oldOffset = offset; page = Math.min(n - 1, Math.floor(y / ph)); offset = Math.round(page * cj); var newScrollTop = y - offset; if (offset != oldOffset) { var range = getVisibleRange(newScrollTop); cleanupRows(range); updateRowPositions(); } if (prevScrollTop != newScrollTop) { vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1; lastRenderedScrollTop = ( scrollTop = prevScrollTop = newScrollTop ); if (hasFrozenColumns()) { $viewportTopL[0].scrollTop = newScrollTop; } if (hasFrozenRows) { $viewportBottomL[0].scrollTop = $viewportBottomR[0].scrollTop = newScrollTop; } $viewportScrollContainerY[0].scrollTop = newScrollTop; trigger(self.onViewportChanged, {}); } } function defaultFormatter(row, cell, value, columnDef, dataContext, grid) { if (value == null) { return ""; } else { return (value + "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); } } function getFormatter(row, column) { var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); // look up by id, then index var columnOverrides = rowMetadata && rowMetadata.columns && (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]); return (columnOverrides && columnOverrides.formatter) || (rowMetadata && rowMetadata.formatter) || column.formatter || (options.formatterFactory && options.formatterFactory.getFormatter(column)) || options.defaultFormatter; } function getEditor(row, cell) { var column = columns[cell]; var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) { return columnMetadata[column.id].editor; } if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) { return columnMetadata[cell].editor; } return column.editor || (options.editorFactory && options.editorFactory.getEditor(column)); } function getDataItemValueForColumn(item, columnDef) { if (options.dataItemColumnValueExtractor) { return options.dataItemColumnValueExtractor(item, columnDef); } return item[columnDef.field]; } function appendRowHtml(stringArrayL, stringArrayR, row, range, dataLength) { var d = getDataItem(row); var dataLoading = row < dataLength && !d; var rowCss = "slick-row" + (hasFrozenRows && row <= options.frozenRow? ' frozen': '') + (dataLoading ? " loading" : "") + (row === activeRow && options.showCellSelection ? " active" : "") + (row % 2 == 1 ? " odd" : " even"); if (!d) { rowCss += " " + options.addNewRowCssClass; } var metadata = data.getItemMetadata && data.getItemMetadata(row); if (metadata && metadata.cssClasses) { rowCss += " " + metadata.cssClasses; } var frozenRowOffset = getFrozenRowOffset(row); var rowHtml = "<div class='ui-widget-content " + rowCss + "' style='top:" + (getRowTop(row) - frozenRowOffset ) + "px'>"; stringArrayL.push(rowHtml); if (hasFrozenColumns()) { stringArrayR.push(rowHtml); } var colspan, m; for (var i = 0, ii = columns.length; i < ii; i++) { m = columns[i]; colspan = 1; if (metadata && metadata.columns) { var columnData = metadata.columns[m.id] || metadata.columns[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } // Do not render cells outside of the viewport. if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { if (!m.alwaysRenderColumn && columnPosLeft[i] > range.rightPx) { // All columns to the right are outside the range. break; } if (hasFrozenColumns() && ( i > options.frozenColumn )) { appendCellHtml(stringArrayR, row, i, colspan, d); } else { appendCellHtml(stringArrayL, row, i, colspan, d); } } else if (m.alwaysRenderColumn || (hasFrozenColumns() && i <= options.frozenColumn)) { appendCellHtml(stringArrayL, row, i, colspan, d); } if (colspan > 1) { i += (colspan - 1); } } stringArrayL.push("</div>"); if (hasFrozenColumns()) { stringArrayR.push("</div>"); } } function appendCellHtml(stringArray, row, cell, colspan, item) { // stringArray: stringBuilder containing the HTML parts // row, cell: row and column index // colspan: HTML colspan // item: grid data for row var m = columns[cell]; var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1) + (m.cssClass ? " " + m.cssClass : ""); if (hasFrozenColumns() && cell <= options.frozenColumn) { cellCss += (" frozen"); } if (row === activeRow && cell === activeCell && options.showCellSelection) { cellCss += (" active"); } // TODO: merge them together in the setter for (var key in cellCssClasses) { if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) { cellCss += (" " + cellCssClasses[key][row][m.id]); } } var value = null, formatterResult = ''; if (item) { value = getDataItemValueForColumn(item, m); formatterResult = getFormatter(row, m)(row, cell, value, m, item, self); if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; } } // get addl css class names from object type formatter return and from string type return of onBeforeAppendCell var addlCssClasses = trigger(self.onBeforeAppendCell, { row: row, cell: cell, value: value, dataContext: item }) || ''; addlCssClasses += (formatterResult && formatterResult.addClasses ? (addlCssClasses ? ' ' : '') + formatterResult.addClasses : ''); var toolTip = formatterResult && formatterResult.toolTip ? "title='" + formatterResult.toolTip + "'" : ''; var customAttrStr = ''; if(m.hasOwnProperty('cellAttrs') && m.cellAttrs instanceof Object) { for (var key in m.cellAttrs) { if (m.cellAttrs.hasOwnProperty(key)) { customAttrStr += ' ' + key + '="' + m.cellAttrs[key] + '" '; } } } stringArray.push("<div class='" + cellCss + (addlCssClasses ? ' ' + addlCssClasses : '') + "' " + toolTip + customAttrStr + ">"); // if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet) if (item) { stringArray.push(Object.prototype.toString.call(formatterResult) !== '[object Object]' ? formatterResult : formatterResult.text); } stringArray.push("</div>"); rowsCache[row].cellRenderQueue.push(cell); rowsCache[row].cellColSpans[cell] = colspan; } function cleanupRows(rangeToKeep) { for (var i in rowsCache) { var removeFrozenRow = true; if (hasFrozenRows && ( ( options.frozenBottom && i >= actualFrozenRow ) // Frozen bottom rows || ( !options.frozenBottom && i <= actualFrozenRow ) // Frozen top rows ) ) { removeFrozenRow = false; } if (( ( i = parseInt(i, 10)) !== activeRow ) && ( i < rangeToKeep.top || i > rangeToKeep.bottom ) && ( removeFrozenRow ) ) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidate() { updateRowCount(); invalidateAllRows(); render(); } function invalidateAllRows() { if (currentEditor) { makeActiveCellNormal(); } for (var row in rowsCache) { removeRowFromCache(row); } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function queuePostProcessedRowForCleanup(cacheEntry, postProcessedRow, rowIdx) { postProcessgroupId++; // store and detach node for later async cleanup for (var columnIdx in postProcessedRow) { if (postProcessedRow.hasOwnProperty(columnIdx)) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cacheEntry.cellNodesByColumnIdx[ columnIdx | 0], columnIdx: columnIdx | 0, rowIdx: rowIdx }); } } postProcessedCleanupQueue.push({ actionType: 'R', groupId: postProcessgroupId, node: cacheEntry.rowNode }); $(cacheEntry.rowNode).detach(); } function queuePostProcessedCellForCleanup(cellnode, columnIdx, rowIdx) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cellnode, columnIdx: columnIdx, rowIdx: rowIdx }); $(cellnode).detach(); } function removeRowFromCache(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } if (rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[0] || (hasFrozenColumns() && rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[1])) { cacheEntry.rowNode.hide(); zombieRowNodeFromLastMouseWheelEvent = cacheEntry.rowNode; } else { cacheEntry.rowNode.each(function() { this.parentElement.removeChild(this); }); } delete rowsCache[row]; delete postProcessedRows[row]; renderedRows--; counter_rows_removed++; } function invalidateRows(rows) { var i, rl; if (!rows || !rows.length) { return; } vScrollDir = 0; rl = rows.length; for (i = 0; i < rl; i++) { if (currentEditor && activeRow === rows[i]) { makeActiveCellNormal(); } if (rowsCache[rows[i]]) { removeRowFromCache(rows[i]); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidateRow(row) { if (!row && row !== 0) { return; } invalidateRows([row]); } function applyFormatResultToCellNode(formatterResult, cellNode, suppressRemove) { if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; } if (Object.prototype.toString.call(formatterResult) !== '[object Object]') { cellNode.innerHTML = formatterResult; return; } cellNode.innerHTML = formatterResult.text; if (formatterResult.removeClasses && !suppressRemove) { $(cellNode).removeClass(formatterResult.removeClasses); } if (formatterResult.addClasses) { $(cellNode).addClass(formatterResult.addClasses); } if (formatterResult.toolTip) { $(cellNode).attr("title", formatterResult.toolTip); } } function updateCell(row, cell) { var cellNode = getCellNode(row, cell); if (!cellNode) { return; } var m = columns[cell], d = getDataItem(row); if (currentEditor && activeRow === row && activeCell === cell) { currentEditor.loadValue(d); } else { var formatterResult = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d, self) : ""; applyFormatResultToCellNode(formatterResult, cellNode); invalidatePostProcessingResults(row); } } function updateRow(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } ensureCellNodesInRowsCache(row); var formatterResult, d = getDataItem(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx], node = cacheEntry.cellNodesByColumnIdx[columnIdx][0]; if (row === activeRow && columnIdx === activeCell && currentEditor) { currentEditor.loadValue(d); } else if (d) { formatterResult = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d, self); applyFormatResultToCellNode(formatterResult, node); } else { node.innerHTML = ""; } } invalidatePostProcessingResults(row); } function getViewportHeight() { if (!options.autoHeight || options.frozenColumn != -1) { topPanelH = ( options.showTopPanel ) ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0; headerRowH = ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0; footerRowH = ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0; } if (options.autoHeight) { var fullHeight = $paneHeaderL.outerHeight(); fullHeight += ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0; fullHeight += ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0; fullHeight += (getCanvasWidth() > viewportW) ? scrollbarDimensions.height : 0; viewportH = options.rowHeight * getDataLengthIncludingAddNew() + ( ( options.frozenColumn == -1 ) ? fullHeight : 0 ); } else { var columnNamesH = ( options.showColumnHeader ) ? parseFloat($.css($headerScroller[0], "height")) + getVBoxDelta($headerScroller) : 0; var preHeaderH = (options.createPreHeaderPanel && options.showPreHeaderPanel) ? options.preHeaderPanelHeight + getVBoxDelta($preHeaderPanelScroller) : 0; viewportH = parseFloat($.css($container[0], "height", true)) - parseFloat($.css($container[0], "paddingTop", true)) - parseFloat($.css($container[0], "paddingBottom", true)) - columnNamesH - topPanelH - headerRowH - footerRowH - preHeaderH; } numVisibleRows = Math.ceil(viewportH / options.rowHeight); return viewportH; } function getViewportWidth() { viewportW = parseFloat($container.width()); } function resizeCanvas() { if (!initialized) { return; } paneTopH = 0; paneBottomH = 0; viewportTopH = 0; viewportBottomH = 0; getViewportWidth(); getViewportHeight(); // Account for Frozen Rows if (hasFrozenRows) { if (options.frozenBottom) { paneTopH = viewportH - frozenRowsHeight - scrollbarDimensions.height; paneBottomH = frozenRowsHeight + scrollbarDimensions.height; } else { paneTopH = frozenRowsHeight; paneBottomH = viewportH - frozenRowsHeight; } } else { paneTopH = viewportH; } // The top pane includes the top panel and the header row paneTopH += topPanelH + headerRowH + footerRowH; if (hasFrozenColumns() && options.autoHeight) { paneTopH += scrollbarDimensions.height; } // The top viewport does not contain the top panel or header row viewportTopH = paneTopH - topPanelH - headerRowH - footerRowH; if (options.autoHeight) { if (hasFrozenColumns()) { $container.height( paneTopH + parseFloat($.css($headerScrollerL[0], "height")) ); } $paneTopL.css('position', 'relative'); } $paneTopL.css({ 'top': $paneHeaderL.height(), 'height': paneTopH }); var paneBottomTop = $paneTopL.position().top + paneTopH; if (!options.autoHeight) { $viewportTopL.height(viewportTopH); } if (hasFrozenColumns()) { $paneTopR.css({ 'top': $paneHeaderL.height(), 'height': paneTopH }); $viewportTopR.height(viewportTopH); if (hasFrozenRows) { $paneBottomL.css({ 'top': paneBottomTop, 'height': paneBottomH }); $paneBottomR.css({ 'top': paneBottomTop, 'height': paneBottomH }); $viewportBottomR.height(paneBottomH); } } else { if (hasFrozenRows) { $paneBottomL.css({ 'width': '100%', 'height': paneBottomH }); $paneBottomL.css('top', paneBottomTop); } } if (hasFrozenRows) { $viewportBottomL.height(paneBottomH); if (options.frozenBottom) { $canvasBottomL.height(frozenRowsHeight); if (hasFrozenColumns()) { $canvasBottomR.height(frozenRowsHeight); } } else { $canvasTopL.height(frozenRowsHeight); if (hasFrozenColumns()) { $canvasTopR.height(frozenRowsHeight); } } } else { $viewportTopR.height(viewportTopH); } if (!scrollbarDimensions || !scrollbarDimensions.width) { scrollbarDimensions = measureScrollbar(); } if (options.autosizeColsMode === Slick.GridAutosizeColsMode.LegacyForceFit) { autosizeColumns(); } updateRowCount(); handleScroll(); // Since the width has changed, force the render() to reevaluate virtually rendered cells. lastRenderedScrollLeft = -1; render(); } function updatePagingStatusFromView( pagingInfo ) { pagingActive = (pagingInfo.pageSize !== 0); pagingIsLastPage = (pagingInfo.pageNum == pagingInfo.totalPages - 1); } function updateRowCount() { if (!initialized) { return; } var dataLength = getDataLength(); var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); var numberOfRows = 0; var oldH = ( hasFrozenRows && !options.frozenBottom ) ? $canvasBottomL.height() : $canvasTopL.height(); if (hasFrozenRows ) { var numberOfRows = getDataLength() - options.frozenRow; } else { var numberOfRows = dataLengthIncludingAddNew + (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0); } var tempViewportH = $viewportScrollContainerY.height(); var oldViewportHasVScroll = viewportHasVScroll; // with autoHeight, we do not need to accommodate the vertical scroll bar viewportHasVScroll = options.alwaysShowVerticalScroll || !options.autoHeight && (numberOfRows * options.rowHeight > tempViewportH); makeActiveCellNormal(); // remove the rows that are now outside of the data range // this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows var r1 = dataLength - 1; for (var i in rowsCache) { if (i > r1) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } if (activeCellNode && activeRow > r1) { resetActiveCell(); } var oldH = h; if (options.autoHeight) { h = options.rowHeight * numberOfRows; } else { th = Math.max(options.rowHeight * numberOfRows, tempViewportH - scrollbarDimensions.height); if (th < maxSupportedCssHeight) { // just one page h = ph = th; n = 1; cj = 0; } else { // break into pages h = maxSupportedCssHeight; ph = h / 100; n = Math.floor(th / ph); cj = (th - h) / (n - 1); } } if (h !== oldH) { if (hasFrozenRows && !options.frozenBottom) { $canvasBottomL.css("height", h); if (hasFrozenColumns()) { $canvasBottomR.css("height", h); } } else { $canvasTopL.css("height", h); $canvasTopR.css("height", h); } scrollTop = $viewportScrollContainerY[0].scrollTop; } var oldScrollTopInRange = (scrollTop + offset <= th - tempViewportH); if (th == 0 || scrollTop == 0) { page = offset = 0; } else if (oldScrollTopInRange) { // maintain virtual position scrollTo(scrollTop + offset); } else { // scroll to bottom scrollTo(th - tempViewportH); } if (h != oldH && options.autoHeight) { resizeCanvas(); } if (options.autosizeColsMode === Slick.GridAutosizeColsMode.LegacyForceFit && oldViewportHasVScroll != viewportHasVScroll) { autosizeColumns(); } updateCanvasWidth(false); } function getVisibleRange(viewportTop, viewportLeft) { if (viewportTop == null) { viewportTop = scrollTop; } if (viewportLeft == null) { viewportLeft = scrollLeft; } return { top: getRowFromPosition(viewportTop), bottom: getRowFromPosition(viewportTop + viewportH) + 1, leftPx: viewportLeft, rightPx: viewportLeft + viewportW }; } function getRenderedRange(viewportTop, viewportLeft) { var range = getVisibleRange(viewportTop, viewportLeft); var buffer = Math.round(viewportH / options.rowHeight); var minBuffer = options.minRowBuffer; if (vScrollDir == -1) { range.top -= buffer; range.bottom += minBuffer; } else if (vScrollDir == 1) { range.top -= minBuffer; range.bottom += buffer; } else { range.top -= minBuffer; range.bottom += minBuffer; } range.top = Math.max(0, range.top); range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom); range.leftPx -= viewportW; range.rightPx += viewportW; range.leftPx = Math.max(0, range.leftPx); range.rightPx = Math.min(canvasWidth, range.rightPx); return range; } function ensureCellNodesInRowsCache(row) { var cacheEntry = rowsCache[row]; if (cacheEntry) { if (cacheEntry.cellRenderQueue.length) { var $lastNode = cacheEntry.rowNode.children().last(); while (cacheEntry.cellRenderQueue.length) { var columnIdx = cacheEntry.cellRenderQueue.pop(); cacheEntry.cellNodesByColumnIdx[columnIdx] = $lastNode; $lastNode = $lastNode.prev(); // Hack to retrieve the frozen columns because if ($lastNode.length === 0) { $lastNode = $(cacheEntry.rowNode[0]).children().last(); } } } } } function cleanUpCells(range, row) { // Ignore frozen rows if (hasFrozenRows && ( ( options.frozenBottom && row > actualFrozenRow ) // Frozen bottom rows || ( row <= actualFrozenRow ) // Frozen top rows ) ) { return; } var totalCellsRemoved = 0; var cacheEntry = rowsCache[row]; // Remove cells outside the range. var cellsToRemove = []; for (var i in cacheEntry.cellNodesByColumnIdx) { // I really hate it when people mess with Array.prototype. if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) { continue; } // This is a string, so it needs to be cast back to a number. i = i | 0; // Ignore frozen columns if (i <= options.frozenColumn) { continue; } // Ignore alwaysRenderedColumns if (Array.isArray(columns) && columns[i] && columns[i].alwaysRenderColumn){ continue; } var colspan = cacheEntry.cellColSpans[i]; if (columnPosLeft[i] > range.rightPx || columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) { if (!(row == activeRow && i == activeCell)) { cellsToRemove.push(i); } } } var cellToRemove; while ((cellToRemove = cellsToRemove.pop()) != null) { cacheEntry.cellNodesByColumnIdx[cellToRemove][0].parentElement.removeChild(cacheEntry.cellNodesByColumnIdx[cellToRemove][0]); delete cacheEntry.cellColSpans[cellToRemove]; delete cacheEntry.cellNodesByColumnIdx[cellToRemove]; if (postProcessedRows[row]) { delete postProcessedRows[row][cellToRemove]; } totalCellsRemoved++; } } function cleanUpAndRenderCells(range) { var cacheEntry; var stringArray = []; var processedRows = []; var cellsAdded; var totalCellsAdded = 0; var colspan; for (var row = range.top, btm = range.bottom; row <= btm; row++) { cacheEntry = rowsCache[row]; if (!cacheEntry) { continue; } // cellRenderQueue populated in renderRows() needs to be cleared first ensureCellNodesInRowsCache(row); cleanUpCells(range, row); // Render missing cells. cellsAdded = 0; var metadata = data.getItemMetadata && data.getItemMetadata(row); metadata = metadata && metadata.columns; var d = getDataItem(row); // TODO: shorten this loop (index? heuristics? binary search?) for (var i = 0, ii = columns.length; i < ii; i++) { // Cells to the right are outside the range. if (columnPosLeft[i] > range.rightPx) { break; } // Already rendered. if ((colspan = cacheEntry.cellColSpans[i]) != null) { i += (colspan > 1 ? colspan - 1 : 0); continue; } colspan = 1; if (metadata) { var columnData = metadata[columns[i].id] || metadata[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { appendCellHtml(stringArray, row, i, colspan, d); cellsAdded++; } i += (colspan > 1 ? colspan - 1 : 0); } if (cellsAdded) { totalCellsAdded += cellsAdded; processedRows.push(row); } } if (!stringArray.length) { return; } var x = document.createElement("div"); x.innerHTML = stringArray.join(""); var processedRow; var node; while ((processedRow = processedRows.pop()) != null) { cacheEntry = rowsCache[processedRow]; var columnIdx; while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) { node = x.lastChild; if (hasFrozenColumns() && (columnIdx > options.frozenColumn)) { cacheEntry.rowNode[1].appendChild(node); } else { cacheEntry.rowNode[0].appendChild(node); } cacheEntry.cellNodesByColumnIdx[columnIdx] = $(node); } } } function renderRows(range) { var stringArrayL = [], stringArrayR = [], rows = [], needToReselectCell = false, dataLength = getDataLength(); for (var i = range.top, ii = range.bottom; i <= ii; i++) { if (rowsCache[i] || ( hasFrozenRows && options.frozenBottom && i == getDataLength() )) { continue; } renderedRows++; rows.push(i); // Create an entry right away so that appendRowHtml() can // start populatating it. rowsCache[i] = { "rowNode": null, // ColSpans of rendered cells (by column idx). // Can also be used for checking whether a cell has been rendered. "cellColSpans": [], // Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache(). "cellNodesByColumnIdx": [], // Column indices of cell nodes that have been rendered, but not yet indexed in // cellNodesByColumnIdx. These are in the same order as cell nodes added at the // end of the row. "cellRenderQueue": [] }; appendRowHtml(stringArrayL, stringArrayR, i, range, dataLength); if (activeCellNode && activeRow === i) { needToReselectCell = true; } counter_rows_rendered++; } if (!rows.length) { return; } var x = document.createElement("div"), xRight = document.createElement("div"); x.innerHTML = stringArrayL.join(""); xRight.innerHTML = stringArrayR.join(""); for (var i = 0, ii = rows.length; i < ii; i++) { if (( hasFrozenRows ) && ( rows[i] >= actualFrozenRow )) { if (hasFrozenColumns()) { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasBottomL)) .add($(xRight.firstChild).appendTo($canvasBottomR)); } else { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasBottomL)); } } else if (hasFrozenColumns()) { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasTopL)) .add($(xRight.firstChild).appendTo($canvasTopR)); } else { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasTopL)); } } if (needToReselectCell) { activeCellNode = getCellNode(activeRow, activeCell); } } function startPostProcessing() { if (!options.enableAsyncPostRender) { return; } clearTimeout(h_postrender); h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); } function startPostProcessingCleanup() { if (!options.enableAsyncPostRenderCleanup) { return; } clearTimeout(h_postrenderCleanup); h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } function invalidatePostProcessingResults(row) { // change status of columns to be re-rendered for (var columnIdx in postProcessedRows[row]) { if (postProcessedRows[row].hasOwnProperty(columnIdx)) { postProcessedRows[row][columnIdx] = 'C'; } } postProcessFromRow = Math.min(postProcessFromRow, row); postProcessToRow = Math.max(postProcessToRow, row); startPostProcessing(); } function updateRowPositions() { for (var row in rowsCache) { var rowNumber = row ? parseInt(row) : 0; rowsCache[rowNumber].rowNode[0].style.top = getRowTop(rowNumber) + "px"; } } function render() { if (!initialized) { return; } scrollThrottle.dequeue(); var visible = getVisibleRange(); var rendered = getRenderedRange(); // remove rows no longer in the viewport cleanupRows(rendered); // add new rows & missing cells in existing rows if (lastRenderedScrollLeft != scrollLeft) { if ( hasFrozenRows ) { var renderedFrozenRows = jQuery.extend(true, {}, rendered); if (options.frozenBottom) { renderedFrozenRows.top=actualFrozenRow; renderedFrozenRows.bottom=getDataLength(); } else { renderedFrozenRows.top=0; renderedFrozenRows.bottom=options.frozenRow; } cleanUpAndRenderCells(renderedFrozenRows); } cleanUpAndRenderCells(rendered); } // render missing rows renderRows(rendered); // Render frozen rows if (hasFrozenRows) { if (options.frozenBottom) { renderRows({ top: actualFrozenRow, bottom: getDataLength() - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx }); } else { renderRows({ top: 0, bottom: options.frozenRow - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx }); } } postProcessFromRow = visible.top; postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom); startPostProcessing(); lastRenderedScrollTop = scrollTop; lastRenderedScrollLeft = scrollLeft; h_render = null; trigger(self.onRendered, { startRow: visible.top, endRow: visible.bottom, grid: self }); } function handleHeaderScroll() { handleElementScroll($headerScrollContainer[0]); } function handleHeaderRowScroll() { var scrollLeft = $headerRowScrollContainer[0].scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handleFooterRowScroll() { var scrollLeft = $footerRowScrollContainer[0].scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handlePreHeaderPanelScroll() { handleElementScroll($preHeaderPanelScroller[0]); } function handleElementScroll(element) { var scrollLeft = element.scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handleScroll() { scrollTop = $viewportScrollContainerY[0].scrollTop; scrollLeft = $viewportScrollContainerX[0].scrollLeft; return _handleScroll(false); } function _handleScroll(isMouseWheel) { var maxScrollDistanceY = $viewportScrollContainerY[0].scrollHeight - $viewportScrollContainerY[0].clientHeight; var maxScrollDistanceX = $viewportScrollContainerY[0].scrollWidth - $viewportScrollContainerY[0].clientWidth; // Protect against erroneous clientHeight/Width greater than scrollHeight/Width. // Sometimes seen in Chrome. maxScrollDistanceY = Math.max(0, maxScrollDistanceY); maxScrollDistanceX = Math.max(0, maxScrollDistanceX); // Ceiling the max scroll values if (scrollTop > maxScrollDistanceY) { scrollTop = maxScrollDistanceY; } if (scrollLeft > maxScrollDistanceX) { scrollLeft = maxScrollDistanceX; } var vScrollDist = Math.abs(scrollTop - prevScrollTop); var hScrollDist = Math.abs(scrollLeft - prevScrollLeft); if (hScrollDist) { prevScrollLeft = scrollLeft; $viewportScrollContainerX[0].scrollLeft = scrollLeft; $headerScrollContainer[0].scrollLeft = scrollLeft; $topPanelScroller[0].scrollLeft = scrollLeft; $headerRowScrollContainer[0].scrollLeft = scrollLeft; if (options.createFooterRow) { $footerRowScrollContainer[0].scrollLeft = scrollLeft; } if (options.createPreHeaderPanel) { if (hasFrozenColumns()) { $preHeaderPanelScrollerR[0].scrollLeft = scrollLeft; } else { $preHeaderPanelScroller[0].scrollLeft = scrollLeft; } } if (hasFrozenColumns()) { if (hasFrozenRows) { $viewportTopR[0].scrollLeft = scrollLeft; } } else { if (hasFrozenRows) { $viewportTopL[0].scrollLeft = scrollLeft; } } } if (vScrollDist) { vScrollDir = prevScrollTop < scrollTop ? 1 : -1; prevScrollTop = scrollTop; if (isMouseWheel) { $viewportScrollContainerY[0].scrollTop = scrollTop; } if (hasFrozenColumns()) { if (hasFrozenRows && !options.frozenBottom) { $viewportBottomL[0].scrollTop = scrollTop; } else { $viewportTopL[0].scrollTop = scrollTop; } } // switch virtual pages if needed if (vScrollDist < viewportH) { scrollTo(scrollTop + offset); } else { var oldOffset = offset; if (h == viewportH) { page = 0; } else { page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph))); } offset = Math.round(page * cj); if (oldOffset != offset) { invalidateAllRows(); } } } if (hScrollDist || vScrollDist) { var dx = Math.abs(lastRenderedScrollLeft - scrollLeft); var dy = Math.abs(lastRenderedScrollTop - scrollTop); if (dx > 20 || dy > 20) { // if rendering is forced or scrolling is small enough to be "easy", just render if (options.forceSyncScrolling || (dy < viewportH && dx < viewportW)) { render(); } else { // otherwise, perform "difficult" renders at a capped frequency scrollThrottle.enqueue(); } trigger(self.onViewportChanged, {}); } } trigger(self.onScroll, {scrollLeft: scrollLeft, scrollTop: scrollTop}); if (hScrollDist || vScrollDist) return true; return false; } /* limits the frequency at which the provided action is executed. call enqueue to execute the action - it will execute either immediately or, if it was executed less than minPeriod_ms in the past, as soon as minPeriod_ms has expired. call dequeue to cancel any pending action. */ function ActionThrottle(action, minPeriod_ms) { var blocked = false; var queued = false; function enqueue() { if (!blocked) { blockAndExecute(); } else { queued = true; } } function dequeue() { queued = false; } function blockAndExecute() { blocked = true; setTimeout(unblock, minPeriod_ms); action(); } function unblock() { if (queued) { dequeue(); blockAndExecute(); } else { blocked = false; } } return { enqueue: enqueue, dequeue: dequeue }; } function asyncPostProcessRows() { var dataLength = getDataLength(); while (postProcessFromRow <= postProcessToRow) { var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--; var cacheEntry = rowsCache[row]; if (!cacheEntry || row >= dataLength) { continue; } if (!postProcessedRows[row]) { postProcessedRows[row] = {}; } ensureCellNodesInRowsCache(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx]; var processedStatus = postProcessedRows[row][columnIdx]; // C=cleanup and re-render, R=rendered if (m.asyncPostRender && processedStatus !== 'R') { var node = cacheEntry.cellNodesByColumnIdx[columnIdx]; if (node) { m.asyncPostRender(node, row, getDataItem(row), m, (processedStatus === 'C')); } postProcessedRows[row][columnIdx] = 'R'; } } h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); return; } } function asyncPostProcessCleanupRows() { if (postProcessedCleanupQueue.length > 0) { var groupId = postProcessedCleanupQueue[0].groupId; // loop through all queue members with this groupID while (postProcessedCleanupQueue.length > 0 && postProcessedCleanupQueue[0].groupId == groupId) { var entry = postProcessedCleanupQueue.shift(); if (entry.actionType == 'R') { $(entry.node).remove(); } if (entry.actionType == 'C') { var column = columns[entry.columnIdx]; if (column.asyncPostRenderCleanup && entry.node) { // cleanup must also remove element column.asyncPostRenderCleanup(entry.node, entry.rowIdx, column); } } } // call this function again after the specified delay h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } } function updateCellCssStylesOnRenderedRows(addedHash, removedHash) { var node, columnId, addedRowHash, removedRowHash; for (var row in rowsCache) { removedRowHash = removedHash && removedHash[row]; addedRowHash = addedHash && addedHash[row]; if (removedRowHash) { for (columnId in removedRowHash) { if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).removeClass(removedRowHash[columnId]); } } } } if (addedRowHash) { for (columnId in addedRowHash) { if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).addClass(addedRowHash[columnId]); } } } } } } function addCellCssStyles(key, hash) { if (cellCssClasses[key]) { throw new Error("addCellCssStyles: cell CSS hash with key '" + key + "' already exists."); } cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, null); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function removeCellCssStyles(key) { if (!cellCssClasses[key]) { return; } updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]); delete cellCssClasses[key]; trigger(self.onCellCssStylesChanged, { "key": key, "hash": null, "grid": self }); } function setCellCssStyles(key, hash) { var prevHash = cellCssClasses[key]; cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, prevHash); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function getCellCssStyles(key) { return cellCssClasses[key]; } function flashCell(row, cell, speed) { speed = speed || 100; function toggleCellClass($cell, times) { if (!times) { return; } setTimeout(function () { $cell.queue(function () { $cell.toggleClass(options.cellFlashingCssClass).dequeue(); toggleCellClass($cell, times - 1); }); }, speed); } if (rowsCache[row]) { var $cell = $(getCellNode(row, cell)); toggleCellClass($cell, 4); } } ////////////////////////////////////////////////////////////////////////////////////////////// // Interactivity function handleMouseWheel(e, delta, deltaX, deltaY) { var $rowNode = $(e.target).closest(".slick-row"); var rowNode = $rowNode[0]; if (rowNode != rowNodeFromLastMouseWheelEvent) { var $gridCanvas = $rowNode.parents('.grid-canvas'); var left = $gridCanvas.hasClass('grid-canvas-left'); if (zombieRowNodeFromLastMouseWheelEvent && zombieRowNodeFromLastMouseWheelEvent[left? 0:1] != rowNode) { var zombieRow = zombieRowNodeFromLastMouseWheelEvent[left || zombieRowNodeFromLastMouseWheelEvent.length == 1? 0:1]; zombieRow.parentElement.removeChild(zombieRow); zombieRowNodeFromLastMouseWheelEvent = null; } rowNodeFromLastMouseWheelEvent = rowNode; } scrollTop = Math.max(0, $viewportScrollContainerY[0].scrollTop - (deltaY * options.rowHeight)); scrollLeft = $viewportScrollContainerX[0].scrollLeft + (deltaX * 10); var handled = _handleScroll(true); if (handled) e.preventDefault(); } function handleDragInit(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragInit, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } // if nobody claims to be handling drag'n'drop by stopping immediate propagation, // cancel out of it return false; } function handleDragStart(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragStart, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } return false; } function handleDrag(e, dd) { return trigger(self.onDrag, dd, e); } function handleDragEnd(e, dd) { trigger(self.onDragEnd, dd, e); } function handleKeyDown(e) { trigger(self.onKeyDown, {row: activeRow, cell: activeCell}, e); var handled = e.isImmediatePropagationStopped(); var keyCode = Slick.keyCode; if (!handled) { if (!e.shiftKey && !e.altKey) { if (options.editable && currentEditor && currentEditor.keyCaptureList) { if (currentEditor.keyCaptureList.indexOf(e.which) > -1) { return; } } if (e.which == keyCode.HOME) { handled = (e.ctrlKey) ? navigateTop() : navigateRowStart(); } else if (e.which == keyCode.END) { handled = (e.ctrlKey) ? navigateBottom() : navigateRowEnd(); } } } if (!handled) { if (!e.shiftKey && !e.altKey && !e.ctrlKey) { // editor may specify an array of keys to bubble if (options.editable && currentEditor && currentEditor.keyCaptureList) { if (currentEditor.keyCaptureList.indexOf( e.which ) > -1) { return; } } if (e.which == keyCode.ESCAPE) { if (!getEditorLock().isActive()) { return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event) } cancelEditAndSetFocus(); } else if (e.which == keyCode.PAGE_DOWN) { navigatePageDown(); handled = true; } else if (e.which == keyCode.PAGE_UP) { navigatePageUp(); handled = true; } else if (e.which == keyCode.LEFT) { handled = navigateLeft(); } else if (e.which == keyCode.RIGHT) { handled = navigateRight(); } else if (e.which == keyCode.UP) { handled = navigateUp(); } else if (e.which == keyCode.DOWN) { handled = navigateDown(); } else if (e.which == keyCode.TAB) { handled = navigateNext(); } else if (e.which == keyCode.ENTER) { if (options.editable) { if (currentEditor) { // adding new row if (activeRow === getDataLength()) { navigateDown(); } else { commitEditAndSetFocus(); } } else { if (getEditorLock().commitCurrentEdit()) { makeActiveCellEditable(undefined, undefined, e); } } } handled = true; } } else if (e.which == keyCode.TAB && e.shiftKey && !e.ctrlKey && !e.altKey) { handled = navigatePrev(); } } if (handled) { // the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it e.stopPropagation(); e.preventDefault(); try { e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.) } // ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl" // (hitting control key only, nothing else), "Shift" (maybe others) catch (error) { } } } function handleClick(e) { if (!currentEditor) { // if this click resulted in some cell child node getting focus, // don't steal it back - keyboard events will still bubble up // IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly. if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) { setFocus(); } } var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onClick, {row: cell.row, cell: cell.cell}, e); if (e.isImmediatePropagationStopped()) { return; } // this optimisation causes trouble - MLeibman #329 //if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) { if (canCellBeActive(cell.row, cell.cell)) { if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) { scrollRowIntoView(cell.row, false); var preClickModeOn = (e.target && e.target.className === Slick.preClickClassName); var column = columns[cell.cell]; var suppressActiveCellChangedEvent = !!(options.editable && column && column.editor && options.suppressActiveCellChangeOnEdit); setActiveCellInternal(getCellNode(cell.row, cell.cell), null, preClickModeOn, suppressActiveCellChangedEvent, e); } } } function handleContextMenu(e) { var $cell = $(e.target).closest(".slick-cell", $canvas); if ($cell.length === 0) { return; } // are we editing this cell? if (activeCellNode === $cell[0] && currentEditor !== null) { return; } trigger(self.onContextMenu, {}, e); } function handleDblClick(e) { var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onDblClick, {row: cell.row, cell: cell.cell}, e); if (e.isImmediatePropagationStopped()) { return; } if (options.editable) { gotoCell(cell.row, cell.cell, true, e); } } function handleHeaderMouseEnter(e) { trigger(self.onHeaderMouseEnter, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderMouseLeave(e) { trigger(self.onHeaderMouseLeave, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderContextMenu(e) { var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); trigger(self.onHeaderContextMenu, {column: column}, e); } function handleHeaderClick(e) { if (columnResizeDragging) return; var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); if (column) { trigger(self.onHeaderClick, {column: column}, e); } } function handleFooterContextMenu(e) { var $footer = $(e.target).closest(".slick-footerrow-column", ".slick-footerrow-columns"); var column = $footer && $footer.data("column"); trigger(self.onFooterContextMenu, {column: column}, e); } function handleFooterClick(e) { var $footer = $(e.target).closest(".slick-footerrow-column", ".slick-footerrow-columns"); var column = $footer && $footer.data("column"); trigger(self.onFooterClick, {column: column}, e); } function handleMouseEnter(e) { trigger(self.onMouseEnter, {}, e); } function handleMouseLeave(e) { trigger(self.onMouseLeave, {}, e); } function cellExists(row, cell) { return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length); } function getCellFromPoint(x, y) { var row = getRowFromPosition(y); var cell = 0; var w = 0; for (var i = 0; i < columns.length && w < x; i++) { w += columns[i].width; cell++; } if (cell < 0) { cell = 0; } return {row: row, cell: cell - 1}; } function getCellFromNode(cellNode) { // read column number from .l<columnNumber> CSS class var cls = /l\d+/.exec(cellNode.className); if (!cls) { throw new Error("getCellFromNode: cannot get cell - " + cellNode.className); } return parseInt(cls[0].substr(1, cls[0].length - 1), 10); } function getRowFromNode(rowNode) { for (var row in rowsCache) { for (var i in rowsCache[row].rowNode) { if (rowsCache[row].rowNode[i] === rowNode) return (row ? parseInt(row) : 0); } } return null; } function getFrozenRowOffset(row) { var offset = ( hasFrozenRows ) ? ( options.frozenBottom ) ? ( row >= actualFrozenRow ) ? ( h < viewportTopH ) ? ( actualFrozenRow * options.rowHeight ) : h : 0 : ( row >= actualFrozenRow ) ? frozenRowsHeight : 0 : 0; return offset; } function getCellFromEvent(e) { var row, cell; var $cell = $(e.target).closest(".slick-cell", $canvas); if (!$cell.length) { return null; } row = getRowFromNode($cell[0].parentNode); if (hasFrozenRows) { var c = $cell.parents('.grid-canvas').offset(); var rowOffset = 0; var isBottom = $cell.parents('.grid-canvas-bottom').length; if (isBottom) { rowOffset = ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight; } row = getCellFromPoint(e.clientX - c.left, e.clientY - c.top + rowOffset + $(document).scrollTop()).row; } cell = getCellFromNode($cell[0]); if (row == null || cell == null) { return null; } else { return { "row": row, "cell": cell }; } } function getCellNodeBox(row, cell) { if (!cellExists(row, cell)) { return null; } var frozenRowOffset = getFrozenRowOffset(row); var y1 = getRowTop(row) - frozenRowOffset; var y2 = y1 + options.rowHeight - 1; var x1 = 0; for (var i = 0; i < cell; i++) { x1 += columns[i].width; if (options.frozenColumn == i) { x1 = 0; } } var x2 = x1 + columns[cell].width; return { top: y1, left: x1, bottom: y2, right: x2 }; } ////////////////////////////////////////////////////////////////////////////////////////////// // Cell switching function resetActiveCell() { setActiveCellInternal(null, false); } function setFocus() { if (tabbingDirection == -1) { $focusSink[0].focus(); } else { $focusSink2[0].focus(); } } function scrollCellIntoView(row, cell, doPaging) { scrollRowIntoView(row, doPaging); if (cell <= options.frozenColumn) { return; } var colspan = getColspan(row, cell); internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)]); } function internalScrollColumnIntoView(left, right) { var scrollRight = scrollLeft + $viewportScrollContainerX.width(); if (left < scrollLeft) { $viewportScrollContainerX.scrollLeft(left); handleScroll(); render(); } else if (right > scrollRight) { $viewportScrollContainerX.scrollLeft(Math.min(left, right - $viewportScrollContainerX[0].clientWidth)); handleScroll(); render(); } } function scrollColumnIntoView(cell) { internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell]); } function setActiveCellInternal(newCell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent, e) { if (activeCellNode !== null) { makeActiveCellNormal(); $(activeCellNode).removeClass("active"); if (rowsCache[activeRow]) { $(rowsCache[activeRow].rowNode).removeClass("active"); } } var activeCellChanged = (activeCellNode !== newCell); activeCellNode = newCell; if (activeCellNode != null) { var $activeCellNode = $(activeCellNode); var $activeCellOffset = $activeCellNode.offset(); var rowOffset = Math.floor($activeCellNode.parents('.grid-canvas').offset().top); var isBottom = $activeCellNode.parents('.grid-canvas-bottom').length; if (hasFrozenRows && isBottom) { rowOffset -= ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight; } var cell = getCellFromPoint($activeCellOffset.left, Math.ceil($activeCellOffset.top) - rowOffset); activeRow = cell.row; activeCell = activePosX = activeCell = activePosX = getCellFromNode(activeCellNode); if (opt_editMode == null) { opt_editMode = (activeRow == getDataLength()) || options.autoEdit; } if (options.showCellSelection) { $activeCellNode.addClass("active"); if (rowsCache[activeRow]) { $(rowsCache[activeRow].rowNode).addClass("active"); } } if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) { clearTimeout(h_editorLoader); if (options.asyncEditorLoading) { h_editorLoader = setTimeout(function () { makeActiveCellEditable(undefined, preClickModeOn, e); }, options.asyncEditorLoadDelay); } else { makeActiveCellEditable(undefined, preClickModeOn, e); } } } else { activeRow = activeCell = null; } // this optimisation causes trouble - MLeibman #329 //if (activeCellChanged) { if (!suppressActiveCellChangedEvent) { trigger(self.onActiveCellChanged, getActiveCell()); } //} } function clearTextSelection() { if (document.selection && document.selection.empty) { try { //IE fails here if selected element is not in dom document.selection.empty(); } catch (e) { } } else if (window.getSelection) { var sel = window.getSelection(); if (sel && sel.removeAllRanges) { sel.removeAllRanges(); } } } function isCellPotentiallyEditable(row, cell) { var dataLength = getDataLength(); // is the data for this row loaded? if (row < dataLength && !getDataItem(row)) { return false; } // are we in the Add New row? can we create new from this cell? if (columns[cell].cannotTriggerInsert && row >= dataLength) { return false; } // does this cell have an editor? if (!getEditor(row, cell)) { return false; } return true; } function makeActiveCellNormal() { if (!currentEditor) { return; } trigger(self.onBeforeCellEditorDestroy, {editor: currentEditor}); currentEditor.destroy(); currentEditor = null; if (activeCellNode) { var d = getDataItem(activeRow); $(activeCellNode).removeClass("editable invalid"); if (d) { var column = columns[activeCell]; var formatter = getFormatter(activeRow, column); var formatterResult = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d, self); applyFormatResultToCellNode(formatterResult, activeCellNode); invalidatePostProcessingResults(activeRow); } } // if there previously was text selected on a page (such as selected text in the edit cell just removed), // IE can't set focus to anything else correctly if (navigator.userAgent.toLowerCase().match(/msie/)) { clearTextSelection(); } getEditorLock().deactivate(editController); } function makeActiveCellEditable(editor, preClickModeOn, e) { if (!activeCellNode) { return; } if (!options.editable) { throw new Error("Grid : makeActiveCellEditable : should never get called when options.editable is false"); } // cancel pending async call if there is one clearTimeout(h_editorLoader); if (!isCellPotentiallyEditable(activeRow, activeCell)) { return; } var columnDef = columns[activeCell]; var item = getDataItem(activeRow); if (trigger(self.onBeforeEditCell, {row: activeRow, cell: activeCell, item: item, column: columnDef}) === false) { setFocus(); return; } getEditorLock().activate(editController); $(activeCellNode).addClass("editable"); var useEditor = editor || getEditor(activeRow, activeCell); // don't clear the cell if a custom editor is passed through if (!editor && !useEditor.suppressClearOnEdit) { activeCellNode.innerHTML = ""; } var metadata = data.getItemMetadata && data.getItemMetadata(activeRow); metadata = metadata && metadata.columns; var columnMetaData = metadata && ( metadata[columnDef.id] || metadata[activeCell] ); currentEditor = new useEditor({ grid: self, gridPosition: absBox($container[0]), position: absBox(activeCellNode), container: activeCellNode, column: columnDef, columnMetaData: columnMetaData, item: item || {}, event: e, commitChanges: commitEditAndSetFocus, cancelChanges: cancelEditAndSetFocus }); if (item) { currentEditor.loadValue(item); if (preClickModeOn && currentEditor.preClick) { currentEditor.preClick(); } } serializedEditorValue = currentEditor.serializeValue(); if (currentEditor.position) { handleActiveCellPositionChange(); } } function commitEditAndSetFocus() { // if the commit fails, it would do so due to a validation error // if so, do not steal the focus from the editor if (getEditorLock().commitCurrentEdit()) { setFocus(); if (options.autoEdit) { navigateDown(); } } } function cancelEditAndSetFocus() { if (getEditorLock().cancelCurrentEdit()) { setFocus(); } } function absBox(elem) { var box = { top: elem.offsetTop, left: elem.offsetLeft, bottom: 0, right: 0, width: $(elem).outerWidth(), height: $(elem).outerHeight(), visible: true }; box.bottom = box.top + box.height; box.right = box.left + box.width; // walk up the tree var offsetParent = elem.offsetParent; while ((elem = elem.parentNode) != document.body) { if (elem == null) break; if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") { box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight; } if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") { box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth; } box.left -= elem.scrollLeft; box.top -= elem.scrollTop; if (elem === offsetParent) { box.left += elem.offsetLeft; box.top += elem.offsetTop; offsetParent = elem.offsetParent; } box.bottom = box.top + box.height; box.right = box.left + box.width; } return box; } function getActiveCellPosition() { return absBox(activeCellNode); } function getGridPosition() { return absBox($container[0]); } function handleActiveCellPositionChange() { if (!activeCellNode) { return; } trigger(self.onActiveCellPositionChanged, {}); if (currentEditor) { var cellBox = getActiveCellPosition(); if (currentEditor.show && currentEditor.hide) { if (!cellBox.visible) { currentEditor.hide(); } else { currentEditor.show(); } } if (currentEditor.position) { currentEditor.position(cellBox); } } } function getCellEditor() { return currentEditor; } function getActiveCell() { if (!activeCellNode) { return null; } else { return {row: activeRow, cell: activeCell}; } } function getActiveCellNode() { return activeCellNode; } function scrollRowIntoView(row, doPaging) { if (!hasFrozenRows || ( !options.frozenBottom && row > actualFrozenRow - 1 ) || ( options.frozenBottom && row < actualFrozenRow - 1 ) ) { var viewportScrollH = $viewportScrollContainerY.height(); // if frozen row on top // subtract number of frozen row var rowNumber = ( hasFrozenRows && !options.frozenBottom ? row - options.frozenRow : row ); var rowAtTop = rowNumber * options.rowHeight; var rowAtBottom = (rowNumber + 1) * options.rowHeight - viewportScrollH + (viewportHasHScroll ? scrollbarDimensions.height : 0); // need to page down? if ((rowNumber + 1) * options.rowHeight > scrollTop + viewportScrollH + offset) { scrollTo(doPaging ? rowAtTop : rowAtBottom); render(); } // or page up? else if (rowNumber * options.rowHeight < scrollTop + offset) { scrollTo(doPaging ? rowAtBottom : rowAtTop); render(); } } } function scrollRowToTop(row) { scrollTo(row * options.rowHeight); render(); } function scrollPage(dir) { var deltaRows = dir * numVisibleRows; /// First fully visible row crosses the line with /// y == bottomOfTopmostFullyVisibleRow var bottomOfTopmostFullyVisibleRow = scrollTop + options.rowHeight - 1; scrollTo((getRowFromPosition(bottomOfTopmostFullyVisibleRow) + deltaRows) * options.rowHeight); render(); if (options.enableCellNavigation && activeRow != null) { var row = activeRow + deltaRows; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); if (row >= dataLengthIncludingAddNew) { row = dataLengthIncludingAddNew - 1; } if (row < 0) { row = 0; } var cell = 0, prevCell = null; var prevActivePosX = activePosX; while (cell <= activePosX) { if (canCellBeActive(row, cell)) { prevCell = cell; } cell += getColspan(row, cell); } if (prevCell !== null) { setActiveCellInternal(getCellNode(row, prevCell)); activePosX = prevActivePosX; } else { resetActiveCell(); } } } function navigatePageDown() { scrollPage(1); } function navigatePageUp() { scrollPage(-1); } function navigateTop() { navigateToRow(0); } function navigateBottom() { navigateToRow(getDataLength()-1); } function navigateToRow(row) { var num_rows = getDataLength(); if (!num_rows) return true; if (row < 0) row = 0; else if (row >= num_rows) row = num_rows - 1; scrollCellIntoView(row, 0, true); if (options.enableCellNavigation && activeRow != null) { var cell = 0, prevCell = null; var prevActivePosX = activePosX; while (cell <= activePosX) { if (canCellBeActive(row, cell)) { prevCell = cell; } cell += getColspan(row, cell); } if (prevCell !== null) { setActiveCellInternal(getCellNode(row, prevCell)); activePosX = prevActivePosX; } else { resetActiveCell(); } } return true; } function getColspan(row, cell) { var metadata = data.getItemMetadata && data.getItemMetadata(row); if (!metadata || !metadata.columns) { return 1; } var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell]; var colspan = (columnData && columnData.colspan); if (colspan === "*") { colspan = columns.length - cell; } else { colspan = colspan || 1; } return colspan; } function findFirstFocusableCell(row) { var cell = 0; while (cell < columns.length) { if (canCellBeActive(row, cell)) { return cell; } cell += getColspan(row, cell); } return null; } function findLastFocusableCell(row) { var cell = 0; var lastFocusableCell = null; while (cell < columns.length) { if (canCellBeActive(row, cell)) { lastFocusableCell = cell; } cell += getColspan(row, cell); } return lastFocusableCell; } function gotoRight(row, cell, posX) { if (cell >= columns.length) { return null; } do { cell += getColspan(row, cell); } while (cell < columns.length && !canCellBeActive(row, cell)); if (cell < columns.length) { return { "row": row, "cell": cell, "posX": cell }; } return null; } function gotoLeft(row, cell, posX) { if (cell <= 0) { return null; } var firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell === null || firstFocusableCell >= cell) { return null; } var prev = { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; var pos; while (true) { pos = gotoRight(prev.row, prev.cell, prev.posX); if (!pos) { return null; } if (pos.cell >= cell) { return prev; } prev = pos; } } function gotoDown(row, cell, posX) { var prevCell; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); while (true) { if (++row >= dataLengthIncludingAddNew) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoUp(row, cell, posX) { var prevCell; while (true) { if (--row < 0) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoNext(row, cell, posX) { if (row == null && cell == null) { row = cell = posX = 0; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos = gotoRight(row, cell, posX); if (pos) { return pos; } var firstFocusableCell = null; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); // if at last row, cycle through columns rather than get stuck in the last one if (row === dataLengthIncludingAddNew - 1) { row--; } while (++row < dataLengthIncludingAddNew) { firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell !== null) { return { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; } } return null; } function gotoPrev(row, cell, posX) { if (row == null && cell == null) { row = getDataLengthIncludingAddNew() - 1; cell = posX = columns.length - 1; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos; var lastSelectableCell; while (!pos) { pos = gotoLeft(row, cell, posX); if (pos) { break; } if (--row < 0) { return null; } cell = 0; lastSelectableCell = findLastFocusableCell(row); if (lastSelectableCell !== null) { pos = { "row": row, "cell": lastSelectableCell, "posX": lastSelectableCell }; } } return pos; } function gotoRowStart(row, cell, posX) { var newCell = findFirstFocusableCell(row); if (newCell === null) return null; return { "row": row, "cell": newCell, "posX": newCell }; } function gotoRowEnd(row, cell, posX) { var newCell = findLastFocusableCell(row); if (newCell === null) return null; return { "row": row, "cell": newCell, "posX": newCell }; } function navigateRight() { return navigate("right"); } function navigateLeft() { return navigate("left"); } function navigateDown() { return navigate("down"); } function navigateUp() { return navigate("up"); } function navigateNext() { return navigate("next"); } function navigatePrev() { return navigate("prev"); } function navigateRowStart() { return navigate("home"); } function navigateRowEnd() { return navigate("end"); } /** * @param {string} dir Navigation direction. * @return {boolean} Whether navigation resulted in a change of active cell. */ function navigate(dir) { if (!options.enableCellNavigation) { return false; } if (!activeCellNode && dir != "prev" && dir != "next") { return false; } if (!getEditorLock().commitCurrentEdit()) { return true; } setFocus(); var tabbingDirections = { "up": -1, "down": 1, "left": -1, "right": 1, "prev": -1, "next": 1, "home": -1, "end": 1 }; tabbingDirection = tabbingDirections[dir]; var stepFunctions = { "up": gotoUp, "down": gotoDown, "left": gotoLeft, "right": gotoRight, "prev": gotoPrev, "next": gotoNext, "home": gotoRowStart, "end": gotoRowEnd }; var stepFn = stepFunctions[dir]; var pos = stepFn(activeRow, activeCell, activePosX); if (pos) { if (hasFrozenRows && options.frozenBottom & pos.row == getDataLength()) { return; } var isAddNewRow = (pos.row == getDataLength()); if (( !options.frozenBottom && pos.row >= actualFrozenRow ) || ( options.frozenBottom && pos.row < actualFrozenRow ) ) { scrollCellIntoView(pos.row, pos.cell, !isAddNewRow && options.emulatePagingWhenScrolling); } setActiveCellInternal(getCellNode(pos.row, pos.cell)); activePosX = pos.posX; return true; } else { setActiveCellInternal(getCellNode(activeRow, activeCell)); return false; } } function getCellNode(row, cell) { if (rowsCache[row]) { ensureCellNodesInRowsCache(row); try { if (rowsCache[row].cellNodesByColumnIdx.length > cell) { return rowsCache[row].cellNodesByColumnIdx[cell][0]; } else { return null; } } catch (e) { return rowsCache[row].cellNodesByColumnIdx[cell]; } } return null; } function setActiveCell(row, cell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent) { if (!initialized) { return; } if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return; } if (!options.enableCellNavigation) { return; } scrollCellIntoView(row, cell, false); setActiveCellInternal(getCellNode(row, cell), opt_editMode, preClickModeOn, suppressActiveCellChangedEvent); } function setActiveRow(row, cell, suppressScrollIntoView) { if (!initialized) { return; } if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return; } activeRow = row; if (!suppressScrollIntoView) { scrollCellIntoView(row, cell || 0, false); } } function canCellBeActive(row, cell) { if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.focusable !== "undefined") { return !!rowMetadata.focusable; } var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable !== "undefined") { return !!columnMetadata[columns[cell].id].focusable; } if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable !== "undefined") { return !!columnMetadata[cell].focusable; } return !!columns[cell].focusable; } function canCellBeSelected(row, cell) { if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.selectable !== "undefined") { return !!rowMetadata.selectable; } var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]); if (columnMetadata && typeof columnMetadata.selectable !== "undefined") { return !!columnMetadata.selectable; } return !!columns[cell].selectable; } function gotoCell(row, cell, forceEdit, e) { if (!initialized) { return; } if (!canCellBeActive(row, cell)) { return; } if (!getEditorLock().commitCurrentEdit()) { return; } scrollCellIntoView(row, cell, false); var newCell = getCellNode(row, cell); // if selecting the 'add new' row, start editing right away var column = columns[cell]; var suppressActiveCellChangedEvent = !!(options.editable && column && column.editor && options.suppressActiveCellChangeOnEdit); setActiveCellInternal(newCell, (forceEdit || (row === getDataLength()) || options.autoEdit), null, suppressActiveCellChangedEvent, e); // if no editor was created, set the focus back on the grid if (!currentEditor) { setFocus(); } } ////////////////////////////////////////////////////////////////////////////////////////////// // IEditor implementation for the editor lock function commitCurrentEdit() { var item = getDataItem(activeRow); var column = columns[activeCell]; if (currentEditor) { if (currentEditor.isValueChanged()) { var validationResults = currentEditor.validate(); if (validationResults.valid) { if (activeRow < getDataLength()) { var editCommand = { row: activeRow, cell: activeCell, editor: currentEditor, serializedValue: currentEditor.serializeValue(), prevSerializedValue: serializedEditorValue, execute: function () { this.editor.applyValue(item, this.serializedValue); updateRow(this.row); trigger(self.onCellChange, { row: this.row, cell: this.cell, item: item, column: column }); }, undo: function () { this.editor.applyValue(item, this.prevSerializedValue); updateRow(this.row); trigger(self.onCellChange, { row: this.row, cell: this.cell, item: item, column: column }); } }; if (options.editCommandHandler) { makeActiveCellNormal(); options.editCommandHandler(item, column, editCommand); } else { editCommand.execute(); makeActiveCellNormal(); } } else { var newItem = {}; currentEditor.applyValue(newItem, currentEditor.serializeValue()); makeActiveCellNormal(); trigger(self.onAddNewRow, {item: newItem, column: column}); } // check whether the lock has been re-acquired by event handlers return !getEditorLock().isActive(); } else { // Re-add the CSS class to trigger transitions, if any. $(activeCellNode).removeClass("invalid"); $(activeCellNode).width(); // force layout $(activeCellNode).addClass("invalid"); trigger(self.onValidationError, { editor: currentEditor, cellNode: activeCellNode, validationResults: validationResults, row: activeRow, cell: activeCell, column: column }); currentEditor.focus(); return false; } } makeActiveCellNormal(); } return true; } function cancelCurrentEdit() { makeActiveCellNormal(); return true; } function rowsToRanges(rows) { var ranges = []; var lastCell = columns.length - 1; for (var i = 0; i < rows.length; i++) { ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell)); } return ranges; } function getSelectedRows() { if (!selectionModel) { throw new Error("Selection model is not set"); } return selectedRows.slice(0); } function setSelectedRows(rows) { if (!selectionModel) { throw new Error("Selection model is not set"); } if (self && self.getEditorLock && !self.getEditorLock().isActive()) { selectionModel.setSelectedRanges(rowsToRanges(rows)); } } ////////////////////////////////////////////////////////////////////////////////////////////// // Debug this.debug = function () { var s = ""; s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered); s += ("\n" + "counter_rows_removed: " + counter_rows_removed); s += ("\n" + "renderedRows: " + renderedRows); s += ("\n" + "numVisibleRows: " + numVisibleRows); s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight); s += ("\n" + "n(umber of pages): " + n); s += ("\n" + "(current) page: " + page); s += ("\n" + "page height (ph): " + ph); s += ("\n" + "vScrollDir: " + vScrollDir); alert(s); }; // a debug helper to be able to access private members this.eval = function (expr) { return eval(expr); }; ////////////////////////////////////////////////////////////////////////////////////////////// // Public API $.extend(this, { "slickGridVersion": "2.4.33", // Events "onScroll": new Slick.Event(), "onSort": new Slick.Event(), "onHeaderMouseEnter": new Slick.Event(), "onHeaderMouseLeave": new Slick.Event(), "onHeaderContextMenu": new Slick.Event(), "onHeaderClick": new Slick.Event(), "onHeaderCellRendered": new Slick.Event(), "onBeforeHeaderCellDestroy": new Slick.Event(), "onHeaderRowCellRendered": new Slick.Event(), "onFooterRowCellRendered": new Slick.Event(), "onFooterContextMenu": new Slick.Event(), "onFooterClick": new Slick.Event(), "onBeforeHeaderRowCellDestroy": new Slick.Event(), "onBeforeFooterRowCellDestroy": new Slick.Event(), "onMouseEnter": new Slick.Event(), "onMouseLeave": new Slick.Event(), "onClick": new Slick.Event(), "onDblClick": new Slick.Event(), "onContextMenu": new Slick.Event(), "onKeyDown": new Slick.Event(), "onAddNewRow": new Slick.Event(), "onBeforeAppendCell": new Slick.Event(), "onValidationError": new Slick.Event(), "onViewportChanged": new Slick.Event(), "onColumnsReordered": new Slick.Event(), "onColumnsDrag": new Slick.Event(), "onColumnsResized": new Slick.Event(), "onBeforeColumnsResize": new Slick.Event(), "onCellChange": new Slick.Event(), "onCompositeEditorChange": new Slick.Event(), "onBeforeEditCell": new Slick.Event(), "onBeforeCellEditorDestroy": new Slick.Event(), "onBeforeDestroy": new Slick.Event(), "onActiveCellChanged": new Slick.Event(), "onActiveCellPositionChanged": new Slick.Event(), "onDragInit": new Slick.Event(), "onDragStart": new Slick.Event(), "onDrag": new Slick.Event(), "onDragEnd": new Slick.Event(), "onSelectedRowsChanged": new Slick.Event(), "onCellCssStylesChanged": new Slick.Event(), "onAutosizeColumns": new Slick.Event(), "onRendered": new Slick.Event(), "onSetOptions": new Slick.Event(), // Methods "registerPlugin": registerPlugin, "unregisterPlugin": unregisterPlugin, "getPluginByName": getPluginByName, "getColumns": getColumns, "setColumns": setColumns, "getColumnIndex": getColumnIndex, "updateColumnHeader": updateColumnHeader, "setSortColumn": setSortColumn, "setSortColumns": setSortColumns, "getSortColumns": getSortColumns, "autosizeColumns": autosizeColumns, "autosizeColumn": autosizeColumn, "getOptions": getOptions, "setOptions": setOptions, "getData": getData, "getDataLength": getDataLength, "getDataItem": getDataItem, "setData": setData, "getSelectionModel": getSelectionModel, "setSelectionModel": setSelectionModel, "getSelectedRows": getSelectedRows, "setSelectedRows": setSelectedRows, "getContainerNode": getContainerNode, "updatePagingStatusFromView": updatePagingStatusFromView, "applyFormatResultToCellNode": applyFormatResultToCellNode, "render": render, "invalidate": invalidate, "invalidateRow": invalidateRow, "invalidateRows": invalidateRows, "invalidateAllRows": invalidateAllRows, "updateCell": updateCell, "updateRow": updateRow, "getViewport": getVisibleRange, "getRenderedRange": getRenderedRange, "resizeCanvas": resizeCanvas, "updateRowCount": updateRowCount, "scrollRowIntoView": scrollRowIntoView, "scrollRowToTop": scrollRowToTop, "scrollCellIntoView": scrollCellIntoView, "scrollColumnIntoView": scrollColumnIntoView, "getCanvasNode": getCanvasNode, "getUID": getUID, "getHeaderColumnWidthDiff": getHeaderColumnWidthDiff, "getScrollbarDimensions": getScrollbarDimensions, "getHeadersWidth": getHeadersWidth, "getCanvasWidth": getCanvasWidth, "getCanvases": getCanvases, "getActiveCanvasNode": getActiveCanvasNode, "setActiveCanvasNode": setActiveCanvasNode, "getViewportNode": getViewportNode, "getActiveViewportNode": getActiveViewportNode, "setActiveViewportNode": setActiveViewportNode, "focus": setFocus, "scrollTo": scrollTo, "cacheCssForHiddenInit": cacheCssForHiddenInit, "restoreCssFromHiddenInit": restoreCssFromHiddenInit, "getCellFromPoint": getCellFromPoint, "getCellFromEvent": getCellFromEvent, "getActiveCell": getActiveCell, "setActiveCell": setActiveCell, "setActiveRow": setActiveRow, "getActiveCellNode": getActiveCellNode, "getActiveCellPosition": getActiveCellPosition, "resetActiveCell": resetActiveCell, "editActiveCell": makeActiveCellEditable, "getCellEditor": getCellEditor, "getCellNode": getCellNode, "getCellNodeBox": getCellNodeBox, "canCellBeSelected": canCellBeSelected, "canCellBeActive": canCellBeActive, "navigatePrev": navigatePrev, "navigateNext": navigateNext, "navigateUp": navigateUp, "navigateDown": navigateDown, "navigateLeft": navigateLeft, "navigateRight": navigateRight, "navigatePageUp": navigatePageUp, "navigatePageDown": navigatePageDown, "navigateTop": navigateTop, "navigateBottom": navigateBottom, "navigateRowStart": navigateRowStart, "navigateRowEnd": navigateRowEnd, "gotoCell": gotoCell, "getTopPanel": getTopPanel, "setTopPanelVisibility": setTopPanelVisibility, "getPreHeaderPanel": getPreHeaderPanel, "getPreHeaderPanelLeft": getPreHeaderPanel, "getPreHeaderPanelRight": getPreHeaderPanelRight, "setPreHeaderPanelVisibility": setPreHeaderPanelVisibility, "getHeader": getHeader, "getHeaderColumn": getHeaderColumn, "setHeaderRowVisibility": setHeaderRowVisibility, "getHeaderRow": getHeaderRow, "getHeaderRowColumn": getHeaderRowColumn, "setFooterRowVisibility": setFooterRowVisibility, "getFooterRow": getFooterRow, "getFooterRowColumn": getFooterRowColumn, "getGridPosition": getGridPosition, "flashCell": flashCell, "addCellCssStyles": addCellCssStyles, "setCellCssStyles": setCellCssStyles, "removeCellCssStyles": removeCellCssStyles, "getCellCssStyles": getCellCssStyles, "getFrozenRowOffset": getFrozenRowOffset, "setColumnHeaderVisibility": setColumnHeaderVisibility, "init": finishInitialization, "destroy": destroy, // IEditor implementation "getEditorLock": getEditorLock, "getEditController": getEditController }); init(); } // exports $.extend(true, window, { Slick: { Grid: SlickGrid } }); }(jQuery));
feat: expose `reRenderColumns` as public method (#583) - this will help in calculation our own column widths and calling `reRenderColumns` to resize columns accordingly
slick.grid.js
feat: expose `reRenderColumns` as public method (#583)
<ide><path>lick.grid.js <ide> "applyFormatResultToCellNode": applyFormatResultToCellNode, <ide> <ide> "render": render, <add> "reRenderColumns": reRenderColumns, <ide> "invalidate": invalidate, <ide> "invalidateRow": invalidateRow, <ide> "invalidateRows": invalidateRows,
JavaScript
mit
681c5305984c0a429fb2acc812d9063231a6dff5
0
hojberg/mastering-react
import React from 'react'; class Header extends React.Component { render() { return <h1 style={{color: 'red'}}>{this.props.children}</h1>; } } class Greeter extends React.Component { constructor(props) { super(props); this.state = { name: 'Bruce Wayne' }; } render() { return ( <div> <Header>Hello {this.state.name}</Header> <input type='text' ref='name' /> <button onClick={this.handleGreet.bind(this)}>Greet!</button> </div> ); } handleGreet() { this.setState({ name: this.refs.name.getDOMNode().value }); } componentWillMount() { console.log('componentWillMount'); } componentDidMount() { console.log('componentDidMount'); } componentWillReceiveProps(nextProps) { console.log('componentWillReceiveProps', nextProps); } shouldComponentUpdate(nextProps, nextState) { console.log('shouldComponentUpdate', nextProps, nextState); return nextState.name !== this.state.name; } componentWillUpdate(nextProps, nextState) { console.log('componentWillUpdate', nextProps, nextState); } componentDidUpdate(nextProps, nextState) { console.log('componentDidUpdate', nextProps, nextState); } componentWillUnmount() { console.log('componentWillUnmount'); } } class App extends React.Component { render() { return <Greeter name='Bruce Wayne' />; } } React.render(<App />, document.querySelector('#app'));
src/main.js
import React from 'react'; class Header extends React.Component { render() { return <h1 style={{color: 'red'}}>{this.props.children}</h1>; } } class Greeter extends React.Component { render() { return <Header>Hello {this.props.name}</Header>; } } class App extends React.Component { render() { return <Greeter name='Bruce Wayne' />; } } React.render(<App />, document.querySelector('#app'));
video 1.4
src/main.js
video 1.4
<ide><path>rc/main.js <ide> } <ide> <ide> class Greeter extends React.Component { <add> constructor(props) { <add> super(props); <add> this.state = { name: 'Bruce Wayne' }; <add> } <add> <ide> render() { <del> return <Header>Hello {this.props.name}</Header>; <add> return ( <add> <div> <add> <Header>Hello {this.state.name}</Header> <add> <input type='text' ref='name' /> <add> <button onClick={this.handleGreet.bind(this)}>Greet!</button> <add> </div> <add> ); <ide> } <add> <add> handleGreet() { <add> this.setState({ name: this.refs.name.getDOMNode().value }); <add> } <add> <add> componentWillMount() { <add> console.log('componentWillMount'); <add> } <add> <add> componentDidMount() { <add> console.log('componentDidMount'); <add> } <add> <add> componentWillReceiveProps(nextProps) { <add> console.log('componentWillReceiveProps', nextProps); <add> } <add> <add> shouldComponentUpdate(nextProps, nextState) { <add> console.log('shouldComponentUpdate', nextProps, nextState); <add> return nextState.name !== this.state.name; <add> } <add> <add> componentWillUpdate(nextProps, nextState) { <add> console.log('componentWillUpdate', nextProps, nextState); <add> } <add> <add> componentDidUpdate(nextProps, nextState) { <add> console.log('componentDidUpdate', nextProps, nextState); <add> } <add> <add> componentWillUnmount() { <add> console.log('componentWillUnmount'); <add> } <add> <ide> } <ide> <ide> class App extends React.Component {
JavaScript
agpl-3.0
f568e92a49ff7f3eb00de592a2691bbc5f0da617
0
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
const parse = require('../src/area-tools/parse-hanson-string').parse const nom = require('nomnom') const stringify = require('json-stable-stringify') const yaml = require('js-yaml') const util = require('util') const getStdin = require('get-stdin') function parseString(args, string) { if (string.length === 0) { throw new Error('Either --stdin or an argument is required') } const parsed = parse(string) if (args.json) { console.log(stringify(parsed, {space: 4})) } else if (args.yaml) { console.log(yaml.safeDump(parsed)) } else { console.log(util.inspect(parsed, {depth: null})) } } exports.cli = function cli() { const args = nom .option('json', {flag: true, help: 'Print the result as valid JSON'}) .option('yaml', {flag: true, help: 'Print the result as YAML'}) .option('stdin', {flag: true, help: 'Take input via STDIN'}) .option('string', {position: 0}) .parse() if (args.stdin) { getStdin().then(string => parseString(args, string)) } else { parseString(args, args.string) } }
bin/parse-result.js
const parse = require('../src/area-tools/parse-hanson-string').parse const nom = require('nomnom') const stringify = require('json-stable-stringify') const yaml = require('js-yaml') const util = require('util') exports.cli = function cli() { const args = nom .option('json', {flag: true, help: 'Print the result as valid JSON'}) .option('yaml', {flag: true, help: 'Print the result as YAML'}) .option('string', {position: 0, required: true}) .parse() const string = parse(args.string) if (args.json) { console.log(stringify(string, {space: 4})) } else if (args.yaml) { console.log(yaml.safeDump(string)) } else { console.log(util.inspect(string, {depth: null})) } }
update parse-result to read from STDIN or arguments
bin/parse-result.js
update parse-result to read from STDIN or arguments
<ide><path>in/parse-result.js <ide> const stringify = require('json-stable-stringify') <ide> const yaml = require('js-yaml') <ide> const util = require('util') <add>const getStdin = require('get-stdin') <add> <add>function parseString(args, string) { <add> if (string.length === 0) { <add> throw new Error('Either --stdin or an argument is required') <add> } <add> <add> const parsed = parse(string) <add> <add> if (args.json) { <add> console.log(stringify(parsed, {space: 4})) <add> } <add> else if (args.yaml) { <add> console.log(yaml.safeDump(parsed)) <add> } <add> else { <add> console.log(util.inspect(parsed, {depth: null})) <add> } <add>} <ide> <ide> exports.cli = function cli() { <ide> const args = nom <ide> .option('json', {flag: true, help: 'Print the result as valid JSON'}) <ide> .option('yaml', {flag: true, help: 'Print the result as YAML'}) <del> .option('string', {position: 0, required: true}) <add> .option('stdin', {flag: true, help: 'Take input via STDIN'}) <add> .option('string', {position: 0}) <ide> .parse() <ide> <del> const string = parse(args.string) <del> <del> if (args.json) { <del> console.log(stringify(string, {space: 4})) <del> } <del> else if (args.yaml) { <del> console.log(yaml.safeDump(string)) <add> if (args.stdin) { <add> getStdin().then(string => parseString(args, string)) <ide> } <ide> else { <del> console.log(util.inspect(string, {depth: null})) <add> parseString(args, args.string) <ide> } <ide> }
Java
apache-2.0
error: pathspec 'Java/Algorithms/src/main/java/com/ilyagubarev/algorithms/sorting/SelectionAlgorithm.java' did not match any file(s) known to git
d162887a4a2c2e624069046b4a96c50d0348069a
1
ilyagubarev/Algorithms
/* * Copyright 2013 Ilya Gubarev. * * 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.ilyagubarev.algorithms.sorting; import com.ilyagubarev.algorithms.adt.analysis.Counter; /** * Selection sort algorithm implementation. * * @see AbstractSortingAlgorithm * * @version 1.01, 07 September 2013 * @since 07 September 2013 * @author Ilya Gubarev */ public final class SelectionAlgorithm extends AbstractSortingAlgorithm { @Override public void sort(Comparable[] array, Counter tests, Counter exchanges) { for (int pivot = 0; pivot < array.length; ++pivot) { int min = pivot; for (int i = pivot + 1; i < array.length; ++i) { tests.increment(); if (isLess(array[i], array[min])) { min = i; } } exchanges.increment(); exchange(array, pivot, min); } } }
Java/Algorithms/src/main/java/com/ilyagubarev/algorithms/sorting/SelectionAlgorithm.java
SelectionSort added
Java/Algorithms/src/main/java/com/ilyagubarev/algorithms/sorting/SelectionAlgorithm.java
SelectionSort added
<ide><path>ava/Algorithms/src/main/java/com/ilyagubarev/algorithms/sorting/SelectionAlgorithm.java <add>/* <add> * Copyright 2013 Ilya Gubarev. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package com.ilyagubarev.algorithms.sorting; <add> <add>import com.ilyagubarev.algorithms.adt.analysis.Counter; <add> <add>/** <add> * Selection sort algorithm implementation. <add> * <add> * @see AbstractSortingAlgorithm <add> * <add> * @version 1.01, 07 September 2013 <add> * @since 07 September 2013 <add> * @author Ilya Gubarev <add> */ <add>public final class SelectionAlgorithm extends AbstractSortingAlgorithm { <add> <add> @Override <add> public void sort(Comparable[] array, Counter tests, Counter exchanges) { <add> for (int pivot = 0; pivot < array.length; ++pivot) { <add> int min = pivot; <add> for (int i = pivot + 1; i < array.length; ++i) { <add> tests.increment(); <add> if (isLess(array[i], array[min])) { <add> min = i; <add> } <add> } <add> exchanges.increment(); <add> exchange(array, pivot, min); <add> } <add> } <add>}
JavaScript
apache-2.0
67e8863b555ee4614a2325f679f41b530f44f975
0
edwardsph/callimachus,edwardsph/callimachus,Thellmann/callimachus,3-Round-Stones/callimachus,jimmccusker/callimachus,edwardsph/callimachus,edwardsph/callimachus,3-Round-Stones/callimachus,Thellmann/callimachus,Thellmann/callimachus,jimmccusker/callimachus,Thellmann/callimachus,edwardsph/callimachus,edwardsph/callimachus,jimmccusker/callimachus,3-Round-Stones/callimachus,Thellmann/callimachus,Thellmann/callimachus,jimmccusker/callimachus,3-Round-Stones/callimachus,jimmccusker/callimachus,3-Round-Stones/callimachus,3-Round-Stones/callimachus,jimmccusker/callimachus
// dropzone.js /* Portions Copyright (c) 2009-10 Zepheira LLC, Some Rights Reserved Portions Copyright (c) 2010-11 Talis Inc, Some Rights Reserved Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 */ (function($, jQuery){ $(document).ready(function() { initDropArea($("[data-construct]")); }); $(document).bind('DOMNodeInserted', function (event) { initDropArea($(event.target).find("[data-construct]").andSelf().filter("[data-construct]")); }); function initDropArea(construct) { var dropzone = construct.add(construct.parents()).filter('[dropzone]'); dropzone.bind('dragenter dragover', function(event) { if (!$(this).hasClass("drag-over")) { $(this).addClass("drag-over"); } event.preventDefault(); return false; }); dropzone.bind('dragleave', function(event) { $(this).removeClass("drag-over"); event.preventDefault(); return false; }); dropzone.bind('drop', function(event) { $(this).removeClass("drag-over"); event.preventDefault(); if (typeof $(this).attr('ondrop') == 'function') { return false; // event registered } else if (typeof $(this).attr('ondrop') == 'string') { return eval('(function(){' + $(this).attr('ondrop') + '})()'); } else { return calli.insertResource(event); } }); dropzone.bind('calliLink', function(event) { var de = jQuery.Event('drop'); de.dataTransfer = {getData:function(){return event.location}}; de.errorMessage = "Invalid Relationship"; $(event.target).trigger(de); }); } })(jQuery, jQuery);
webapps/callimachus/scripts/dropzone.js
// dropzone.js /* Portions Copyright (c) 2009-10 Zepheira LLC, Some Rights Reserved Portions Copyright (c) 2010-11 Talis Inc, Some Rights Reserved Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 */ (function($, jQuery){ $(document).ready(function() { initDropArea($("[data-construct]")); }); $(document).bind('DOMNodeInserted', function (event) { initDropArea($(event.target).find("[data-construct]").andSelf().filter("[data-construct]")); }); function initDropArea(construct) { var dropzone = construct.add(construct.parents()).filter('[dropzone]'); dropzone.bind('dragenter dragover', function(event) { if (!$(this).hasClass("drag-over")) { $(this).addClass("drag-over"); } event.preventDefault(); return false; }); dropzone.bind('dragleave', function(event) { $(this).removeClass("drag-over"); event.preventDefault(); return false; }); dropzone.bind('drop', function(event) { $(this).removeClass("drag-over"); event.preventDefault(); if (typeof dropzone.attr('ondrop') == 'function') { return false; // event registered } else if (typeof dropzone.attr('ondrop') == 'string') { return eval('(function(){' + dropzone.attr('ondrop') + '})()'); } else { return calli.insertResource(event); } }); dropzone.bind('calliLink', function(event) { var de = jQuery.Event('drop'); de.dataTransfer = {getData:function(){return event.location}}; de.errorMessage = "Invalid Relationship"; $(event.target).trigger(de); }); } })(jQuery, jQuery);
Prevent drop item from appearing multiple times in forms with multiple dropzones
webapps/callimachus/scripts/dropzone.js
Prevent drop item from appearing multiple times in forms with multiple dropzones
<ide><path>ebapps/callimachus/scripts/dropzone.js <ide> dropzone.bind('drop', function(event) { <ide> $(this).removeClass("drag-over"); <ide> event.preventDefault(); <del> if (typeof dropzone.attr('ondrop') == 'function') { <add> if (typeof $(this).attr('ondrop') == 'function') { <ide> return false; // event registered <del> } else if (typeof dropzone.attr('ondrop') == 'string') { <del> return eval('(function(){' + dropzone.attr('ondrop') + '})()'); <add> } else if (typeof $(this).attr('ondrop') == 'string') { <add> return eval('(function(){' + $(this).attr('ondrop') + '})()'); <ide> } else { <ide> return calli.insertResource(event); <ide> }
Java
apache-2.0
e6a60213b6e2e86ea9dfacbb61e97e76508668ac
0
vanitasvitae/Smack,Flowdalic/Smack,Flowdalic/Smack,igniterealtime/Smack,Flowdalic/Smack,igniterealtime/Smack,vanitasvitae/Smack,vanitasvitae/Smack,igniterealtime/Smack
/** * * Copyright 2020 Florian Schmaus, Aditya Borikar * * 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 org.jivesoftware.smack.packet; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.packet.StreamOpen.StreamContentNamespace; import org.jivesoftware.smack.util.StringUtils; /** * AbstractStreamOpen is actually a {@link TopLevelStreamElement}, however we * implement {@link Nonza} here. This is because, {@link XMPPConnection} doesn't * yet support sending {@link TopLevelStreamElement} directly and the same can only * be achieved through {@link XMPPConnection#sendNonza(Nonza)}. */ public abstract class AbstractStreamOpen implements Nonza { public static final String CLIENT_NAMESPACE = "jabber:client"; public static final String SERVER_NAMESPACE = "jabber:server"; /** * RFC 6120 § 4.7.5. */ public static final String VERSION = "1.0"; /** * RFC 6120 § 4.7.1. */ protected final String from; /** * RFC 6120 § 4.7.2. */ protected final String to; /** * RFC 6120 § 4.7.3. */ protected final String id; /** * RFC 6120 § 4.7.4. */ protected final String lang; /** * RFC 6120 § 4.8.2. */ protected final String contentNamespace; public AbstractStreamOpen(CharSequence to, CharSequence from, String id, String lang) { this(to, from, id, lang, StreamContentNamespace.client); } public AbstractStreamOpen(CharSequence to, CharSequence from, String id, String lang, StreamContentNamespace ns) { this.to = StringUtils.maybeToString(to); this.from = StringUtils.maybeToString(from); this.id = id; this.lang = lang; switch (ns) { case client: this.contentNamespace = CLIENT_NAMESPACE; break; case server: this.contentNamespace = SERVER_NAMESPACE; break; default: throw new IllegalStateException(); } } }
smack-core/src/main/java/org/jivesoftware/smack/packet/AbstractStreamOpen.java
/** * * Copyright 2020 Aditya Borikar * * 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 org.jivesoftware.smack.packet; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.packet.StreamOpen.StreamContentNamespace; import org.jivesoftware.smack.util.StringUtils; /** * AbstractStreamOpen is actually a {@link TopLevelStreamElement}, however we * implement {@link Nonza} here. This is because, {@link XMPPConnection} doesn't * yet support sending {@link TopLevelStreamElement} directly and the same can only * be achieved through {@link XMPPConnection#sendNonza(Nonza)}. */ public abstract class AbstractStreamOpen implements Nonza { public static final String CLIENT_NAMESPACE = "jabber:client"; public static final String SERVER_NAMESPACE = "jabber:server"; /** * RFC 6120 § 4.7.5. */ public static final String VERSION = "1.0"; /** * RFC 6120 § 4.7.1. */ protected final String from; /** * RFC 6120 § 4.7.2. */ protected final String to; /** * RFC 6120 § 4.7.3. */ protected final String id; /** * RFC 6120 § 4.7.4. */ protected final String lang; /** * RFC 6120 § 4.8.2. */ protected final String contentNamespace; public AbstractStreamOpen(CharSequence to, CharSequence from, String id, String lang, StreamContentNamespace ns) { this.to = StringUtils.maybeToString(to); this.from = StringUtils.maybeToString(from); this.id = id; this.lang = lang; switch (ns) { case client: this.contentNamespace = CLIENT_NAMESPACE; break; case server: this.contentNamespace = SERVER_NAMESPACE; break; default: throw new IllegalStateException(); } } }
[core] Add convenience constructor to AbstractStreamOpen Most of the times when we construct a stream-open-like element, we want the jabber:client namespace. Hence add a constructor that does select the namespace implicitly.
smack-core/src/main/java/org/jivesoftware/smack/packet/AbstractStreamOpen.java
[core] Add convenience constructor to AbstractStreamOpen
<ide><path>mack-core/src/main/java/org/jivesoftware/smack/packet/AbstractStreamOpen.java <ide> /** <ide> * <del> * Copyright 2020 Aditya Borikar <add> * Copyright 2020 Florian Schmaus, Aditya Borikar <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> */ <ide> protected final String contentNamespace; <ide> <add> public AbstractStreamOpen(CharSequence to, CharSequence from, String id, String lang) { <add> this(to, from, id, lang, StreamContentNamespace.client); <add> } <add> <ide> public AbstractStreamOpen(CharSequence to, CharSequence from, String id, String lang, StreamContentNamespace ns) { <ide> this.to = StringUtils.maybeToString(to); <ide> this.from = StringUtils.maybeToString(from);
Java
mpl-2.0
e5385ab0792b2a4a5161749b73a503c4d17b6b95
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.jhv.layers; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.annotation.Nullable; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.SwingConstants; import org.helioviewer.jhv.base.Colors; import org.helioviewer.jhv.camera.Camera; import org.helioviewer.jhv.gui.components.base.WheelSupport; import org.helioviewer.jhv.display.Display; import org.helioviewer.jhv.display.Viewport; import org.helioviewer.jhv.math.MathUtils; import org.helioviewer.jhv.opengl.GLInfo; import org.helioviewer.jhv.opengl.GLText; import org.helioviewer.jhv.opengl.text.JhvTextRenderer; import org.json.JSONObject; import com.jogamp.opengl.GL2; public class TimestampLayer extends AbstractLayer { private static final int MIN_SCALE = 50; private static final int MAX_SCALE = 200; private int scale = 100; private boolean top = false; private final JPanel optionsPanel; @Override public void serialize(JSONObject jo) { jo.put("scale", scale); jo.put("top", top); } private void deserialize(JSONObject jo) { scale = MathUtils.clip(jo.optInt("scale", scale), MIN_SCALE, MAX_SCALE); top = jo.optBoolean("top", top); } public TimestampLayer(JSONObject jo) { if (jo != null) deserialize(jo); optionsPanel = optionsPanel(); } @Override public void render(Camera camera, Viewport vp, GL2 gl) { } @Override public void renderFloat(Camera camera, Viewport vp, GL2 gl) { if (!isVisible[vp.idx]) return; String text = camera.getViewpoint().time.toString(); //Movie.getTime().toString(); if (Display.multiview) { ImageLayer im = ImageLayers.getImageLayerInViewport(vp.idx); if (im != null) { text = im.getName() + ' ' + im.getTimeString(); } } int size = (int) (vp.height * (scale * 0.01 * 0.015)); if (GLInfo.pixelScale[1] == 1) //! nasty size *= 2; int deltaX = (int) (vp.height * 0.01); int deltaY = top ? (int) (vp.height - GLInfo.pixelScale[1] * deltaX - size) : deltaX; //! JhvTextRenderer renderer = GLText.getRenderer(size); renderer.beginRendering(vp.width, vp.height); renderer.setColor(GLText.shadowColor); renderer.draw(text, deltaX + GLText.shadowOffset[0], deltaY + GLText.shadowOffset[1]); renderer.setColor(Colors.LightGrayFloat); renderer.draw(text, deltaX, deltaY); renderer.endRendering(); } @Override public void init(GL2 gl) { } @Override public void remove(GL2 gl) { dispose(gl); } @Override public Component getOptionsPanel() { return optionsPanel; } @Override public String getName() { return "Timestamp"; } @Nullable @Override public String getTimeString() { return null; } @Override public boolean isDeletable() { return false; } @Override public void dispose(GL2 gl) { } private JPanel optionsPanel() { JSlider slider = new JSlider(JSlider.HORIZONTAL, MIN_SCALE, MAX_SCALE, scale); slider.addChangeListener(e -> { scale = slider.getValue(); MovieDisplay.display(); }); WheelSupport.installMouseWheelSupport(slider); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c0 = new GridBagConstraints(); c0.anchor = GridBagConstraints.LINE_END; c0.weightx = 1.; c0.weighty = 1.; c0.gridy = 0; c0.gridx = 0; panel.add(new JLabel("Size", JLabel.RIGHT), c0); c0.anchor = GridBagConstraints.LINE_START; c0.gridx = 1; panel.add(slider, c0); c0.gridx = 2; c0.anchor = GridBagConstraints.LINE_END; JCheckBox showTop = new JCheckBox("Top", top); showTop.setHorizontalTextPosition(SwingConstants.LEFT); showTop.addActionListener(e -> { top = showTop.isSelected(); MovieDisplay.display(); }); panel.add(showTop, c0); return panel; } }
src/org/helioviewer/jhv/layers/TimestampLayer.java
package org.helioviewer.jhv.layers; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.annotation.Nullable; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.SwingConstants; import org.helioviewer.jhv.base.Colors; import org.helioviewer.jhv.camera.Camera; import org.helioviewer.jhv.gui.components.base.WheelSupport; import org.helioviewer.jhv.display.Display; import org.helioviewer.jhv.display.Viewport; import org.helioviewer.jhv.math.MathUtils; import org.helioviewer.jhv.opengl.GLInfo; import org.helioviewer.jhv.opengl.GLText; import org.helioviewer.jhv.opengl.text.JhvTextRenderer; import org.json.JSONObject; import com.jogamp.opengl.GL2; public class TimestampLayer extends AbstractLayer { private static final int MIN_SCALE = 50; private static final int MAX_SCALE = 200; private int scale = 100; private boolean top = false; private final JPanel optionsPanel; @Override public void serialize(JSONObject jo) { jo.put("scale", scale); jo.put("top", top); } private void deserialize(JSONObject jo) { scale = MathUtils.clip(jo.optInt("scale", scale), MIN_SCALE, MAX_SCALE); top = jo.optBoolean("top", top); } public TimestampLayer(JSONObject jo) { if (jo != null) deserialize(jo); optionsPanel = optionsPanel(); } @Override public void render(Camera camera, Viewport vp, GL2 gl) { } @Override public void renderFloat(Camera camera, Viewport vp, GL2 gl) { if (!isVisible[vp.idx]) return; String text = camera.getViewpoint().time.toString(); //Movie.getTime().toString(); if (Display.multiview) { ImageLayer im = ImageLayers.getImageLayerInViewport(vp.idx); if (im != null) { text = im.getTimeString() + ' ' + im.getName(); } } int size = (int) (vp.height * (scale * 0.01 * 0.015)); if (GLInfo.pixelScale[1] == 1) //! nasty size *= 2; int deltaX = (int) (vp.height * 0.01); int deltaY = top ? (int) (vp.height - GLInfo.pixelScale[1] * deltaX - size) : deltaX; //! JhvTextRenderer renderer = GLText.getRenderer(size); renderer.beginRendering(vp.width, vp.height); renderer.setColor(GLText.shadowColor); renderer.draw(text, deltaX + GLText.shadowOffset[0], deltaY + GLText.shadowOffset[1]); renderer.setColor(Colors.LightGrayFloat); renderer.draw(text, deltaX, deltaY); renderer.endRendering(); } @Override public void init(GL2 gl) { } @Override public void remove(GL2 gl) { dispose(gl); } @Override public Component getOptionsPanel() { return optionsPanel; } @Override public String getName() { return "Timestamp"; } @Nullable @Override public String getTimeString() { return null; } @Override public boolean isDeletable() { return false; } @Override public void dispose(GL2 gl) { } private JPanel optionsPanel() { JSlider slider = new JSlider(JSlider.HORIZONTAL, MIN_SCALE, MAX_SCALE, scale); slider.addChangeListener(e -> { scale = slider.getValue(); MovieDisplay.display(); }); WheelSupport.installMouseWheelSupport(slider); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c0 = new GridBagConstraints(); c0.anchor = GridBagConstraints.LINE_END; c0.weightx = 1.; c0.weighty = 1.; c0.gridy = 0; c0.gridx = 0; panel.add(new JLabel("Size", JLabel.RIGHT), c0); c0.anchor = GridBagConstraints.LINE_START; c0.gridx = 1; panel.add(slider, c0); c0.gridx = 2; c0.anchor = GridBagConstraints.LINE_END; JCheckBox showTop = new JCheckBox("Top", top); showTop.setHorizontalTextPosition(SwingConstants.LEFT); showTop.addActionListener(e -> { top = showTop.isSelected(); MovieDisplay.display(); }); panel.add(showTop, c0); return panel; } }
Name first in timestamp
src/org/helioviewer/jhv/layers/TimestampLayer.java
Name first in timestamp
<ide><path>rc/org/helioviewer/jhv/layers/TimestampLayer.java <ide> if (Display.multiview) { <ide> ImageLayer im = ImageLayers.getImageLayerInViewport(vp.idx); <ide> if (im != null) { <del> text = im.getTimeString() + ' ' + im.getName(); <add> text = im.getName() + ' ' + im.getTimeString(); <ide> } <ide> } <ide>
Java
lgpl-2.1
e14f49c8270df3b1b0cfdde42ecb2baf8e7ea781
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2006 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.exedio.dsmf.SQLRuntimeException; public final class Properties extends com.exedio.cope.util.Properties { private static final String DIALECT_FROM_URL = "from url"; private final StringField dialectCode = new StringField("dialect", DIALECT_FROM_URL); private final StringField databaseUrl = new StringField("database.url"); private final StringField databaseUser = new StringField("database.user"); private final StringField databasePassword = new StringField("database.password", true); private final BooleanField databaseLog = new BooleanField("database.log", false); private final BooleanField databaseLogStatementInfo = new BooleanField("database.logStatementInfo", false); private final BooleanField databaseDontSupportPreparedStatements = new BooleanField("database.dontSupport.preparedStatements", false); private final BooleanField databaseDontSupportEmptyStrings = new BooleanField("database.dontSupport.emptyStrings", false); private final BooleanField databaseDontSupportNativeDate = new BooleanField("database.dontSupport.nativeDate", false); private final BooleanField databaseDontSupportLimit = new BooleanField("database.dontSupport.limit", false); private final MapField databaseForcedNames = new MapField("database.forcename"); private final MapField databaseTableOptions = new MapField("database.tableOption"); private final MapField databaseCustomProperties; static final String PKSOURCE_BUTTERFLY = "pksource.butterfly"; private final BooleanField pksourceButterfly = new BooleanField(PKSOURCE_BUTTERFLY, false); private final BooleanField fulltextIndex = new BooleanField("fulltextIndex", false); private final IntField connectionPoolIdleInitial = new IntField("connectionPool.idleInitial", 0, 0); private final IntField connectionPoolIdleLimit = new IntField("connectionPool.idleLimit", 10, 0); private final BooleanField transactionLog = new BooleanField("transaction.log", false); private final IntField cacheLimit = new IntField("cache.limit", 10000, 0); private final IntField cacheQueryLimit = new IntField("cache.queryLimit", 10000, 0); public static final String CACHE_QUERY_HISTOGRAM = "cache.queryHistogram"; private final BooleanField cacheQueryHistogram = new BooleanField(CACHE_QUERY_HISTOGRAM, false); final IntField dataFieldBufferSizeDefault = new IntField("dataField.bufferSizeDefault", 20*1024, 1); final IntField dataFieldBufferSizeLimit = new IntField("dataField.bufferSizeLimit", 1024*1024, 1); private final FileField datadirPath = new FileField("datadir.path"); private final StringField mediaRooturl = new StringField("media.rooturl", "media/"); private final IntField mediaOffsetExpires = new IntField("media.offsetExpires", 1000 * 5, 0); private final Constructor<? extends Dialect> dialect; public Properties() { this(getDefaultPropertyFile()); } public static final File getDefaultPropertyFile() { String result = System.getProperty("com.exedio.cope.properties"); if(result==null) result = "cope.properties"; return new File(result); } public Properties(final File file) { this(loadProperties(file), file.getAbsolutePath()); } public Properties(final java.util.Properties properties, final String source) { super(properties, source); final String dialectCodeRaw = this.dialectCode.getStringValue(); final String dialectCode; if(DIALECT_FROM_URL.equals(dialectCodeRaw)) { final String url = databaseUrl.getStringValue(); final String prefix = "jdbc:"; if(!url.startsWith(prefix)) throw new RuntimeException("cannot parse " + databaseUrl.getKey() + '=' + url + ", missing prefix '" + prefix + '\''); final int pos = url.indexOf(':', prefix.length()); if(pos<0) throw new RuntimeException("cannot parse " + databaseUrl.getKey() + '=' + url + ", missing second colon"); dialectCode = url.substring(prefix.length(), pos); } else dialectCode = dialectCodeRaw; dialect = getDialectConstructor(dialectCode, source); databaseCustomProperties = new MapField("database." + dialectCode); if(connectionPoolIdleInitial.getIntValue()>connectionPoolIdleLimit.getIntValue()) throw new RuntimeException("value for " + connectionPoolIdleInitial.getKey() + " must not be greater than " + connectionPoolIdleLimit.getKey()); if(datadirPath.getFileValue()!=null) { final File value = datadirPath.getFileValue(); if(!value.exists()) throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " does not exist."); if(!value.isDirectory()) throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " is not a directory."); if(!value.canRead()) throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " is not readable."); if(!value.canWrite()) throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " is not writable."); } ensureValidity(new String[]{"x-build"}); } private static final Constructor<? extends Dialect> getDialectConstructor(final String dialectCode, final String source) { if(dialectCode.length()<=2) throw new RuntimeException("dialect from " + source + " must have at least two characters, but was " + dialectCode); final String dialectName = "com.exedio.cope." + Character.toUpperCase(dialectCode.charAt(0)) + dialectCode.substring(1) + "Dialect"; final Class<?> dialectClassRaw; try { dialectClassRaw = Class.forName(dialectName); } catch(ClassNotFoundException e) { throw new RuntimeException("class " + dialectName + " from " + source + " not found."); } if(!Dialect.class.isAssignableFrom(dialectClassRaw)) { throw new RuntimeException(dialectClassRaw.toString() + " from " + source + " not a subclass of " + Dialect.class.getName() + '.'); } final Class<? extends Dialect> dialectClass = dialectClassRaw.asSubclass(Dialect.class); try { return dialectClass.getDeclaredConstructor(new Class[]{DialectParameters.class}); } catch(NoSuchMethodException e) { throw new RuntimeException("class " + dialectName + " from " + source + " does not have the required constructor."); } } private final RuntimeException newNotSetException(final String key) { return new RuntimeException("property " + key + " in " + getSource() + " not set."); } Database createDatabase(final boolean migrationSupported) { final DialectParameters parameters; Connection probeConnection = null; try { probeConnection = DriverManager.getConnection(getDatabaseUrl(), getDatabaseUser(), getDatabasePassword()); parameters = new DialectParameters(this, probeConnection); } catch(SQLException e) { throw new SQLRuntimeException(e, "create"); } finally { if(probeConnection!=null) { try { probeConnection.close(); probeConnection = null; } catch(SQLException e) { throw new SQLRuntimeException(e, "close"); } } } final Dialect dialect; try { dialect = this.dialect.newInstance(parameters); } catch(InstantiationException e) { throw new RuntimeException(e); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch(InvocationTargetException e) { throw new RuntimeException(e); } return new Database(dialect.driver, parameters, dialect, migrationSupported); } public String getDialect() { return dialect.getDeclaringClass().getName(); } /** * @deprecated Has been renamed to {@link #getDialect()}. */ @Deprecated public String getDatabase() { return getDialect(); } public String getDatabaseUrl() { return databaseUrl.getStringValue(); } public String getDatabaseUser() { return databaseUser.getStringValue(); } public String getDatabasePassword() { return databasePassword.getStringValue(); } public boolean getDatabaseLog() { return databaseLog.getBooleanValue(); } public boolean getDatabaseLogStatementInfo() { return databaseLogStatementInfo.getBooleanValue(); } public boolean getDatabaseDontSupportPreparedStatements() { return databaseDontSupportPreparedStatements.getBooleanValue(); } public boolean getDatabaseDontSupportEmptyStrings() { return databaseDontSupportEmptyStrings.getBooleanValue(); } public boolean getDatabaseDontSupportLimit() { return databaseDontSupportLimit.getBooleanValue(); } public boolean getDatabaseDontSupportNativeDate() { return databaseDontSupportNativeDate.getBooleanValue(); } java.util.Properties getDatabaseForcedNames() { return databaseForcedNames.getMapValue(); } java.util.Properties getDatabaseTableOptions() { return databaseTableOptions.getMapValue(); } String getDatabaseCustomProperty(final String key) { return databaseCustomProperties.getValue(key); } public boolean getPkSourceButterfly() { return pksourceButterfly.getBooleanValue(); } public boolean getFulltextIndex() { return fulltextIndex.getBooleanValue(); } public int getConnectionPoolIdleInitial() { return connectionPoolIdleInitial.getIntValue(); } public int getConnectionPoolIdleLimit() { return connectionPoolIdleLimit.getIntValue(); } public boolean getTransactionLog() { return transactionLog.getBooleanValue(); } public int getCacheLimit() { return cacheLimit.getIntValue(); } public int getCacheQueryLimit() { return cacheQueryLimit.getIntValue(); } public boolean getCacheQueryHistogram() { return cacheQueryHistogram.getBooleanValue(); } public boolean hasDatadirPath() { return datadirPath.getFileValue()!=null; } public File getDatadirPath() { final File result = datadirPath.getFileValue(); if(result==null) throw newNotSetException(datadirPath.getKey()); return result; } public String getMediaRootUrl() { return mediaRooturl.getStringValue(); } /** * Returns the offset, the Expires http header of media * is set into the future. * Together with a http reverse proxy this ensures, * that for that time no request for that data will reach the servlet. * This may reduce the load on the server. * If zero, no Expires header is sent. * * TODO: make this configurable per media as well. */ public int getMediaOffsetExpires() { return mediaOffsetExpires.getIntValue(); } }
runtime/src/com/exedio/cope/Properties.java
/* * Copyright (C) 2004-2006 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.exedio.dsmf.SQLRuntimeException; public final class Properties extends com.exedio.cope.util.Properties { private static final String DIALECT_FROM_URL = "from url"; private final StringField dialectCode = new StringField("dialect", DIALECT_FROM_URL); private final StringField databaseUrl = new StringField("database.url"); private final StringField databaseUser = new StringField("database.user"); private final StringField databasePassword = new StringField("database.password", true); private final BooleanField databaseLog = new BooleanField("database.log", false); private final BooleanField databaseLogStatementInfo = new BooleanField("database.logStatementInfo", false); private final BooleanField databaseDontSupportPreparedStatements = new BooleanField("database.dontSupport.preparedStatements", false); private final BooleanField databaseDontSupportEmptyStrings = new BooleanField("database.dontSupport.emptyStrings", false); private final BooleanField databaseDontSupportNativeDate = new BooleanField("database.dontSupport.nativeDate", false); private final BooleanField databaseDontSupportLimit = new BooleanField("database.dontSupport.limit", false); private final MapField databaseForcedNames = new MapField("database.forcename"); private final MapField databaseTableOptions = new MapField("database.tableOption"); private final MapField databaseCustomProperties; static final String PKSOURCE_BUTTERFLY = "pksource.butterfly"; private final BooleanField pksourceButterfly = new BooleanField(PKSOURCE_BUTTERFLY, false); private final BooleanField fulltextIndex = new BooleanField("fulltextIndex", false); private final IntField connectionPoolIdleInitial = new IntField("connectionPool.idleInitial", 0, 0); private final IntField connectionPoolIdleLimit = new IntField("connectionPool.idleLimit", 10, 0); private final BooleanField transactionLog = new BooleanField("transaction.log", false); private final IntField cacheLimit = new IntField("cache.limit", 10000, 0); private final IntField cacheQueryLimit = new IntField("cache.queryLimit", 10000, 0); public static final String CACHE_QUERY_HISTOGRAM = "cache.queryHistogram"; private final BooleanField cacheQueryHistogram = new BooleanField(CACHE_QUERY_HISTOGRAM, false); final IntField dataFieldBufferSizeDefault = new IntField("dataField.bufferSizeDefault", 20*1024, 1); final IntField dataFieldBufferSizeLimit = new IntField("dataField.bufferSizeLimit", 1024*1024, 1); private final FileField datadirPath = new FileField("datadir.path"); private final StringField mediaRooturl = new StringField("media.rooturl", "media/"); private final IntField mediaOffsetExpires = new IntField("media.offsetExpires", 1000 * 5, 0); private final Constructor<? extends Dialect> dialect; public Properties() { this(getDefaultPropertyFile()); } public static final File getDefaultPropertyFile() { String result = System.getProperty("com.exedio.cope.properties"); if(result==null) result = "cope.properties"; return new File(result); } public Properties(final File file) { this(loadProperties(file), file.getAbsolutePath()); } public Properties(final java.util.Properties properties, final String source) { super(properties, source); final String dialectCodeRaw = this.dialectCode.getStringValue(); final String dialectCode; if(DIALECT_FROM_URL.equals(dialectCodeRaw)) { final String url = databaseUrl.getStringValue(); final String prefix = "jdbc:"; if(!url.startsWith(prefix)) throw new RuntimeException("cannot parse " + databaseUrl.getKey() + '=' + url + ", missing prefix '" + prefix + '\''); final int pos = url.indexOf(':', prefix.length()); if(pos<0) throw new RuntimeException("cannot parse " + databaseUrl.getKey() + '=' + url + ", missing second colon"); dialectCode = url.substring(prefix.length(), pos); } else dialectCode = dialectCodeRaw; dialect = getDialectConstructor(dialectCode, source); databaseCustomProperties = new MapField("database." + dialectCode); if(connectionPoolIdleInitial.getIntValue()>connectionPoolIdleLimit.getIntValue()) throw new RuntimeException("value for " + connectionPoolIdleInitial.getKey() + " must not be greater than " + connectionPoolIdleLimit.getKey()); if(datadirPath.getFileValue()!=null) { final File value = datadirPath.getFileValue(); if(!value.exists()) throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " does not exist."); if(!value.isDirectory()) throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " is not a directory."); if(!value.canRead()) throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " is not readable."); if(!value.canWrite()) throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " is not writable."); } ensureValidity(new String[]{"x-build"}); } private static final Constructor<? extends Dialect> getDialectConstructor(final String dialectCode, final String source) { if(dialectCode.length()<=2) throw new RuntimeException("dialect from " + source + " must have at least two characters, but was " + dialectCode); final String dialectName = "com.exedio.cope." + Character.toUpperCase(dialectCode.charAt(0)) + dialectCode.substring(1) + "Dialect"; final Class<?> dialectClassRaw; try { dialectClassRaw = Class.forName(dialectName); } catch(ClassNotFoundException e) { throw new RuntimeException("class " + dialectName + " from " + source + " not found."); } if(!Dialect.class.isAssignableFrom(dialectClassRaw)) { throw new RuntimeException(dialectClassRaw.toString() + " from " + source + " not a subclass of " + Dialect.class.getName() + '.'); } final Class<? extends Dialect> dialectClass = dialectClassRaw.asSubclass(Dialect.class); try { return dialectClass.getDeclaredConstructor(new Class[]{DialectParameters.class}); } catch(NoSuchMethodException e) { throw new RuntimeException("class " + dialectName + " from " + source + " does not have the required constructor."); } } private final RuntimeException newNotSetException(final String key) { return new RuntimeException("property " + key + " in " + getSource() + " not set."); } Database createDatabase(final boolean migrationSupported) { final DialectParameters parameters; Connection probeConnection = null; try { probeConnection = DriverManager.getConnection(getDatabaseUrl(), getDatabaseUser(), getDatabasePassword()); parameters = new DialectParameters(this, probeConnection); } catch(SQLException e) { throw new SQLRuntimeException(e, "create"); } finally { if(probeConnection!=null) { try { probeConnection.close(); probeConnection = null; } catch(SQLException e) { throw new SQLRuntimeException(e, "close"); } } } final Dialect dialect; try { dialect = this.dialect.newInstance(parameters); } catch(InstantiationException e) { throw new RuntimeException(e); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch(InvocationTargetException e) { throw new RuntimeException(e); } return new Database(dialect.driver, parameters, dialect, migrationSupported); } public String getDialect() { return dialect.getDeclaringClass().getName(); } /** * @deprecated Has been renamed to {@link #getDialect()}. */ @Deprecated public String getDatabase() { return getDialect(); } public String getDatabaseUrl() // TODO SOON rename to JDBC { return databaseUrl.getStringValue(); } public String getDatabaseUser() // TODO SOON rename to JDBC { return databaseUser.getStringValue(); } public String getDatabasePassword() // TODO SOON rename to JDBC { return databasePassword.getStringValue(); } public boolean getDatabaseLog() { return databaseLog.getBooleanValue(); } public boolean getDatabaseLogStatementInfo() { return databaseLogStatementInfo.getBooleanValue(); } public boolean getDatabaseDontSupportPreparedStatements() { return databaseDontSupportPreparedStatements.getBooleanValue(); } public boolean getDatabaseDontSupportEmptyStrings() { return databaseDontSupportEmptyStrings.getBooleanValue(); } public boolean getDatabaseDontSupportLimit() { return databaseDontSupportLimit.getBooleanValue(); } public boolean getDatabaseDontSupportNativeDate() { return databaseDontSupportNativeDate.getBooleanValue(); } java.util.Properties getDatabaseForcedNames() { return databaseForcedNames.getMapValue(); } java.util.Properties getDatabaseTableOptions() { return databaseTableOptions.getMapValue(); } String getDatabaseCustomProperty(final String key) { return databaseCustomProperties.getValue(key); } public boolean getPkSourceButterfly() { return pksourceButterfly.getBooleanValue(); } public boolean getFulltextIndex() { return fulltextIndex.getBooleanValue(); } public int getConnectionPoolIdleInitial() { return connectionPoolIdleInitial.getIntValue(); } public int getConnectionPoolIdleLimit() { return connectionPoolIdleLimit.getIntValue(); } public boolean getTransactionLog() { return transactionLog.getBooleanValue(); } public int getCacheLimit() { return cacheLimit.getIntValue(); } public int getCacheQueryLimit() { return cacheQueryLimit.getIntValue(); } public boolean getCacheQueryHistogram() { return cacheQueryHistogram.getBooleanValue(); } public boolean hasDatadirPath() { return datadirPath.getFileValue()!=null; } public File getDatadirPath() { final File result = datadirPath.getFileValue(); if(result==null) throw newNotSetException(datadirPath.getKey()); return result; } public String getMediaRootUrl() { return mediaRooturl.getStringValue(); } /** * Returns the offset, the Expires http header of media * is set into the future. * Together with a http reverse proxy this ensures, * that for that time no request for that data will reach the servlet. * This may reduce the load on the server. * If zero, no Expires header is sent. * * TODO: make this configurable per media as well. */ public int getMediaOffsetExpires() { return mediaOffsetExpires.getIntValue(); } }
remove non-sense TODO git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@7192 e7d4fc99-c606-0410-b9bf-843393a9eab7
runtime/src/com/exedio/cope/Properties.java
remove non-sense TODO
<ide><path>untime/src/com/exedio/cope/Properties.java <ide> return getDialect(); <ide> } <ide> <del> public String getDatabaseUrl() // TODO SOON rename to JDBC <add> public String getDatabaseUrl() <ide> { <ide> return databaseUrl.getStringValue(); <ide> } <ide> <del> public String getDatabaseUser() // TODO SOON rename to JDBC <add> public String getDatabaseUser() <ide> { <ide> return databaseUser.getStringValue(); <ide> } <ide> <del> public String getDatabasePassword() // TODO SOON rename to JDBC <add> public String getDatabasePassword() <ide> { <ide> return databasePassword.getStringValue(); <ide> }
JavaScript
mit
e1a067dea0ffcacd1f664f30cd14463b00f52fa7
0
chenglou/react,cpojer/react,flarnie/react,camsong/react,jzmq/react,mjackson/react,chicoxyzzy/react,yungsters/react,billfeller/react,facebook/react,terminatorheart/react,trueadm/react,jameszhan/react,jdlehman/react,tomocchino/react,VioletLife/react,VioletLife/react,jzmq/react,terminatorheart/react,trueadm/react,mjackson/react,flarnie/react,trueadm/react,kaushik94/react,ericyang321/react,tomocchino/react,Simek/react,rickbeerendonk/react,rickbeerendonk/react,STRML/react,nhunzaker/react,chenglou/react,STRML/react,facebook/react,empyrical/react,Simek/react,mjackson/react,rricard/react,Simek/react,empyrical/react,mjackson/react,kaushik94/react,ArunTesco/react,STRML/react,Simek/react,rickbeerendonk/react,Simek/react,TheBlasfem/react,acdlite/react,yiminghe/react,facebook/react,VioletLife/react,terminatorheart/react,cpojer/react,Simek/react,yungsters/react,kaushik94/react,jameszhan/react,tomocchino/react,jdlehman/react,camsong/react,flarnie/react,TheBlasfem/react,billfeller/react,terminatorheart/react,jdlehman/react,camsong/react,nhunzaker/react,ericyang321/react,chicoxyzzy/react,flarnie/react,jdlehman/react,nhunzaker/react,rricard/react,nhunzaker/react,tomocchino/react,cpojer/react,VioletLife/react,rickbeerendonk/react,mjackson/react,yiminghe/react,VioletLife/react,facebook/react,jameszhan/react,yungsters/react,trueadm/react,chicoxyzzy/react,billfeller/react,glenjamin/react,mosoft521/react,empyrical/react,jameszhan/react,billfeller/react,flarnie/react,kaushik94/react,yiminghe/react,STRML/react,glenjamin/react,jameszhan/react,yiminghe/react,yungsters/react,jdlehman/react,jzmq/react,kaushik94/react,empyrical/react,mjackson/react,camsong/react,jzmq/react,yiminghe/react,acdlite/react,rricard/react,yiminghe/react,rickbeerendonk/react,nhunzaker/react,TheBlasfem/react,rricard/react,kaushik94/react,tomocchino/react,ericyang321/react,glenjamin/react,cpojer/react,ericyang321/react,tomocchino/react,billfeller/react,TheBlasfem/react,acdlite/react,mjackson/react,kaushik94/react,yungsters/react,flarnie/react,chenglou/react,cpojer/react,terminatorheart/react,jzmq/react,acdlite/react,yiminghe/react,trueadm/react,chicoxyzzy/react,glenjamin/react,rricard/react,Simek/react,facebook/react,STRML/react,ericyang321/react,ArunTesco/react,cpojer/react,trueadm/react,camsong/react,facebook/react,VioletLife/react,trueadm/react,camsong/react,TheBlasfem/react,glenjamin/react,camsong/react,yungsters/react,facebook/react,empyrical/react,mosoft521/react,jdlehman/react,acdlite/react,mosoft521/react,rickbeerendonk/react,TheBlasfem/react,tomocchino/react,mosoft521/react,chicoxyzzy/react,jzmq/react,mosoft521/react,mosoft521/react,terminatorheart/react,ericyang321/react,jameszhan/react,chenglou/react,rricard/react,jameszhan/react,glenjamin/react,STRML/react,jdlehman/react,yungsters/react,glenjamin/react,nhunzaker/react,chenglou/react,chenglou/react,ArunTesco/react,empyrical/react,chicoxyzzy/react,rickbeerendonk/react,acdlite/react,nhunzaker/react,chenglou/react,billfeller/react,STRML/react,cpojer/react,empyrical/react,acdlite/react,ericyang321/react,VioletLife/react,jzmq/react,chicoxyzzy/react,flarnie/react,mosoft521/react,billfeller/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Interaction, Subscriber} from './Tracing'; import {enableSchedulerTracing} from 'shared/ReactFeatureFlags'; import {__subscriberRef} from './Tracing'; let subscribers: Set<Subscriber> = (null: any); if (enableSchedulerTracing) { subscribers = new Set(); } export function unstable_subscribe(subscriber: Subscriber): void { if (enableSchedulerTracing) { subscribers.add(subscriber); if (subscribers.size === 1) { __subscriberRef.current = { onInteractionScheduledWorkCompleted, onInteractionTraced, onWorkCanceled, onWorkScheduled, onWorkStarted, onWorkStopped, }; } } } export function unstable_unsubscribe(subscriber: Subscriber): void { if (enableSchedulerTracing) { subscribers.delete(subscriber); if (subscribers.size === 0) { __subscriberRef.current = null; } } } function onInteractionTraced(interaction: Interaction): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onInteractionTraced(interaction); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onInteractionScheduledWorkCompleted(interaction: Interaction): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onInteractionScheduledWorkCompleted(interaction); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkScheduled( interactions: Set<Interaction>, threadID: number, ): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onWorkScheduled(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkStarted(interactions: Set<Interaction>, threadID: number): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onWorkStarted(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkStopped(interactions: Set<Interaction>, threadID: number): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onWorkStopped(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkCanceled( interactions: Set<Interaction>, threadID: number, ): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onWorkCanceled(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } }
packages/scheduler/src/TracingSubscriptions.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Interaction, Subscriber} from './Tracing'; import {enableSchedulerTracing} from 'shared/ReactFeatureFlags'; import {__subscriberRef} from 'scheduler/tracing'; let subscribers: Set<Subscriber> = (null: any); if (enableSchedulerTracing) { subscribers = new Set(); } export function unstable_subscribe(subscriber: Subscriber): void { if (enableSchedulerTracing) { subscribers.add(subscriber); if (subscribers.size === 1) { __subscriberRef.current = { onInteractionScheduledWorkCompleted, onInteractionTraced, onWorkCanceled, onWorkScheduled, onWorkStarted, onWorkStopped, }; } } } export function unstable_unsubscribe(subscriber: Subscriber): void { if (enableSchedulerTracing) { subscribers.delete(subscriber); if (subscribers.size === 0) { __subscriberRef.current = null; } } } function onInteractionTraced(interaction: Interaction): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onInteractionTraced(interaction); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onInteractionScheduledWorkCompleted(interaction: Interaction): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onInteractionScheduledWorkCompleted(interaction); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkScheduled( interactions: Set<Interaction>, threadID: number, ): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onWorkScheduled(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkStarted(interactions: Set<Interaction>, threadID: number): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onWorkStarted(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkStopped(interactions: Set<Interaction>, threadID: number): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onWorkStopped(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkCanceled( interactions: Set<Interaction>, threadID: number, ): void { let didCatchError = false; let caughtError = null; subscribers.forEach(subscriber => { try { subscriber.onWorkCanceled(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } }
Fix circular dependency in TracingSubscriptions (#13689)
packages/scheduler/src/TracingSubscriptions.js
Fix circular dependency in TracingSubscriptions (#13689)
<ide><path>ackages/scheduler/src/TracingSubscriptions.js <ide> import type {Interaction, Subscriber} from './Tracing'; <ide> <ide> import {enableSchedulerTracing} from 'shared/ReactFeatureFlags'; <del>import {__subscriberRef} from 'scheduler/tracing'; <add>import {__subscriberRef} from './Tracing'; <ide> <ide> let subscribers: Set<Subscriber> = (null: any); <ide> if (enableSchedulerTracing) {
Java
apache-2.0
4c675f868be2259f5d5e0fda4d125d39d6abdc1d
0
eg-zhang/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,vbelakov/h2o,rowhit/h2o-2,h2oai/h2o-2,rowhit/h2o-2,h2oai/h2o-2,100star/h2o,h2oai/h2o-2,vbelakov/h2o,h2oai/h2o,calvingit21/h2o-2,111t8e/h2o-2,elkingtonmcb/h2o-2,h2oai/h2o-2,vbelakov/h2o,111t8e/h2o-2,h2oai/h2o,rowhit/h2o-2,rowhit/h2o-2,111t8e/h2o-2,h2oai/h2o,calvingit21/h2o-2,eg-zhang/h2o-2,vbelakov/h2o,111t8e/h2o-2,eg-zhang/h2o-2,100star/h2o,h2oai/h2o-2,eg-zhang/h2o-2,h2oai/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,elkingtonmcb/h2o-2,h2oai/h2o,rowhit/h2o-2,vbelakov/h2o,h2oai/h2o-2,eg-zhang/h2o-2,calvingit21/h2o-2,h2oai/h2o,h2oai/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,h2oai/h2o,elkingtonmcb/h2o-2,111t8e/h2o-2,eg-zhang/h2o-2,h2oai/h2o,h2oai/h2o,vbelakov/h2o,calvingit21/h2o-2,100star/h2o,100star/h2o,eg-zhang/h2o-2,eg-zhang/h2o-2,rowhit/h2o-2,rowhit/h2o-2,111t8e/h2o-2,elkingtonmcb/h2o-2,elkingtonmcb/h2o-2,rowhit/h2o-2,100star/h2o,calvingit21/h2o-2,vbelakov/h2o,eg-zhang/h2o-2,rowhit/h2o-2,100star/h2o,111t8e/h2o-2,100star/h2o,vbelakov/h2o,h2oai/h2o,calvingit21/h2o-2,h2oai/h2o-2,100star/h2o,vbelakov/h2o,calvingit21/h2o-2,eg-zhang/h2o-2,vbelakov/h2o,100star/h2o,elkingtonmcb/h2o-2,elkingtonmcb/h2o-2,rowhit/h2o-2,h2oai/h2o,calvingit21/h2o-2,calvingit21/h2o-2,h2oai/h2o-2,calvingit21/h2o-2
package hex.glm; import hex.glm.GLMParams.CaseMode; import hex.glm.GLMParams.Family; import hex.glm.GLMValidation.GLMXValidation; import java.text.DecimalFormat; import java.util.HashMap; import water.*; import water.H2O.H2OCountedCompleter; import water.api.DocGen; import water.api.Request.API; import water.fvec.Chunk; import water.fvec.Frame; import water.util.RString; public class GLMModel extends Model implements Comparable<GLMModel> { static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. @API(help="mean of response in the training dataset") final double ymu; @API(help="predicate applied to the response column to turn it into 0/1") final CaseMode _caseMode; @API(help="value used to co compare agains using case-predicate to turn the response into 0/1") final double _caseVal; @API(help="offsets of categorical columns into the beta vector. The last value is the offset of the first numerical column.") final int [] catOffsets; @API(help="warnings") final String [] warnings; @API(help="Decision threshold.") final double threshold; @API(help="glm params") final GLMParams glm; @API(help="beta epsilon - stop iterating when beta diff is below this threshold.") final double beta_eps; @API(help="regularization parameter driving proportion of L1/L2 penalty.") final double alpha; @API(help="index of lambda giving best results") int best_lambda_idx; public double auc(){ if(glm.family == Family.binomial && submodels != null && submodels[best_lambda_idx].validation != null) return submodels[best_lambda_idx].validation.auc; return -1; } public double aic(){ if(submodels != null && submodels[best_lambda_idx].validation != null) return submodels[best_lambda_idx].validation.aic; return Double.MAX_VALUE; } public double devExplained(){ if(submodels == null || submodels[best_lambda_idx].validation == null) return 0; GLMValidation val = submodels[best_lambda_idx].validation; return 1.0 - val.residual_deviance/val.null_deviance; } @Override public int compareTo(GLMModel m){ // assert m._dataKey.equals(_dataKey); assert m.glm.family == glm.family; assert m.glm.link == glm.link; switch(glm.family){ case binomial: // compare by AUC, higher is better return (int)(1e6*(m.auc()-auc())); case gamma: // compare by percentage of explained deviance, higher is better return (int)(100*(m.devExplained()-devExplained())); default: // compare by AICs by default, lower is better return (int)(100*(aic()- m.aic())); } } @API(help="Overall run time") long run_time; @API(help="computation started at") long start_time; static class Submodel extends Iced { static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. @API(help="regularization param giving the strength of the applied regularization. high values drive coeffficients to zero.") final double lambda; @API(help="number of iterations computed.") final int iteration; @API(help="running time of the algo in ms.") final long run_time; @API(help="Validation") GLMValidation validation; @API(help="Beta vector containing model coefficients.") double [] beta; @API(help="Beta vector containing normalized coefficients (coefficients obtained on normalized data).") double [] norm_beta; final int rank; final int [] idxs; public Submodel(double lambda, double [] beta, double [] norm_beta, long run_time, int iteration){ this.lambda = lambda; this.beta = beta; this.norm_beta = norm_beta; this.run_time = run_time; this.iteration = iteration; int r = 0; if(beta != null){ final double [] b = norm_beta != null?norm_beta:beta; // grab the indeces of non-zero coefficients for(double d:beta)if(d != 0)++r; idxs = new int[r]; int ii = 0; for(int i = 0; i < b.length; ++i)if(b[i] != 0)idxs[ii++] = i; // now sort them for(int i = 1; i < r; ++i){ for(int j = 1; j < r-i;++j){ if(Math.abs(b[idxs[j-1]]) < Math.abs(b[idxs[j]])){ int jj = idxs[j]; idxs[j] = idxs[j-1]; idxs[j-1] = jj; } } } } else idxs = null; rank = r; } } @API(help = "models computed for particular lambda values") Submodel [] submodels; private static final DecimalFormat DFORMAT = new DecimalFormat("###.####"); public GLMModel(Key selfKey, Frame fr, int [] catOffsets, GLMParams glm, double beta_eps, double alpha, double [] lambda, double ymu, CaseMode caseMode, double caseVal ) { super(selfKey,null,fr); this.ymu = ymu; this.glm = glm; threshold = 0.5; this.catOffsets = catOffsets; this.warnings = null; this.alpha = alpha; this.beta_eps = beta_eps; _caseVal = caseVal; _caseMode = caseMode; submodels = new Submodel[lambda.length]; for(int i = 0; i < submodels.length; ++i) submodels[i] = new Submodel(lambda[i], null, null, 0, 0); run_time = 0; start_time = System.currentTimeMillis(); } public void setLambdaSubmodel(int lambdaIdx,double lambda, double [] beta, double [] norm_beta, int iteration){ submodels[lambdaIdx] = new Submodel(lambda, beta, norm_beta, run_time, iteration); run_time = (System.currentTimeMillis()-start_time); } // // public void setBeta(int lambdaIdx, double [] beta, double [] norm_beta){ // Submodel sm = submodels[lambdaIdx]; // sm.beta = beta; // sm.norm_beta = norm_beta; // } public double lambda(){ if(submodels == null)return Double.NaN; return submodels[best_lambda_idx].lambda; } public double lambdaMax(){ return submodels[0].lambda; } public double lambdaMin(){ return submodels[submodels.length-1].lambda; } public GLMValidation validation(){ return submodels[best_lambda_idx].validation; } public int iteration(){return submodels[best_lambda_idx].iteration;} public double [] beta(){return submodels[best_lambda_idx].beta;} public double [] beta(int i){return submodels[i].beta;} public double [] norm_beta(){return submodels[best_lambda_idx].norm_beta;} public double [] norm_beta(int i){return submodels[i].norm_beta;} @Override protected float[] score0(double[] data, float[] preds) { return score0(data,preds,best_lambda_idx); } protected float[] score0(double[] data, float[] preds, int lambdaIdx) { double eta = 0.0; final double [] b = beta(lambdaIdx); for(int i = 0; i < catOffsets.length-1; ++i) if(data[i] != 0) eta += b[catOffsets[i] + (int)(data[i]-1)]; final int noff = catOffsets[catOffsets.length-1] - catOffsets.length + 1; for(int i = catOffsets.length-1; i < data.length; ++i) eta += b[noff+i]*data[i]; eta += b[b.length-1]; // add intercept double mu = glm.linkInv(eta); preds[0] = (float)mu; if(glm.family == Family.binomial){ // threshold if(preds.length > 1)preds[1] = preds[0]; preds[0] = preds[0] >= threshold?1:0; } return preds; } public final int ncoefs() {return beta().length;} public static class GLMValidationTask<T extends GLMValidationTask<T>> extends MRTask2<T> { protected final GLMModel _model; protected GLMValidation _res; public int _lambdaIdx; public boolean _improved; public static Key makeKey(){return Key.make("__GLMValidation_" + Key.make().toString());} public GLMValidationTask(GLMModel model, int lambdaIdx){this(model,lambdaIdx,null);} public GLMValidationTask(GLMModel model, int lambdaIdx, H2OCountedCompleter completer){super(completer); _lambdaIdx = lambdaIdx; _model = model;} @Override public void map(Chunk [] chunks){ _res = new GLMValidation(null,_model.ymu,_model.glm,_model.rank(_lambdaIdx)); final int nrows = chunks[0]._len; double [] row = MemoryManager.malloc8d(_model._names.length); float [] preds = MemoryManager.malloc4f(_model.glm.family == Family.binomial?2:1); OUTER: for(int i = 0; i < nrows; ++i){ if(chunks[chunks.length-1].isNA0(i))continue; for(int j = 0; j < chunks.length-1; ++j){ if(chunks[j].isNA0(i))continue OUTER; row[j] = chunks[j].at0(i); } _model.score0(row, preds,_lambdaIdx); double response = chunks[chunks.length-1].at80(i); if(_model._caseMode != CaseMode.none) response = _model._caseMode.isCase(response, _model._caseVal)?1:0; _res.add(response, _model.glm.family == Family.binomial?preds[1]:preds[0]); } _res.avg_err /= _res.nobs; } @Override public void reduce(GLMValidationTask gval){_res.add(gval._res);} @Override public void postGlobal(){ _res.finalize_AIC_AUC(); _improved = _model.setAndTestValidation(_lambdaIdx, _res); UKV.put(_model._selfKey,_model); } } // use general score to reduce number of possible different code paths public static class GLMXValidationTask extends GLMValidationTask<GLMXValidationTask>{ protected final GLMModel [] _xmodels; protected GLMValidation [] _xvals; public static Key makeKey(){return Key.make("__GLMValidation_" + Key.make().toString());} public GLMXValidationTask(GLMModel mainModel,int lambdaIdx, GLMModel [] xmodels){this(mainModel,lambdaIdx,xmodels,null);} public GLMXValidationTask(GLMModel mainModel,int lambdaIdx, GLMModel [] xmodels, H2OCountedCompleter completer){super(mainModel, lambdaIdx, completer); _xmodels = xmodels;} @Override public void map(Chunk [] chunks){ _xvals = new GLMValidation[_xmodels.length]; for(int i = 0; i < _xmodels.length; ++i) _xvals[i] = new GLMValidation(null,_xmodels[i].ymu,_xmodels[i].glm,_xmodels[i].rank()); final int nrows = chunks[0]._len; double [] row = MemoryManager.malloc8d(_model._names.length); float [] preds = MemoryManager.malloc4f(_model.glm.family == Family.binomial?2:1); OUTER: for(int i = 0; i < nrows; ++i){ if(chunks[chunks.length-1].isNA0(i))continue; for(int j = 0; j < chunks.length-1; ++j){ if(chunks[j].isNA0(i))continue OUTER; row[j] = chunks[j].at0(i); } final int mid = i % _xmodels.length; final GLMModel model = _xmodels[mid]; final GLMValidation val = _xvals[mid]; model.score0(row, preds); double response = chunks[chunks.length-1].at80(i); if(model._caseMode != CaseMode.none) response = model._caseMode.isCase(response, model._caseVal)?1:0; val.add(response, model.glm.family == Family.binomial?preds[1]:preds[0]); } for(GLMValidation val:_xvals) if(val.nobs > 0)val.avg_err = Math.sqrt(val.avg_err)/val.nobs; } @Override public void reduce(GLMXValidationTask gval){ for(int i = 0; i < _xvals.length; ++i) _xvals[i].add(gval._xvals[i]);} @Override public void postGlobal(){ for(int i = 0; i < _xmodels.length; ++i){ _xvals[i].finalize_AIC_AUC(); _xmodels[i].setValidation(0, _xvals[i]); Futures fs = new Futures(); DKV.put(_xmodels[i]._selfKey, _xmodels[i],fs); _res = new GLMXValidation(_model, _xmodels,_lambdaIdx); _improved = _model.setAndTestValidation(_lambdaIdx, _res); DKV.put(_model._selfKey, _model); fs.blockForPending(); } } } public void generateHTML(String title, StringBuilder sb) { if(title != null && !title.isEmpty())DocGen.HTML.title(sb,title); DocGen.HTML.paragraph(sb,"Model Key: "+_selfKey); if(submodels != null) DocGen.HTML.paragraph(sb,water.api.Predict.link(_selfKey,"Predict!")); String succ = (warnings == null || warnings.length == 0)?"alert-success":"alert-warning"; sb.append("<div class='alert " + succ + "'>"); pprintTime(sb.append(iteration() + " iterations computed in "),run_time); if(warnings != null && warnings.length > 0){ sb.append("<b>Warnings:</b><ul>"); for(String w:warnings)sb.append("<li>" + w + "</li>"); sb.append("</ul>"); } sb.append("</div>"); sb.append("<h4>Parameters</h4>"); parm(sb,"family",glm.family); parm(sb,"link",glm.link); parm(sb,"&epsilon;<sub>&beta;</sub>",beta_eps); parm(sb,"&alpha;",alpha); parm(sb,"&lambda;",lambda()); if(beta() != null) coefs2html(sb); GLMValidation val = validation(); if(val != null)val.generateHTML("Training Set Validation", sb); } /** * get beta coefficients in a map indexed by name * @return */ public HashMap<String,Double> coefficients(){ String [] names = coefNames(); HashMap<String, Double> res = new HashMap<String, Double>(); final double [] b = beta(); if(b != null) for(int i = 0; i < b.length; ++i)res.put(names[i],b[i]); return res; } public String [] coefNames(){ final int cats = catOffsets.length-1; int k = 0; double [] b = beta(); if(b == null)return null; String [] res = new String[b.length]; for(int i = 0; i < cats; ++i) for(int j = 1; j < _domains[i].length; ++j) res[k++] = _names[i] + "." + _domains[i][j]; final int nums = b.length-k-1; for(int i = 0; i < nums; ++i) res[k+i] = _names[cats+i]; assert k + nums == res.length-1; res[k+nums] = "Intercept"; return res; } private static void parm( StringBuilder sb, String x, Object... y ) { sb.append("<span><b>").append(x).append(": </b>").append(y[0]).append("</span> "); } private void coefs2html(StringBuilder sb){ final Submodel sm = submodels[best_lambda_idx]; StringBuilder names = new StringBuilder(); StringBuilder equation = new StringBuilder(); StringBuilder vals = new StringBuilder(); StringBuilder normVals = sm.norm_beta == null?null:new StringBuilder(); String [] cNames = coefNames(); for(int i:sm.idxs){ names.append("<th>" + cNames[i] + "</th>"); vals.append("<td>" + sm.beta[i] + "</td>"); if(i != 0) equation.append(sm.beta[i] > 0?" + ":" - "); equation.append(DFORMAT.format(Math.abs(sm.beta[i]))); if(i < (cNames.length-1)) equation.append("*x[" + cNames[i] + "]"); if(sm.norm_beta != null) normVals.append("<td>" + sm.norm_beta[i] + "</td>"); } sb.append("<h4>Equation</h4>"); RString eq = null; switch( glm.link ) { case identity: eq = new RString("y = %equation"); break; case logit: eq = new RString("y = 1/(1 + Math.exp(-(%equation)))"); break; case log: eq = new RString("y = Math.exp((%equation)))"); break; case inverse: eq = new RString("y = 1/(%equation)"); break; case tweedie: eq = new RString("y = (%equation)^(1 - )"); break; default: eq = new RString("equation display not implemented"); break; } eq.replace("equation",equation.toString()); sb.append("<div style='width:100%;overflow:scroll;'>"); sb.append("<div><code>" + eq + "</code></div>"); sb.append("<h4>Coefficients</h4><table class='table table-bordered table-condensed'>"); sb.append("<tr>" + names.toString() + "</tr>"); sb.append("<tr>" + vals.toString() + "</tr>"); sb.append("</table>"); if(sm.norm_beta != null){ sb.append("<h4>Normalized Coefficients</h4>" + "<table class='table table-bordered table-condensed'>"); sb.append("<tr>" + names.toString() + "</tr>"); sb.append("<tr>" + normVals.toString() + "</tr>"); sb.append("</table>"); } sb.append("</div>"); } private void pprintTime(StringBuilder sb, long t){ long hrs = t / (1000*60*60); long minutes = (t -= 1000*60*60*hrs)/(1000*60); long seconds = (t -= 1000*60*minutes)/1000; t -= 1000*seconds; if(hrs > 0)sb.append(hrs + "hrs "); if(hrs > 0 || minutes > 0)sb.append(minutes + "min "); if(hrs > 0 || minutes > 0 | seconds > 0)sb.append(seconds + "sec "); sb.append(t + "msec"); } @Override public String toString(){ final double [] beta = beta(), norm_beta = norm_beta(); StringBuilder sb = new StringBuilder("GLM Model (key=" + _selfKey + " , trained on " + _dataKey + ", family = " + glm.family + ", link = " + glm.link + ", #iterations = " + iteration() + "):\n"); final int cats = catOffsets.length-1; int k = 0; for(int i = 0; i < cats; ++i) for(int j = 1; j < _domains[i].length; ++j) sb.append(_names[i] + "." + _domains[i][j] + ": " + beta[k++] + "\n"); final int nums = beta.length-k-1; for(int i = 0; i < nums; ++i) sb.append(_names[cats+i] + ": " + beta[k+i] + "\n"); sb.append("Intercept: " + beta[beta.length-1] + "\n"); return sb.toString(); } public int rank() {return rank(best_lambda_idx);} public int rank(int lambdaIdx) { final double [] beta = beta(lambdaIdx); if( beta == null ) return -1; int res = 0; for( double b : beta ) if( b != 0 ) ++res; return res; } @Override public void delete(){super.delete();} public void setValidation(int lambdaIdx,GLMValidation val ){ submodels[lambdaIdx].validation = val; } public boolean setAndTestValidation(int lambdaIdx,GLMValidation val ){ submodels[lambdaIdx].validation = val; if(lambdaIdx == 0 || rank(lambdaIdx) == 1) return true; double diff = submodels[best_lambda_idx].validation.residual_deviance - val.residual_deviance; if(diff/val.null_deviance >= 0.01) best_lambda_idx = lambdaIdx; return (diff >= 0); } }
src/main/java/hex/glm/GLMModel.java
package hex.glm; import hex.glm.GLMParams.CaseMode; import hex.glm.GLMParams.Family; import hex.glm.GLMValidation.GLMXValidation; import java.text.DecimalFormat; import java.util.HashMap; import water.*; import water.H2O.H2OCountedCompleter; import water.api.DocGen; import water.api.Request.API; import water.fvec.Chunk; import water.fvec.Frame; import water.util.RString; public class GLMModel extends Model implements Comparable<GLMModel> { static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. @API(help="mean of response in the training dataset") final double ymu; @API(help="predicate applied to the response column to turn it into 0/1") final CaseMode _caseMode; @API(help="value used to co compare agains using case-predicate to turn the response into 0/1") final double _caseVal; @API(help="offsets of categorical columns into the beta vector. The last value is the offset of the first numerical column.") final int [] catOffsets; @API(help="warnings") final String [] warnings; @API(help="Decision threshold.") final double threshold; @API(help="glm params") final GLMParams glm; @API(help="beta epsilon - stop iterating when beta diff is below this threshold.") final double beta_eps; @API(help="regularization parameter driving proportion of L1/L2 penalty.") final double alpha; @API(help="index of lambda giving best results") int best_lambda_idx; public double auc(){ if(glm.family == Family.binomial && submodels != null && submodels[best_lambda_idx].validation != null) return submodels[best_lambda_idx].validation.auc; return -1; } public double aic(){ if(submodels != null && submodels[best_lambda_idx].validation != null) return submodels[best_lambda_idx].validation.aic; return Double.MAX_VALUE; } public double devExplained(){ if(submodels == null || submodels[best_lambda_idx].validation == null) return 0; GLMValidation val = submodels[best_lambda_idx].validation; return 1.0 - val.residual_deviance/val.null_deviance; } @Override public int compareTo(GLMModel m){ // assert m._dataKey.equals(_dataKey); assert m.glm.family == glm.family; assert m.glm.link == glm.link; switch(glm.family){ case binomial: // compare by AUC, higher is better return (int)(1e6*(m.auc()-auc())); case gamma: // compare by percentage of explained deviance, higher is better return (int)(100*(m.devExplained()-devExplained())); default: // compare by AICs by default, lower is better return (int)(100*(aic()- m.aic())); } } @API(help="Overall run time") long run_time; @API(help="computation started at") long start_time; static class Submodel extends Iced { static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. @API(help="regularization param giving the strength of the applied regularization. high values drive coeffficients to zero.") final double lambda; @API(help="number of iterations computed.") final int iteration; @API(help="running time of the algo in ms.") final long run_time; @API(help="Validation") GLMValidation validation; @API(help="Beta vector containing model coefficients.") double [] beta; @API(help="Beta vector containing normalized coefficients (coefficients obtained on normalized data).") double [] norm_beta; public Submodel(double lambda, double [] beta, double [] norm_beta, long run_time, int iteration){ this.lambda = lambda; this.beta = beta; this.norm_beta = norm_beta; this.run_time = run_time; this.iteration = iteration; } } @API(help = "models computed for particular lambda values") Submodel [] submodels; private static final DecimalFormat DFORMAT = new DecimalFormat("###.####"); public GLMModel(Key selfKey, Frame fr, int [] catOffsets, GLMParams glm, double beta_eps, double alpha, double [] lambda, double ymu, CaseMode caseMode, double caseVal ) { super(selfKey,null,fr); this.ymu = ymu; this.glm = glm; threshold = 0.5; this.catOffsets = catOffsets; this.warnings = null; this.alpha = alpha; this.beta_eps = beta_eps; _caseVal = caseVal; _caseMode = caseMode; submodels = new Submodel[lambda.length]; for(int i = 0; i < submodels.length; ++i) submodels[i] = new Submodel(lambda[i], null, null, 0, 0); run_time = 0; start_time = System.currentTimeMillis(); } public void setLambdaSubmodel(int lambdaIdx,double lambda, double [] beta, double [] norm_beta, int iteration){ submodels[lambdaIdx] = new Submodel(lambda, beta, norm_beta, run_time, iteration); run_time = (System.currentTimeMillis()-start_time); } public void setBeta(int lambdaIdx, double [] beta, double [] norm_beta){ Submodel sm = submodels[lambdaIdx]; sm.beta = beta; sm.norm_beta = norm_beta; } public double lambda(){ if(submodels == null)return Double.NaN; return submodels[best_lambda_idx].lambda; } public double lambdaMax(){ return submodels[0].lambda; } public double lambdaMin(){ return submodels[submodels.length-1].lambda; } public GLMValidation validation(){ return submodels[best_lambda_idx].validation; } public int iteration(){return submodels[best_lambda_idx].iteration;} public double [] beta(){return submodels[best_lambda_idx].beta;} public double [] beta(int i){return submodels[i].beta;} public double [] norm_beta(){return submodels[best_lambda_idx].norm_beta;} public double [] norm_beta(int i){return submodels[i].norm_beta;} @Override protected float[] score0(double[] data, float[] preds) { return score0(data,preds,best_lambda_idx); } protected float[] score0(double[] data, float[] preds, int lambdaIdx) { double eta = 0.0; final double [] b = beta(lambdaIdx); for(int i = 0; i < catOffsets.length-1; ++i) if(data[i] != 0) eta += b[catOffsets[i] + (int)(data[i]-1)]; final int noff = catOffsets[catOffsets.length-1] - catOffsets.length + 1; for(int i = catOffsets.length-1; i < data.length; ++i) eta += b[noff+i]*data[i]; eta += b[b.length-1]; // add intercept double mu = glm.linkInv(eta); preds[0] = (float)mu; if(glm.family == Family.binomial){ // threshold if(preds.length > 1)preds[1] = preds[0]; preds[0] = preds[0] >= threshold?1:0; } return preds; } public final int ncoefs() {return beta().length;} public static class GLMValidationTask<T extends GLMValidationTask<T>> extends MRTask2<T> { protected final GLMModel _model; protected GLMValidation _res; public int _lambdaIdx; public boolean _improved; public static Key makeKey(){return Key.make("__GLMValidation_" + Key.make().toString());} public GLMValidationTask(GLMModel model, int lambdaIdx){this(model,lambdaIdx,null);} public GLMValidationTask(GLMModel model, int lambdaIdx, H2OCountedCompleter completer){super(completer); _lambdaIdx = lambdaIdx; _model = model;} @Override public void map(Chunk [] chunks){ _res = new GLMValidation(null,_model.ymu,_model.glm,_model.rank(_lambdaIdx)); final int nrows = chunks[0]._len; double [] row = MemoryManager.malloc8d(_model._names.length); float [] preds = MemoryManager.malloc4f(_model.glm.family == Family.binomial?2:1); OUTER: for(int i = 0; i < nrows; ++i){ if(chunks[chunks.length-1].isNA0(i))continue; for(int j = 0; j < chunks.length-1; ++j){ if(chunks[j].isNA0(i))continue OUTER; row[j] = chunks[j].at0(i); } _model.score0(row, preds,_lambdaIdx); double response = chunks[chunks.length-1].at80(i); if(_model._caseMode != CaseMode.none) response = _model._caseMode.isCase(response, _model._caseVal)?1:0; _res.add(response, _model.glm.family == Family.binomial?preds[1]:preds[0]); } _res.avg_err /= _res.nobs; } @Override public void reduce(GLMValidationTask gval){_res.add(gval._res);} @Override public void postGlobal(){ _res.finalize_AIC_AUC(); _improved = _model.setAndTestValidation(_lambdaIdx, _res); UKV.put(_model._selfKey,_model); } } // use general score to reduce number of possible different code paths public static class GLMXValidationTask extends GLMValidationTask<GLMXValidationTask>{ protected final GLMModel [] _xmodels; protected GLMValidation [] _xvals; public static Key makeKey(){return Key.make("__GLMValidation_" + Key.make().toString());} public GLMXValidationTask(GLMModel mainModel,int lambdaIdx, GLMModel [] xmodels){this(mainModel,lambdaIdx,xmodels,null);} public GLMXValidationTask(GLMModel mainModel,int lambdaIdx, GLMModel [] xmodels, H2OCountedCompleter completer){super(mainModel, lambdaIdx, completer); _xmodels = xmodels;} @Override public void map(Chunk [] chunks){ _xvals = new GLMValidation[_xmodels.length]; for(int i = 0; i < _xmodels.length; ++i) _xvals[i] = new GLMValidation(null,_xmodels[i].ymu,_xmodels[i].glm,_xmodels[i].rank()); final int nrows = chunks[0]._len; double [] row = MemoryManager.malloc8d(_model._names.length); float [] preds = MemoryManager.malloc4f(_model.glm.family == Family.binomial?2:1); OUTER: for(int i = 0; i < nrows; ++i){ if(chunks[chunks.length-1].isNA0(i))continue; for(int j = 0; j < chunks.length-1; ++j){ if(chunks[j].isNA0(i))continue OUTER; row[j] = chunks[j].at0(i); } final int mid = i % _xmodels.length; final GLMModel model = _xmodels[mid]; final GLMValidation val = _xvals[mid]; model.score0(row, preds); double response = chunks[chunks.length-1].at80(i); if(model._caseMode != CaseMode.none) response = model._caseMode.isCase(response, model._caseVal)?1:0; val.add(response, model.glm.family == Family.binomial?preds[1]:preds[0]); } for(GLMValidation val:_xvals) if(val.nobs > 0)val.avg_err = Math.sqrt(val.avg_err)/val.nobs; } @Override public void reduce(GLMXValidationTask gval){ for(int i = 0; i < _xvals.length; ++i) _xvals[i].add(gval._xvals[i]);} @Override public void postGlobal(){ for(int i = 0; i < _xmodels.length; ++i){ _xvals[i].finalize_AIC_AUC(); _xmodels[i].setValidation(0, _xvals[i]); Futures fs = new Futures(); DKV.put(_xmodels[i]._selfKey, _xmodels[i],fs); _res = new GLMXValidation(_model, _xmodels,_lambdaIdx); _improved = _model.setAndTestValidation(_lambdaIdx, _res); DKV.put(_model._selfKey, _model); fs.blockForPending(); } } } public void generateHTML(String title, StringBuilder sb) { if(title != null && !title.isEmpty())DocGen.HTML.title(sb,title); DocGen.HTML.paragraph(sb,"Model Key: "+_selfKey); if(submodels != null) DocGen.HTML.paragraph(sb,water.api.Predict.link(_selfKey,"Predict!")); String succ = (warnings == null || warnings.length == 0)?"alert-success":"alert-warning"; sb.append("<div class='alert " + succ + "'>"); pprintTime(sb.append(iteration() + " iterations computed in "),run_time); if(warnings != null && warnings.length > 0){ sb.append("<b>Warnings:</b><ul>"); for(String w:warnings)sb.append("<li>" + w + "</li>"); sb.append("</ul>"); } sb.append("</div>"); sb.append("<h4>Parameters</h4>"); parm(sb,"family",glm.family); parm(sb,"link",glm.link); parm(sb,"&epsilon;<sub>&beta;</sub>",beta_eps); parm(sb,"&alpha;",alpha); parm(sb,"&lambda;",lambda()); if(beta() != null) coefs2html(sb); GLMValidation val = validation(); if(val != null)val.generateHTML("Training Set Validation", sb); } /** * get beta coefficients in a map indexed by name * @return */ public HashMap<String,Double> coefficients(){ String [] names = coefNames(); HashMap<String, Double> res = new HashMap<String, Double>(); final double [] b = beta(); if(b != null) for(int i = 0; i < b.length; ++i)res.put(names[i],b[i]); return res; } public String [] coefNames(){ final int cats = catOffsets.length-1; int k = 0; double [] b = beta(); if(b == null)return null; String [] res = new String[b.length]; for(int i = 0; i < cats; ++i) for(int j = 1; j < _domains[i].length; ++j) res[k++] = _names[i] + "." + _domains[i][j]; final int nums = b.length-k-1; for(int i = 0; i < nums; ++i) res[k+i] = _names[cats+i]; assert k + nums == res.length-1; res[k+nums] = "Intercept"; return res; } private static void parm( StringBuilder sb, String x, Object... y ) { sb.append("<span><b>").append(x).append(": </b>").append(y[0]).append("</span> "); } private void coefs2html(StringBuilder sb){ final double [] beta = beta(), norm_beta = norm_beta(); StringBuilder names = new StringBuilder(); StringBuilder equation = new StringBuilder(); StringBuilder vals = new StringBuilder(); StringBuilder normVals = norm_beta == null?null:new StringBuilder(); String [] cNames = coefNames(); for(int i = 0; i < cNames.length; ++i){ names.append("<th>" + cNames[i] + "</th>"); vals.append("<td>" + beta[i] + "</td>"); if(i != 0) equation.append(beta[i] > 0?" + ":" - "); equation.append(DFORMAT.format(Math.abs(beta[i]))); if(i < (cNames.length-1)) equation.append("*x[" + cNames[i] + "]"); if(norm_beta != null) normVals.append("<td>" + norm_beta[i] + "</td>"); } sb.append("<h4>Equation</h4>"); RString eq = null; switch( glm.link ) { case identity: eq = new RString("y = %equation"); break; case logit: eq = new RString("y = 1/(1 + Math.exp(-(%equation)))"); break; case log: eq = new RString("y = Math.exp((%equation)))"); break; case inverse: eq = new RString("y = 1/(%equation)"); break; case tweedie: eq = new RString("y = (%equation)^(1 - )"); break; default: eq = new RString("equation display not implemented"); break; } eq.replace("equation",equation.toString()); sb.append("<div style='width:100%;overflow:scroll;'>"); sb.append("<div><code>" + eq + "</code></div>"); sb.append("<h4>Coefficients</h4><table class='table table-bordered table-condensed'>"); sb.append("<tr>" + names.toString() + "</tr>"); sb.append("<tr>" + vals.toString() + "</tr>"); sb.append("</table>"); if(norm_beta != null){ sb.append("<h4>Normalized Coefficients</h4>" + "<table class='table table-bordered table-condensed'>"); sb.append("<tr>" + names.toString() + "</tr>"); sb.append("<tr>" + normVals.toString() + "</tr>"); sb.append("</table>"); } sb.append("</div>"); } private void pprintTime(StringBuilder sb, long t){ long hrs = t / (1000*60*60); long minutes = (t -= 1000*60*60*hrs)/(1000*60); long seconds = (t -= 1000*60*minutes)/1000; t -= 1000*seconds; if(hrs > 0)sb.append(hrs + "hrs "); if(hrs > 0 || minutes > 0)sb.append(minutes + "min "); if(hrs > 0 || minutes > 0 | seconds > 0)sb.append(seconds + "sec "); sb.append(t + "msec"); } @Override public String toString(){ final double [] beta = beta(), norm_beta = norm_beta(); StringBuilder sb = new StringBuilder("GLM Model (key=" + _selfKey + " , trained on " + _dataKey + ", family = " + glm.family + ", link = " + glm.link + ", #iterations = " + iteration() + "):\n"); final int cats = catOffsets.length-1; int k = 0; for(int i = 0; i < cats; ++i) for(int j = 1; j < _domains[i].length; ++j) sb.append(_names[i] + "." + _domains[i][j] + ": " + beta[k++] + "\n"); final int nums = beta.length-k-1; for(int i = 0; i < nums; ++i) sb.append(_names[cats+i] + ": " + beta[k+i] + "\n"); sb.append("Intercept: " + beta[beta.length-1] + "\n"); return sb.toString(); } public int rank() {return rank(best_lambda_idx);} public int rank(int lambdaIdx) { final double [] beta = beta(lambdaIdx); if( beta == null ) return -1; int res = 0; for( double b : beta ) if( b != 0 ) ++res; return res; } @Override public void delete(){super.delete();} public void setValidation(int lambdaIdx,GLMValidation val ){ submodels[lambdaIdx].validation = val; } public boolean setAndTestValidation(int lambdaIdx,GLMValidation val ){ submodels[lambdaIdx].validation = val; if(lambdaIdx == 0 || rank(lambdaIdx) == 1) return true; double diff = submodels[best_lambda_idx].validation.residual_deviance - val.residual_deviance; if(diff/val.null_deviance >= 0.01) best_lambda_idx = lambdaIdx; return (diff >= 0); } }
Added sorting of coefficients in GLM2.
src/main/java/hex/glm/GLMModel.java
Added sorting of coefficients in GLM2.
<ide><path>rc/main/java/hex/glm/GLMModel.java <ide> @API(help="Beta vector containing model coefficients.") double [] beta; <ide> @API(help="Beta vector containing normalized coefficients (coefficients obtained on normalized data).") double [] norm_beta; <ide> <del> <add> final int rank; <add> final int [] idxs; <ide> <ide> public Submodel(double lambda, double [] beta, double [] norm_beta, long run_time, int iteration){ <ide> this.lambda = lambda; <ide> this.norm_beta = norm_beta; <ide> this.run_time = run_time; <ide> this.iteration = iteration; <add> int r = 0; <add> if(beta != null){ <add> final double [] b = norm_beta != null?norm_beta:beta; <add> // grab the indeces of non-zero coefficients <add> for(double d:beta)if(d != 0)++r; <add> idxs = new int[r]; <add> int ii = 0; <add> for(int i = 0; i < b.length; ++i)if(b[i] != 0)idxs[ii++] = i; <add> // now sort them <add> for(int i = 1; i < r; ++i){ <add> for(int j = 1; j < r-i;++j){ <add> if(Math.abs(b[idxs[j-1]]) < Math.abs(b[idxs[j]])){ <add> int jj = idxs[j]; <add> idxs[j] = idxs[j-1]; <add> idxs[j-1] = jj; <add> } <add> } <add> } <add> <add> } else idxs = null; <add> rank = r; <ide> } <ide> } <ide> <ide> submodels[lambdaIdx] = new Submodel(lambda, beta, norm_beta, run_time, iteration); <ide> run_time = (System.currentTimeMillis()-start_time); <ide> } <del> <del> public void setBeta(int lambdaIdx, double [] beta, double [] norm_beta){ <del> Submodel sm = submodels[lambdaIdx]; <del> sm.beta = beta; <del> sm.norm_beta = norm_beta; <del> } <add>// <add>// public void setBeta(int lambdaIdx, double [] beta, double [] norm_beta){ <add>// Submodel sm = submodels[lambdaIdx]; <add>// sm.beta = beta; <add>// sm.norm_beta = norm_beta; <add>// } <ide> <ide> public double lambda(){ <ide> if(submodels == null)return Double.NaN; <ide> sb.append("<span><b>").append(x).append(": </b>").append(y[0]).append("</span> "); <ide> } <ide> private void coefs2html(StringBuilder sb){ <del> final double [] beta = beta(), norm_beta = norm_beta(); <add> final Submodel sm = submodels[best_lambda_idx]; <add> <ide> StringBuilder names = new StringBuilder(); <ide> StringBuilder equation = new StringBuilder(); <ide> StringBuilder vals = new StringBuilder(); <del> StringBuilder normVals = norm_beta == null?null:new StringBuilder(); <add> StringBuilder normVals = sm.norm_beta == null?null:new StringBuilder(); <ide> String [] cNames = coefNames(); <del> for(int i = 0; i < cNames.length; ++i){ <add> for(int i:sm.idxs){ <ide> names.append("<th>" + cNames[i] + "</th>"); <del> vals.append("<td>" + beta[i] + "</td>"); <add> vals.append("<td>" + sm.beta[i] + "</td>"); <ide> if(i != 0) <del> equation.append(beta[i] > 0?" + ":" - "); <del> equation.append(DFORMAT.format(Math.abs(beta[i]))); <add> equation.append(sm.beta[i] > 0?" + ":" - "); <add> equation.append(DFORMAT.format(Math.abs(sm.beta[i]))); <ide> if(i < (cNames.length-1)) <ide> equation.append("*x[" + cNames[i] + "]"); <del> if(norm_beta != null) normVals.append("<td>" + norm_beta[i] + "</td>"); <add> if(sm.norm_beta != null) normVals.append("<td>" + sm.norm_beta[i] + "</td>"); <ide> } <ide> sb.append("<h4>Equation</h4>"); <ide> RString eq = null; <ide> sb.append("<tr>" + names.toString() + "</tr>"); <ide> sb.append("<tr>" + vals.toString() + "</tr>"); <ide> sb.append("</table>"); <del> if(norm_beta != null){ <add> if(sm.norm_beta != null){ <ide> sb.append("<h4>Normalized Coefficients</h4>" + <ide> "<table class='table table-bordered table-condensed'>"); <ide> sb.append("<tr>" + names.toString() + "</tr>");
Java
apache-2.0
57277e469de709509c19e938b03e400e08e20af6
0
jitsi/jitsi,level7systems/jitsi,jibaro/jitsi,HelioGuilherme66/jitsi,laborautonomo/jitsi,mckayclarey/jitsi,mckayclarey/jitsi,bebo/jitsi,marclaporte/jitsi,tuijldert/jitsi,bebo/jitsi,jitsi/jitsi,459below/jitsi,HelioGuilherme66/jitsi,Metaswitch/jitsi,459below/jitsi,dkcreinoso/jitsi,mckayclarey/jitsi,HelioGuilherme66/jitsi,ibauersachs/jitsi,Metaswitch/jitsi,ringdna/jitsi,dkcreinoso/jitsi,cobratbq/jitsi,gpolitis/jitsi,mckayclarey/jitsi,459below/jitsi,cobratbq/jitsi,damencho/jitsi,bebo/jitsi,ibauersachs/jitsi,gpolitis/jitsi,gpolitis/jitsi,459below/jitsi,martin7890/jitsi,laborautonomo/jitsi,jitsi/jitsi,dkcreinoso/jitsi,martin7890/jitsi,level7systems/jitsi,pplatek/jitsi,jibaro/jitsi,iant-gmbh/jitsi,pplatek/jitsi,marclaporte/jitsi,gpolitis/jitsi,laborautonomo/jitsi,level7systems/jitsi,level7systems/jitsi,Metaswitch/jitsi,damencho/jitsi,jibaro/jitsi,bebo/jitsi,laborautonomo/jitsi,procandi/jitsi,procandi/jitsi,procandi/jitsi,jitsi/jitsi,tuijldert/jitsi,procandi/jitsi,martin7890/jitsi,jibaro/jitsi,jibaro/jitsi,ringdna/jitsi,ringdna/jitsi,gpolitis/jitsi,ibauersachs/jitsi,tuijldert/jitsi,jitsi/jitsi,HelioGuilherme66/jitsi,tuijldert/jitsi,dkcreinoso/jitsi,iant-gmbh/jitsi,bhatvv/jitsi,HelioGuilherme66/jitsi,damencho/jitsi,bhatvv/jitsi,laborautonomo/jitsi,bhatvv/jitsi,damencho/jitsi,mckayclarey/jitsi,martin7890/jitsi,459below/jitsi,damencho/jitsi,level7systems/jitsi,cobratbq/jitsi,Metaswitch/jitsi,martin7890/jitsi,cobratbq/jitsi,bebo/jitsi,iant-gmbh/jitsi,ringdna/jitsi,ibauersachs/jitsi,pplatek/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,tuijldert/jitsi,marclaporte/jitsi,ibauersachs/jitsi,ringdna/jitsi,cobratbq/jitsi,iant-gmbh/jitsi,bhatvv/jitsi,marclaporte/jitsi,dkcreinoso/jitsi,procandi/jitsi,pplatek/jitsi,pplatek/jitsi,bhatvv/jitsi
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.slick.protocol.sip; import junit.framework.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.service.protocol.*; import java.text.ParseException; import net.java.sip.communicator.service.protocol.event.*; import java.util.*; /** * Tests Basic telephony functionality by making one provider call the other. * * @author Emil Ivov */ public class TestOperationSetBasicTelephonySipImpl extends TestCase { private static final Logger logger = Logger.getLogger(TestOperationSetBasicTelephonySipImpl.class); /** * */ private SipSlickFixture fixture = new SipSlickFixture(); /** * Initializes the test with the specified <tt>name</tt>. * * @param name the name of the test to initialize. */ public TestOperationSetBasicTelephonySipImpl(String name) { super(name); } /** * JUnit setup method. * @throws Exception in case anything goes wrong. */ protected void setUp() throws Exception { super.setUp(); fixture.setUp(); } /** * JUnit teardown method. * @throws Exception in case anything goes wrong. */ protected void tearDown() throws Exception { fixture.tearDown(); super.tearDown(); } /** * Creates a call from provider1 to provider2 then cancels it without * waiting for provider1 to answer. * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void testCreateCancelCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call participants are properly created assertEquals("callAtP1.getCallParticipantsCount()" , 1, callAtP1.getCallParticipantsCount()); assertEquals("callAtP2.getCallParticipantsCount()" , 1, callAtP2.getCallParticipantsCount()); CallParticipant participantAtP1 = (CallParticipant)callAtP1.getCallParticipants().next(); CallParticipant participantAtP2 = (CallParticipant)callAtP2.getCallParticipants().next(); //now add listeners to the participants and make sure they have entered //the states they were expected to. //check states for call participants at both parties CallParticipantStateEventCollector stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.ALERTING_REMOTE_SIDE); CallParticipantStateEventCollector stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("participantAtP1.getCall" , participantAtP1.getCall(), callAtP1); assertSame("participantAtP2.getCall" , participantAtP2.getCall(), callAtP2); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.ALERTING_REMOTE_SIDE , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.INCOMING_CALL , participantAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) { //check properties on the remote call participant for the party that //initiated the call. String expectedParticipant1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedParticipant1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant1Address.indexOf( participantAtP1.getAddress()) != -1 || participantAtP1.getAddress().indexOf( expectedParticipant1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedParticipant1DisplayName , participantAtP1.getDisplayName()); //check properties on the remote call participant for the party that //receives the call. String expectedParticipant2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedParticipant2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant2Address.indexOf( participantAtP2.getAddress()) != -1 || participantAtP2.getAddress().indexOf( expectedParticipant2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedParticipant2DisplayName , participantAtP2.getDisplayName()); } //we'll now try to cancel the call //listeners monitoring state change of the participant stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.DISCONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.DISCONNECTED); //listeners waiting for the op set to announce the end of the call call1Listener = new CallEventCollector(basicTelephonyP1); call2Listener = new CallEventCollector(basicTelephonyP2); //listeners monitoring the state of the call CallStateEventCollector call1StateCollector = new CallStateEventCollector(callAtP1, CallState.CALL_ENDED); CallStateEventCollector call2StateCollector = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); //Now make the caller CANCEL the call. basicTelephonyP1.hangupCallParticipant(participantAtP1); //wait for everything to happen call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); call1StateCollector.waitForEvent(10000); call2StateCollector.waitForEvent(10000); //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP1.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call1Listener.collectedEvents.size()); CallEvent collectedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //same for provider 2 //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP2.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call2Listener.collectedEvents.size()); collectedEvent = (CallEvent)call2Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //make sure that the call objects are in an ENDED state. assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP1.getCallState()); assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP2.getCallState()); } /** * Creates a call from provider1 to provider2 then rejects the call from the * side of provider2 (provider2 replies with busy-tone). * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void testCreateRejectCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call participants are properly created assertEquals("callAtP1.getCallParticipantsCount()" , 1, callAtP1.getCallParticipantsCount()); assertEquals("callAtP2.getCallParticipantsCount()" , 1, callAtP2.getCallParticipantsCount()); CallParticipant participantAtP1 = (CallParticipant)callAtP1.getCallParticipants().next(); CallParticipant participantAtP2 = (CallParticipant)callAtP2.getCallParticipants().next(); //now add listeners to the participants and make sure they have entered //the states they were expected to. //check states for call participants at both parties CallParticipantStateEventCollector stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.ALERTING_REMOTE_SIDE); CallParticipantStateEventCollector stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("participantAtP1.getCall" , participantAtP1.getCall(), callAtP1); assertSame("participantAtP2.getCall" , participantAtP2.getCall(), callAtP2); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.ALERTING_REMOTE_SIDE , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.INCOMING_CALL , participantAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) { //check properties on the remote call participant for the party that //initiated the call. String expectedParticipant1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedParticipant1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant1Address.indexOf( participantAtP1.getAddress()) != -1 || participantAtP1.getAddress().indexOf( expectedParticipant1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedParticipant1DisplayName , participantAtP1.getDisplayName()); //check properties on the remote call participant for the party that //receives the call. String expectedParticipant2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedParticipant2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant2Address.indexOf( participantAtP2.getAddress()) != -1 || participantAtP2.getAddress().indexOf( expectedParticipant2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedParticipant2DisplayName , participantAtP2.getDisplayName()); } //we'll now try to send busy tone. //listeners monitoring state change of the participant CallParticipantStateEventCollector busyStateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.BUSY); stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.DISCONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.DISCONNECTED); //listeners waiting for the op set to announce the end of the call call1Listener = new CallEventCollector(basicTelephonyP1); call2Listener = new CallEventCollector(basicTelephonyP2); //listeners monitoring the state of the call CallStateEventCollector call1StateCollector = new CallStateEventCollector(callAtP1, CallState.CALL_ENDED); CallStateEventCollector call2StateCollector = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); //Now make the caller CANCEL the call. basicTelephonyP2.hangupCallParticipant(participantAtP2); busyStateCollectorForPp1.waitForEvent(10000); basicTelephonyP1.hangupCallParticipant(participantAtP1); //wait for everything to happen call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); call1StateCollector.waitForEvent(10000); call2StateCollector.waitForEvent(10000); //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP1.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call1Listener.collectedEvents.size()); CallEvent collectedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //same for provider 2 //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP2.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call2Listener.collectedEvents.size()); collectedEvent = (CallEvent)call2Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //make sure that the call objects are in an ENDED state. assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP1.getCallState()); assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP2.getCallState()); } /** * Creates a call from provider1 to provider2, makes provider2 answer it * and then reject it. * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void aTestCreateAnswerHangupCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call participants are properly created assertEquals("callAtP1.getCallParticipantsCount()" , 1, callAtP1.getCallParticipantsCount()); assertEquals("callAtP2.getCallParticipantsCount()" , 1, callAtP2.getCallParticipantsCount()); CallParticipant participantAtP1 = (CallParticipant)callAtP1.getCallParticipants().next(); CallParticipant participantAtP2 = (CallParticipant)callAtP2.getCallParticipants().next(); //now add listeners to the participants and make sure they have entered //the states they were expected to. //check states for call participants at both parties CallParticipantStateEventCollector stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.ALERTING_REMOTE_SIDE); CallParticipantStateEventCollector stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("participantAtP1.getCall" , participantAtP1.getCall(), callAtP1); assertSame("participantAtP2.getCall" , participantAtP2.getCall(), callAtP2); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.ALERTING_REMOTE_SIDE , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.INCOMING_CALL , participantAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) { //check properties on the remote call participant for the party that //initiated the call. String expectedParticipant1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedParticipant1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant1Address.indexOf( participantAtP1.getAddress()) != -1 || participantAtP1.getAddress().indexOf( expectedParticipant1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedParticipant1DisplayName , participantAtP1.getDisplayName()); //check properties on the remote call participant for the party that //receives the call. String expectedParticipant2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedParticipant2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant2Address.indexOf( participantAtP2.getAddress()) != -1 || participantAtP2.getAddress().indexOf( expectedParticipant2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedParticipant2DisplayName , participantAtP2.getDisplayName()); } //add listeners to the participants and make sure enter //a connected state after we answer stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.CONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.CONNECTED); //we will now anser the call and verify that both parties change states //accordingly. basicTelephonyP2.answerCallParticipant(participantAtP2); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.CONNECTED , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.CONNECTED , participantAtP2.getState()); //make sure that events have been distributed when states were changed. assertEquals("No event was dispatched when a call participant changed " +"its state." , 1 , stateCollectorForPp1.collectedEvents.size()); assertEquals("No event was dispatched when a call participant changed " +"its state." , 1 , stateCollectorForPp2.collectedEvents.size()); //add listeners to the participants and make sure they have entered //the states they are expected to. stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.DISCONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.DISCONNECTED); //we will now end the call and verify that both parties change states //accordingly. basicTelephonyP2.hangupCallParticipant(participantAtP2); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP2.getState()); //make sure that the corresponding events were delivered. assertEquals("a provider did not distribute an event when a call " +"participant changed states." , 1 , stateCollectorForPp1.collectedEvents.size()); assertEquals("a provider did not distribute an event when a call " +"participant changed states." , 1 , stateCollectorForPp2.collectedEvents.size()); } /** * Allows tests to wait for and collect events issued upon creation and * reception of calls. */ public class CallEventCollector implements CallListener { public ArrayList collectedEvents = new ArrayList(); public OperationSetBasicTelephony listenedOpSet = null; /** * Creates an instance of this call event collector and registers it * with listenedOpSet. * @param listenedOpSet the operation set that we will be scanning for * new calls. */ public CallEventCollector(OperationSetBasicTelephony listenedOpSet) { this.listenedOpSet = listenedOpSet; this.listenedOpSet.addCallListener(this); } /** * Blocks until at least one event is received or until waitFor * miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { logger.trace("Waiting for a CallEvent"); synchronized(this) { if(collectedEvents.size() > 0){ logger.trace("Event already received. " + collectedEvents); listenedOpSet.removeCallListener(this); return; } try{ wait(waitFor); if(collectedEvents.size() > 0) logger.trace("Received a CallEvent."); else logger.trace("No CallEvent received for "+waitFor+"ms."); listenedOpSet.removeCallListener(this); } catch (InterruptedException ex) { logger.debug( "Interrupted while waiting for a call event", ex); } } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void incomingCallReceived(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void outgoingCallCreated(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void callEnded(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } } /** * Allows tests to wait for and collect events issued upon call participant * status changes. */ public class CallParticipantStateEventCollector implements CallParticipantListener { public ArrayList collectedEvents = new ArrayList(); private CallParticipant listenedCallParticipant = null; public CallParticipantState awaitedState = null; /** * Creates an instance of this collector and adds it as a listener * to <tt>callParticipant</tt>. * @param callParticipant the CallParticipant that we will be listening * to. * @param awaitedState the state that we will be waiting for inside * this collector. */ public CallParticipantStateEventCollector( CallParticipant callParticipant, CallParticipantState awaitedState) { this.listenedCallParticipant = callParticipant; this.listenedCallParticipant.addCallParticipantListener(this); this.awaitedState = awaitedState; } /** * Stores the received event and notifies all waiting on this object * * @param event the event containing the source call. */ public void participantStateChanged(CallParticipantChangeEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); if(((CallParticipantState)event.getNewValue()) .equals(awaitedState)) { this.collectedEvents.add(event); notifyAll(); } } } /** * Unused by this collector. * @param event ignored. */ public void participantImageChanged(CallParticipantChangeEvent event) {} /** * Unused by this collector * @param event ignored. */ public void participantAddressChanged(CallParticipantChangeEvent event) {} /** * Unused by this collector * @param event ignored. */ public void participantTransportAddressChanged( CallParticipantChangeEvent event) {} /** * Unused by this collector * @param event ignored. */ public void participantDisplayNameChanged( CallParticipantChangeEvent event) {} /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { waitForEvent(waitFor, false); } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. * @param exitIfAlreadyInState specifies whether the method is to return * if the call participant is already in such a state even if no event * has been received for the sate change. */ public void waitForEvent(long waitFor, boolean exitIfAlreadyInState) { logger.trace("Waiting for a CallParticipantEvent with newState=" + awaitedState + " for participant " + this.listenedCallParticipant); synchronized (this) { if(exitIfAlreadyInState && listenedCallParticipant.getState().equals(awaitedState)) { logger.trace("Src participant is already in the awaited " + "state." + collectedEvents); listenedCallParticipant.removeCallParticipantListener(this); return; } if(collectedEvents.size() > 0) { CallParticipantChangeEvent lastEvent = (CallParticipantChangeEvent) collectedEvents .get(collectedEvents.size() - 1); if (lastEvent.getNewValue().equals(awaitedState)) { logger.trace("Event already received. " + collectedEvents); listenedCallParticipant .removeCallParticipantListener(this); return; } } try { wait(waitFor); if (collectedEvents.size() > 0) logger.trace("Received a CallParticpantStateEvent."); else logger.trace("No CallParticpantStateEvent received for " + waitFor + "ms."); listenedCallParticipant .removeCallParticipantListener(this); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a " + "CallParticpantEvent" , ex); } } } } /** * Allows tests to wait for and collect events issued upon call state * changes. */ public class CallStateEventCollector implements CallChangeListener { public ArrayList collectedEvents = new ArrayList(); private Call listenedCall = null; public CallState awaitedState = null; /** * Creates an instance of this collector and adds it as a listener * to <tt>call</tt>. * @param call the Call that we will be listening to. * @param awaitedState the state that we will be waiting for inside * this collector. */ public CallStateEventCollector(Call call, CallState awaitedState) { this.listenedCall = call; this.listenedCall.addCallChangeListener(this); this.awaitedState = awaitedState; } /** * Stores the received event and notifies all waiting on this object * * @param event the event containing the source call. */ public void callStateChanged(CallChangeEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); if(((CallState)event.getNewValue()).equals(awaitedState)) { this.collectedEvents.add(event); notifyAll(); } } } /** * Unused by this collector. * @param event ignored. */ public void callParticipantAdded(CallParticipantEvent event) { } /** * Unused by this collector. * @param event ignored. */ public void callParticipantRemoved(CallParticipantEvent event) { } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { logger.trace("Waiting for a CallParticpantEvent"); synchronized (this) { if (listenedCall.getCallState() == awaitedState) { logger.trace("Event already received. " + collectedEvents); listenedCall.removeCallChangeListener(this); return; } try { wait(waitFor); if (collectedEvents.size() > 0) logger.trace("Received a CallChangeEvent."); else logger.trace("No CallChangeEvent received for " + waitFor + "ms."); listenedCall.removeCallChangeListener(this); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a " + "CallParticpantEvent" , ex); } } } } }
test/net/java/sip/communicator/slick/protocol/sip/TestOperationSetBasicTelephonySipImpl.java
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.slick.protocol.sip; import junit.framework.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.service.protocol.*; import java.text.ParseException; import net.java.sip.communicator.service.protocol.event.*; import java.util.*; /** * Tests Basic telephony functionality by making one provider call the other. * * @author Emil Ivov */ public class TestOperationSetBasicTelephonySipImpl extends TestCase { private static final Logger logger = Logger.getLogger(TestOperationSetBasicTelephonySipImpl.class); /** * */ private SipSlickFixture fixture = new SipSlickFixture(); /** * Initializes the test with the specified <tt>name</tt>. * * @param name the name of the test to initialize. */ public TestOperationSetBasicTelephonySipImpl(String name) { super(name); } /** * JUnit setup method. * @throws Exception in case anything goes wrong. */ protected void setUp() throws Exception { super.setUp(); fixture.setUp(); } /** * JUnit teardown method. * @throws Exception in case anything goes wrong. */ protected void tearDown() throws Exception { fixture.tearDown(); super.tearDown(); } /** * Creates a call from provider1 to provider2 then cancels it without * waiting for provider1 to answer. * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void testCreateCancelCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call participants are properly created assertEquals("callAtP1.getCallParticipantsCount()" , 1, callAtP1.getCallParticipantsCount()); assertEquals("callAtP2.getCallParticipantsCount()" , 1, callAtP2.getCallParticipantsCount()); CallParticipant participantAtP1 = (CallParticipant)callAtP1.getCallParticipants().next(); CallParticipant participantAtP2 = (CallParticipant)callAtP2.getCallParticipants().next(); //now add listeners to the participants and make sure they have entered //the states they were expected to. //check states for call participants at both parties CallParticipantStateEventCollector stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.ALERTING_REMOTE_SIDE); CallParticipantStateEventCollector stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("participantAtP1.getCall" , participantAtP1.getCall(), callAtP1); assertSame("participantAtP2.getCall" , participantAtP2.getCall(), callAtP2); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.ALERTING_REMOTE_SIDE , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.INCOMING_CALL , participantAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) { //check properties on the remote call participant for the party that //initiated the call. String expectedParticipant1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedParticipant1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant1Address.indexOf( participantAtP1.getAddress()) != -1 || participantAtP1.getAddress().indexOf( expectedParticipant1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedParticipant1DisplayName , participantAtP1.getDisplayName()); //check properties on the remote call participant for the party that //receives the call. String expectedParticipant2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedParticipant2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant2Address.indexOf( participantAtP2.getAddress()) != -1 || participantAtP2.getAddress().indexOf( expectedParticipant2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedParticipant2DisplayName , participantAtP2.getDisplayName()); } //we'll now try to cancel the call //listeners monitoring state change of the participant stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.DISCONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.DISCONNECTED); //listeners waiting for the op set to announce the end of the call call1Listener = new CallEventCollector(basicTelephonyP1); call2Listener = new CallEventCollector(basicTelephonyP2); //listeners monitoring the state of the call CallStateEventCollector call1StateCollector = new CallStateEventCollector(callAtP1, CallState.CALL_ENDED); CallStateEventCollector call2StateCollector = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); //Now make the caller CANCEL the call. basicTelephonyP1.hangupCallParticipant(participantAtP1); //wait for everything to happen call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); call1StateCollector.waitForEvent(10000); call2StateCollector.waitForEvent(10000); //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP1.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call1Listener.collectedEvents.size()); CallEvent collectedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //same for provider 2 //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP2.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call2Listener.collectedEvents.size()); collectedEvent = (CallEvent)call2Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //make sure that the call objects are in an ENDED state. assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP1.getCallState()); assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP2.getCallState()); } /** * Creates a call from provider1 to provider2 then rejects the call from the * side of provider2 (provider2 replies with busy-tone). * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void testCreateRejectCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call participants are properly created assertEquals("callAtP1.getCallParticipantsCount()" , 1, callAtP1.getCallParticipantsCount()); assertEquals("callAtP2.getCallParticipantsCount()" , 1, callAtP2.getCallParticipantsCount()); CallParticipant participantAtP1 = (CallParticipant)callAtP1.getCallParticipants().next(); CallParticipant participantAtP2 = (CallParticipant)callAtP2.getCallParticipants().next(); //now add listeners to the participants and make sure they have entered //the states they were expected to. //check states for call participants at both parties CallParticipantStateEventCollector stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.ALERTING_REMOTE_SIDE); CallParticipantStateEventCollector stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("participantAtP1.getCall" , participantAtP1.getCall(), callAtP1); assertSame("participantAtP2.getCall" , participantAtP2.getCall(), callAtP2); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.ALERTING_REMOTE_SIDE , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.INCOMING_CALL , participantAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) { //check properties on the remote call participant for the party that //initiated the call. String expectedParticipant1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedParticipant1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant1Address.indexOf( participantAtP1.getAddress()) != -1 || participantAtP1.getAddress().indexOf( expectedParticipant1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedParticipant1DisplayName , participantAtP1.getDisplayName()); //check properties on the remote call participant for the party that //receives the call. String expectedParticipant2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedParticipant2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant2Address.indexOf( participantAtP2.getAddress()) != -1 || participantAtP2.getAddress().indexOf( expectedParticipant2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedParticipant2DisplayName , participantAtP2.getDisplayName()); } //we'll now try to send busy tone. //listeners monitoring state change of the participant CallParticipantStateEventCollector busyStateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.BUSY); stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.DISCONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.DISCONNECTED); //listeners waiting for the op set to announce the end of the call call1Listener = new CallEventCollector(basicTelephonyP1); call2Listener = new CallEventCollector(basicTelephonyP2); //listeners monitoring the state of the call CallStateEventCollector call1StateCollector = new CallStateEventCollector(callAtP1, CallState.CALL_ENDED); CallStateEventCollector call2StateCollector = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); //Now make the caller CANCEL the call. basicTelephonyP2.hangupCallParticipant(participantAtP2); busyStateCollectorForPp1.waitForEvent(10000); basicTelephonyP1.hangupCallParticipant(participantAtP1); //wait for everything to happen call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); call1StateCollector.waitForEvent(10000); call2StateCollector.waitForEvent(10000); //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP1.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call1Listener.collectedEvents.size()); CallEvent collectedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //same for provider 2 //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP2.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call2Listener.collectedEvents.size()); collectedEvent = (CallEvent)call2Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //make sure that the call objects are in an ENDED state. assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP1.getCallState()); assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP2.getCallState()); } /** * Creates a call from provider1 to provider2, makes provider2 answer it * and then reject it. * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void testCreateAnswerHangupCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call participants are properly created assertEquals("callAtP1.getCallParticipantsCount()" , 1, callAtP1.getCallParticipantsCount()); assertEquals("callAtP2.getCallParticipantsCount()" , 1, callAtP2.getCallParticipantsCount()); CallParticipant participantAtP1 = (CallParticipant)callAtP1.getCallParticipants().next(); CallParticipant participantAtP2 = (CallParticipant)callAtP2.getCallParticipants().next(); //now add listeners to the participants and make sure they have entered //the states they were expected to. //check states for call participants at both parties CallParticipantStateEventCollector stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.ALERTING_REMOTE_SIDE); CallParticipantStateEventCollector stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("participantAtP1.getCall" , participantAtP1.getCall(), callAtP1); assertSame("participantAtP2.getCall" , participantAtP2.getCall(), callAtP2); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.ALERTING_REMOTE_SIDE , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.INCOMING_CALL , participantAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) { //check properties on the remote call participant for the party that //initiated the call. String expectedParticipant1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedParticipant1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant1Address.indexOf( participantAtP1.getAddress()) != -1 || participantAtP1.getAddress().indexOf( expectedParticipant1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedParticipant1DisplayName , participantAtP1.getDisplayName()); //check properties on the remote call participant for the party that //receives the call. String expectedParticipant2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedParticipant2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant2Address.indexOf( participantAtP2.getAddress()) != -1 || participantAtP2.getAddress().indexOf( expectedParticipant2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedParticipant2DisplayName , participantAtP2.getDisplayName()); } //add listeners to the participants and make sure enter //a connected state after we answer stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.CONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.CONNECTED); //we will now anser the call and verify that both parties change states //accordingly. basicTelephonyP2.answerCallParticipant(participantAtP2); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.CONNECTED , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.CONNECTED , participantAtP2.getState()); //make sure that events have been distributed when states were changed. assertEquals("No event was dispatched when a call participant changed " +"its state." , 1 , stateCollectorForPp1.collectedEvents.size()); assertEquals("No event was dispatched when a call participant changed " +"its state." , 1 , stateCollectorForPp2.collectedEvents.size()); //add listeners to the participants and make sure they have entered //the states they are expected to. stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallParticipantState.DISCONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallParticipantState.DISCONNECTED); //we will now end the call and verify that both parties change states //accordingly. basicTelephonyP2.hangupCallParticipant(participantAtP2); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallParticipantState.DISCONNECTED , participantAtP2.getState()); //make sure that the corresponding events were delivered. assertEquals("a provider did not distribute an event when a call " +"participant changed states." , 1 , stateCollectorForPp1.collectedEvents.size()); assertEquals("a provider did not distribute an event when a call " +"participant changed states." , 1 , stateCollectorForPp2.collectedEvents.size()); } /** * Allows tests to wait for and collect events issued upon creation and * reception of calls. */ public class CallEventCollector implements CallListener { public ArrayList collectedEvents = new ArrayList(); public OperationSetBasicTelephony listenedOpSet = null; /** * Creates an instance of this call event collector and registers it * with listenedOpSet. * @param listenedOpSet the operation set that we will be scanning for * new calls. */ public CallEventCollector(OperationSetBasicTelephony listenedOpSet) { this.listenedOpSet = listenedOpSet; this.listenedOpSet.addCallListener(this); } /** * Blocks until at least one event is received or until waitFor * miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { logger.trace("Waiting for a CallEvent"); synchronized(this) { if(collectedEvents.size() > 0){ logger.trace("Event already received. " + collectedEvents); listenedOpSet.removeCallListener(this); return; } try{ wait(waitFor); if(collectedEvents.size() > 0) logger.trace("Received a CallEvent."); else logger.trace("No CallEvent received for "+waitFor+"ms."); listenedOpSet.removeCallListener(this); } catch (InterruptedException ex) { logger.debug( "Interrupted while waiting for a call event", ex); } } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void incomingCallReceived(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void outgoingCallCreated(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void callEnded(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } } /** * Allows tests to wait for and collect events issued upon call participant * status changes. */ public class CallParticipantStateEventCollector implements CallParticipantListener { public ArrayList collectedEvents = new ArrayList(); private CallParticipant listenedCallParticipant = null; public CallParticipantState awaitedState = null; /** * Creates an instance of this collector and adds it as a listener * to <tt>callParticipant</tt>. * @param callParticipant the CallParticipant that we will be listening * to. * @param awaitedState the state that we will be waiting for inside * this collector. */ public CallParticipantStateEventCollector( CallParticipant callParticipant, CallParticipantState awaitedState) { this.listenedCallParticipant = callParticipant; this.listenedCallParticipant.addCallParticipantListener(this); this.awaitedState = awaitedState; } /** * Stores the received event and notifies all waiting on this object * * @param event the event containing the source call. */ public void participantStateChanged(CallParticipantChangeEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); if(((CallParticipantState)event.getNewValue()) .equals(awaitedState)) { this.collectedEvents.add(event); notifyAll(); } } } /** * Unused by this collector. * @param event ignored. */ public void participantImageChanged(CallParticipantChangeEvent event) {} /** * Unused by this collector * @param event ignored. */ public void participantAddressChanged(CallParticipantChangeEvent event) {} /** * Unused by this collector * @param event ignored. */ public void participantTransportAddressChanged( CallParticipantChangeEvent event) {} /** * Unused by this collector * @param event ignored. */ public void participantDisplayNameChanged( CallParticipantChangeEvent event) {} /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { waitForEvent(waitFor, false); } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. * @param exitIfAlreadyInState specifies whether the method is to return * if the call participant is already in such a state even if no event * has been received for the sate change. */ public void waitForEvent(long waitFor, boolean exitIfAlreadyInState) { logger.trace("Waiting for a CallParticipantEvent with newState=" + awaitedState + " for participant " + this.listenedCallParticipant); synchronized (this) { if(exitIfAlreadyInState && listenedCallParticipant.getState().equals(awaitedState)) { logger.trace("Src participant is already in the awaited " + "state." + collectedEvents); listenedCallParticipant.removeCallParticipantListener(this); return; } if(collectedEvents.size() > 0) { CallParticipantChangeEvent lastEvent = (CallParticipantChangeEvent) collectedEvents .get(collectedEvents.size() - 1); if (lastEvent.getNewValue().equals(awaitedState)) { logger.trace("Event already received. " + collectedEvents); listenedCallParticipant .removeCallParticipantListener(this); return; } } try { wait(waitFor); if (collectedEvents.size() > 0) logger.trace("Received a CallParticpantStateEvent."); else logger.trace("No CallParticpantStateEvent received for " + waitFor + "ms."); listenedCallParticipant .removeCallParticipantListener(this); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a " + "CallParticpantEvent" , ex); } } } } /** * Allows tests to wait for and collect events issued upon call state * changes. */ public class CallStateEventCollector implements CallChangeListener { public ArrayList collectedEvents = new ArrayList(); private Call listenedCall = null; public CallState awaitedState = null; /** * Creates an instance of this collector and adds it as a listener * to <tt>call</tt>. * @param call the Call that we will be listening to. * @param awaitedState the state that we will be waiting for inside * this collector. */ public CallStateEventCollector(Call call, CallState awaitedState) { this.listenedCall = call; this.listenedCall.addCallChangeListener(this); this.awaitedState = awaitedState; } /** * Stores the received event and notifies all waiting on this object * * @param event the event containing the source call. */ public void callStateChanged(CallChangeEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); if(((CallState)event.getNewValue()).equals(awaitedState)) { this.collectedEvents.add(event); notifyAll(); } } } /** * Unused by this collector. * @param event ignored. */ public void callParticipantAdded(CallParticipantEvent event) { } /** * Unused by this collector. * @param event ignored. */ public void callParticipantRemoved(CallParticipantEvent event) { } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { logger.trace("Waiting for a CallParticpantEvent"); synchronized (this) { if (listenedCall.getCallState() == awaitedState) { logger.trace("Event already received. " + collectedEvents); listenedCall.removeCallChangeListener(this); return; } try { wait(waitFor); if (collectedEvents.size() > 0) logger.trace("Received a CallChangeEvent."); else logger.trace("No CallChangeEvent received for " + waitFor + "ms."); listenedCall.removeCallChangeListener(this); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a " + "CallParticpantEvent" , ex); } } } } }
Temporarily removed test as it fails. Will get back to it when I find the time
test/net/java/sip/communicator/slick/protocol/sip/TestOperationSetBasicTelephonySipImpl.java
Temporarily removed test as it fails. Will get back to it when I find the time
<ide><path>est/net/java/sip/communicator/slick/protocol/sip/TestOperationSetBasicTelephonySipImpl.java <ide> * @throws ParseException if we hand a malformed URI to someone <ide> * @throws OperationFailedException if something weird happens. <ide> */ <del> public void testCreateAnswerHangupCall() <add> public void aTestCreateAnswerHangupCall() <ide> throws ParseException, OperationFailedException <ide> { <ide> OperationSetBasicTelephony basicTelephonyP1
Java
agpl-3.0
f4c514045bce07dcd88822287dcaeb1cad443cb0
0
deerwalk/voltdb,creative-quant/voltdb,flybird119/voltdb,migue/voltdb,flybird119/voltdb,kumarrus/voltdb,zuowang/voltdb,simonzhangsm/voltdb,zuowang/voltdb,ingted/voltdb,kobronson/cs-voltdb,paulmartel/voltdb,deerwalk/voltdb,wolffcm/voltdb,migue/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,flybird119/voltdb,kumarrus/voltdb,kumarrus/voltdb,kobronson/cs-voltdb,migue/voltdb,creative-quant/voltdb,paulmartel/voltdb,kumarrus/voltdb,migue/voltdb,VoltDB/voltdb,flybird119/voltdb,VoltDB/voltdb,zuowang/voltdb,creative-quant/voltdb,kumarrus/voltdb,VoltDB/voltdb,wolffcm/voltdb,zuowang/voltdb,kobronson/cs-voltdb,kobronson/cs-voltdb,wolffcm/voltdb,paulmartel/voltdb,migue/voltdb,simonzhangsm/voltdb,kumarrus/voltdb,ingted/voltdb,paulmartel/voltdb,wolffcm/voltdb,migue/voltdb,kobronson/cs-voltdb,ingted/voltdb,creative-quant/voltdb,creative-quant/voltdb,VoltDB/voltdb,paulmartel/voltdb,ingted/voltdb,zuowang/voltdb,wolffcm/voltdb,creative-quant/voltdb,wolffcm/voltdb,migue/voltdb,kumarrus/voltdb,kumarrus/voltdb,deerwalk/voltdb,creative-quant/voltdb,zuowang/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,ingted/voltdb,flybird119/voltdb,zuowang/voltdb,kobronson/cs-voltdb,flybird119/voltdb,VoltDB/voltdb,wolffcm/voltdb,flybird119/voltdb,flybird119/voltdb,simonzhangsm/voltdb,kobronson/cs-voltdb,deerwalk/voltdb,creative-quant/voltdb,migue/voltdb,deerwalk/voltdb,deerwalk/voltdb,wolffcm/voltdb,ingted/voltdb,paulmartel/voltdb,zuowang/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,ingted/voltdb,paulmartel/voltdb,ingted/voltdb,simonzhangsm/voltdb,VoltDB/voltdb,kobronson/cs-voltdb,paulmartel/voltdb
/* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.sysprocs.saverestore; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.ListIterator; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.google.common.primitives.Longs; import org.json_voltpatches.JSONArray; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.voltcore.utils.CoreUtils; import org.voltcore.utils.Pair; import org.voltdb.catalog.Table; import org.voltdb.dtxn.SiteTracker; import org.voltdb.rejoin.StreamSnapshotDataTarget; import org.voltdb.SnapshotDataFilter; import org.voltdb.SnapshotDataTarget; import org.voltdb.SnapshotFormat; import org.voltdb.SnapshotSiteProcessor; import org.voltdb.SnapshotTableTask; import org.voltdb.sysprocs.SnapshotRegistry; import org.voltdb.SystemProcedureExecutionContext; import org.voltdb.utils.CatalogUtil; import org.voltdb.VoltTable; /** * Create a snapshot write plan for snapshots streamed to other sites * (specified in the jsData). Each source site specified in the streamPairs * key will write all of its tables, partitioned and replicated, to a target * per-site. */ public class StreamSnapshotWritePlan extends SnapshotWritePlan { protected boolean createSetupInternal( String file_path, String file_nonce, long txnId, Map<Integer, Long> partitionTransactionIds, JSONObject jsData, SystemProcedureExecutionContext context, String hostname, final VoltTable result, Map<String, Map<Integer, Pair<Long, Long>>> exportSequenceNumbers, SiteTracker tracker, long timestamp) throws IOException { // not empty if targeting only one site (used for rejoin) // set later from the "data" JSON string Map<Long, Long> streamPairs; assert(SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.isEmpty()); final List<Table> tables = getTablesToInclude(jsData, context); final AtomicInteger numTables = new AtomicInteger(tables.size()); final SnapshotRegistry.Snapshot snapshotRecord = SnapshotRegistry.startSnapshot( txnId, context.getHostId(), file_path, file_nonce, SnapshotFormat.STREAM, tables.toArray(new Table[0])); // table schemas for all the tables we'll snapshot on this partition Map<Integer, byte[]> schemas = new HashMap<Integer, byte[]>(); for (final Table table : tables) { VoltTable schemaTable = CatalogUtil.getVoltTable(table); schemas.put(table.getRelativeIndex(), schemaTable.getSchemaBytes()); } try { streamPairs = getStreamPairs(jsData, tracker); } catch (JSONException e) { // Can't proceed without valid JSON, Ned SnapshotRegistry.discardSnapshot(snapshotRecord); return true; } Map<Long, SnapshotDataTarget> sdts = new HashMap<Long, SnapshotDataTarget>(); if (streamPairs.size() > 0) { SNAP_LOG.debug("Sites to stream from: " + CoreUtils.hsIdCollectionToString(streamPairs.keySet())); for (Entry<Long, Long> entry : streamPairs.entrySet()) { sdts.put(entry.getKey(), new StreamSnapshotDataTarget(entry.getValue(), schemas)); } } else { // There's no work to do on this host, just claim success, return an empty plan, and things // will sort themselves out properly return false; } for (Entry<Long, SnapshotDataTarget> entry : sdts.entrySet()) { final ArrayList<SnapshotTableTask> partitionedSnapshotTasks = new ArrayList<SnapshotTableTask>(); final ArrayList<SnapshotTableTask> replicatedSnapshotTasks = new ArrayList<SnapshotTableTask>(); SnapshotDataTarget sdt = entry.getValue(); m_targets.add(sdt); for (final Table table : tables) { final Runnable onClose = new TargetStatsClosure(sdt, table.getTypeName(), numTables, snapshotRecord); sdt.setOnCloseHandler(onClose); final SnapshotTableTask task = new SnapshotTableTask( table.getRelativeIndex(), sdt, new SnapshotDataFilter[0], // This task no longer needs partition filtering table.getIsreplicated(), table.getTypeName()); if (table.getIsreplicated()) { replicatedSnapshotTasks.add(task); } else { partitionedSnapshotTasks.add(task); } result.addRow(context.getHostId(), hostname, table.getTypeName(), "SUCCESS", ""); } // Stream snapshots need to write all partitioned tables to all // selected partitions and all replicated tables to all selected // partitions List<Long> thisOne = new ArrayList<Long>(); thisOne.add(entry.getKey()); placePartitionedTasks(partitionedSnapshotTasks, thisOne); placeReplicatedTasks(replicatedSnapshotTasks, thisOne); } return false; } private List<Table> getTablesToInclude(JSONObject jsData, SystemProcedureExecutionContext context) { final List<Table> tables = SnapshotUtil.getTablesToSave(context.getDatabase()); final Set<Integer> tableIdsToInclude = new HashSet<Integer>(); if (jsData != null) { JSONArray tableIds = jsData.optJSONArray("tableIds"); if (tableIds != null) { for (int i = 0; i < tableIds.length(); i++) { try { tableIdsToInclude.add(tableIds.getInt(i)); } catch (JSONException e) { SNAP_LOG.warn("Unable to parse tables to include for stream snapshot", e); } } } } if (tableIdsToInclude.isEmpty()) { // It doesn't make any sense to take a snapshot that doesn't include any table, // it must be that the request doesn't specify a table filter, // so default to all tables. return tables; } ListIterator<Table> iter = tables.listIterator(); while (iter.hasNext()) { Table table = iter.next(); if (!tableIdsToInclude.contains(table.getRelativeIndex())) { // If the table index is not in the list to include, remove it iter.remove(); } } return tables; } private Map<Long, Long> getStreamPairs(JSONObject jsData, SiteTracker tracker) throws JSONException { Map<Long, Long> streamPairs = new HashMap<Long, Long>(); if (jsData != null) { List<Long> localHSIds = Longs.asList(tracker.getLocalSites()); JSONObject sp = jsData.getJSONObject("streamPairs"); @SuppressWarnings("unchecked") Iterator<String> it = sp.keys(); while (it.hasNext()) { String key = it.next(); long sourceHSId = Long.valueOf(key); // See whether this source HSID is a local site, if so, we need // the partition ID if (localHSIds.contains(sourceHSId)) { Long destHSId = Long.valueOf(sp.getString(key)); streamPairs.put(sourceHSId, destHSId); } } } return streamPairs; } }
src/frontend/org/voltdb/sysprocs/saverestore/StreamSnapshotWritePlan.java
/* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.sysprocs.saverestore; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.voltcore.utils.CoreUtils; import org.voltcore.utils.Pair; import org.voltdb.catalog.Table; import org.voltdb.dtxn.SiteTracker; import org.voltdb.rejoin.StreamSnapshotDataTarget; import org.voltdb.SnapshotDataFilter; import org.voltdb.SnapshotDataTarget; import org.voltdb.SnapshotFormat; import org.voltdb.SnapshotSiteProcessor; import org.voltdb.SnapshotTableTask; import org.voltdb.sysprocs.SnapshotRegistry; import org.voltdb.SystemProcedureExecutionContext; import org.voltdb.utils.CatalogUtil; import org.voltdb.VoltTable; /** * Create a snapshot write plan for snapshots streamed to other sites * (specified in the jsData). Each source site specified in the streamPairs * key will write all of its tables, partitioned and replicated, to a target * per-site. */ public class StreamSnapshotWritePlan extends SnapshotWritePlan { protected boolean createSetupInternal( String file_path, String file_nonce, long txnId, Map<Integer, Long> partitionTransactionIds, JSONObject jsData, SystemProcedureExecutionContext context, String hostname, final VoltTable result, Map<String, Map<Integer, Pair<Long, Long>>> exportSequenceNumbers, SiteTracker tracker, long timestamp) throws IOException { // not empty if targeting only one site (used for rejoin) // set later from the "data" JSON string List<Long> sitesToInclude = new ArrayList<Long>(); Map<Long, Long> streamPairs = new HashMap<Long, Long>(); assert(SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.isEmpty()); final List<Table> tables = SnapshotUtil.getTablesToSave(context.getDatabase()); final AtomicInteger numTables = new AtomicInteger(tables.size()); final SnapshotRegistry.Snapshot snapshotRecord = SnapshotRegistry.startSnapshot( txnId, context.getHostId(), file_path, file_nonce, SnapshotFormat.STREAM, tables.toArray(new Table[0])); // table schemas for all the tables we'll snapshot on this partition Map<Integer, byte[]> schemas = new HashMap<Integer, byte[]>(); for (final Table table : tables) { VoltTable schemaTable = CatalogUtil.getVoltTable(table); schemas.put(table.getRelativeIndex(), schemaTable.getSchemaBytes()); } if (jsData != null) { try { List<Long> localHSIds = tracker.getSitesForHost(context.getHostId()); JSONObject sp = jsData.getJSONObject("streamPairs"); @SuppressWarnings("unchecked") Iterator<String> it = sp.keys(); while (it.hasNext()) { String key = it.next(); long sourceHSId = Long.valueOf(key); // See whether this source HSID is a local site, if so, we need // the partition ID if (localHSIds.contains(sourceHSId)) { Long destHSId = Long.valueOf(sp.getString(key)); sitesToInclude.add(sourceHSId); streamPairs.put(sourceHSId, destHSId); } } } catch (JSONException e) { // Can't proceed without valid JSON, Ned SnapshotRegistry.discardSnapshot(snapshotRecord); return true; } } Map<Long, SnapshotDataTarget> sdts = new HashMap<Long, SnapshotDataTarget>(); if (streamPairs.size() > 0) { SNAP_LOG.debug("Sites to stream from: " + CoreUtils.hsIdCollectionToString(sitesToInclude)); for (Entry<Long, Long> entry : streamPairs.entrySet()) { sdts.put(entry.getKey(), new StreamSnapshotDataTarget(entry.getValue(), schemas)); } } else { // There's no work to do on this host, just claim success, return an empty plan, and things // will sort themselves out properly return false; } for (Entry<Long, SnapshotDataTarget> entry : sdts.entrySet()) { final ArrayList<SnapshotTableTask> partitionedSnapshotTasks = new ArrayList<SnapshotTableTask>(); final ArrayList<SnapshotTableTask> replicatedSnapshotTasks = new ArrayList<SnapshotTableTask>(); SnapshotDataTarget sdt = entry.getValue(); m_targets.add(sdt); for (final Table table : tables) { final Runnable onClose = new TargetStatsClosure(sdt, table.getTypeName(), numTables, snapshotRecord); sdt.setOnCloseHandler(onClose); final SnapshotTableTask task = new SnapshotTableTask( table.getRelativeIndex(), sdt, new SnapshotDataFilter[0], // This task no longer needs partition filtering table.getIsreplicated(), table.getTypeName()); if (table.getIsreplicated()) { replicatedSnapshotTasks.add(task); } else { partitionedSnapshotTasks.add(task); } result.addRow(context.getHostId(), hostname, table.getTypeName(), "SUCCESS", ""); } // Stream snapshots need to write all partitioned tables to all // selected partitions and all replicated tables to all selected // partitions List<Long> thisOne = new ArrayList<Long>(); thisOne.add(entry.getKey()); placePartitionedTasks(partitionedSnapshotTasks, thisOne); placeReplicatedTasks(replicatedSnapshotTasks, thisOne); } return false; } }
ENG-4418: Allow filtering tables for stream snapshot. If the JSON data in the request specifies which tables the destination wants, the source will only send data of those tables.
src/frontend/org/voltdb/sysprocs/saverestore/StreamSnapshotWritePlan.java
ENG-4418: Allow filtering tables for stream snapshot.
<ide><path>rc/frontend/org/voltdb/sysprocs/saverestore/StreamSnapshotWritePlan.java <ide> <ide> import java.util.ArrayList; <ide> <add>import java.util.HashSet; <add>import java.util.ListIterator; <add>import java.util.Set; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> import java.util.HashMap; <ide> import java.util.Iterator; <ide> <ide> import java.util.Map.Entry; <ide> <add>import com.google.common.primitives.Longs; <add>import org.json_voltpatches.JSONArray; <ide> import org.json_voltpatches.JSONException; <ide> import org.json_voltpatches.JSONObject; <ide> <ide> { <ide> // not empty if targeting only one site (used for rejoin) <ide> // set later from the "data" JSON string <del> List<Long> sitesToInclude = new ArrayList<Long>(); <del> Map<Long, Long> streamPairs = new HashMap<Long, Long>(); <add> Map<Long, Long> streamPairs; <ide> <ide> assert(SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.isEmpty()); <ide> <del> final List<Table> tables = SnapshotUtil.getTablesToSave(context.getDatabase()); <add> final List<Table> tables = getTablesToInclude(jsData, context); <ide> <ide> final AtomicInteger numTables = new AtomicInteger(tables.size()); <ide> final SnapshotRegistry.Snapshot snapshotRecord = <ide> schemas.put(table.getRelativeIndex(), schemaTable.getSchemaBytes()); <ide> } <ide> <del> if (jsData != null) { <del> try { <del> List<Long> localHSIds = tracker.getSitesForHost(context.getHostId()); <del> JSONObject sp = jsData.getJSONObject("streamPairs"); <del> @SuppressWarnings("unchecked") <del> Iterator<String> it = sp.keys(); <del> while (it.hasNext()) { <del> String key = it.next(); <del> long sourceHSId = Long.valueOf(key); <del> // See whether this source HSID is a local site, if so, we need <del> // the partition ID <del> if (localHSIds.contains(sourceHSId)) { <del> Long destHSId = Long.valueOf(sp.getString(key)); <del> sitesToInclude.add(sourceHSId); <del> streamPairs.put(sourceHSId, destHSId); <del> } <del> } <del> } <del> catch (JSONException e) { <del> // Can't proceed without valid JSON, Ned <del> SnapshotRegistry.discardSnapshot(snapshotRecord); <del> return true; <del> } <add> try { <add> streamPairs = getStreamPairs(jsData, tracker); <add> } <add> catch (JSONException e) { <add> // Can't proceed without valid JSON, Ned <add> SnapshotRegistry.discardSnapshot(snapshotRecord); <add> return true; <ide> } <ide> <ide> Map<Long, SnapshotDataTarget> sdts = new HashMap<Long, SnapshotDataTarget>(); <ide> if (streamPairs.size() > 0) { <ide> SNAP_LOG.debug("Sites to stream from: " + <del> CoreUtils.hsIdCollectionToString(sitesToInclude)); <add> CoreUtils.hsIdCollectionToString(streamPairs.keySet())); <ide> for (Entry<Long, Long> entry : streamPairs.entrySet()) { <ide> sdts.put(entry.getKey(), new StreamSnapshotDataTarget(entry.getValue(), schemas)); <ide> } <ide> } <ide> return false; <ide> } <add> <add> private List<Table> getTablesToInclude(JSONObject jsData, <add> SystemProcedureExecutionContext context) <add> { <add> final List<Table> tables = SnapshotUtil.getTablesToSave(context.getDatabase()); <add> final Set<Integer> tableIdsToInclude = new HashSet<Integer>(); <add> <add> if (jsData != null) { <add> JSONArray tableIds = jsData.optJSONArray("tableIds"); <add> if (tableIds != null) { <add> for (int i = 0; i < tableIds.length(); i++) { <add> try { <add> tableIdsToInclude.add(tableIds.getInt(i)); <add> } catch (JSONException e) { <add> SNAP_LOG.warn("Unable to parse tables to include for stream snapshot", e); <add> } <add> } <add> } <add> } <add> <add> if (tableIdsToInclude.isEmpty()) { <add> // It doesn't make any sense to take a snapshot that doesn't include any table, <add> // it must be that the request doesn't specify a table filter, <add> // so default to all tables. <add> return tables; <add> } <add> <add> ListIterator<Table> iter = tables.listIterator(); <add> while (iter.hasNext()) { <add> Table table = iter.next(); <add> if (!tableIdsToInclude.contains(table.getRelativeIndex())) { <add> // If the table index is not in the list to include, remove it <add> iter.remove(); <add> } <add> } <add> <add> return tables; <add> } <add> <add> private Map<Long, Long> getStreamPairs(JSONObject jsData, SiteTracker tracker) throws JSONException <add> { <add> Map<Long, Long> streamPairs = new HashMap<Long, Long>(); <add> <add> if (jsData != null) { <add> List<Long> localHSIds = Longs.asList(tracker.getLocalSites()); <add> JSONObject sp = jsData.getJSONObject("streamPairs"); <add> @SuppressWarnings("unchecked") <add> Iterator<String> it = sp.keys(); <add> while (it.hasNext()) { <add> String key = it.next(); <add> long sourceHSId = Long.valueOf(key); <add> // See whether this source HSID is a local site, if so, we need <add> // the partition ID <add> if (localHSIds.contains(sourceHSId)) { <add> Long destHSId = Long.valueOf(sp.getString(key)); <add> streamPairs.put(sourceHSId, destHSId); <add> } <add> } <add> } <add> <add> return streamPairs; <add> } <ide> }
Java
apache-2.0
520370688c27afece90fbb07b8e07a1603d87b05
0
colezlaw/DependencyCheck,jeremylong/DependencyCheck,hansjoachim/DependencyCheck,hansjoachim/DependencyCheck,stevespringett/DependencyCheck,stevespringett/DependencyCheck,wmaintw/DependencyCheck,recena/DependencyCheck,dwvisser/DependencyCheck,dwvisser/DependencyCheck,colezlaw/DependencyCheck,adilakhter/DependencyCheck,stevespringett/DependencyCheck,colezlaw/DependencyCheck,jeremylong/DependencyCheck,stevespringett/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,colezlaw/DependencyCheck,colezlaw/DependencyCheck,colezlaw/DependencyCheck,awhitford/DependencyCheck,stefanneuhaus/DependencyCheck,recena/DependencyCheck,stefanneuhaus/DependencyCheck,stevespringett/DependencyCheck,hansjoachim/DependencyCheck,hansjoachim/DependencyCheck,adilakhter/DependencyCheck,hansjoachim/DependencyCheck,dwvisser/DependencyCheck,awhitford/DependencyCheck,wmaintw/DependencyCheck,recena/DependencyCheck,wmaintw/DependencyCheck,recena/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,dwvisser/DependencyCheck,stefanneuhaus/DependencyCheck,wmaintw/DependencyCheck,wmaintw/DependencyCheck,adilakhter/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,wmaintw/DependencyCheck,adilakhter/DependencyCheck,adilakhter/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,recena/DependencyCheck,hansjoachim/DependencyCheck,awhitford/DependencyCheck,stevespringett/DependencyCheck,recena/DependencyCheck,jeremylong/DependencyCheck,stevespringett/DependencyCheck,jeremylong/DependencyCheck,dwvisser/DependencyCheck,colezlaw/DependencyCheck,awhitford/DependencyCheck,adilakhter/DependencyCheck,hansjoachim/DependencyCheck,dwvisser/DependencyCheck
/** * Contains classes used to work with the NVD CVE data. */ package org.owasp.dependencycheck.data.nvdcve;
dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/package-info.java
/** * <html> * <head> * <title>org.owasp.dependencycheck.data.nvdcve</title> * </head> * <body> * Contains classes used to work with the NVD CVE data. * </body> * </html> */ package org.owasp.dependencycheck.data.nvdcve;
updated package-info Former-commit-id: c577b32102ac872b713df1c88b2af3424f00565c
dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/package-info.java
updated package-info
<ide><path>ependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/package-info.java <ide> /** <del> * <html> <del> * <head> <del> * <title>org.owasp.dependencycheck.data.nvdcve</title> <del> * </head> <del> * <body> <ide> * Contains classes used to work with the NVD CVE data. <del> * </body> <del> * </html> <del>*/ <del> <add> */ <ide> package org.owasp.dependencycheck.data.nvdcve;
JavaScript
apache-2.0
f09cd3ca7aaa1db737f3144355753776eba51625
0
postmanlabs/postman-runtime,postmanlabs/postman-runtime
var net = require('net'), sinon = require('sinon'), expect = require('chai').expect; describe('protocolProfileBehavior', function () { var server, testrun, rawRequest, PORT = 5050, URL = 'http://localhost:' + PORT; before(function (done) { // Echo raw request message to handle body for http methods (GET, HEAD) // Node's `http` server won't parse body for GET method. server = net.createServer(function (socket) { socket.on('data', function (chunk) { rawRequest = chunk.toString(); // Request Message: [POSTMAN / HTTP/1.1 ...] socket.write('HTTP/1.1 200 ok\r\n'); socket.write('Content-Type: text/plain\r\n\r\n'); // Respond with raw request message. // // @note http-parser will blow up if body is sent for HEAD request. // RFC-7231: The HEAD method is identical to GET except that the // server MUST NOT send a message body in the response. if (!rawRequest.startsWith('HEAD / HTTP/1.1')) { socket.write(rawRequest); } socket.end(); }); }).listen(PORT, done); }); after(function (done) { server.close(done); }); describe('with disableBodyPruning: true', function () { describe('HTTP GET', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'GET', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: true } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with GET method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); expect(response).to.include('GET / HTTP/1.1') .and.include('Content-Type: text/plain') .and.include('content-length: 7') .and.include('foo=bar'); }); }); describe('HTTP HEAD', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'HEAD', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: true } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with HEAD method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = rawRequest; // raw request message for this request expect(response).to.include('HEAD / HTTP/1.1') .and.include('Content-Type: text/plain') .and.include('content-length: 7') .and.include('foo=bar'); }); }); describe('HTTP POSTMAN', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'POSTMAN', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: true } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with custom method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); expect(response).to.include('POSTMAN / HTTP/1.1') .and.include('Content-Type: text/plain') .and.include('content-length: 7') .and.include('foo=bar'); }); }); }); describe('with disableBodyPruning: false', function () { describe('HTTP GET', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'GET', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: false } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should not send body with GET method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); expect(response).to.include('GET / HTTP/1.1'); expect(response).to.not.include('Content-Type'); expect(response).to.not.include('foo=bar'); }); }); describe('HTTP HEAD', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'HEAD', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: false } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should not send body with HEAD method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = rawRequest; // raw request message for this request expect(response).to.include('HEAD / HTTP/1.1'); expect(response).to.not.include('Content-Type'); expect(response).to.not.include('foo=bar'); }); }); describe('HTTP POSTMAN', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'POSTMAN', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: false } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with custom method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); expect(response).to.include('POSTMAN / HTTP/1.1') .and.include('Content-Type: text/plain') .and.include('content-length: 7') .and.include('foo=bar'); }); }); }); describe('with disableBodyPruning: undefined', function () { describe('HTTP GET', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'GET', body: { mode: 'raw', raw: 'foo=bar' } } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should not send body by default for GET method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); expect(response).to.include('GET / HTTP/1.1'); expect(response).to.not.include('Content-Type'); expect(response).to.not.include('foo=bar'); }); }); describe('HTTP HEAD', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'HEAD', body: { mode: 'raw', raw: 'foo=bar' } } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should not send body by default for HEAD method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = rawRequest; // raw request message for this request expect(response).to.include('HEAD / HTTP/1.1'); expect(response).to.not.include('Content-Type'); expect(response).to.not.include('foo=bar'); }); }); describe('HTTP POSTMAN', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'POSTMAN', body: { mode: 'raw', raw: 'foo=bar' } } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with custom method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); expect(response).to.include('POSTMAN / HTTP/1.1') .and.include('Content-Type: text/plain') .and.include('content-length: 7') .and.include('foo=bar'); }); }); }); });
test/integration/request-body/protocolProfileBehavior.test.js
var net = require('net'), sinon = require('sinon'), expect = require('chai').expect; describe('protocolProfileBehavior', function () { var server, testrun, rawRequest, PORT = 5050, URL = 'http://localhost:' + PORT; before(function (done) { // Echo raw request message to handle body for http methods (GET, HEAD) // Node's `http` server won't parse body for GET method. server = net.createServer(function (socket) { socket.on('data', function (chunk) { rawRequest = chunk.toString(); // Request Message: [POSTMAN / HTTP/1.1 ...] socket.write('HTTP/1.1 200 ok\r\n'); socket.write('Content-Type: text/plain\r\n\r\n'); // Respond with raw request message. // // @note http-parser will blow up if body is sent for HEAD request. // RFC-7231: The HEAD method is identical to GET except that the // server MUST NOT send a message body in the response. if (!rawRequest.startsWith('HEAD / HTTP/1.1')) { socket.write(rawRequest); } socket.end(); }); }).listen(PORT, done); }); after(function (done) { server.close(done); }); describe('with disableBodyPruning: true', function () { describe('HTTP GET', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'GET', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: true } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with GET method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); // eslint-disable-next-line max-len expect(response).to.include('GET / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); }); }); describe('HTTP HEAD', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'HEAD', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: true } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with HEAD method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = rawRequest; // raw request message for this request // eslint-disable-next-line max-len expect(response).to.include('HEAD / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); }); }); describe('HTTP POSTMAN', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'POSTMAN', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: true } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with custom method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); // eslint-disable-next-line max-len expect(response).to.include('POSTMAN / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); }); }); }); describe('with disableBodyPruning: false', function () { describe('HTTP GET', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'GET', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: false } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should not send body with GET method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); expect(response).to.include('GET / HTTP/1.1'); expect(response).to.not.include('Content-Type'); expect(response).to.not.include('foo=bar'); }); }); describe('HTTP HEAD', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'HEAD', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: false } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should not send body with HEAD method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = rawRequest; // raw request message for this request expect(response).to.include('HEAD / HTTP/1.1'); expect(response).to.not.include('Content-Type'); expect(response).to.not.include('foo=bar'); }); }); describe('HTTP POSTMAN', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'POSTMAN', body: { mode: 'raw', raw: 'foo=bar' } }, protocolProfileBehavior: { disableBodyPruning: false } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with custom method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); // eslint-disable-next-line max-len expect(response).to.include('POSTMAN / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); }); }); }); describe('with disableBodyPruning: undefined', function () { describe('HTTP GET', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'GET', body: { mode: 'raw', raw: 'foo=bar' } } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should not send body by default for GET method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); expect(response).to.include('GET / HTTP/1.1'); expect(response).to.not.include('Content-Type'); expect(response).to.not.include('foo=bar'); }); }); describe('HTTP HEAD', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'HEAD', body: { mode: 'raw', raw: 'foo=bar' } } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should not send body by default for HEAD method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = rawRequest; // raw request message for this request expect(response).to.include('HEAD / HTTP/1.1'); expect(response).to.not.include('Content-Type'); expect(response).to.not.include('foo=bar'); }); }); describe('HTTP POSTMAN', function () { before(function (done) { this.run({ collection: { item: [{ request: { url: URL, method: 'POSTMAN', body: { mode: 'raw', raw: 'foo=bar' } } }] } }, function (err, results) { testrun = results; done(err); }); }); after(function () { testrun = rawRequest = null; }); it('should complete the run', function () { expect(testrun).to.be.ok; sinon.assert.calledOnce(testrun.start); sinon.assert.calledOnce(testrun.done); sinon.assert.calledWith(testrun.done.getCall(0), null); }); it('should send body with custom method', function () { sinon.assert.calledOnce(testrun.request); sinon.assert.calledWith(testrun.request.getCall(0), null); sinon.assert.calledOnce(testrun.response); sinon.assert.calledWith(testrun.response.getCall(0), null); var response = testrun.request.getCall(0).args[2].stream.toString(); // eslint-disable-next-line max-len expect(response).to.include('POSTMAN / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); }); }); }); });
Fix tests for protocolProfileBehavior
test/integration/request-body/protocolProfileBehavior.test.js
Fix tests for protocolProfileBehavior
<ide><path>est/integration/request-body/protocolProfileBehavior.test.js <ide> <ide> var response = testrun.request.getCall(0).args[2].stream.toString(); <ide> <del> // eslint-disable-next-line max-len <del> expect(response).to.include('GET / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); <add> expect(response).to.include('GET / HTTP/1.1') <add> .and.include('Content-Type: text/plain') <add> .and.include('content-length: 7') <add> .and.include('foo=bar'); <ide> }); <ide> }); <ide> <ide> <ide> var response = rawRequest; // raw request message for this request <ide> <del> // eslint-disable-next-line max-len <del> expect(response).to.include('HEAD / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); <add> expect(response).to.include('HEAD / HTTP/1.1') <add> .and.include('Content-Type: text/plain') <add> .and.include('content-length: 7') <add> .and.include('foo=bar'); <ide> }); <ide> }); <ide> <ide> <ide> var response = testrun.request.getCall(0).args[2].stream.toString(); <ide> <del> // eslint-disable-next-line max-len <del> expect(response).to.include('POSTMAN / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); <add> expect(response).to.include('POSTMAN / HTTP/1.1') <add> .and.include('Content-Type: text/plain') <add> .and.include('content-length: 7') <add> .and.include('foo=bar'); <ide> }); <ide> }); <ide> }); <ide> <ide> var response = testrun.request.getCall(0).args[2].stream.toString(); <ide> <del> // eslint-disable-next-line max-len <del> expect(response).to.include('POSTMAN / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); <add> expect(response).to.include('POSTMAN / HTTP/1.1') <add> .and.include('Content-Type: text/plain') <add> .and.include('content-length: 7') <add> .and.include('foo=bar'); <ide> }); <ide> }); <ide> }); <ide> <ide> var response = testrun.request.getCall(0).args[2].stream.toString(); <ide> <del> // eslint-disable-next-line max-len <del> expect(response).to.include('POSTMAN / HTTP/1.1', 'Content-Type: text/plain', 'content-length: 7', 'foo=bar'); <add> expect(response).to.include('POSTMAN / HTTP/1.1') <add> .and.include('Content-Type: text/plain') <add> .and.include('content-length: 7') <add> .and.include('foo=bar'); <ide> }); <ide> }); <ide> });
Java
apache-2.0
777f9716998a7e520d6d422928dda1c568d49b87
0
semonte/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,caot/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,jagguli/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ernestp/consulo,ftomassetti/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,diorcety/intellij-community,robovm/robovm-studio,robovm/robovm-studio,allotria/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,supersven/intellij-community,hurricup/intellij-community,dslomov/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,consulo/consulo,samthor/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,ibinti/intellij-community,blademainer/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,ernestp/consulo,apixandru/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,gnuhub/intellij-community,jexp/idea2,Distrotech/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,semonte/intellij-community,youdonghai/intellij-community,kool79/intellij-community,diorcety/intellij-community,vladmm/intellij-community,samthor/intellij-community,caot/intellij-community,da1z/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,ibinti/intellij-community,fitermay/intellij-community,hurricup/intellij-community,allotria/intellij-community,gnuhub/intellij-community,supersven/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ernestp/consulo,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,slisson/intellij-community,signed/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,kdwink/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,caot/intellij-community,jexp/idea2,fnouama/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,caot/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,izonder/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,supersven/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,clumsy/intellij-community,da1z/intellij-community,slisson/intellij-community,allotria/intellij-community,caot/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,adedayo/intellij-community,da1z/intellij-community,fnouama/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,robovm/robovm-studio,ibinti/intellij-community,fitermay/intellij-community,jagguli/intellij-community,dslomov/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,fitermay/intellij-community,adedayo/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,allotria/intellij-community,tmpgit/intellij-community,izonder/intellij-community,signed/intellij-community,robovm/robovm-studio,holmes/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,joewalnes/idea-community,apixandru/intellij-community,fitermay/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,signed/intellij-community,jexp/idea2,fitermay/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,amith01994/intellij-community,vladmm/intellij-community,ibinti/intellij-community,diorcety/intellij-community,FHannes/intellij-community,xfournet/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,caot/intellij-community,izonder/intellij-community,nicolargo/intellij-community,samthor/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,kdwink/intellij-community,kool79/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,semonte/intellij-community,Lekanich/intellij-community,semonte/intellij-community,samthor/intellij-community,jexp/idea2,blademainer/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,kool79/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,semonte/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,FHannes/intellij-community,dslomov/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,tmpgit/intellij-community,holmes/intellij-community,retomerz/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,signed/intellij-community,consulo/consulo,asedunov/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,ernestp/consulo,adedayo/intellij-community,supersven/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,slisson/intellij-community,allotria/intellij-community,amith01994/intellij-community,izonder/intellij-community,retomerz/intellij-community,da1z/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,ibinti/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,izonder/intellij-community,signed/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,robovm/robovm-studio,adedayo/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,kdwink/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,diorcety/intellij-community,blademainer/intellij-community,ibinti/intellij-community,kool79/intellij-community,holmes/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,joewalnes/idea-community,blademainer/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,asedunov/intellij-community,consulo/consulo,izonder/intellij-community,kdwink/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,robovm/robovm-studio,clumsy/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ernestp/consulo,tmpgit/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,clumsy/intellij-community,retomerz/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,signed/intellij-community,da1z/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,izonder/intellij-community,ernestp/consulo,Lekanich/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,jexp/idea2,vvv1559/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,allotria/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,holmes/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,jexp/idea2,holmes/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,signed/intellij-community,hurricup/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,retomerz/intellij-community,kdwink/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,diorcety/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,adedayo/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,jexp/idea2,lucafavatella/intellij-community,xfournet/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,jexp/idea2,orekyuu/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,kdwink/intellij-community,apixandru/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,caot/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,asedunov/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,signed/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,kool79/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,allotria/intellij-community,kool79/intellij-community,da1z/intellij-community,ryano144/intellij-community,asedunov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,xfournet/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,caot/intellij-community,hurricup/intellij-community,fnouama/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,samthor/intellij-community,retomerz/intellij-community,vladmm/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,consulo/consulo,slisson/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,signed/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,samthor/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,consulo/consulo,retomerz/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,amith01994/intellij-community,diorcety/intellij-community,fnouama/intellij-community,diorcety/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,da1z/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,hurricup/intellij-community,caot/intellij-community,caot/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,jagguli/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,allotria/intellij-community,ryano144/intellij-community,semonte/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,samthor/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,signed/intellij-community,holmes/intellij-community
/* * Copyright 2000-2005 JetBrains s.r.o. * * 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.intellij.openapi.components; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; /** * The base interface class for all components. * * @see ApplicationComponent * @see ProjectComponent */ public interface BaseComponent { /** * Unique name of this component. If there is another component with the same name or * name is null internal assertion will occur. * * @return the name of this component */ @NonNls @NotNull String getComponentName(); /** * Component should do initialization and communication with another components in this method. */ void initComponent(); /** * Component should dispose system resources or perform another cleanup in this method. */ void disposeComponent(); }
appcore/src/api/com/intellij/openapi/components/BaseComponent.java
/* * Copyright 2000-2005 JetBrains s.r.o. * * 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.intellij.openapi.components; import org.jetbrains.annotations.NonNls; /** * The base interface class for all components. * * @see ApplicationComponent * @see ProjectComponent */ public interface BaseComponent { /** * Unique name of this component. If there is another component with the same name or * name is null internal assertion will occur. * * @return the name of this component */ @NonNls String getComponentName(); /** * Component should do initialization and communication with another components in this method. */ void initComponent(); /** * Component should dispose system resources or perform another cleanup in this method. */ void disposeComponent(); }
tests fix
appcore/src/api/com/intellij/openapi/components/BaseComponent.java
tests fix
<ide><path>ppcore/src/api/com/intellij/openapi/components/BaseComponent.java <ide> package com.intellij.openapi.components; <ide> <ide> import org.jetbrains.annotations.NonNls; <add>import org.jetbrains.annotations.NotNull; <ide> <ide> /** <ide> * The base interface class for all components. <ide> * <ide> * @return the name of this component <ide> */ <del> @NonNls <add> @NonNls @NotNull <ide> String getComponentName(); <ide> <ide> /**
JavaScript
mit
f01421b0914c84d19939eca79d796e3e6f3ef8dd
0
webuildsg/webuild,webuildsg/webuild,webuildsg/webuild
'use strict' var express = require('express') var bodyParser = require('body-parser') var compress = require('compression') var errorHandler = require('errorhandler') var http = require('http') var path = require('path') var request = require('request') var cors = require('cors') var cal = require('./lib/cal') var morgan = require('morgan') var logger = require('./lib/logger') var updateLib = require('./lib/update') var app = express() var configLib = require('./config.js') configLib(function (config) { var wb = require('webuild-events').init(config) wb.repos = require('webuild-repos').init(config).repos var archives = require('./archives').init(config) var podcastApiUrl = config.podcastApiUrl var whitelistGroups = config.whitelistGroups app.use(compress()) app.set('view engine', 'pug') app.use('/public', express.static(path.join(__dirname, '/public'))) app.use('/humans.txt', express.static(path.join(__dirname, '/public/humans.txt'))) app.use('/robots.txt', express.static(path.join(__dirname, '/public/robots.txt'))) app.use(errorHandler()) app.use(bodyParser.urlencoded({ extended: true })) app.use(wb.passport.initialize()) app.use(morgan(':date[iso] :method :url :status - :response-time ms')) app.locals.pretty = true app.locals.moment = require('moment-timezone') app.get('/', function (req, res) { res.render('./index.pug', { repos: wb.repos.feed.repos.slice(0, 10), events: wb.events.feed.events.slice(0, 10) }) }) app.get('/api/v1/check/:checkdate', cors(), function (req, res) { var clashedEvents = require('./lib/clashedEvents') res.send(clashedEvents(req.params.checkdate, config, wb.events.feed.events)) }) app.get('/api/v1/events', cors(), function (req, res) { return req.query.n ? res.send(wb.events.get(req.query.n)) : res.send(wb.events.feed) }) app.get('/api/v1/events/day', cors(), function (req, res) { res.send(wb.events.day) }) app.get('/api/v1/events/hour', cors(), function (req, res) { res.send(wb.events.hour) }) app.get('/api/v1/repos', cors(), function (req, res) { return req.query.n ? res.send(wb.repos.get(req.query.n)) : res.send(wb.repos.feed) }) app.get('/api/v1/repos/day', cors(), function (req, res) { res.send(wb.repos.day) }) app.get('/api/v1/repos/hour', cors(), function (req, res) { res.send(wb.repos.hour) }) app.get('/api/v1/repos/:language', cors(), function (req, res) { var reposWithLanguage = require('./lib/reposWithLanguage')(req.params, config, wb.repos) res.send(reposWithLanguage) }) app.get('/admin', function (req, res) { res.render('./admin.pug', { auth0: config.auth0, error: req.query.error, user: req.query.user ? req.query.user : '', groups: require('./lib/notApprovedGroups')(wb.events.feed.events, whitelistGroups) }) }) app.get('/apps', function (req, res) { res.render('./apps.pug') }) app.get('/privacy', function (req, res) { res.render('./privacy.pug') }) app.get('/cal', function (req, res) { cal(config, wb.events.feed.events, res) }) app.get('/check', function (req, res) { res.redirect('/#check') }) app.get('/callback', wb.passport.callback) app.post('/api/v1/events/update', function (req, res) { updateLib(req, res, wb, 'events') }) app.post('/api/v1/repos/update', function (req, res) { updateLib(req, res, wb, 'repos') }) app.post('/api/v1/archives/update', function (req, res) { if (req.body.secret !== process.env.WEBUILD_API_SECRET) { res.status(503).send('Incorrect secret key') return } var dataOptions = { events: wb.events.day, repos: wb.repos.day } archives.update(dataOptions) res.status(200).send('Updating the archives sit tight!') }) app.use('/api/v1/podcasts', cors(), function (req, res) { res.setHeader('Cache-Control', 'public, max-age=86400') // 1 day request(podcastApiUrl, function (err, msg, response) { if (err) { res.status(503).send('We Build Live Error') return } res.end(response) }) }) app.use(function (req, res) { res.redirect('/') }) var ip = process.env.NODE_IP || process.env.OPENSHIFT_NODE4_IP || '0.0.0.0' var port = process.env.NODE_PORT || process.env.OPENSHIFT_NODE4_PORT || process.env.PORT || 3000 http.createServer(app).listen(port, ip, function () { logger.trace(`Express server started at ${ip}:${port}`) }) })
app.js
'use strict' var express = require('express') var bodyParser = require('body-parser') var compress = require('compression') var errorHandler = require('errorhandler') var http = require('http') var path = require('path') var request = require('request') var cors = require('cors') var cal = require('./lib/cal') var morgan = require('morgan') var logger = require('./lib/logger') var updateLib = require('./lib/update') var app = express() var configLib = require('./config.js') configLib(function (config) { var wb = require('webuild-events').init(config) wb.repos = require('webuild-repos').init(config).repos var archives = require('./archives').init(config) var podcastApiUrl = config.podcastApiUrl var whitelistGroups = config.whitelistGroups app.use(compress()) app.set('view engine', 'pug'); app.use('/public', express.static(path.join(__dirname, '/public'))) app.use('/humans.txt', express.static(path.join(__dirname, '/public/humans.txt'))) app.use('/robots.txt', express.static(path.join(__dirname, '/public/robots.txt'))) app.use(errorHandler()) app.use(bodyParser.urlencoded({ extended: true })) app.use(wb.passport.initialize()) app.use(morgan(':date[iso] :method :url :status - :response-time ms')) app.locals.pretty = true app.locals.moment = require('moment-timezone') app.get('/', function (req, res) { res.render('./index.pug', { repos: wb.repos.feed.repos.slice(0, 10), events: wb.events.feed.events.slice(0, 10) }) }) app.get('/api/v1/check/:checkdate', cors(), function (req, res) { var clashedEvents = require('./lib/clashedEvents') res.send(clashedEvents(req.params.checkdate, config, wb.events.feed.events)) }) app.get('/api/v1/events', cors(), function (req, res) { return req.query.n ? res.send(wb.events.get(req.query.n)) : res.send(wb.events.feed) }) app.get('/api/v1/events/day', cors(), function (req, res) { res.send(wb.events.day) }) app.get('/api/v1/events/hour', cors(), function (req, res) { res.send(wb.events.hour) }) app.get('/api/v1/repos', cors(), function (req, res) { return req.query.n ? res.send(wb.repos.get(req.query.n)) : res.send(wb.repos.feed) }) app.get('/api/v1/repos/day', cors(), function (req, res) { res.send(wb.repos.day) }) app.get('/api/v1/repos/hour', cors(), function (req, res) { res.send(wb.repos.hour) }) app.get('/api/v1/repos/:language', cors(), function (req, res) { var reposWithLanguage = require('./lib/reposWithLanguage')(req.params, config, wb.repos) res.send(reposWithLanguage) }) app.get('/admin', function (req, res) { res.render('./admin.pug', { auth0: config.auth0, error: req.query.error, user: req.query.user ? req.query.user : '', groups: require('./lib/notApprovedGroups')(wb.events.feed.events, whitelistGroups) }) }) app.get('/apps', function (req, res) { res.render('./apps.pug') }) app.get('/privacy', function (req, res) { res.render('./privacy.pug') }) app.get('/cal', function (req, res) { cal(config, wb.events.feed.events, res) }) app.get('/check', function (req, res) { res.redirect('/#check') }) app.get('/callback', wb.passport.callback) app.post('/api/v1/events/update', function (req, res) { updateLib(req, res, wb, 'events') }) app.post('/api/v1/repos/update', function (req, res) { updateLib(req, res, wb, 'repos') }) app.post('/api/v1/archives/update', function (req, res) { if (req.body.secret !== process.env.WEBUILD_API_SECRET) { res.status(503).send('Incorrect secret key') return } var dataOptions = { events: wb.events.day, repos: wb.repos.day } archives.update(dataOptions) res.status(200).send('Updating the archives sit tight!') }) app.use('/api/v1/podcasts', cors(), function (req, res) { res.setHeader('Cache-Control', 'public, max-age=86400') // 1 day request(podcastApiUrl, function (err, msg, response) { if (err) { res.status(503).send('We Build Live Error') return } res.end(response) }) }) app.use(function (req, res) { res.redirect('/') }) var ip = process.env.NODE_IP || process.env.OPENSHIFT_NODE4_IP || '0.0.0.0' var port = process.env.NODE_PORT || process.env.OPENSHIFT_NODE4_PORT || process.env.PORT || 3000 http.createServer(app).listen(port, ip, function () { logger.trace(`Express server started at ${ip}:${port}`) }) })
fix build remove semicolon
app.js
fix build remove semicolon
<ide><path>pp.js <ide> var whitelistGroups = config.whitelistGroups <ide> <ide> app.use(compress()) <del> app.set('view engine', 'pug'); <add> app.set('view engine', 'pug') <ide> app.use('/public', express.static(path.join(__dirname, '/public'))) <ide> app.use('/humans.txt', express.static(path.join(__dirname, '/public/humans.txt'))) <ide> app.use('/robots.txt', express.static(path.join(__dirname, '/public/robots.txt')))
Java
apache-2.0
3008ae4942f1d6784d8e1b71ffc23b41d0a5ab3b
0
aw32/son-sp-infrabstract,aw32/son-sp-infrabstract,aw32/son-sp-infrabstract,aw32/son-sp-infrabstract,aw32/son-sp-infrabstract
sandman/placement/src/main/java/sonata/kernel/placement/service/PlacementMapping.java
package sonata.kernel.placement.service; import sonata.kernel.placement.config.PopResource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; public class PlacementMapping { final static Logger logger = Logger.getLogger(PlacementMapping.class); public final List<PopResource> resources; // Maps instance node names to resource node names public final Map<String,String> mapping; // Maps instance node names to pop // should be consistent to the "mapping" map public final Map<String,PopResource> popMapping; public PlacementMapping(){ logger.debug("Placement Mapping"); mapping = new HashMap<String,String>(); resources = new ArrayList<PopResource>(); popMapping = new HashMap<String,PopResource>(); } }
Removed PlacementMapping
sandman/placement/src/main/java/sonata/kernel/placement/service/PlacementMapping.java
Removed PlacementMapping
<ide><path>andman/placement/src/main/java/sonata/kernel/placement/service/PlacementMapping.java <del>package sonata.kernel.placement.service; <del> <del>import sonata.kernel.placement.config.PopResource; <del> <del>import java.util.ArrayList; <del>import java.util.HashMap; <del>import java.util.List; <del>import java.util.Map; <del> <del>import org.apache.log4j.Logger; <del> <del>public class PlacementMapping { <del> final static Logger logger = Logger.getLogger(PlacementMapping.class); <del> public final List<PopResource> resources; <del> <del> // Maps instance node names to resource node names <del> public final Map<String,String> mapping; <del> <del> // Maps instance node names to pop <del> // should be consistent to the "mapping" map <del> public final Map<String,PopResource> popMapping; <del> <del> <del> public PlacementMapping(){ <del> logger.debug("Placement Mapping"); <del> mapping = new HashMap<String,String>(); <del> resources = new ArrayList<PopResource>(); <del> popMapping = new HashMap<String,PopResource>(); <del> } <del> <del>}
Java
mit
7634271c0be639882fb3199b930290d3f3ae02a3
0
etsy/statsd-jvm-profiler,etsy/statsd-jvm-profiler,etsy/statsd-jvm-profiler,etsy/statsd-jvm-profiler,etsy/statsd-jvm-profiler
package com.etsy.statsd.profiler.reporter; import com.etsy.statsd.profiler.Arguments; import com.etsy.statsd.profiler.util.TagUtil; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import org.influxdb.InfluxDB; import org.influxdb.InfluxDBFactory; import org.influxdb.dto.BatchPoints; import org.influxdb.dto.Point; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * Reporter that sends data to InfluxDB * * @author Andrew Johnson */ public class InfluxDBReporter extends Reporter<InfluxDB> { private static final Logger LOGGER = Logger.getLogger(InfluxDBReporter.class.getName()); public static final String VALUE_COLUMN = "value"; public static final String USERNAME_ARG = "username"; public static final String PASSWORD_ARG = "password"; public static final String DATABASE_ARG = "database"; public static final String TAG_MAPPING_ARG = "tagMapping"; public static final String USE_HTTPS_ARG = "useHttps"; private String username; private String password; private String database; private String tagMapping; private Boolean useHttps; private final Map<String, String> tags; public InfluxDBReporter(Arguments arguments) { super(arguments); String prefix = arguments.metricsPrefix; // If we have a tag mapping it must match the number of components of the prefix Preconditions.checkArgument(tagMapping == null || tagMapping.split("\\.").length == prefix.split("\\.").length); tags = TagUtil.getTags(tagMapping, prefix, true); } /** * Record a gauge value in InfluxDB * * @param key The key for the gauge * @param value The value of the gauge */ @Override public void recordGaugeValue(String key, long value) { Map<String, Long> gauges = ImmutableMap.of(key, value); recordGaugeValues(gauges); } /** * @see #recordGaugeValue(String, long) */ @Override public void recordGaugeValue(String key, double value) { Map<String, ? extends Number> gauges = ImmutableMap.of(key, value); recordGaugeValues(gauges); } /** * Record multiple gauge values in InfluxDB * * @param gauges A map of gauge names to values */ @Override public void recordGaugeValues(Map<String, ? extends Number> gauges) { long time = System.currentTimeMillis(); BatchPoints batchPoints = BatchPoints.database(database).build(); for (Map.Entry<String, ? extends Number> gauge: gauges.entrySet()) { batchPoints.point(constructPoint(time, gauge.getKey(), gauge.getValue())); } client.write(batchPoints); } /** * InfluxDB has a rich query language and does not need the bounds metrics emitted by CPUTracingProfiler * As such we can disable emitting these metrics * * @return false */ @Override public boolean emitBounds() { return false; } /** * * @param server The server to which to report data * @param port The port on which the server is running * @param prefix The prefix for metrics * @return An InfluxDB client */ @Override protected InfluxDB createClient(String server, int port, String prefix) { String protocol = useHttps ? "https" : "http"; String url = String.format("%s://%s:%d", protocol, server, port); logInfo(String.format("Connecting to influxDB at %s", url)); return InfluxDBFactory.connect(url, username, password); } private void logInfo(String message) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info(message); } } /** * Handle remaining arguments * * @param arguments The arguments given to the profiler agent */ @Override protected void handleArguments(Arguments arguments) { username = arguments.remainingArgs.get(USERNAME_ARG); password = arguments.remainingArgs.get(PASSWORD_ARG); database = arguments.remainingArgs.get(DATABASE_ARG); tagMapping = arguments.remainingArgs.get(TAG_MAPPING_ARG); if (arguments.remainingArgs.containsKey(USE_HTTPS_ARG)) { useHttps = Boolean.parseBoolean(arguments.remainingArgs.get(USE_HTTPS_ARG)); } else { useHttps = false; } logInfo(String.format("Received arguments: username = %s, password = XXXXX, database = %s, tagMapping= %s, useHttps = %s", username, database, tagMapping, useHttps)); Preconditions.checkNotNull(username); Preconditions.checkNotNull(password); Preconditions.checkNotNull(database); } private Point constructPoint(long time, String key, Number value) { Point.Builder builder = Point.measurement(key) .time(time, TimeUnit.MILLISECONDS) .field(VALUE_COLUMN, value); for (Map.Entry<String, String> entry : tags.entrySet()) { builder = builder.tag(entry.getKey(), entry.getValue()); } return builder.build(); } }
src/main/java/com/etsy/statsd/profiler/reporter/InfluxDBReporter.java
package com.etsy.statsd.profiler.reporter; import com.etsy.statsd.profiler.Arguments; import com.etsy.statsd.profiler.util.TagUtil; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import org.influxdb.InfluxDB; import org.influxdb.InfluxDBFactory; import org.influxdb.dto.BatchPoints; import org.influxdb.dto.Point; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Reporter that sends data to InfluxDB * * @author Andrew Johnson */ public class InfluxDBReporter extends Reporter<InfluxDB> { public static final String VALUE_COLUMN = "value"; public static final String USERNAME_ARG = "username"; public static final String PASSWORD_ARG = "password"; public static final String DATABASE_ARG = "database"; public static final String TAG_MAPPING_ARG = "tagMapping"; private String username; private String password; private String database; private String tagMapping; private final Map<String, String> tags; public InfluxDBReporter(Arguments arguments) { super(arguments); String prefix = arguments.metricsPrefix; // If we have a tag mapping it must match the number of components of the prefix Preconditions.checkArgument(tagMapping == null || tagMapping.split("\\.").length == prefix.split("\\.").length); tags = TagUtil.getTags(tagMapping, prefix, true); } /** * Record a gauge value in InfluxDB * * @param key The key for the gauge * @param value The value of the gauge */ @Override public void recordGaugeValue(String key, long value) { Map<String, Long> gauges = ImmutableMap.of(key, value); recordGaugeValues(gauges); } /** * @see #recordGaugeValue(String, long) */ @Override public void recordGaugeValue(String key, double value) { Map<String, ? extends Number> gauges = ImmutableMap.of(key, value); recordGaugeValues(gauges); } /** * Record multiple gauge values in InfluxDB * * @param gauges A map of gauge names to values */ @Override public void recordGaugeValues(Map<String, ? extends Number> gauges) { long time = System.currentTimeMillis(); BatchPoints batchPoints = BatchPoints.database(database).build(); for (Map.Entry<String, ? extends Number> gauge: gauges.entrySet()) { batchPoints.point(constructPoint(time, gauge.getKey(), gauge.getValue())); } client.write(batchPoints); } /** * InfluxDB has a rich query language and does not need the bounds metrics emitted by CPUTracingProfiler * As such we can disable emitting these metrics * * @return false */ @Override public boolean emitBounds() { return false; } /** * * @param server The server to which to report data * @param port The port on which the server is running * @param prefix The prefix for metrics * @return An InfluxDB client */ @Override protected InfluxDB createClient(String server, int port, String prefix) { return InfluxDBFactory.connect(String.format("http://%s:%d", server, port), username, password); } /** * Handle remaining arguments * * @param arguments The arguments given to the profiler agent */ @Override protected void handleArguments(Arguments arguments) { username = arguments.remainingArgs.get(USERNAME_ARG); password = arguments.remainingArgs.get(PASSWORD_ARG); database = arguments.remainingArgs.get(DATABASE_ARG); tagMapping = arguments.remainingArgs.get(TAG_MAPPING_ARG); Preconditions.checkNotNull(username); Preconditions.checkNotNull(password); Preconditions.checkNotNull(database); } private Point constructPoint(long time, String key, Number value) { Point.Builder builder = Point.measurement(key) .time(time, TimeUnit.MILLISECONDS) .field(VALUE_COLUMN, value); for (Map.Entry<String, String> entry : tags.entrySet()) { builder = builder.tag(entry.getKey(), entry.getValue()); } return builder.build(); } }
added https support
src/main/java/com/etsy/statsd/profiler/reporter/InfluxDBReporter.java
added https support
<ide><path>rc/main/java/com/etsy/statsd/profiler/reporter/InfluxDBReporter.java <ide> <ide> import java.util.Map; <ide> import java.util.concurrent.TimeUnit; <add>import java.util.logging.Level; <add>import java.util.logging.Logger; <ide> <ide> /** <ide> * Reporter that sends data to InfluxDB <ide> * @author Andrew Johnson <ide> */ <ide> public class InfluxDBReporter extends Reporter<InfluxDB> { <add> private static final Logger LOGGER = Logger.getLogger(InfluxDBReporter.class.getName()); <add> <ide> public static final String VALUE_COLUMN = "value"; <ide> public static final String USERNAME_ARG = "username"; <ide> public static final String PASSWORD_ARG = "password"; <ide> public static final String DATABASE_ARG = "database"; <ide> public static final String TAG_MAPPING_ARG = "tagMapping"; <add> public static final String USE_HTTPS_ARG = "useHttps"; <ide> <ide> private String username; <ide> private String password; <ide> private String database; <ide> private String tagMapping; <add> private Boolean useHttps; <ide> private final Map<String, String> tags; <ide> <ide> public InfluxDBReporter(Arguments arguments) { <ide> */ <ide> @Override <ide> protected InfluxDB createClient(String server, int port, String prefix) { <del> return InfluxDBFactory.connect(String.format("http://%s:%d", server, port), username, password); <add> String protocol = useHttps ? "https" : "http"; <add> String url = String.format("%s://%s:%d", protocol, server, port); <add> logInfo(String.format("Connecting to influxDB at %s", url)); <add> <add> return InfluxDBFactory.connect(url, username, password); <add> } <add> <add> private void logInfo(String message) { <add> if (LOGGER.isLoggable(Level.INFO)) { <add> LOGGER.info(message); <add> } <ide> } <ide> <ide> /** <ide> password = arguments.remainingArgs.get(PASSWORD_ARG); <ide> database = arguments.remainingArgs.get(DATABASE_ARG); <ide> tagMapping = arguments.remainingArgs.get(TAG_MAPPING_ARG); <add> if (arguments.remainingArgs.containsKey(USE_HTTPS_ARG)) { <add> useHttps = Boolean.parseBoolean(arguments.remainingArgs.get(USE_HTTPS_ARG)); <add> } else { <add> useHttps = false; <add> } <add> <add> logInfo(String.format("Received arguments: username = %s, password = XXXXX, database = %s, tagMapping= %s, useHttps = %s", username, database, tagMapping, useHttps)); <ide> <ide> Preconditions.checkNotNull(username); <ide> Preconditions.checkNotNull(password);
JavaScript
mit
71ba78952667e707052fff5755172637426d5298
0
anrl/JAM,anrl/JAM,anrl/JAM,anrl/JAM,anrl/JAM,anrl/JAM
/* eslint-env node */ 'use strict'; // -------------------------------------------------------------------- // Imports // -------------------------------------------------------------------- var fs = require('fs'); var path = require('path'); var ohm = require('ohm-js'); var cTranslator = require('../c/c').cTranslator; // var cSymbolTable = require('../c/c').cSymbolTable; var es5Translator = require('../ecmascript/es5').es5Translator; // -------------------------------------------------------------------- // Helpers // -------------------------------------------------------------------- var ActivityID = 0; var callbacks = { c: { async: [], sync: [] }, js: { async: [], sync: [] } }; var typedefs = []; var namespace_funcs = []; var activities = { c: { async: [], sync: [] }, js: { async: [], sync: [] } }; var prototypes = new Map(); var types = { 'int': { c_pattern: '%i', jamlib: 'ival', js_type: 'number', c_code: 'i', js_code: 'n' }, 'float': { c_pattern: '%f', jamlib: 'dval', js_type: 'number', c_code: 'f', js_code: 'n' }, 'char*': { c_pattern: '\\"%s\\"', jamlib: 'sval', js_type: 'string', c_code: 's', js_code: 's' }, 'jcallback': { c_pattern: '\\"%s\\"', jamlib: 'sval', js_type: 'string', c_code: 's', js_code: 's' } }; function error(node, message) { throw message; } // function generate_c_async_callbacks(callbackFuncs) { // var cout = ''; // callbackFuncs.forEach(function(value, key) { // var c_codes = []; // cout += 'void call' + key + '(void *act, void *arg) {\n'; // cout += 'command_t *cmd = (command_t *)arg;\n'; // cout += key + '('; // for (var i = 0; i < value.length; i++) { // var param = value[i]; // var pointer = ''; // if(param.pointer != undefined) { // pointer = ' ' + CTranslator.match(param.pointer, 'walk').trim(); // } // cout += 'cmd->args[' + i + '].val.' + types[param.type].jamlib // if(i < value.length - 1 ) { // cout += ', '; // } // c_codes.push(types[param.type].c_code); // } // cout += ');\n'; // cout += '}\n'; // callbacks.c.sync.push([key, undefined, c_codes]); // }); // return cout; // } function generate_js_logger_vars() { var jsout = ''; symbolTable.forEach(function(value, key, map) { if(value.type == 'jdata' && value.other.jdata_type == 'logger') { jsout += `var ${key} = new JLogger("${key}", false, JManager);\n`; } }); return jsout; } function generate_c_broadcaster_vars() { var cout = ''; symbolTable.forEach(function(value, key, map) { if(value.type == 'jdata' && value.other.jdata_type == 'broadcaster') { cout += `jbroadcaster *${key} = jbraodcaster_init(JBROADCAST_STRING, "${key}", ((void*)0));\n`; } }); return cout; } function generate_c_shuffler_vars() { var cout = ''; symbolTable.forEach(function(value, key, map) { if(value.type == 'jdata' && value.other.jdata_type == 'shuffler') { cout += `jbroadcaster *${key} = jshuffler_init(JBROADCAST_STRING, "${key}", ((void*)0));\n`; } }); return cout; } function generate_js_callbacks() { var jsout = ''; for (var i = 0; i < callbacks.js.sync.length; i++) { var callback = callbacks.js.sync[i]; jsout += 'jlib.JServer.registerCallback(' + callback[0] + ', "' + callback[1].join('') + '");\n'; } for (var i = 0; i < callbacks.js.async.length; i++) { var callback = callbacks.js.async[i]; jsout += 'jlib.JServer.registerCallback(' + callback[0] + ', "' + callback[1].join('') + '");\n'; } return jsout; } function generate_c_activities() { var cout = ''; for (var i = 0; i < callbacks.c.sync.length; i++) { var callback = callbacks.c.sync[i]; cout += 'activity_regcallback(js->atable, "' + callback[0] + '", SYNC, "' + callback[2].join('') + '", call' + callback[0] + ');\n'; } for (var i = 0; i < callbacks.c.async.length; i++) { var callback = callbacks.c.async[i]; cout += 'activity_regcallback(js->atable, "' + callback[0] + '", ASYNC, "' + callback[2].join('') + '", call' + callback[0] + ');\n'; } return cout; } function generate_jam_run_app() { var cout = '\nvoid jam_run_app(void *arg) {\n'; cout += 'user_main();\n' cout += '}\n'; return cout; } function generate_setup() { var cout = '\nvoid user_setup() {\n'; cout += generate_c_activities(); cout += '}\n'; return cout; } function generate_taskmain() { var cout = `\nvoid taskmain(int argc, char **argv) {\n js = jam_init(); user_setup(); taskcreate(jam_event_loop, js, 50000); taskcreate(jam_run_app, js, 50000); }`; return cout; } function CreateCASyncJSFunction(fname, params) { var ps = []; params.forEach(function(p) { ps.push(p.name); }); var funccode = "function " + fname + "(" + ps.join(',') + ") {"; // write the code that would call the remote function funccode += 'jlib.JServer.remoteAsyncExec("' + fname + '", [' + ps.join(',') + '], "true");'; // write the end of the function funccode += "}"; return { JS: funccode, annotated_JS: funccode } } function CreateCASyncCFunction(dspec, fname, params, stmt) { var cout = ""; var typed_params = []; var c_codes = []; params.forEach(function(p) { typed_params.push(p.type + ' ' + p.name); c_codes.push(types[p.type].c_code); }); // Main function cout += 'void ' + fname + '(' + typed_params.join(", ") + ')' + stmt; // Calling function cout += 'void call' + fname + '(void *act, void *arg) {\n'; cout += 'command_t *cmd = (command_t *)arg;\n'; cout += fname + '('; for (var i = 0; i < params.length; i++) { cout += 'cmd->args[' + i + '].val.' + types[params[i].type].jamlib; if(i < params.length - 1 ) { cout += ', '; } } cout += ');\n'; cout += '}\n'; callbacks.c.async.push([fname, undefined, c_codes]); return cout; } function CreateCSyncJSFunction(fname, params) { var ps = []; params.forEach(function(p) { ps.push(p.name); }); var funccode = fname + " = " + "async(function(" + ps.join(',') + ") {\n"; // write the code that would call the remote function funccode += 'await (jlib.JServer.remoteSyncExec("' + fname + '", [' + ps.join(',') + '], "true"));\n'; // write the end of the function funccode += "});\n"; return { JS: funccode, annotated_JS: funccode } } function CreateCSyncCFunction(dspec, fname, params, stmt) { var cout = ""; var typed_params = []; var c_codes = []; params.forEach(function(p) { typed_params.push(p.type + ' ' + p.name); c_codes.push(types[p.type].c_code); }); // Main function cout += dspec + ' ' + fname + '(' + typed_params.join(", ") + ')' + stmt + '\n'; // Calling function cout += 'void call' + fname + '(void *act, void *arg) {\n'; cout += 'command_t *cmd = (command_t *)arg;\n'; var funcCall = fname + '('; for (var i = 0; i < params.length; i++) { funcCall += 'cmd->args[' + i + '].val.' + types[params[i].type].jamlib if(i < params.length - 1 ) { cout += ', '; } } funcCall += ')'; if(dspec != 'void') { cout += 'activity_complete(js->atable, "' + types[dspec].c_code + '", ' + funcCall + ');\n'; } else { cout += funcCall + ';\n'; cout += 'activity_complete(js->atable, "");\n'; } cout += '}\n'; callbacks.c.sync.push([fname, undefined, c_codes]); return cout; } function CreateJSASyncJSFunction(fname, cParams, jParams, stmt) { var ps = []; var annotated_ps = []; var js_codes = []; for (var i = 0; i < cParams.length; i++) { ps.push(jParams[i]); annotated_ps.push(jParams[i] + ':' + types[cParams[i]].js_type); js_codes.push(types[cParams[i]].js_code); } var jsout = "function " + fname + "(" + ps.join(',') + ") {\n" + stmt + "\n}"; var annotated_jsout = "function " + fname + "(" + annotated_ps.join(',') + "): void" + stmt; callbacks.js.async.push([fname, js_codes, undefined]); return { JS: jsout, annotated_JS: annotated_jsout }; } function CreateJSASyncCFunction(fname, cParams, jParams) { var ps = [], qs = [], c_codes = []; for (var i = 0; i < cParams.length; i++) { ps.push(cParams[i] + ' ' + jParams[i]); qs.push(jParams[i]); c_codes.push(types[cParams[i]].c_code); } var cout = "jactivity_t *" + fname + "(" + ps.join(', ') + ") {\n"; cout += 'jactivity_t *res = jam_rexec_async(js, "' + fname + '", "' + c_codes.join('') + '"'; if(qs.length > 0) { cout += ',' + qs.join(', '); } cout += ');\n'; cout += 'return res;'; cout += '}\n'; return cout; } function CreateJSSyncJSFunction(rtype, fname, cParams, jParams, stmt) { var ps = []; var annotated_ps = []; var js_codes = []; for (var i = 0; i < cParams.length; i++) { ps.push(jParams[i]); annotated_ps.push(jParams[i] + ':' + types[cParams[i]].js_type); js_codes.push(types[cParams[i]].js_code); } var js_return_type; if(rtype == "void") { js_return_type = "void"; } else { js_return_type = types[rtype].js_type; } var jsout = "function " + fname + "(" + ps.join(',') + ") {\n" + stmt + "\n}"; var annotated_jsout = "function " + fname + "(" + annotated_ps.join(',') + "):" + js_return_type + stmt; callbacks.js.sync.push([fname, js_codes, undefined]); return { JS: jsout, annotated_JS: annotated_jsout }; } function CreateJSSyncCFunction(dspec, fname, cParams, jParams) { var ps = [], qs = []; var c_codes = []; for (var i = 0; i < cParams.length; i++) { ps.push(cParams[i] + ' ' + jParams[i]); qs.push(jParams[i]); c_codes.push(types[cParams[i]].c_code); } var cout = dspec + " " + fname + "(" + ps.join(', ') + ") {\n"; cout += 'arg_t *res = jam_rexec_sync(js, "' + fname + '", "' + c_codes.join('') + '"'; if(qs.length > 0) { cout += ',' + qs.join(', '); } cout += ');\n'; if(dspec == 'void') { cout += 'command_arg_free(res);\n' cout += 'return;\n'; } else { var retval = 'res->val.' + types[dspec].jamlib; if(dspec == 'char *') { retval = 'strdup(' + retval + ')'; } cout += dspec + ' ret = ' + retval + ';\n'; cout += 'command_arg_free(res);\n' cout += 'return ret;\n'; } cout += '}\n'; return cout; } function isUndefined(x) { return x === void 0; } // Take an Array of nodes, and whenever an _iter node is encountered, splice in its // recursively-flattened children instead. function flattenIterNodes(nodes) { var result = []; for (var i = 0; i < nodes.length; ++i) { if (nodes[i]._node.ctorName === '_iter') { result.push.apply(result, flattenIterNodes(nodes[i].children)); } else { result.push(nodes[i]); } } return result; } // Comparison function for sorting nodes based on their source's start index. function compareByInterval(node, otherNode) { return node.source.startIdx - otherNode.source.startIdx; } function parseList(list, sep) { if(list.child(0).ctorName == "NonemptyListOf") { return parseNonEmptyList(list.child(0), sep); } else { return ""; } } function parseNonEmptyList(list, sep) { var code = list.child(0).jamCTranslator; var rest = list.child(2); for (var i = 0; i < rest.numChildren; i++) { code += sep + rest.child(i).jamCTranslator } return code; } function parseArrayList(list, sep) { var code = ''; for (var i = 0; i < list.numChildren; i++) { code += list.child(i).jamCTranslator + sep; } return code; } var symbolTable = new Map(); var jamJSTranslator = { Program: function(directives, elements) { var jsout = ""; var cout = ""; var annotated_JS = ""; jsout += "var jcondition = new Map();\n" for (var i = 0; i < elements.children.length; i++) { if(elements.child(i).child(0).child(0).ctorName == "Activity_def") { var output = elements.child(i).child(0).child(0).jamJSTranslator; cout += output.C + '\n'; jsout += output.JS + '\n'; annotated_JS += output.annotated_JS + '\n'; } else { jsout += elements.child(i).child(0).child(0).jamJSTranslator + '\n'; } } return {'C': cout, 'JS': jsout, 'annotated_JS': annotated_JS}; }, Activity_def: function(node) { return node.jamJSTranslator; }, jdata_type: function(type) { return type.sourceString; }, Jdata_spec: function(type_spec, id, _1, jdata_type, _2) { symbolTable.set(id.sourceString, { type: "jdata", other: { type_spec: type_spec.sourceString, jdata_type: jdata_type.jamJSTranslator } }); }, Jdata_decl: function(_1, _2, jdata_spec, _3) { jdata_spec.jamJSTranslator; return ''; }, Jcond_rule: function(id, op, num, _) { return 'jcondition_context["' + id.sourceString + '"] ' + op.sourceString + ' ' + num.es5Translator; }, Jcond_entry: function(type, _1, rules, _2) { var code = rules.child(0).jamJSTranslator; for (var i = 1; i < rules.numChildren; i++) { code += ' && ' + rules.child(i).jamJSTranslator; } return code; }, Jconditional: function(_1, id, _2, entries, _3) { return "jcondition.set('" + id.es5Translator + "', '" + entries.jamJSTranslator + "');"; }, Jcond_expr_paran: function(_1, expr, _2) { return "(" + expr.jamJSTranslator + ")"; }, Jcond_expr_not: function(_, expr) { return "!" + expr.jamJSTranslator; }, Jcond_expr_bin_op: function(expr1, op, expr2) { return expr1.jamJSTranslator + " " + op.sourceString + " " + expr2.jamJSTranslator; }, Jcond_expr_id: function(id) { return `eval(jcondition.get(${id.sourceString}))`; }, Jcond_specifier: function(_1, jconds, _2) { var jsout = ''; jsout += 'var jcondition_context = jlib.JServer.get_jcond();\n' jsout += 'if(!(' + jconds.jamJSTranslator + ')){\n' jsout += 'console.log(jlib.JServer.jcond_failure);\n'; jsout += 'jlib.JServer.jcond_failure;\n'; jsout += '}\n'; return jsout; }, Sync_activity: function(_, jcond_spec, functionDeclaration) { var jcond = ""; if(jcond_spec.numChildren > 0) { jcond = jcond_spec.jamJSTranslator; } var specs = functionDeclaration.jamJSTranslator; var rtype = undefined; var cParams; var jParams = specs.params; if(prototypes.has(specs.fname)) { rtype = prototypes.get(specs.fname).return_type; cParams = prototypes.get(specs.fname).params; } // activities.js.sync.push({ // name: specs.fname, // params: specs.params // }); // console.log(prototypes.keys()); var js_output = CreateJSSyncJSFunction(rtype, specs.fname, cParams, jParams, jcond + specs.block); var c_output = CreateJSSyncCFunction(rtype, specs.fname, cParams, jParams); return { C: c_output, JS: js_output.JS, annotated_JS: js_output.annotated_JS } }, Async_activity: function(_, jcond_spec, functionDeclaration) { var jcond = ""; if(jcond_spec.numChildren > 0) { jcond = jcond_spec.jamJSTranslator; } var specs = functionDeclaration.jamJSTranslator; // activities.js.sync.push({ // name: specs.fname, // params: specs.params // }); var cParams; var jParams = specs.params; if(prototypes.has(specs.fname)) { cParams = prototypes.get(specs.fname).params; } var js_output = CreateJSASyncJSFunction(specs.fname, cParams, jParams, jcond + specs.block); var c_output = CreateJSASyncCFunction(specs.fname, cParams, jParams); return { C: c_output, JS: js_output.JS, annotated_JS: js_output.annotated_JS } }, FunctionDeclaration: function(_1, id, _2, params, _3, _4, block, _5) { return { fname: id.es5Translator, params: params.jamJSTranslator, block: block.es5Translator } }, FormalParameterList: function(params){ var paramArray = []; if(params.child(0).ctorName == "NonemptyListOf") { var list = params.child(0); paramArray.push(list.child(0).es5Translator); var rest = list.child(2); for (var i = 0; i < rest.numChildren; i++) { paramArray.push(rest.child(i).es5Translator); } } return paramArray; }, _nonterminal: function(children) { var flatChildren = flattenIterNodes(children).sort(compareByInterval); var childResults = flatChildren.map(function(n) { return n.jamJSTranslator; }); if (flatChildren.length === 0 || childResults.every(isUndefined)) { return undefined; } var code = ''; for (var i = 0; i < flatChildren.length; ++i) { if (childResults[i] != null) { code += childResults[i]; } } return code; }, _terminal: function() { return this.primitiveValue; }, NonemptyListOf: function(first, sep, rest) { var code = first.jamJSTranslator; for (var i = 0; i < rest.numChildren; i++) { code += sep.child(i).primitiveValue + ' ' + rest.child(i).jamJSTranslator; } return code; }, EmptyListOf: function() { return ""; } } var jamCTranslator = { Namespace_spec: function(_, namespace) { return namespace.sourceString; }, Sync_activity: function(_, specs, decl, namespace, stmt) { var decl = declarator.jamCTranslator; var funcname = decl.name; var params = decl.params; var rtype = specs.cTranslator; if(decl.pointer != '') { rtype += decl.pointer } var namespc; if(namespace.numChildren > 0) { namespc = namespace.jamCTranslator // funcname = namespc + "_func_" + namespace_funcs[namespc].indexOf(funcname); } var js_output = CreateCSyncJSFunction(funcname, params); var c_output = CreateCSyncCFunction(rtype, funcname, params, stmt.cTranslator); return { C: c_output, JS: js_output.JS, annotated_JS: js_output.annotated_JS } }, Async_activity: function(_, decl, namespace, stmt) { var funcname = decl.jamCTranslator.name; var params = decl.jamCTranslator.params; if(namespace.numChildren > 0) { // funcname = namespc + "_func_" + namespace_funcs[namespc].indexOf(funcname); } var js_output = CreateCASyncJSFunction(funcname, params); var c_output = CreateCASyncCFunction("jactivity_t*", funcname, params, stmt.cTranslator); return { C: c_output, JS: js_output.JS, annotated_JS: js_output.annotated_JS } }, Activity_def: function(node) { return node.jamCTranslator; }, Source: function(decls) { var cout = ""; var jsout = ""; var annotated_JS = ""; for (var i = 0; i < decls.numChildren; i++) { // if(decls.child(i).child(0).ctorName == "Jdata_decl") { // decls.child(i).child(0).jamTranslator; // } else if(decls.child(i).child(0).ctorName == "Activity_def") { var output = decls.child(i).child(0).jamCTranslator; cout += output.C + '\n'; jsout += output.JS + '\n'; annotated_JS += output.annotated_JS + '\n'; } else if(decls.child(i).child(0).ctorName == "Prototype") { if(decls.child(i).child(0).sourceString == "int main();") { cout = ""; } cout += decls.child(i).child(0).jamCTranslator + '\n'; } else { cout += decls.child(i).child(0).cTranslator + '\n'; } } // cout += generate_c_async_callbacks(input.data.cCallbacks); cout = generate_c_broadcaster_vars() + cout; cout += generate_setup(); cout += generate_jam_run_app(); cout += generate_taskmain(); cout = 'jamstate_t *js;\n' + cout; cout = 'typedef char* jcallback;\n' + cout; jsout = generate_js_logger_vars() + jsout; jsout += generate_js_callbacks(); // annotated_JS = "/* @flow */\n" + struct_objects + annotated_JS + this.generate_js_callbacks(); return {'C': cout, 'JS': jsout, 'annotated_JS': annotated_JS}; }, Prototype: function(specs, pointer, id, _1, params, _2, gcc, _3) { var rtype = specs.cTranslator; if(pointer.numChildren > 0) { rtype += pointer.cTranslator; } var parameters = []; if(params.numChildren > 0) { parameters = params.jamCTranslator[0]; } prototypes.set(id.cTranslator, { return_type: rtype, params: parameters }); return this.cTranslator; }, Pcall_decl: function(node) { return node.jamCTranslator; }, Pcall_decl_ParamTypeList: function(_1, node, _2) { return node.jamCTranslator; }, Pcall_decl_Empty: function(_1, _2) { return []; }, Param_type_lst: function(param_list) { var params = [] params.push(param_list.child(0).jamCTranslator); // console.log(params); var rest = param_list.child(2); for (var i = 0; i < rest.numChildren; i++) { params.push(rest.child(i).jamCTranslator); } return params; }, Declarator: function(pointer, dir_declarator, _1, _2) { var dir_decl = dir_declarator.jamCTranslator; return { pointer: pointer.cTranslator, name: dir_decl.name, params: dir_decl.params } }, Dir_declarator_PCall: function(name, params) { return { name: name.cTranslator, params: params.jamCTranslator }; }, Dir_declarator_Id: function(id) { return { name: id.cTranslator } }, Dir_declarator: function(node) { return node.jamCTranslator; }, Param_decl: function(node) { return node.jamCTranslator; }, Param_decl_Declarator: function(decl_specs, decl) { var varType = decl_specs.cTranslator; if(decl.jamCTranslator.pointer != '') { varType += decl.jamCTranslator.pointer } return { type: varType, name: decl.jamCTranslator.name }; }, _nonterminal: function(children) { var flatChildren = flattenIterNodes(children).sort(compareByInterval); var childResults = flatChildren.map(function(n) { return n.jamCTranslator; }); if (flatChildren.length === 0 || childResults.every(isUndefined)) { return undefined; } var code = ''; for (var i = 0; i < flatChildren.length; ++i) { if (childResults[i] != null) { code += childResults[i]; } } return code; }, _terminal: function() { return this.primitiveValue; }, NonemptyListOf: function(first, sep, rest) { var code = first.jamCTranslator; for (var i = 0; i < rest.numChildren; i++) { code += sep.child(i).primitiveValue + ' ' + rest.child(i).jamCTranslator; } return code; }, EmptyListOf: function() { return ""; } } // cTranslator.Assign_expr_assign = function(left, op, right) { // var symbol = symbolTable.get(left.cTranslator); // if(symbol !== undefined) { // if(symbol.other.jdata_type == "broadcaster" ) { // error(left, 'Cannot save to broadcaster ' + left.cTranslator); // } else if(symbol.other.jdata_type == "logger") { // console.log(`jdata_log_to_server(${left.cTranslator}, "${right.cTranslator}", NULL)`); // return `jdata_log_to_server(${left.cTranslator}, "${right.cTranslator}", NULL)`; // } // } // return left.cTranslator + ' ' + op.sourceString + ' ' + right.cTranslator; // } cTranslator.Dir_declarator_Id = function(id) { var symbol = symbolTable.get(id.sourceString); if(symbol !== undefined) { if(symbol.other.jdata_type == "broadcaster" ) { error(id, 'Cannot declare broadcaster ' + id.sourceString); } } return id.sourceString; } cTranslator.Primary_expr = function(node) { if(node.ctorName == "id") { var symbol = symbolTable.get(node.sourceString); if(symbol !== undefined && symbol.type == "jdata") { if(symbol.other.jdata_type == "logger" || symbol.other.jdata_type == "shuffler") { error(node, 'Cannot read values from ' + symbol.other.jdata_type + ' ' + node.sourceString); } else if(symbol.other.jdata_type == "broadcaster") { return `get_broadcaster_value(${node.sourceString});` } else if(symbol.other.jdata_type == "shuffler") { return `(char *)jshuffler_poll(${node.sourceString});` } } } return node.cTranslator; } cTranslator.Assign_stmt = function(left, _1, right, _4) { var symbol = symbolTable.get(left.cTranslator); if(symbol !== undefined) { if(symbol.other.jdata_type == "broadcaster" ) { error(id, 'Cannot declare broadcaster ' + id.sourceString); } else if(symbol.other.jdata_type == "logger") { return `jdata_log_to_server("${left.cTranslator}", "${right.cTranslator}", ((void*)0));`; } else if(symbol.other.jdata_type == "shuffler") { return `jshuffler_push("${left.cTranslator}", "${right.cTranslator}");`; } } return left.cTranslator + ' = ' + right.cTranslator + ';'; } es5Translator.AssignmentStatement = function(left, _, right) { var symbol = symbolTable.get(left.es5Translator); if(symbol !== undefined) { if(symbol.other.jdata_type == "broadcaster" ) { return `JManager.broadcastMessage("${left.es5Translator}", "${right.es5Translator}"");`; } else if(symbol.other.jdata_type == "logger") { error(left, `Cannot write to logger var ${left.es5Translator} from javascript`); } } return left.es5Translator + ' = ' + right.es5Translator + ';'; } // Instantiate the JAMScript grammar. var jamc = fs.readFileSync(path.join(__dirname, 'jamc.ohm')); var jamjs = fs.readFileSync(path.join(__dirname, 'jamjs.ohm')); var ns = {}; ns.C = ohm.grammar(fs.readFileSync(path.join(__dirname, '../c/c.ohm'))); ns.ES5 = ohm.grammar(fs.readFileSync(path.join(__dirname, '../ecmascript/es5.ohm'))); var jamCGrammar = ohm.grammar(jamc, ns); var jamJSGrammar = ohm.grammar(jamjs, ns); var cSemantics = jamCGrammar.createSemantics(); var jsSemantics = jamJSGrammar.createSemantics(); cSemantics.addAttribute('jamCTranslator', jamCTranslator); cSemantics.addAttribute('cTranslator', cTranslator); jsSemantics.addAttribute('jamJSTranslator', jamJSTranslator); jsSemantics.addAttribute('es5Translator', es5Translator); // semantics.addAttribute('cSymbolTable', cSymbolTable); module.exports = { jamJSGrammar: jamJSGrammar, jamCGrammar: jamCGrammar, cSemantics: cSemantics, jsSemantics: jsSemantics };
lib/ohm/jamscript/jam.js
/* eslint-env node */ 'use strict'; // -------------------------------------------------------------------- // Imports // -------------------------------------------------------------------- var fs = require('fs'); var path = require('path'); var ohm = require('ohm-js'); var cTranslator = require('../c/c').cTranslator; // var cSymbolTable = require('../c/c').cSymbolTable; var es5Translator = require('../ecmascript/es5').es5Translator; // -------------------------------------------------------------------- // Helpers // -------------------------------------------------------------------- var ActivityID = 0; var callbacks = { c: { async: [], sync: [] }, js: { async: [], sync: [] } }; var typedefs = []; var namespace_funcs = []; var activities = { c: { async: [], sync: [] }, js: { async: [], sync: [] } }; var prototypes = new Map(); var types = { 'int': { c_pattern: '%i', jamlib: 'ival', js_type: 'number', c_code: 'i', js_code: 'n' }, 'float': { c_pattern: '%f', jamlib: 'dval', js_type: 'number', c_code: 'f', js_code: 'n' }, 'char*': { c_pattern: '\\"%s\\"', jamlib: 'sval', js_type: 'string', c_code: 's', js_code: 's' }, 'jcallback': { c_pattern: '\\"%s\\"', jamlib: 'sval', js_type: 'string', c_code: 's', js_code: 's' } }; function error(node, message) { throw message; } // function generate_c_async_callbacks(callbackFuncs) { // var cout = ''; // callbackFuncs.forEach(function(value, key) { // var c_codes = []; // cout += 'void call' + key + '(void *act, void *arg) {\n'; // cout += 'command_t *cmd = (command_t *)arg;\n'; // cout += key + '('; // for (var i = 0; i < value.length; i++) { // var param = value[i]; // var pointer = ''; // if(param.pointer != undefined) { // pointer = ' ' + CTranslator.match(param.pointer, 'walk').trim(); // } // cout += 'cmd->args[' + i + '].val.' + types[param.type].jamlib // if(i < value.length - 1 ) { // cout += ', '; // } // c_codes.push(types[param.type].c_code); // } // cout += ');\n'; // cout += '}\n'; // callbacks.c.sync.push([key, undefined, c_codes]); // }); // return cout; // } function generate_js_logger_vars() { var jsout = ''; symbolTable.forEach(function(value, key, map) { if(value.type == 'jdata' && value.other.jdata_type == 'logger') { jsout += `var ${key} = new JLogger("${key}", false, JManager);\n`; } }); return jsout; } function generate_c_broadcaster_vars() { var cout = ''; symbolTable.forEach(function(value, key, map) { if(value.type == 'jdata' && value.other.jdata_type == 'broadcaster') { cout += `jbroadcaster *${key} = jbraodcaster_init(JBROADCAST_STRING, "${key}", ((void*)0));\n`; } }); return cout; } function generate_c_shuffler_vars() { var cout = ''; symbolTable.forEach(function(value, key, map) { if(value.type == 'jdata' && value.other.jdata_type == 'shuffler') { cout += `jbroadcaster *${key} = jshuffler_init(JBROADCAST_STRING, "${key}", ((void*)0));\n`; } }); return cout; } function generate_js_callbacks() { var jsout = ''; for (var i = 0; i < callbacks.js.sync.length; i++) { var callback = callbacks.js.sync[i]; jsout += 'jlib.JServer.registerCallback(' + callback[0] + ', "' + callback[1].join('') + '");\n'; } for (var i = 0; i < callbacks.js.async.length; i++) { var callback = callbacks.js.async[i]; jsout += 'jlib.JServer.registerCallback(' + callback[0] + ', "' + callback[1].join('') + '");\n'; } return jsout; } function generate_c_activities() { var cout = ''; for (var i = 0; i < callbacks.c.sync.length; i++) { var callback = callbacks.c.sync[i]; cout += 'activity_regcallback(js->atable, "' + callback[0] + '", SYNC, "' + callback[2].join('') + '", call' + callback[0] + ');\n'; } for (var i = 0; i < callbacks.c.async.length; i++) { var callback = callbacks.c.async[i]; cout += 'activity_regcallback(js->atable, "' + callback[0] + '", ASYNC, "' + callback[2].join('') + '", call' + callback[0] + ');\n'; } return cout; } function generate_jam_run_app() { var cout = '\nvoid jam_run_app(void *arg) {\n'; cout += 'user_main();\n' cout += '}\n'; return cout; } function generate_setup() { var cout = '\nvoid user_setup() {\n'; cout += generate_c_activities(); cout += '}\n'; return cout; } function generate_taskmain() { var cout = `\nvoid taskmain(int argc, char **argv) {\n js = jam_init(); user_setup(); taskcreate(jam_event_loop, js, 50000); taskcreate(jam_run_app, js, 50000); }`; return cout; } function CreateCASyncJSFunction(fname, params) { var ps = []; params.forEach(function(p) { ps.push(p.name); }); var funccode = "function " + fname + "(" + ps.join(',') + ") {"; // write the code that would call the remote function funccode += 'jlib.JServer.remoteAsyncExec("' + fname + '", [' + ps.join(',') + '], "true");'; // write the end of the function funccode += "}"; return { JS: funccode, annotated_JS: funccode } } function CreateCASyncCFunction(dspec, fname, params, stmt) { var cout = ""; var typed_params = []; var c_codes = []; params.forEach(function(p) { typed_params.push(p.type + ' ' + p.name); c_codes.push(types[p.type].c_code); }); // Main function cout += 'void ' + fname + '(' + typed_params.join(", ") + ')' + stmt; // Calling function cout += 'void call' + fname + '(void *act, void *arg) {\n'; cout += 'command_t *cmd = (command_t *)arg;\n'; cout += fname + '('; for (var i = 0; i < params.length; i++) { cout += 'cmd->args[' + i + '].val.' + types[params[i].type].jamlib; if(i < params.length - 1 ) { cout += ', '; } } cout += ');\n'; cout += '}\n'; callbacks.c.async.push([fname, undefined, c_codes]); return cout; } function CreateCSyncJSFunction(fname, params) { var ps = []; params.forEach(function(p) { ps.push(p.name); }); var funccode = fname + " = " + "async(function(" + ps.join(',') + ") {\n"; // write the code that would call the remote function funccode += 'await (jlib.JServer.remoteSyncExec("' + fname + '", [' + ps.join(',') + '], "true"));\n'; // write the end of the function funccode += "});\n"; return { JS: funccode, annotated_JS: funccode } } function CreateCSyncCFunction(dspec, fname, params, stmt) { var cout = ""; var typed_params = []; var c_codes = []; params.forEach(function(p) { typed_params.push(p.type + ' ' + p.name); c_codes.push(types[p.type].c_code); }); // Main function cout += dspec + ' ' + fname + '(' + typed_params.join(", ") + ')' + stmt + '\n'; // Calling function cout += 'void call' + fname + '(void *act, void *arg) {\n'; cout += 'command_t *cmd = (command_t *)arg;\n'; var funcCall = fname + '('; for (var i = 0; i < params.length; i++) { funcCall += 'cmd->args[' + i + '].val.' + types[params[i].type].jamlib if(i < params.length - 1 ) { cout += ', '; } } funcCall += ')'; if(dspec != 'void') { cout += 'activity_complete(js->atable, "' + types[dspec].c_code + '", ' + funcCall + ');\n'; } else { cout += funcCall + ';\n'; cout += 'activity_complete(js->atable, "");\n'; } cout += '}\n'; callbacks.c.sync.push([fname, undefined, c_codes]); return cout; } function CreateJSASyncJSFunction(fname, cParams, jParams, stmt) { var ps = []; var annotated_ps = []; var js_codes = []; for (var i = 0; i < cParams.length; i++) { ps.push(jParams[i]); annotated_ps.push(jParams[i] + ':' + types[cParams[i]].js_type); js_codes.push(types[cParams[i]].js_code); } var jsout = "function " + fname + "(" + ps.join(',') + ") {\n" + stmt + "\n}"; var annotated_jsout = "function " + fname + "(" + annotated_ps.join(',') + "): void" + stmt; callbacks.js.async.push([fname, js_codes, undefined]); return { JS: jsout, annotated_JS: annotated_jsout }; } function CreateJSASyncCFunction(fname, cParams, jParams) { var ps = [], qs = [], c_codes = []; for (var i = 0; i < cParams.length; i++) { ps.push(cParams[i] + ' ' + jParams[i]); qs.push(jParams[i]); c_codes.push(types[cParams[i]].c_code); } var cout = "jactivity_t *" + fname + "(" + ps.join(', ') + ") {\n"; cout += 'jactivity_t *res = jam_rexec_async(js, "' + fname + '", "' + c_codes.join('') + '"'; if(qs.length > 0) { cout += ',' + qs.join(', '); } cout += ');\n'; cout += 'return res;'; cout += '}\n'; return cout; } function CreateJSSyncJSFunction(rtype, fname, cParams, jParams, stmt) { var ps = []; var annotated_ps = []; var js_codes = []; for (var i = 0; i < cParams.length; i++) { ps.push(jParams[i]); annotated_ps.push(jParams[i] + ':' + types[cParams[i]].js_type); js_codes.push(types[cParams[i]].js_code); } var js_return_type; if(rtype == "void") { js_return_type = "void"; } else { js_return_type = types[rtype].js_type; } var jsout = "function " + fname + "(" + ps.join(',') + ") {\n" + stmt + "\n}"; var annotated_jsout = "function " + fname + "(" + annotated_ps.join(',') + "):" + js_return_type + stmt; callbacks.js.sync.push([fname, js_codes, undefined]); return { JS: jsout, annotated_JS: annotated_jsout }; } function CreateJSSyncCFunction(dspec, fname, cParams, jParams) { var ps = [], qs = []; var c_codes = []; for (var i = 0; i < cParams.length; i++) { ps.push(cParams[i] + ' ' + jParams[i]); qs.push(jParams[i]); c_codes.push(types[cParams[i]].c_code); } var cout = dspec + " " + fname + "(" + ps.join(', ') + ") {\n"; cout += 'arg_t *res = jam_rexec_sync(js, "' + fname + '", "' + c_codes.join('') + '"'; if(qs.length > 0) { cout += ',' + qs.join(', '); } cout += ');\n'; if(dspec == 'void') { cout += 'command_arg_free(res);\n' cout += 'return;\n'; } else { var retval = 'res->val.' + types[dspec].jamlib; if(dspec == 'char *') { retval = 'strdup(' + retval + ')'; } cout += dspec + ' ret = ' + retval + ';\n'; cout += 'command_arg_free(res);\n' cout += 'return ret;\n'; } cout += '}\n'; return cout; } function isUndefined(x) { return x === void 0; } // Take an Array of nodes, and whenever an _iter node is encountered, splice in its // recursively-flattened children instead. function flattenIterNodes(nodes) { var result = []; for (var i = 0; i < nodes.length; ++i) { if (nodes[i]._node.ctorName === '_iter') { result.push.apply(result, flattenIterNodes(nodes[i].children)); } else { result.push(nodes[i]); } } return result; } // Comparison function for sorting nodes based on their source's start index. function compareByInterval(node, otherNode) { return node.source.startIdx - otherNode.source.startIdx; } function parseList(list, sep) { if(list.child(0).ctorName == "NonemptyListOf") { return parseNonEmptyList(list.child(0), sep); } else { return ""; } } function parseNonEmptyList(list, sep) { var code = list.child(0).jamCTranslator; var rest = list.child(2); for (var i = 0; i < rest.numChildren; i++) { code += sep + rest.child(i).jamCTranslator } return code; } function parseArrayList(list, sep) { var code = ''; for (var i = 0; i < list.numChildren; i++) { code += list.child(i).jamCTranslator + sep; } return code; } var symbolTable = new Map(); var jamJSTranslator = { Program: function(directives, elements) { var jsout = ""; var cout = ""; var annotated_JS = ""; jsout += "var jcondition = new Map();\n" for (var i = 0; i < elements.children.length; i++) { if(elements.child(i).child(0).child(0).ctorName == "Activity_def") { var output = elements.child(i).child(0).child(0).jamJSTranslator; cout += output.C + '\n'; jsout += output.JS + '\n'; annotated_JS += output.annotated_JS + '\n'; } else { jsout += elements.child(i).child(0).child(0).jamJSTranslator + '\n'; } } jsout += generate_js_callbacks(); return {'C': cout, 'JS': jsout, 'annotated_JS': annotated_JS}; }, Activity_def: function(node) { return node.jamJSTranslator; }, jdata_type: function(type) { return type.sourceString; }, Jdata_spec: function(type_spec, id, _1, jdata_type, _2) { symbolTable.set(id.sourceString, { type: "jdata", other: { type_spec: type_spec.sourceString, jdata_type: jdata_type.jamJSTranslator } }); }, Jdata_decl: function(_1, _2, jdata_spec, _3) { jdata_spec.jamJSTranslator; return ''; }, Jcond_rule: function(id, op, num, _) { return 'jcondition_context["' + id.sourceString + '"] ' + op.sourceString + ' ' + num.es5Translator; }, Jcond_entry: function(type, _1, rules, _2) { var code = rules.child(0).jamJSTranslator; for (var i = 1; i < rules.numChildren; i++) { code += ' && ' + rules.child(i).jamJSTranslator; } return code; }, Jconditional: function(_1, id, _2, entries, _3) { return "jcondition.set('" + id.es5Translator + "', '" + entries.jamJSTranslator + "');"; }, Jcond_expr_paran: function(_1, expr, _2) { return "(" + expr.jamJSTranslator + ")"; }, Jcond_expr_not: function(_, expr) { return "!" + expr.jamJSTranslator; }, Jcond_expr_bin_op: function(expr1, op, expr2) { return expr1.jamJSTranslator + " " + op.sourceString + " " + expr2.jamJSTranslator; }, Jcond_expr_id: function(id) { return `eval(jcondition.get(${id.sourceString}))`; }, Jcond_specifier: function(_1, jconds, _2) { var jsout = ''; jsout += 'var jcondition_context = jlib.JServer.get_jcond();\n' jsout += 'if(!(' + jconds.jamJSTranslator + ')){\n' jsout += 'console.log(jlib.JServer.jcond_failure);\n'; jsout += 'jlib.JServer.jcond_failure;\n'; jsout += '}\n'; return jsout; }, Sync_activity: function(_, jcond_spec, functionDeclaration) { var jcond = ""; if(jcond_spec.numChildren > 0) { jcond = jcond_spec.jamJSTranslator; } var specs = functionDeclaration.jamJSTranslator; var rtype = undefined; var cParams; var jParams = specs.params; if(prototypes.has(specs.fname)) { rtype = prototypes.get(specs.fname).return_type; cParams = prototypes.get(specs.fname).params; } // activities.js.sync.push({ // name: specs.fname, // params: specs.params // }); // console.log(prototypes.keys()); var js_output = CreateJSSyncJSFunction(rtype, specs.fname, cParams, jParams, jcond + specs.block); var c_output = CreateJSSyncCFunction(rtype, specs.fname, cParams, jParams); return { C: c_output, JS: js_output.JS, annotated_JS: js_output.annotated_JS } }, Async_activity: function(_, jcond_spec, functionDeclaration) { var jcond = ""; if(jcond_spec.numChildren > 0) { jcond = jcond_spec.jamJSTranslator; } var specs = functionDeclaration.jamJSTranslator; // activities.js.sync.push({ // name: specs.fname, // params: specs.params // }); var cParams; var jParams = specs.params; if(prototypes.has(specs.fname)) { cParams = prototypes.get(specs.fname).params; } var js_output = CreateJSASyncJSFunction(specs.fname, cParams, jParams, jcond + specs.block); var c_output = CreateJSASyncCFunction(specs.fname, cParams, jParams); return { C: c_output, JS: js_output.JS, annotated_JS: js_output.annotated_JS } }, FunctionDeclaration: function(_1, id, _2, params, _3, _4, block, _5) { return { fname: id.es5Translator, params: params.jamJSTranslator, block: block.es5Translator } }, FormalParameterList: function(params){ var paramArray = []; if(params.child(0).ctorName == "NonemptyListOf") { var list = params.child(0); paramArray.push(list.child(0).es5Translator); var rest = list.child(2); for (var i = 0; i < rest.numChildren; i++) { paramArray.push(rest.child(i).es5Translator); } } return paramArray; }, _nonterminal: function(children) { var flatChildren = flattenIterNodes(children).sort(compareByInterval); var childResults = flatChildren.map(function(n) { return n.jamJSTranslator; }); if (flatChildren.length === 0 || childResults.every(isUndefined)) { return undefined; } var code = ''; for (var i = 0; i < flatChildren.length; ++i) { if (childResults[i] != null) { code += childResults[i]; } } return code; }, _terminal: function() { return this.primitiveValue; }, NonemptyListOf: function(first, sep, rest) { var code = first.jamJSTranslator; for (var i = 0; i < rest.numChildren; i++) { code += sep.child(i).primitiveValue + ' ' + rest.child(i).jamJSTranslator; } return code; }, EmptyListOf: function() { return ""; } } var jamCTranslator = { Namespace_spec: function(_, namespace) { return namespace.sourceString; }, Sync_activity: function(_, specs, decl, namespace, stmt) { var decl = declarator.jamCTranslator; var funcname = decl.name; var params = decl.params; var rtype = specs.cTranslator; if(decl.pointer != '') { rtype += decl.pointer } var namespc; if(namespace.numChildren > 0) { namespc = namespace.jamCTranslator // funcname = namespc + "_func_" + namespace_funcs[namespc].indexOf(funcname); } var js_output = CreateCSyncJSFunction(funcname, params); var c_output = CreateCSyncCFunction(rtype, funcname, params, stmt.cTranslator); return { C: c_output, JS: js_output.JS, annotated_JS: js_output.annotated_JS } }, Async_activity: function(_, decl, namespace, stmt) { var funcname = decl.jamCTranslator.name; var params = decl.jamCTranslator.params; if(namespace.numChildren > 0) { // funcname = namespc + "_func_" + namespace_funcs[namespc].indexOf(funcname); } var js_output = CreateCASyncJSFunction(funcname, params); var c_output = CreateCASyncCFunction("jactivity_t*", funcname, params, stmt.cTranslator); return { C: c_output, JS: js_output.JS, annotated_JS: js_output.annotated_JS } }, Activity_def: function(node) { return node.jamCTranslator; }, Source: function(decls) { var cout = ""; var jsout = ""; var annotated_JS = ""; for (var i = 0; i < decls.numChildren; i++) { // if(decls.child(i).child(0).ctorName == "Jdata_decl") { // decls.child(i).child(0).jamTranslator; // } else if(decls.child(i).child(0).ctorName == "Activity_def") { var output = decls.child(i).child(0).jamCTranslator; cout += output.C + '\n'; jsout += output.JS + '\n'; annotated_JS += output.annotated_JS + '\n'; } else if(decls.child(i).child(0).ctorName == "Prototype") { if(decls.child(i).child(0).jamCTranslator == "int main();") { cout = ""; } cout += decls.child(i).child(0).jamCTranslator + '\n'; } else { cout += decls.child(i).child(0).cTranslator + '\n'; } } // cout += generate_c_async_callbacks(input.data.cCallbacks); cout = generate_c_broadcaster_vars() + cout; cout += generate_setup(); cout += generate_jam_run_app(); cout += generate_taskmain(); cout = 'jamstate_t *js;\n' + cout; cout = 'typedef char* jcallback;\n' + cout; jsout = generate_js_logger_vars() + jsout; // annotated_JS = "/* @flow */\n" + struct_objects + annotated_JS + this.generate_js_callbacks(); return {'C': cout, 'JS': jsout, 'annotated_JS': annotated_JS}; }, Prototype: function(specs, pointer, id, _1, params, _2, gcc, _3) { var rtype = specs.cTranslator; if(pointer.numChildren > 0) { rtype += pointer.cTranslator; } var parameters = []; if(params.numChildren > 0) { parameters = params.jamCTranslator[0]; } prototypes.set(id.cTranslator, { return_type: rtype, params: parameters }); return this.cTranslator; }, Pcall_decl: function(node) { return node.jamCTranslator; }, Pcall_decl_ParamTypeList: function(_1, node, _2) { return node.jamCTranslator; }, Pcall_decl_Empty: function(_1, _2) { return []; }, Param_type_lst: function(param_list) { var params = [] params.push(param_list.child(0).jamCTranslator); // console.log(params); var rest = param_list.child(2); for (var i = 0; i < rest.numChildren; i++) { params.push(rest.child(i).jamCTranslator); } return params; }, Declarator: function(pointer, dir_declarator, _1, _2) { var dir_decl = dir_declarator.jamCTranslator; return { pointer: pointer.cTranslator, name: dir_decl.name, params: dir_decl.params } }, Dir_declarator_PCall: function(name, params) { return { name: name.cTranslator, params: params.jamCTranslator }; }, Dir_declarator_Id: function(id) { return { name: id.cTranslator } }, Dir_declarator: function(node) { return node.jamCTranslator; }, Param_decl: function(node) { return node.jamCTranslator; }, Param_decl_Declarator: function(decl_specs, decl) { var varType = decl_specs.cTranslator; if(decl.jamCTranslator.pointer != '') { varType += decl.jamCTranslator.pointer } return { type: varType, name: decl.jamCTranslator.name }; }, _nonterminal: function(children) { var flatChildren = flattenIterNodes(children).sort(compareByInterval); var childResults = flatChildren.map(function(n) { return n.jamCTranslator; }); if (flatChildren.length === 0 || childResults.every(isUndefined)) { return undefined; } var code = ''; for (var i = 0; i < flatChildren.length; ++i) { if (childResults[i] != null) { code += childResults[i]; } } return code; }, _terminal: function() { return this.primitiveValue; }, NonemptyListOf: function(first, sep, rest) { var code = first.jamCTranslator; for (var i = 0; i < rest.numChildren; i++) { code += sep.child(i).primitiveValue + ' ' + rest.child(i).jamCTranslator; } return code; }, EmptyListOf: function() { return ""; } } // cTranslator.Assign_expr_assign = function(left, op, right) { // var symbol = symbolTable.get(left.cTranslator); // if(symbol !== undefined) { // if(symbol.other.jdata_type == "broadcaster" ) { // error(left, 'Cannot save to broadcaster ' + left.cTranslator); // } else if(symbol.other.jdata_type == "logger") { // console.log(`jdata_log_to_server(${left.cTranslator}, "${right.cTranslator}", NULL)`); // return `jdata_log_to_server(${left.cTranslator}, "${right.cTranslator}", NULL)`; // } // } // return left.cTranslator + ' ' + op.sourceString + ' ' + right.cTranslator; // } cTranslator.Dir_declarator_Id = function(id) { var symbol = symbolTable.get(id.sourceString); if(symbol !== undefined) { if(symbol.other.jdata_type == "broadcaster" ) { error(id, 'Cannot declare broadcaster ' + id.sourceString); } } return id.sourceString; } cTranslator.Primary_expr = function(node) { if(node.ctorName == "id") { var symbol = symbolTable.get(node.sourceString); if(symbol !== undefined && symbol.type == "jdata") { if(symbol.other.jdata_type == "logger" || symbol.other.jdata_type == "shuffler") { error(node, 'Cannot read values from ' + symbol.other.jdata_type + ' ' + node.sourceString); } else if(symbol.other.jdata_type == "broadcaster") { return `get_broadcaster_value(${node.sourceString});` } else if(symbol.other.jdata_type == "shuffler") { return `(char *)jshuffler_poll(${node.sourceString});` } } } return node.cTranslator; } cTranslator.Assign_stmt = function(left, _1, right, _4) { var symbol = symbolTable.get(left.cTranslator); if(symbol !== undefined) { if(symbol.other.jdata_type == "broadcaster" ) { error(id, 'Cannot declare broadcaster ' + id.sourceString); } else if(symbol.other.jdata_type == "logger") { return `jdata_log_to_server("${left.cTranslator}", "${right.cTranslator}", ((void*)0));`; } else if(symbol.other.jdata_type == "shuffler") { return `jshuffler_push("${left.cTranslator}", "${right.cTranslator}");`; } } return left.cTranslator + ' = ' + right.cTranslator + ';'; } es5Translator.AssignmentStatement = function(left, _, right) { var symbol = symbolTable.get(left.es5Translator); if(symbol !== undefined) { if(symbol.other.jdata_type == "broadcaster" ) { return `JManager.broadcastMessage("${left.es5Translator}", "${right.es5Translator}"");`; } else if(symbol.other.jdata_type == "logger") { error(left, `Cannot write to logger var ${left.es5Translator} from javascript`); } } return left.es5Translator + ' = ' + right.es5Translator + ';'; } // Instantiate the JAMScript grammar. var jamc = fs.readFileSync(path.join(__dirname, 'jamc.ohm')); var jamjs = fs.readFileSync(path.join(__dirname, 'jamjs.ohm')); var ns = {}; ns.C = ohm.grammar(fs.readFileSync(path.join(__dirname, '../c/c.ohm'))); ns.ES5 = ohm.grammar(fs.readFileSync(path.join(__dirname, '../ecmascript/es5.ohm'))); var jamCGrammar = ohm.grammar(jamc, ns); var jamJSGrammar = ohm.grammar(jamjs, ns); var cSemantics = jamCGrammar.createSemantics(); var jsSemantics = jamJSGrammar.createSemantics(); cSemantics.addAttribute('jamCTranslator', jamCTranslator); cSemantics.addAttribute('cTranslator', cTranslator); jsSemantics.addAttribute('jamJSTranslator', jamJSTranslator); jsSemantics.addAttribute('es5Translator', es5Translator); // semantics.addAttribute('cSymbolTable', cSymbolTable); module.exports = { jamJSGrammar: jamJSGrammar, jamCGrammar: jamCGrammar, cSemantics: cSemantics, jsSemantics: jsSemantics };
Good stuff Revert "Add js callbacks" This reverts commit 45374b0990b40ee4d2f59f953364555f055c3eae.
lib/ohm/jamscript/jam.js
Good stuff Revert "Add js callbacks"
<ide><path>ib/ohm/jamscript/jam.js <ide> jsout += elements.child(i).child(0).child(0).jamJSTranslator + '\n'; <ide> } <ide> } <del> jsout += generate_js_callbacks(); <del> <ide> return {'C': cout, 'JS': jsout, 'annotated_JS': annotated_JS}; <ide> }, <ide> Activity_def: function(node) { <ide> jsout += output.JS + '\n'; <ide> annotated_JS += output.annotated_JS + '\n'; <ide> } else if(decls.child(i).child(0).ctorName == "Prototype") { <del> if(decls.child(i).child(0).jamCTranslator == "int main();") { <add> if(decls.child(i).child(0).sourceString == "int main();") { <ide> cout = ""; <ide> } <ide> cout += decls.child(i).child(0).jamCTranslator + '\n'; <ide> cout = 'jamstate_t *js;\n' + cout; <ide> cout = 'typedef char* jcallback;\n' + cout; <ide> jsout = generate_js_logger_vars() + jsout; <add> jsout += generate_js_callbacks(); <ide> <ide> // annotated_JS = "/* @flow */\n" + struct_objects + annotated_JS + this.generate_js_callbacks(); <ide>
Java
apache-2.0
error: pathspec 'src/main/java/com/cube/storm/ui/lib/spec/ListDividerSpec.java' did not match any file(s) known to git
570381e524be77815f50597c2cebad3082d3d61c
1
3sidedcube/Android-LightningUi
package com.cube.storm.ui.lib.spec; import com.cube.storm.ui.model.Model; import com.cube.storm.ui.model.list.Divider; import com.cube.storm.ui.model.list.ListItem; import com.cube.storm.ui.model.list.StandardListItem; import java.util.List; /** * Default {@link com.cube.storm.ui.lib.spec.DividerSpec} for {@link com.cube.storm.ui.controller.adapter.StormListAdapter} * * @author Callum Taylor * @project LightningUi */ public class ListDividerSpec implements DividerSpec { @Override public ListItem shouldAddDivider(int position, List<Model> items) { if (position > 0 && position < items.size() - 1) { if (items.get(position) instanceof com.cube.storm.ui.model.list.List.ListHeader) { return null; } if (items.get(position - 1) instanceof com.cube.storm.ui.model.list.List.ListHeader) { return new Divider(); } if ((items.get(position + 1) instanceof StandardListItem)) { return new Divider(); } } return null; } }
src/main/java/com/cube/storm/ui/lib/spec/ListDividerSpec.java
Created default list divider spec
src/main/java/com/cube/storm/ui/lib/spec/ListDividerSpec.java
Created default list divider spec
<ide><path>rc/main/java/com/cube/storm/ui/lib/spec/ListDividerSpec.java <add>package com.cube.storm.ui.lib.spec; <add> <add>import com.cube.storm.ui.model.Model; <add>import com.cube.storm.ui.model.list.Divider; <add>import com.cube.storm.ui.model.list.ListItem; <add>import com.cube.storm.ui.model.list.StandardListItem; <add> <add>import java.util.List; <add> <add>/** <add> * Default {@link com.cube.storm.ui.lib.spec.DividerSpec} for {@link com.cube.storm.ui.controller.adapter.StormListAdapter} <add> * <add> * @author Callum Taylor <add> * @project LightningUi <add> */ <add>public class ListDividerSpec implements DividerSpec <add>{ <add> @Override public ListItem shouldAddDivider(int position, List<Model> items) <add> { <add> if (position > 0 && position < items.size() - 1) <add> { <add> if (items.get(position) instanceof com.cube.storm.ui.model.list.List.ListHeader) <add> { <add> return null; <add> } <add> <add> if (items.get(position - 1) instanceof com.cube.storm.ui.model.list.List.ListHeader) <add> { <add> return new Divider(); <add> } <add> <add> if ((items.get(position + 1) instanceof StandardListItem)) <add> { <add> return new Divider(); <add> } <add> } <add> <add> return null; <add> } <add>}
Java
agpl-3.0
c3d551810c73b582b43fb6507f953a2d89b85342
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
cdf59e06-2e5f-11e5-9284-b827eb9e62be
hello.java
cdf02930-2e5f-11e5-9284-b827eb9e62be
cdf59e06-2e5f-11e5-9284-b827eb9e62be
hello.java
cdf59e06-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>cdf02930-2e5f-11e5-9284-b827eb9e62be <add>cdf59e06-2e5f-11e5-9284-b827eb9e62be
Java
apache-2.0
5191f244c62f33f6a68d12b0614ba848172d2704
0
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * 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 org.opensingular.form.wicket; import org.opensingular.form.*; import org.opensingular.form.aspect.AspectRef; import org.opensingular.form.aspect.QualifierStrategyByClassQualifier; import org.opensingular.form.aspect.SingleAspectRegistry; import org.opensingular.form.type.core.*; import org.opensingular.form.type.core.attachment.STypeAttachment; import org.opensingular.form.type.core.attachment.STypeAttachmentImage; import org.opensingular.form.type.country.brazil.STypeCNPJ; import org.opensingular.form.type.country.brazil.STypeCPF; import org.opensingular.form.type.country.brazil.STypeTelefoneNacional; import org.opensingular.form.type.util.STypeLatitudeLongitude; import org.opensingular.form.type.util.STypeYearMonth; import org.opensingular.form.view.*; import org.opensingular.form.wicket.mapper.*; import org.opensingular.form.wicket.mapper.attachment.image.AttachmentImageMapper; import org.opensingular.form.wicket.mapper.attachment.image.AttachmentImageMapperToolTip; import org.opensingular.form.wicket.mapper.attachment.list.AttachmentListMapper; import org.opensingular.form.wicket.mapper.attachment.single.AttachmentMapper; import org.opensingular.form.wicket.mapper.composite.BlocksCompositeMapper; import org.opensingular.form.wicket.mapper.composite.DefaultCompositeMapper; import org.opensingular.form.wicket.mapper.country.brazil.CNPJMapper; import org.opensingular.form.wicket.mapper.country.brazil.CPFMapper; import org.opensingular.form.wicket.mapper.maps.LatitudeLongitudeMapper; import org.opensingular.form.wicket.mapper.masterdetail.ListMasterDetailMapper; import org.opensingular.form.wicket.mapper.richtext.PortletRichTextMapper; import org.opensingular.form.wicket.mapper.search.SearchModalMapper; import org.opensingular.form.wicket.mapper.selection.*; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * @author Daniel C. Bordin on 25/08/2017. */ public class IWicketComponentMapperRegistry extends SingleAspectRegistry<IWicketComponentMapper, Class<? extends SView>> { public IWicketComponentMapperRegistry(@Nonnull AspectRef<IWicketComponentMapper> aspectRef) { super(aspectRef, new QualifierStrategyByView()); registerDefaultMapping(); } public static class QualifierStrategyByView extends QualifierStrategyByClassQualifier<Class<? extends SView>> { @Nullable @Override protected Class<? extends SView> extractQualifier(@Nonnull SInstance instance) { SView view = ViewResolver.resolve(instance); return view.getClass(); } @Nullable @Override protected Class<? extends SView> extractQualifier(@Nonnull SType<?> type) { SView view = ViewResolver.resolveView(type); return view == null ? null : view.getClass(); } } private void registerDefaultMapping() { add(STypeSimple.class, SViewSelectionByRadio.class, RadioMapper::new); add(STypeSimple.class, SViewSelectionBySelect.class, SelectMapper::new); add(STypeSimple.class, SViewReadOnly.class, ReadOnlyControlsFieldComponentMapper::new); add(STypeBoolean.class, SViewSelectionBySelect.class, BooleanSelectMapper::new); add(STypeBoolean.class, BooleanMapper::new); add(STypeBoolean.class, SViewBooleanSwitch.class, BooleanSwitchMapper::new); add(STypeBoolean.class, SViewBooleanByRadio.class, BooleanRadioMapper::new); add(STypeInteger.class, () -> new NumberMapper<>(Integer.class)); add(STypeLong.class, () -> new NumberMapper<>(Long.class)); add(STypeString.class, StringMapper::new); add(STypeString.class, SViewSearchModal.class, SearchModalMapper::new); add(STypeString.class, SViewTextArea.class, TextAreaMapper::new); add(STypeString.class, SViewAutoComplete.class, AutocompleteMapper::new); add(STypeDate.class, DateMapper::new); add(STypeYearMonth.class, YearMonthMapper::new); add(STypeDecimal.class, DecimalMapper::new); add(STypeMonetary.class, MoneyMapper::new); add(STypeAttachment.class, AttachmentMapper::new); add(STypeAttachmentImage.class, SViewAttachmentImage.class, AttachmentImageMapper::new); add(STypeAttachmentImage.class, SViewAttachmentImageTooltip.class,AttachmentImageMapperToolTip::new); add(STypeLatitudeLongitude.class, LatitudeLongitudeMapper::new); add(STypeComposite.class, DefaultCompositeMapper::new); add(STypeComposite.class, SViewTab.class, TabMapper::new); add(STypeComposite.class, SViewByBlock.class, BlocksCompositeMapper::new); add(STypeComposite.class, SViewSelectionByRadio.class, RadioMapper::new); add(STypeComposite.class, SViewSelectionBySelect.class, SelectMapper::new); add(STypeComposite.class, SViewSearchModal.class, SearchModalMapper::new); add(STypeComposite.class, SViewAutoComplete.class, AutocompleteMapper::new); add(STypeComposite.class, SViewReadOnly.class, ReadOnlyControlsFieldComponentMapper::new); add(STypeList.class, SMultiSelectionBySelectView.class, MultipleSelectBSMapper::new); add(STypeList.class, SMultiSelectionByCheckboxView.class, MultipleCheckMapper::new); add(STypeList.class, SMultiSelectionByPicklistView.class, PicklistMapper::new); add(STypeList.class, TableListMapper::new); add(STypeList.class, SViewListByTable.class, TableListMapper::new); add(STypeList.class, SViewListByForm.class, PanelListMapper::new); add(STypeList.class, SViewListByMasterDetail.class, ListMasterDetailMapper::new); add(STypeList.class, SViewBreadcrumb.class, ListBreadcrumbMapper::new); add(STypeDateTime.class, DateTimeMapper::new); add(STypeDateTime.class, SViewDateTime.class, DateTimeMapper::new); add(STypeTime.class, TimeMapper::new); add(STypeTelefoneNacional.class, TelefoneNacionalMapper::new); add(STypeHTML.class, SViewByRichText.class, RichTextMapper::new); add(STypeAttachmentList.class, SViewAttachmentList.class, AttachmentListMapper::new); add(STypeCNPJ.class, CNPJMapper::new); add(STypeCPF.class, CPFMapper::new); add(STypeHTML.class, PortletRichTextMapper::new); add(STypePassword.class, PasswordMapper::new); add(STypeHiddenString.class, InputHiddenMapper::new); //@formatter:on } }
form/wicket/src/main/java/org/opensingular/form/wicket/IWicketComponentMapperRegistry.java
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * 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 org.opensingular.form.wicket; import org.opensingular.form.*; import org.opensingular.form.aspect.AspectRef; import org.opensingular.form.aspect.QualifierStrategyByClassQualifier; import org.opensingular.form.aspect.SingleAspectRegistry; import org.opensingular.form.type.core.*; import org.opensingular.form.type.core.attachment.STypeAttachment; import org.opensingular.form.type.core.attachment.STypeAttachmentImage; import org.opensingular.form.type.country.brazil.STypeCNPJ; import org.opensingular.form.type.country.brazil.STypeCPF; import org.opensingular.form.type.country.brazil.STypeTelefoneNacional; import org.opensingular.form.type.util.STypeLatitudeLongitude; import org.opensingular.form.type.util.STypeYearMonth; import org.opensingular.form.view.*; import org.opensingular.form.wicket.mapper.*; import org.opensingular.form.wicket.mapper.attachment.list.AttachmentListMapper; import org.opensingular.form.wicket.mapper.attachment.single.AttachmentMapper; import org.opensingular.form.wicket.mapper.composite.BlocksCompositeMapper; import org.opensingular.form.wicket.mapper.composite.DefaultCompositeMapper; import org.opensingular.form.wicket.mapper.country.brazil.CNPJMapper; import org.opensingular.form.wicket.mapper.country.brazil.CPFMapper; import org.opensingular.form.wicket.mapper.maps.LatitudeLongitudeMapper; import org.opensingular.form.wicket.mapper.masterdetail.ListMasterDetailMapper; import org.opensingular.form.wicket.mapper.richtext.PortletRichTextMapper; import org.opensingular.form.wicket.mapper.search.SearchModalMapper; import org.opensingular.form.wicket.mapper.selection.*; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * @author Daniel C. Bordin on 25/08/2017. */ public class IWicketComponentMapperRegistry extends SingleAspectRegistry<IWicketComponentMapper, Class<? extends SView>> { public IWicketComponentMapperRegistry(@Nonnull AspectRef<IWicketComponentMapper> aspectRef) { super(aspectRef, new QualifierStrategyByView()); registerDefaultMapping(); } public static class QualifierStrategyByView extends QualifierStrategyByClassQualifier<Class<? extends SView>> { @Nullable @Override protected Class<? extends SView> extractQualifier(@Nonnull SInstance instance) { SView view = ViewResolver.resolve(instance); return view.getClass(); } @Nullable @Override protected Class<? extends SView> extractQualifier(@Nonnull SType<?> type) { SView view = ViewResolver.resolveView(type); return view == null ? null : view.getClass(); } } private void registerDefaultMapping() { add(STypeSimple.class, SViewSelectionByRadio.class, RadioMapper::new); add(STypeSimple.class, SViewSelectionBySelect.class, SelectMapper::new); add(STypeSimple.class, SViewReadOnly.class, ReadOnlyControlsFieldComponentMapper::new); add(STypeBoolean.class, SViewSelectionBySelect.class, BooleanSelectMapper::new); add(STypeBoolean.class, BooleanMapper::new); add(STypeBoolean.class, SViewBooleanSwitch.class, BooleanSwitchMapper::new); add(STypeBoolean.class, SViewBooleanByRadio.class, BooleanRadioMapper::new); add(STypeInteger.class, () -> new NumberMapper<>(Integer.class)); add(STypeLong.class, () -> new NumberMapper<>(Long.class)); add(STypeString.class, StringMapper::new); add(STypeString.class, SViewSearchModal.class, SearchModalMapper::new); add(STypeString.class, SViewTextArea.class, TextAreaMapper::new); add(STypeString.class, SViewAutoComplete.class, AutocompleteMapper::new); add(STypeDate.class, DateMapper::new); add(STypeYearMonth.class, YearMonthMapper::new); add(STypeDecimal.class, DecimalMapper::new); add(STypeMonetary.class, MoneyMapper::new); add(STypeAttachment.class, AttachmentMapper::new); add(STypeAttachmentImage.class, SViewAttachmentImage.class, AttachmentImageMapper::new); add(STypeAttachmentImage.class, SViewAttachmentImageTooltip.class,AttachmentImageMapperToolTip::new); add(STypeLatitudeLongitude.class, LatitudeLongitudeMapper::new); add(STypeComposite.class, DefaultCompositeMapper::new); add(STypeComposite.class, SViewTab.class, TabMapper::new); add(STypeComposite.class, SViewByBlock.class, BlocksCompositeMapper::new); add(STypeComposite.class, SViewSelectionByRadio.class, RadioMapper::new); add(STypeComposite.class, SViewSelectionBySelect.class, SelectMapper::new); add(STypeComposite.class, SViewSearchModal.class, SearchModalMapper::new); add(STypeComposite.class, SViewAutoComplete.class, AutocompleteMapper::new); add(STypeComposite.class, SViewReadOnly.class, ReadOnlyControlsFieldComponentMapper::new); add(STypeList.class, SMultiSelectionBySelectView.class, MultipleSelectBSMapper::new); add(STypeList.class, SMultiSelectionByCheckboxView.class, MultipleCheckMapper::new); add(STypeList.class, SMultiSelectionByPicklistView.class, PicklistMapper::new); add(STypeList.class, TableListMapper::new); add(STypeList.class, SViewListByTable.class, TableListMapper::new); add(STypeList.class, SViewListByForm.class, PanelListMapper::new); add(STypeList.class, SViewListByMasterDetail.class, ListMasterDetailMapper::new); add(STypeList.class, SViewBreadcrumb.class, ListBreadcrumbMapper::new); add(STypeDateTime.class, DateTimeMapper::new); add(STypeDateTime.class, SViewDateTime.class, DateTimeMapper::new); add(STypeTime.class, TimeMapper::new); add(STypeTelefoneNacional.class, TelefoneNacionalMapper::new); add(STypeHTML.class, RichTextMapper::new); add(STypeAttachmentList.class, SViewAttachmentList.class, AttachmentListMapper::new); add(STypeCNPJ.class, CNPJMapper::new); add(STypeCPF.class, CPFMapper::new); add(STypeHTML.class, SViewByPortletRichText.class, PortletRichTextMapper::new); add(STypePassword.class, PasswordMapper::new); add(STypeHiddenString.class, InputHiddenMapper::new); //@formatter:on } }
Correção RichText
form/wicket/src/main/java/org/opensingular/form/wicket/IWicketComponentMapperRegistry.java
Correção RichText
<ide><path>orm/wicket/src/main/java/org/opensingular/form/wicket/IWicketComponentMapperRegistry.java <ide> import org.opensingular.form.type.util.STypeYearMonth; <ide> import org.opensingular.form.view.*; <ide> import org.opensingular.form.wicket.mapper.*; <add>import org.opensingular.form.wicket.mapper.attachment.image.AttachmentImageMapper; <add>import org.opensingular.form.wicket.mapper.attachment.image.AttachmentImageMapperToolTip; <ide> import org.opensingular.form.wicket.mapper.attachment.list.AttachmentListMapper; <ide> import org.opensingular.form.wicket.mapper.attachment.single.AttachmentMapper; <ide> import org.opensingular.form.wicket.mapper.composite.BlocksCompositeMapper; <ide> add(STypeSimple.class, SViewSelectionByRadio.class, RadioMapper::new); <ide> add(STypeSimple.class, SViewSelectionBySelect.class, SelectMapper::new); <ide> add(STypeSimple.class, SViewReadOnly.class, ReadOnlyControlsFieldComponentMapper::new); <del> add(STypeBoolean.class, SViewSelectionBySelect.class, BooleanSelectMapper::new); <add> add(STypeBoolean.class, SViewSelectionBySelect.class, BooleanSelectMapper::new); <ide> add(STypeBoolean.class, BooleanMapper::new); <ide> add(STypeBoolean.class, SViewBooleanSwitch.class, BooleanSwitchMapper::new); <ide> add(STypeBoolean.class, SViewBooleanByRadio.class, BooleanRadioMapper::new); <ide> add(STypeDateTime.class, SViewDateTime.class, DateTimeMapper::new); <ide> add(STypeTime.class, TimeMapper::new); <ide> add(STypeTelefoneNacional.class, TelefoneNacionalMapper::new); <del> add(STypeHTML.class, RichTextMapper::new); <add> add(STypeHTML.class, SViewByRichText.class, RichTextMapper::new); <ide> add(STypeAttachmentList.class, SViewAttachmentList.class, AttachmentListMapper::new); <ide> add(STypeCNPJ.class, CNPJMapper::new); <ide> add(STypeCPF.class, CPFMapper::new); <del> add(STypeHTML.class, SViewByPortletRichText.class, PortletRichTextMapper::new); <add> add(STypeHTML.class, PortletRichTextMapper::new); <ide> add(STypePassword.class, PasswordMapper::new); <ide> add(STypeHiddenString.class, InputHiddenMapper::new); <ide> //@formatter:on
Java
epl-1.0
8725a5224994f2f889007fec44b3110758fe13ea
0
ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.msu.nscl.olog.api; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * * @author berryman */ public class LogBuilder { private Long id; private StringBuilder description; private String level; private Date createdDate; private Date modifiedDate; private int version; private Set<TagBuilder> tags = new HashSet<TagBuilder>(); private Set<LogbookBuilder> logbooks = new HashSet<LogbookBuilder>(); private Set<PropertyBuilder> properties = new HashSet<PropertyBuilder>(); @SuppressWarnings("deprecation") private Set<AttachmentBuilder> attachments = new HashSet<AttachmentBuilder>(); public static LogBuilder log(Log log) { LogBuilder logBuilder = new LogBuilder(); logBuilder.id = log.getId(); logBuilder.description = new StringBuilder(log.getDescription()); logBuilder.level = log.getLevel(); logBuilder.createdDate = log.getCreatedDate(); logBuilder.modifiedDate = log.getModifiedDate(); logBuilder.version = log.getVersion(); for (Tag tag : log.getTags()) { logBuilder.tags.add(TagBuilder.tag(tag)); } for (Logbook logbook : log.getLogbooks()) { logBuilder.logbooks.add(LogbookBuilder.logbook(logbook)); } for (Attachment attachment : log.getAttachments()) { logBuilder.attachments .add(AttachmentBuilder.attachment(attachment)); } for (Property property : log.getProperties()) { logBuilder.properties.add(PropertyBuilder.property(property)); } return logBuilder; } // if the subject is the only required field this constructor is wrong // // public static LogBuilder log(Long id) { // LogBuilder logBuilder = new LogBuilder(); // logBuilder.id = id; // return logBuilder; // } public static LogBuilder log() { LogBuilder logBuilder = new LogBuilder(); return logBuilder; } public LogBuilder id(Long id) { this.id = id; return this; } public LogBuilder description(String description) { if(description != null) this.description = new StringBuilder(description); else if(description == null) this.description = null; return this; } public LogBuilder appendDescription(String description) { if(this.description == null) this.description = new StringBuilder(description); else if(this.description != null) this.description.append("\n").append(description); return this; } public LogBuilder level(String level) { this.level = level; return this; } public LogBuilder withTags(Set<TagBuilder> tags){ this.tags = tags; return this; } public LogBuilder withProperties(Set<PropertyBuilder> properties){ this.properties = properties; return this; } public LogBuilder inLogbooks(Set<LogbookBuilder> logbooks){ this.logbooks = logbooks; return this; } public LogBuilder appendTag(TagBuilder tag) { this.tags.add(tag); return this; } public LogBuilder appendProperty(PropertyBuilder property) { this.properties.add(property); return this; } public LogBuilder appendToLogbook(LogbookBuilder logbook) { this.logbooks.add(logbook); return this; } // @deprecated not really deprecated, but javadoc doesn't have unsupported @Deprecated public LogBuilder attach(AttachmentBuilder attachment) { attachments.add(attachment); return this; } public LogBuilder property(PropertyBuilder property) { properties.add(property); return this; } @SuppressWarnings("deprecation") XmlLog toXml() { XmlLog xmlLog = new XmlLog(); xmlLog.setId(id); xmlLog.setDescription(description.toString()); xmlLog.setLevel(level); xmlLog.setCreatedDate(createdDate); xmlLog.setModifiedDate(modifiedDate); xmlLog.setVersion(version); for (TagBuilder tag : tags) { xmlLog.addXmlTag(tag.toXml()); } for (LogbookBuilder logbook : logbooks) { xmlLog.addXmlLogbook(logbook.toXml()); } for (AttachmentBuilder attachment : attachments) { xmlLog.addXmlAttachment(attachment.toXml()); } for (PropertyBuilder property : properties) { xmlLog.addXmlProperty(property.toXml()); } return xmlLog; } public Log build() { return new Log(this.toXml()); } }
src/edu/msu/nscl/olog/api/LogBuilder.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.msu.nscl.olog.api; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * * @author berryman */ public class LogBuilder { private Long id; private StringBuilder description; private String level; private Date createdDate; private Date modifiedDate; private int version; private Set<TagBuilder> tags = new HashSet<TagBuilder>(); private Set<LogbookBuilder> logbooks = new HashSet<LogbookBuilder>(); private Set<PropertyBuilder> properties = new HashSet<PropertyBuilder>(); @SuppressWarnings("deprecation") private Set<AttachmentBuilder> attachments = new HashSet<AttachmentBuilder>(); public static LogBuilder log(Log log) { LogBuilder logBuilder = new LogBuilder(); logBuilder.id = log.getId(); logBuilder.description = new StringBuilder(log.getDescription()); logBuilder.level = log.getLevel(); logBuilder.createdDate = log.getCreatedDate(); logBuilder.modifiedDate = log.getModifiedDate(); logBuilder.version = log.getVersion(); for (Tag tag : log.getTags()) { logBuilder.tags.add(TagBuilder.tag(tag)); } for (Logbook logbook : log.getLogbooks()) { logBuilder.logbooks.add(LogbookBuilder.logbook(logbook)); } for (Attachment attachment : log.getAttachments()) { logBuilder.attachments .add(AttachmentBuilder.attachment(attachment)); } for (Property property : log.getProperties()) { logBuilder.properties.add(PropertyBuilder.property(property)); } return logBuilder; } // if the subject is the only required field this constructor is wrong // // public static LogBuilder log(Long id) { // LogBuilder logBuilder = new LogBuilder(); // logBuilder.id = id; // return logBuilder; // } public static LogBuilder log() { LogBuilder logBuilder = new LogBuilder(); return logBuilder; } public LogBuilder id(Long id) { this.id = id; return this; } public LogBuilder description(String description) { if(description != null) this.description = new StringBuilder(description); else if(description == null) this.description = null; return this; } public LogBuilder appendDescription(String description) { if(this.description == null) this.description = new StringBuilder(description); else if(this.description != null) this.description.append("\n").append(description); return this; } public LogBuilder level(String level) { this.level = level; return this; } public LogBuilder withTags(Set<TagBuilder> tags){ this.tags = tags; return this; } public LogBuilder withProperties(Set<PropertyBuilder> properties){ this.properties = properties; return this; } public LogBuilder inLogbooks(Set<LogbookBuilder> logbooks){ this.logbooks = logbooks; return this; } public LogBuilder appendTag(TagBuilder tag) { this.tags.add(tag); return this; } public LogBuilder appendProperty(PropertyBuilder property) { this.properties.add(property); return this; } public LogBuilder appendToLogbook(LogbookBuilder logbook) { this.logbooks.add(logbook); return this; } // @deprecated not really deprecated, but javadoc doesn't have unsupported @Deprecated public LogBuilder attach(AttachmentBuilder attachment) { attachments.add(attachment); return this; } public LogBuilder property(PropertyBuilder property) { properties.add(property); return this; } @SuppressWarnings("deprecation") XmlLog toXml() { XmlLog xmlLog = new XmlLog(); xmlLog.setId(id); xmlLog.setDescription(description.toString()); xmlLog.setLevel(level); xmlLog.setCreatedDate(createdDate); xmlLog.setModifiedDate(modifiedDate); xmlLog.setVersion(version); for (TagBuilder tag : tags) { xmlLog.addXmlTag(tag.toXml()); } for (LogbookBuilder logbook : logbooks) { xmlLog.addXmlLogbook(logbook.toXml()); } for (AttachmentBuilder attachment : attachments) { xmlLog.addXmlAttachment(attachment.toXml()); } for (PropertyBuilder property : properties) { xmlLog.addXmlProperty(property.toXml()); } return xmlLog; } Log build() { return new Log(this.toXml()); } }
..logbook: updating the Attachment to have inputstream too. Change-Id: If7aa1eee840444af135109f9baf5d5cb48183d3f Signed-off-by: Kunal Shroff <[email protected]>
src/edu/msu/nscl/olog/api/LogBuilder.java
..logbook: updating the Attachment to have inputstream too.
<ide><path>rc/edu/msu/nscl/olog/api/LogBuilder.java <ide> <ide> } <ide> <del> Log build() { <add> public Log build() { <ide> return new Log(this.toXml()); <ide> } <ide>
JavaScript
mit
e2bd1190f48eae07f17dbc0ccdc19386b29d4236
0
kalabox/kalabox-engine-docker,kalabox/kalabox-engine-docker
'use strict'; var fs = require('fs'); var path = require('path'); var mkdirp = require('mkdirp'); var meta = require('./meta.js'); var PROVIDER_ATTEMPTS = 3; module.exports = function(kbox) { var sysProfiler = kbox.install.sysProfiler; var provider = kbox.engine.provider; var shell = kbox.util.shell; var provisioned = kbox.core.deps.lookup('globalConfig').provisioned; kbox.install.registerStep(function(step) { step.name = 'engine-docker-provider-profile'; step.deps = ['core-downloads']; step.description = 'Setting up the provider profile...'; step.all = function(state, done) { state.status = true; if (!fs.existsSync(path.join(state.config.sysProviderRoot, 'profile'))) { mkdirp.sync(state.config.sysProviderRoot); var downloadDir = kbox.util.disk.getTempDir(); var src = path.join( downloadDir, path.basename(meta.PROVIDER_PROFILE_URL) ); var dst = path.join( state.config.sysProviderRoot, 'profile' ); fs.rename(src, dst, function(err) { if (err) { state.status = false; done(err); } else { done(); } }); } else { done(); } }; }); kbox.install.registerStep(function(step) { step.name = 'engine-up'; step.deps = ['engine-docker-provider-profile']; step.description = 'Setting up and activating the engine...'; step.all = function(state, done) { var iso = path.join(state.config.sysProviderRoot, 'boot2docker.iso'); state.log.debug('iso -> ' + iso); var exists = fs.existsSync(iso); state.log.debug('exists -> ' + exists); if (exists) { //@todo: revisit why this is here? //fs.unlinkSync(iso); } kbox.engine.provider.up(function(err, data) { if (data) { state.log.debug(data); } if (err) { state.status = false; done(err); } else { done(); } }); }; }); if (!provisioned) { // @todo: add this step into the install docs /* kbox.install.registerStep(function(step) { step.name = 'engine-docker-finalize-engine'; step.description = 'Halting engine on Windows...'; step.subscribes = ['core-finish']; step.deps = ['services-kalabox-finalize']; step.all.win32 = function(state, done) { var winB2d = '"C:\\Program Files\\Boot2Docker for Windows\\boot2docker.exe"'; var turnUpForWhat = [winB2d + ' --vm="Kalabox2" down']; var child = kbox.install.cmd.runCmdsAsync(turnUpForWhat); child.stdout.on('data', function(data) { state.log.debug(data); }); child.on('exit', function(code) { state.log.debug('Install completed with code ' + code); done(); }); }; step.all.darwin = function(state, done) { done(); }; step.all.linux = step.all.darwin; }); */ kbox.install.registerStep(function(step) { step.name = 'engine-docker-downloads'; step.description = 'Queuing up provider downloads...'; step.subscribes = ['core-downloads']; step.all = function(state) { state.downloads.push(meta.PROVIDER_PROFILE_URL); state.downloads.push(meta.PROVIDER_DOWNLOAD_URL[process.platform].b2d); if (process.platform === 'linux' && !state.vbIsInstalled) { var nix = kbox.install.linuxOsInfo.get(); state.downloads.push( meta.PROVIDER_DOWNLOAD_URL.linux.vb[nix.ID][nix.VERSION_ID] ); } if (process.platform === 'win32' && !state.vbIsInstalled) { state.downloads.push(meta.PROVIDER_INF_URL); } }; }); kbox.install.registerStep(function(step) { step.name = 'engine-docker-install-engine'; step.description = 'Queuing provider admin commands...'; step.deps = ['core-auth']; step.subscribes = ['core-run-admin-commands']; step.all.darwin = function(state, done) { kbox.util.disk.getMacVolume(function(err, volume) { if (err) { state.status = false; done(err); } else { var downloadDir = kbox.util.disk.getTempDir(); var pkg = path.join( downloadDir, path.basename(meta.PROVIDER_DOWNLOAD_URL.darwin.b2d) ); var cmd = kbox.install.cmd.buildInstallCmd(pkg, volume); state.adminCommands.push(cmd); } done(err); }); }; step.all.linux = function(state, done) { var downloadDir = kbox.util.disk.getTempDir(); var nix = kbox.install.linuxOsInfo.get(); var vb = meta.PROVIDER_DOWNLOAD_URL.linux.vb[nix.ID][nix.VERSION_ID]; var pkg = path.join( downloadDir, path.basename(vb) ); var cmd = kbox.install.cmd.buildInstallCmd(pkg, nix); state.adminCommands.push(cmd); var b2dBin = path.join( downloadDir, path.basename(meta.PROVIDER_DOWNLOAD_URL.linux.b2d) ); var b2dBinDest = path.join('/usr/local/bin', 'boot2docker'); // Need to do this if the user is moving a file across partitions var is = fs.createReadStream(b2dBin); var os = fs.createWriteStream(b2dBinDest); is.pipe(os); is.on('end', function() { fs.unlinkSync(b2dBin); fs.chmodSync(b2dBinDest, '0755'); }); done(); }; step.all.win32 = function(state, done) { var downloadDir = kbox.util.disk.getTempDir(); var pkg = path.join( downloadDir, path.basename(meta.PROVIDER_DOWNLOAD_URL.win32.b2d) ); var cmd = kbox.install.cmd.buildInstallCmd( pkg, path.join(downloadDir, path.basename(meta.PROVIDER_INF_URL)) ); state.adminCommands.push(cmd); done(); }; }); } // Make sure the engine is on before we prepare it. if (provisioned) { kbox.install.registerStep(function(step) { step.name = 'engine-docker-prepared'; step.deps = [ 'core-apps-prepare', 'core-image-prepare' ]; step.description = 'Restarting engine for updates...'; step.all = function(state, done) { kbox.engine.down(PROVIDER_ATTEMPTS, function(err) { if (err) { done(err); } else { kbox.engine.up(PROVIDER_ATTEMPTS, function(err) { if (err) { done(err); } else { done(); } }); } }); }; }); } };
lib/install.js
'use strict'; var fs = require('fs'); var path = require('path'); var mkdirp = require('mkdirp'); var meta = require('./meta.js'); var PROVIDER_ATTEMPTS = 3; module.exports = function(kbox) { var sysProfiler = kbox.install.sysProfiler; var provider = kbox.engine.provider; var shell = kbox.util.shell; var provisioned = kbox.core.deps.lookup('globalConfig').provisioned; kbox.install.registerStep(function(step) { step.name = 'engine-docker-provider-profile'; step.deps = ['core-downloads']; step.description = 'Setting up the provider profile...'; step.all = function(state, done) { state.status = true; if (!fs.existsSync(path.join(state.config.sysProviderRoot, 'profile'))) { mkdirp.sync(state.config.sysProviderRoot); var downloadDir = kbox.util.disk.getTempDir(); var src = path.join( downloadDir, path.basename(meta.PROVIDER_PROFILE_URL) ); var dst = path.join( state.config.sysProviderRoot, 'profile' ); fs.rename(src, dst, function(err) { if (err) { state.status = false; done(err); } else { done(); } }); } else { done(); } }; }); kbox.install.registerStep(function(step) { step.name = 'engine-up'; step.deps = ['engine-docker-provider-profile']; step.description = 'Setting up and activating the engine...'; step.all = function(state, done) { var iso = path.join(state.config.sysProviderRoot, 'boot2docker.iso'); state.log.debug('iso -> ' + iso); var exists = fs.existsSync(iso); state.log.debug('exists -> ' + exists); if (exists) { //@todo: revisit why this is here? //fs.unlinkSync(iso); } kbox.engine.provider.up(function(err, data) { if (data) { state.log.debug(data); } if (err) { state.status = false; done(err); } else { done(); } }); }; }); if (!provisioned) { kbox.install.registerStep(function(step) { step.name = 'engine-docker-finalize-engine'; step.description = 'Halting engine on Windows...'; step.subscribes = ['core-finish']; step.deps = ['services-kalabox-finalize']; step.all.win32 = function(state, done) { var winB2d = '"C:\\Program Files\\Boot2Docker for Windows\\boot2docker.exe"'; var turnUpForWhat = [winB2d + ' --vm="Kalabox2" down']; var child = kbox.install.cmd.runCmdsAsync(turnUpForWhat); child.stdout.on('data', function(data) { state.log.debug(data); }); child.on('exit', function(code) { state.log.debug('Install completed with code ' + code); done(); }); }; step.all.darwin = function(state, done) { done(); }; step.all.linux = step.all.darwin; }); kbox.install.registerStep(function(step) { step.name = 'engine-docker-downloads'; step.description = 'Queuing up provider downloads...'; step.subscribes = ['core-downloads']; step.all = function(state) { state.downloads.push(meta.PROVIDER_PROFILE_URL); state.downloads.push(meta.PROVIDER_DOWNLOAD_URL[process.platform].b2d); if (process.platform === 'linux' && !state.vbIsInstalled) { var nix = kbox.install.linuxOsInfo.get(); state.downloads.push( meta.PROVIDER_DOWNLOAD_URL.linux.vb[nix.ID][nix.VERSION_ID] ); } if (process.platform === 'win32' && !state.vbIsInstalled) { state.downloads.push(meta.PROVIDER_INF_URL); } }; }); kbox.install.registerStep(function(step) { step.name = 'engine-docker-install-engine'; step.description = 'Queuing provider admin commands...'; step.subscribes = ['core-run-admin-commands']; step.all.darwin = function(state, done) { kbox.util.disk.getMacVolume(function(err, volume) { if (err) { state.status = false; done(err); } else { var downloadDir = kbox.util.disk.getTempDir(); var pkg = path.join( downloadDir, path.basename(meta.PROVIDER_DOWNLOAD_URL.darwin.b2d) ); var cmd = kbox.install.cmd.buildInstallCmd(pkg, volume); state.adminCommands.push(cmd); } done(err); }); }; step.all.linux = function(state, done) { var downloadDir = kbox.util.disk.getTempDir(); var nix = kbox.install.linuxOsInfo.get(); var vb = meta.PROVIDER_DOWNLOAD_URL.linux.vb[nix.ID][nix.VERSION_ID]; var pkg = path.join( downloadDir, path.basename(vb) ); var cmd = kbox.install.cmd.buildInstallCmd(pkg, nix); state.adminCommands.push(cmd); var b2dBin = path.join( downloadDir, path.basename(meta.PROVIDER_DOWNLOAD_URL.linux.b2d) ); var b2dBinDest = path.join('/usr/local/bin', 'boot2docker'); // Need to do this if the user is moving a file across partitions var is = fs.createReadStream(b2dBin); var os = fs.createWriteStream(b2dBinDest); is.pipe(os); is.on('end', function() { fs.unlinkSync(b2dBin); fs.chmodSync(b2dBinDest, '0755'); }); done(); }; step.all.win32 = function(state, done) { var downloadDir = kbox.util.disk.getTempDir(); var pkg = path.join( downloadDir, path.basename(meta.PROVIDER_DOWNLOAD_URL.win32.b2d) ); var cmd = kbox.install.cmd.buildInstallCmd( pkg, path.join(downloadDir, path.basename(meta.PROVIDER_INF_URL)) ); state.adminCommands.push(cmd); done(); }; }); } // Make sure the engine is on before we prepare it. if (provisioned) { kbox.install.registerStep(function(step) { step.name = 'engine-docker-prepared'; step.deps = [ 'core-apps-prepare', 'core-image-prepare' ]; step.description = 'Restarting engine for updates...'; step.all = function(state, done) { kbox.engine.down(PROVIDER_ATTEMPTS, function(err) { if (err) { done(err); } else { kbox.engine.up(PROVIDER_ATTEMPTS, function(err) { if (err) { done(err); } else { done(); } }); } }); }; }); } };
#364: Clean up, aisle 3
lib/install.js
#364: Clean up, aisle 3
<ide><path>ib/install.js <ide> <ide> if (!provisioned) { <ide> <add> // @todo: add this step into the install docs <add> /* <ide> kbox.install.registerStep(function(step) { <ide> step.name = 'engine-docker-finalize-engine'; <ide> step.description = 'Halting engine on Windows...'; <ide> step.all.darwin = function(state, done) { done(); }; <ide> step.all.linux = step.all.darwin; <ide> }); <add> */ <ide> <ide> kbox.install.registerStep(function(step) { <ide> step.name = 'engine-docker-downloads'; <ide> kbox.install.registerStep(function(step) { <ide> step.name = 'engine-docker-install-engine'; <ide> step.description = 'Queuing provider admin commands...'; <add> step.deps = ['core-auth']; <ide> step.subscribes = ['core-run-admin-commands']; <ide> step.all.darwin = function(state, done) { <ide> kbox.util.disk.getMacVolume(function(err, volume) {
Java
apache-2.0
0339bf0209a09e5853958c2dede9ab5c050f8907
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.vcs.log.ui.table; import com.intellij.ide.IdeTooltip; import com.intellij.ide.IdeTooltipManager; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.vcs.changes.issueLinks.TableLinkMouseListener; import com.intellij.ui.SimpleColoredComponent; import com.intellij.ui.components.panels.Wrapper; import com.intellij.util.ui.JBUI; import com.intellij.vcs.log.CommitId; import com.intellij.vcs.log.VcsShortCommitDetails; import com.intellij.vcs.log.data.LoadingDetails; import com.intellij.vcs.log.data.VcsLogData; import com.intellij.vcs.log.graph.EdgePrintElement; import com.intellij.vcs.log.graph.NodePrintElement; import com.intellij.vcs.log.graph.PrintElement; import com.intellij.vcs.log.graph.actions.GraphAction; import com.intellij.vcs.log.graph.actions.GraphAnswer; import com.intellij.vcs.log.impl.CommonUiProperties; import com.intellij.vcs.log.impl.VcsLogUiProperties; import com.intellij.vcs.log.paint.GraphCellPainter; import com.intellij.vcs.log.paint.PositionUtil; import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector; import com.intellij.vcs.log.ui.VcsLogColorManager; import com.intellij.vcs.log.ui.frame.CommitPresentationUtil; import com.intellij.vcs.log.ui.render.GraphCommitCellRenderer; import com.intellij.vcs.log.ui.render.SimpleColoredComponentLinkMouseListener; import com.intellij.vcs.log.util.VcsLogUiUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collection; import java.util.Collections; import static com.intellij.vcs.log.ui.table.GraphTableModel.*; /** * Processes mouse clicks and moves on the table */ public class GraphTableController { @NotNull private final VcsLogGraphTable myTable; @NotNull private final VcsLogData myLogData; @NotNull private final VcsLogUiProperties myProperties; @NotNull private final VcsLogColorManager myColorManager; @NotNull private final GraphCellPainter myGraphCellPainter; @NotNull private final GraphCommitCellRenderer myCommitRenderer; public GraphTableController(@NotNull VcsLogData logData, @NotNull VcsLogColorManager colorManager, @NotNull VcsLogUiProperties properties, @NotNull VcsLogGraphTable table, @NotNull GraphCellPainter graphCellPainter, @NotNull GraphCommitCellRenderer commitRenderer) { myTable = table; myLogData = logData; myProperties = properties; myColorManager = colorManager; myGraphCellPainter = graphCellPainter; myCommitRenderer = commitRenderer; MouseAdapter mouseAdapter = new MyMouseAdapter(); table.addMouseMotionListener(mouseAdapter); table.addMouseListener(mouseAdapter); } @Nullable PrintElement findPrintElement(@NotNull MouseEvent e) { int row = myTable.rowAtPoint(e.getPoint()); if (row >= 0 && row < myTable.getRowCount()) { return findPrintElement(row, e); } return null; } @Nullable private PrintElement findPrintElement(int row, @NotNull MouseEvent e) { Point point = calcPoint4Graph(e.getPoint()); Collection<? extends PrintElement> printElements = myTable.getVisibleGraph().getRowInfo(row).getPrintElements(); return myGraphCellPainter.getElementUnderCursor(printElements, point.x, point.y); } private void performGraphAction(@Nullable PrintElement printElement, @NotNull MouseEvent e, @NotNull GraphAction.Type actionType) { boolean isClickOnGraphElement = actionType == GraphAction.Type.MOUSE_CLICK && printElement != null; if (isClickOnGraphElement) { triggerElementClick(printElement); } Selection previousSelection = myTable.getSelection(); GraphAnswer<Integer> answer = myTable.getVisibleGraph().getActionController().performAction(new GraphAction.GraphActionImpl(printElement, actionType)); handleGraphAnswer(answer, isClickOnGraphElement, previousSelection, e); } public void handleGraphAnswer(@Nullable GraphAnswer<Integer> answer, boolean dataCouldChange, @Nullable Selection previousSelection, @Nullable MouseEvent e) { if (dataCouldChange) { myTable.getModel().fireTableDataChanged(); // since fireTableDataChanged clears selection we restore it here if (previousSelection != null) { previousSelection .restore(myTable.getVisibleGraph(), answer == null || (answer.getCommitToJump() != null && answer.doJump()), false); } } myTable.repaint(); if (answer == null) { return; } if (answer.getCursorToSet() != null) { myTable.setCursor(answer.getCursorToSet()); } if (answer.getCommitToJump() != null) { Integer row = myTable.getModel().getVisiblePack().getVisibleGraph().getVisibleRowIndex(answer.getCommitToJump()); if (row != null && row >= 0 && answer.doJump()) { myTable.jumpToRow(row); // TODO wait for the full log and then jump return; } if (e != null) showToolTip(getArrowTooltipText(answer.getCommitToJump(), row), e); } } @NotNull private Point calcPoint4Graph(@NotNull Point clickPoint) { int width = 0; for (int i = 0; i < myTable.getColumnModel().getColumnCount(); i++) { TableColumn column = myTable.getColumnModel().getColumn(i); if (column.getModelIndex() == COMMIT_COLUMN) break; width += column.getWidth(); } return new Point(clickPoint.x - width, PositionUtil.getYInsideRow(clickPoint, myTable.getRowHeight())); } @NotNull private String getArrowTooltipText(int commit, @Nullable Integer row) { VcsShortCommitDetails details; if (row != null && row >= 0) { details = myTable.getModel().getCommitMetadata(row); // preload rows around the commit } else { details = myLogData.getMiniDetailsGetter().getCommitData(commit, Collections.singleton(commit)); // preload just the commit } String balloonText = ""; if (details instanceof LoadingDetails) { CommitId commitId = myLogData.getCommitId(commit); if (commitId != null) { balloonText = "Jump to commit" + " " + commitId.getHash().toShortString(); if (myColorManager.isMultipleRoots()) { balloonText += " in " + commitId.getRoot().getName(); } } } else { balloonText = "Jump to " + CommitPresentationUtil.getShortSummary(details); } return balloonText; } private void showToolTip(@NotNull String text, @NotNull MouseEvent e) { // standard tooltip does not allow to customize its location, and locating tooltip above can obscure some important info VcsLogUiUtil.showTooltip(myTable, new Point(e.getX() + 5, e.getY()), Balloon.Position.atRight, text); } private void showOrHideCommitTooltip(int row, int column, @NotNull MouseEvent e) { if (!showTooltip(row, column, e.getPoint(), false)) { if (IdeTooltipManager.getInstance().hasCurrent()) { IdeTooltipManager.getInstance().hideCurrent(e); } } } private boolean showTooltip(int row, int column, @NotNull Point point, boolean now) { JComponent tipComponent = myCommitRenderer.getTooltip(myTable.getValueAt(row, myTable.convertColumnIndexToView(column)), calcPoint4Graph(point), row); if (tipComponent != null) { myTable.getExpandableItemsHandler().setEnabled(false); IdeTooltip tooltip = new IdeTooltip(myTable, point, new Wrapper(tipComponent)).setPreferredPosition(Balloon.Position.below); IdeTooltipManager.getInstance().show(tooltip, now); return true; } return false; } public void showTooltip(int row) { Point point = new Point(getColumnLeftXCoordinate(myTable.convertColumnIndexToView(COMMIT_COLUMN)) + myCommitRenderer.getTooltipXCoordinate(row), row * myTable.getRowHeight() + myTable.getRowHeight() / 2); showTooltip(row, COMMIT_COLUMN, point, true); } private void performRootColumnAction() { if (myColorManager.isMultipleRoots() && myProperties.exists(CommonUiProperties.SHOW_ROOT_NAMES)) { VcsLogUsageTriggerCollector.triggerUsage("RootColumnClick"); myProperties.set(CommonUiProperties.SHOW_ROOT_NAMES, !myProperties.get(CommonUiProperties.SHOW_ROOT_NAMES)); } } private static void triggerElementClick(@NotNull PrintElement printElement) { if (printElement instanceof NodePrintElement) { VcsLogUsageTriggerCollector.triggerUsage("GraphNodeClick"); } else if (printElement instanceof EdgePrintElement) { if (((EdgePrintElement)printElement).hasArrow()) { VcsLogUsageTriggerCollector.triggerUsage("GraphArrowClick"); } } } protected int getColumnLeftXCoordinate(int viewColumnIndex) { int x = 0; for (int i = 0; i < viewColumnIndex; i++) { x += myTable.getColumnModel().getColumn(i).getWidth(); } return x; } private class MyMouseAdapter extends MouseAdapter { private static final int BORDER_THICKNESS = 3; @NotNull private final TableLinkMouseListener myLinkListener = new MyLinkMouseListener(); @Nullable private Cursor myLastCursor = null; @Override public void mouseClicked(MouseEvent e) { if (myLinkListener.onClick(e, e.getClickCount())) { return; } int c = myTable.columnAtPoint(e.getPoint()); int column = myTable.convertColumnIndexToModel(c); if (e.getClickCount() == 2) { // when we reset column width, commit column eats all the remaining space // (or gives the required space) // so it is logical that we reset column width by right border if it is on the left of the commit column // and by the left border otherwise int commitColumnIndex = myTable.convertColumnIndexToView(COMMIT_COLUMN); boolean useLeftBorder = c > commitColumnIndex; if ((useLeftBorder ? isOnLeftBorder(e, c) : isOnRightBorder(e, c)) && (column == AUTHOR_COLUMN || column == DATE_COLUMN)) { myTable.resetColumnWidth(column); } else { // user may have clicked just outside of the border // in that case, c is not the column we are looking for int c2 = myTable.columnAtPoint(new Point(e.getPoint().x + (useLeftBorder ? 1 : -1) * JBUI.scale(BORDER_THICKNESS), e.getPoint().y)); int column2 = myTable.convertColumnIndexToModel(c2); if ((useLeftBorder ? isOnLeftBorder(e, c2) : isOnRightBorder(e, c2)) && (column2 == AUTHOR_COLUMN || column2 == DATE_COLUMN)) { myTable.resetColumnWidth(column2); } } } int row = myTable.rowAtPoint(e.getPoint()); if ((row >= 0 && row < myTable.getRowCount()) && e.getClickCount() == 1) { if (column == ROOT_COLUMN) { performRootColumnAction(); } else if (column == COMMIT_COLUMN) { PrintElement printElement = findPrintElement(row, e); if (printElement != null) { performGraphAction(printElement, e, GraphAction.Type.MOUSE_CLICK); } } } } public boolean isOnLeftBorder(@NotNull MouseEvent e, int column) { return Math.abs(getColumnLeftXCoordinate(column) - e.getPoint().x) <= JBUI.scale(BORDER_THICKNESS); } public boolean isOnRightBorder(@NotNull MouseEvent e, int column) { return Math.abs(getColumnLeftXCoordinate(column) + myTable.getColumnModel().getColumn(column).getWidth() - e.getPoint().x) <= JBUI.scale(BORDER_THICKNESS); } @Override public void mouseMoved(MouseEvent e) { if (myTable.isResizingColumns()) return; myTable.getExpandableItemsHandler().setEnabled(true); if (myLinkListener.getTagAt(e) != null) { swapCursor(Cursor.HAND_CURSOR); return; } int row = myTable.rowAtPoint(e.getPoint()); if (row >= 0 && row < myTable.getRowCount()) { int column = myTable.convertColumnIndexToModel(myTable.columnAtPoint(e.getPoint())); if (column == ROOT_COLUMN) { swapCursor(Cursor.HAND_CURSOR); return; } else if (column == COMMIT_COLUMN) { PrintElement printElement = findPrintElement(row, e); if (printElement == null) restoreCursor(Cursor.HAND_CURSOR); performGraphAction(printElement, e, GraphAction.Type.MOUSE_OVER); // if printElement is null, still need to unselect whatever was selected in a graph if (printElement == null) { showOrHideCommitTooltip(row, column, e); } return; } } restoreCursor(Cursor.HAND_CURSOR); } private void swapCursor(int newCursorType) { if (myTable.getCursor().getType() != newCursorType && myLastCursor == null) { Cursor newCursor = Cursor.getPredefinedCursor(newCursorType); myLastCursor = myTable.getCursor(); myTable.setCursor(newCursor); } } private void restoreCursor(int newCursorType) { if (myLastCursor != null && myTable.getCursor().getType() == newCursorType) { myTable.setCursor(myLastCursor); myLastCursor = null; } } @Override public void mouseEntered(MouseEvent e) { // Do nothing } @Override public void mouseExited(MouseEvent e) { myTable.getExpandableItemsHandler().setEnabled(true); } private class MyLinkMouseListener extends SimpleColoredComponentLinkMouseListener { @Nullable @Override public Object getTagAt(@NotNull MouseEvent e) { Object tag = super.getTagAt(e); if (!(tag instanceof SimpleColoredComponent.BrowserLauncherTag)) return null; return tag; } } } }
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/GraphTableController.java
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.vcs.log.ui.table; import com.intellij.ide.IdeTooltip; import com.intellij.ide.IdeTooltipManager; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.vcs.changes.issueLinks.TableLinkMouseListener; import com.intellij.ui.components.panels.Wrapper; import com.intellij.util.ui.JBUI; import com.intellij.vcs.log.CommitId; import com.intellij.vcs.log.VcsShortCommitDetails; import com.intellij.vcs.log.data.LoadingDetails; import com.intellij.vcs.log.data.VcsLogData; import com.intellij.vcs.log.graph.EdgePrintElement; import com.intellij.vcs.log.graph.NodePrintElement; import com.intellij.vcs.log.graph.PrintElement; import com.intellij.vcs.log.graph.actions.GraphAction; import com.intellij.vcs.log.graph.actions.GraphAnswer; import com.intellij.vcs.log.impl.CommonUiProperties; import com.intellij.vcs.log.impl.VcsLogUiProperties; import com.intellij.vcs.log.paint.GraphCellPainter; import com.intellij.vcs.log.paint.PositionUtil; import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector; import com.intellij.vcs.log.ui.VcsLogColorManager; import com.intellij.vcs.log.ui.frame.CommitPresentationUtil; import com.intellij.vcs.log.ui.render.GraphCommitCellRenderer; import com.intellij.vcs.log.ui.render.SimpleColoredComponentLinkMouseListener; import com.intellij.vcs.log.util.VcsLogUiUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collection; import java.util.Collections; import static com.intellij.vcs.log.ui.table.GraphTableModel.*; /** * Processes mouse clicks and moves on the table */ public class GraphTableController { @NotNull private final VcsLogGraphTable myTable; @NotNull private final VcsLogData myLogData; @NotNull private final VcsLogUiProperties myProperties; @NotNull private final VcsLogColorManager myColorManager; @NotNull private final GraphCellPainter myGraphCellPainter; @NotNull private final GraphCommitCellRenderer myCommitRenderer; public GraphTableController(@NotNull VcsLogData logData, @NotNull VcsLogColorManager colorManager, @NotNull VcsLogUiProperties properties, @NotNull VcsLogGraphTable table, @NotNull GraphCellPainter graphCellPainter, @NotNull GraphCommitCellRenderer commitRenderer) { myTable = table; myLogData = logData; myProperties = properties; myColorManager = colorManager; myGraphCellPainter = graphCellPainter; myCommitRenderer = commitRenderer; MouseAdapter mouseAdapter = new MyMouseAdapter(); table.addMouseMotionListener(mouseAdapter); table.addMouseListener(mouseAdapter); } @Nullable PrintElement findPrintElement(@NotNull MouseEvent e) { int row = myTable.rowAtPoint(e.getPoint()); if (row >= 0 && row < myTable.getRowCount()) { return findPrintElement(row, e); } return null; } @Nullable private PrintElement findPrintElement(int row, @NotNull MouseEvent e) { Point point = calcPoint4Graph(e.getPoint()); Collection<? extends PrintElement> printElements = myTable.getVisibleGraph().getRowInfo(row).getPrintElements(); return myGraphCellPainter.getElementUnderCursor(printElements, point.x, point.y); } private void performGraphAction(@Nullable PrintElement printElement, @NotNull MouseEvent e, @NotNull GraphAction.Type actionType) { boolean isClickOnGraphElement = actionType == GraphAction.Type.MOUSE_CLICK && printElement != null; if (isClickOnGraphElement) { triggerElementClick(printElement); } Selection previousSelection = myTable.getSelection(); GraphAnswer<Integer> answer = myTable.getVisibleGraph().getActionController().performAction(new GraphAction.GraphActionImpl(printElement, actionType)); handleGraphAnswer(answer, isClickOnGraphElement, previousSelection, e); } public void handleGraphAnswer(@Nullable GraphAnswer<Integer> answer, boolean dataCouldChange, @Nullable Selection previousSelection, @Nullable MouseEvent e) { if (dataCouldChange) { myTable.getModel().fireTableDataChanged(); // since fireTableDataChanged clears selection we restore it here if (previousSelection != null) { previousSelection .restore(myTable.getVisibleGraph(), answer == null || (answer.getCommitToJump() != null && answer.doJump()), false); } } myTable.repaint(); if (answer == null) { return; } if (answer.getCursorToSet() != null) { myTable.setCursor(answer.getCursorToSet()); } if (answer.getCommitToJump() != null) { Integer row = myTable.getModel().getVisiblePack().getVisibleGraph().getVisibleRowIndex(answer.getCommitToJump()); if (row != null && row >= 0 && answer.doJump()) { myTable.jumpToRow(row); // TODO wait for the full log and then jump return; } if (e != null) showToolTip(getArrowTooltipText(answer.getCommitToJump(), row), e); } } @NotNull private Point calcPoint4Graph(@NotNull Point clickPoint) { int width = 0; for (int i = 0; i < myTable.getColumnModel().getColumnCount(); i++) { TableColumn column = myTable.getColumnModel().getColumn(i); if (column.getModelIndex() == COMMIT_COLUMN) break; width += column.getWidth(); } return new Point(clickPoint.x - width, PositionUtil.getYInsideRow(clickPoint, myTable.getRowHeight())); } @NotNull private String getArrowTooltipText(int commit, @Nullable Integer row) { VcsShortCommitDetails details; if (row != null && row >= 0) { details = myTable.getModel().getCommitMetadata(row); // preload rows around the commit } else { details = myLogData.getMiniDetailsGetter().getCommitData(commit, Collections.singleton(commit)); // preload just the commit } String balloonText = ""; if (details instanceof LoadingDetails) { CommitId commitId = myLogData.getCommitId(commit); if (commitId != null) { balloonText = "Jump to commit" + " " + commitId.getHash().toShortString(); if (myColorManager.isMultipleRoots()) { balloonText += " in " + commitId.getRoot().getName(); } } } else { balloonText = "Jump to " + CommitPresentationUtil.getShortSummary(details); } return balloonText; } private void showToolTip(@NotNull String text, @NotNull MouseEvent e) { // standard tooltip does not allow to customize its location, and locating tooltip above can obscure some important info VcsLogUiUtil.showTooltip(myTable, new Point(e.getX() + 5, e.getY()), Balloon.Position.atRight, text); } private void showOrHideCommitTooltip(int row, int column, @NotNull MouseEvent e) { if (!showTooltip(row, column, e.getPoint(), false)) { if (IdeTooltipManager.getInstance().hasCurrent()) { IdeTooltipManager.getInstance().hideCurrent(e); } } } private boolean showTooltip(int row, int column, @NotNull Point point, boolean now) { JComponent tipComponent = myCommitRenderer.getTooltip(myTable.getValueAt(row, myTable.convertColumnIndexToView(column)), calcPoint4Graph(point), row); if (tipComponent != null) { myTable.getExpandableItemsHandler().setEnabled(false); IdeTooltip tooltip = new IdeTooltip(myTable, point, new Wrapper(tipComponent)).setPreferredPosition(Balloon.Position.below); IdeTooltipManager.getInstance().show(tooltip, now); return true; } return false; } public void showTooltip(int row) { Point point = new Point(getColumnLeftXCoordinate(myTable.convertColumnIndexToView(COMMIT_COLUMN)) + myCommitRenderer.getTooltipXCoordinate(row), row * myTable.getRowHeight() + myTable.getRowHeight() / 2); showTooltip(row, COMMIT_COLUMN, point, true); } private void performRootColumnAction() { if (myColorManager.isMultipleRoots() && myProperties.exists(CommonUiProperties.SHOW_ROOT_NAMES)) { VcsLogUsageTriggerCollector.triggerUsage("RootColumnClick"); myProperties.set(CommonUiProperties.SHOW_ROOT_NAMES, !myProperties.get(CommonUiProperties.SHOW_ROOT_NAMES)); } } private static void triggerElementClick(@NotNull PrintElement printElement) { if (printElement instanceof NodePrintElement) { VcsLogUsageTriggerCollector.triggerUsage("GraphNodeClick"); } else if (printElement instanceof EdgePrintElement) { if (((EdgePrintElement)printElement).hasArrow()) { VcsLogUsageTriggerCollector.triggerUsage("GraphArrowClick"); } } } protected int getColumnLeftXCoordinate(int viewColumnIndex) { int x = 0; for (int i = 0; i < viewColumnIndex; i++) { x += myTable.getColumnModel().getColumn(i).getWidth(); } return x; } private class MyMouseAdapter extends MouseAdapter { private static final int BORDER_THICKNESS = 3; @NotNull private final TableLinkMouseListener myLinkListener = new SimpleColoredComponentLinkMouseListener(); @Nullable private Cursor myLastCursor = null; @Override public void mouseClicked(MouseEvent e) { if (myLinkListener.onClick(e, e.getClickCount())) { return; } int c = myTable.columnAtPoint(e.getPoint()); int column = myTable.convertColumnIndexToModel(c); if (e.getClickCount() == 2) { // when we reset column width, commit column eats all the remaining space // (or gives the required space) // so it is logical that we reset column width by right border if it is on the left of the commit column // and by the left border otherwise int commitColumnIndex = myTable.convertColumnIndexToView(COMMIT_COLUMN); boolean useLeftBorder = c > commitColumnIndex; if ((useLeftBorder ? isOnLeftBorder(e, c) : isOnRightBorder(e, c)) && (column == AUTHOR_COLUMN || column == DATE_COLUMN)) { myTable.resetColumnWidth(column); } else { // user may have clicked just outside of the border // in that case, c is not the column we are looking for int c2 = myTable.columnAtPoint(new Point(e.getPoint().x + (useLeftBorder ? 1 : -1) * JBUI.scale(BORDER_THICKNESS), e.getPoint().y)); int column2 = myTable.convertColumnIndexToModel(c2); if ((useLeftBorder ? isOnLeftBorder(e, c2) : isOnRightBorder(e, c2)) && (column2 == AUTHOR_COLUMN || column2 == DATE_COLUMN)) { myTable.resetColumnWidth(column2); } } } int row = myTable.rowAtPoint(e.getPoint()); if ((row >= 0 && row < myTable.getRowCount()) && e.getClickCount() == 1) { if (column == ROOT_COLUMN) { performRootColumnAction(); } else if (column == COMMIT_COLUMN) { PrintElement printElement = findPrintElement(row, e); if (printElement != null) { performGraphAction(printElement, e, GraphAction.Type.MOUSE_CLICK); } } } } public boolean isOnLeftBorder(@NotNull MouseEvent e, int column) { return Math.abs(getColumnLeftXCoordinate(column) - e.getPoint().x) <= JBUI.scale(BORDER_THICKNESS); } public boolean isOnRightBorder(@NotNull MouseEvent e, int column) { return Math.abs(getColumnLeftXCoordinate(column) + myTable.getColumnModel().getColumn(column).getWidth() - e.getPoint().x) <= JBUI.scale(BORDER_THICKNESS); } @Override public void mouseMoved(MouseEvent e) { if (myTable.isResizingColumns()) return; myTable.getExpandableItemsHandler().setEnabled(true); if (myLinkListener.getTagAt(e) != null) { swapCursor(Cursor.HAND_CURSOR); return; } int row = myTable.rowAtPoint(e.getPoint()); if (row >= 0 && row < myTable.getRowCount()) { int column = myTable.convertColumnIndexToModel(myTable.columnAtPoint(e.getPoint())); if (column == ROOT_COLUMN) { swapCursor(Cursor.HAND_CURSOR); return; } else if (column == COMMIT_COLUMN) { PrintElement printElement = findPrintElement(row, e); if (printElement == null) restoreCursor(Cursor.HAND_CURSOR); performGraphAction(printElement, e, GraphAction.Type.MOUSE_OVER); // if printElement is null, still need to unselect whatever was selected in a graph if (printElement == null) { showOrHideCommitTooltip(row, column, e); } return; } } restoreCursor(Cursor.HAND_CURSOR); } private void swapCursor(int newCursorType) { if (myTable.getCursor().getType() != newCursorType && myLastCursor == null) { Cursor newCursor = Cursor.getPredefinedCursor(newCursorType); myLastCursor = myTable.getCursor(); myTable.setCursor(newCursor); } } private void restoreCursor(int newCursorType) { if (myLastCursor != null && myTable.getCursor().getType() == newCursorType) { myTable.setCursor(myLastCursor); myLastCursor = null; } } @Override public void mouseEntered(MouseEvent e) { // Do nothing } @Override public void mouseExited(MouseEvent e) { myTable.getExpandableItemsHandler().setEnabled(true); } } }
[file-history] only allow to click on browser links (and not on speed search matches)
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/GraphTableController.java
[file-history] only allow to click on browser links (and not on speed search matches)
<ide><path>latform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/GraphTableController.java <ide> import com.intellij.ide.IdeTooltipManager; <ide> import com.intellij.openapi.ui.popup.Balloon; <ide> import com.intellij.openapi.vcs.changes.issueLinks.TableLinkMouseListener; <add>import com.intellij.ui.SimpleColoredComponent; <ide> import com.intellij.ui.components.panels.Wrapper; <ide> import com.intellij.util.ui.JBUI; <ide> import com.intellij.vcs.log.CommitId; <ide> <ide> private class MyMouseAdapter extends MouseAdapter { <ide> private static final int BORDER_THICKNESS = 3; <del> @NotNull private final TableLinkMouseListener myLinkListener = new SimpleColoredComponentLinkMouseListener(); <add> @NotNull private final TableLinkMouseListener myLinkListener = new MyLinkMouseListener(); <ide> @Nullable private Cursor myLastCursor = null; <ide> <ide> @Override <ide> public void mouseExited(MouseEvent e) { <ide> myTable.getExpandableItemsHandler().setEnabled(true); <ide> } <add> <add> private class MyLinkMouseListener extends SimpleColoredComponentLinkMouseListener { <add> @Nullable <add> @Override <add> public Object getTagAt(@NotNull MouseEvent e) { <add> Object tag = super.getTagAt(e); <add> if (!(tag instanceof SimpleColoredComponent.BrowserLauncherTag)) return null; <add> return tag; <add> } <add> } <ide> } <ide> }
Java
apache-2.0
730e6b3d232896350f2acfafa4293bcc096200b2
0
luoxn28/mybatis-wheel
package com.intrack.session; import com.intrack.cursor.Cursor; import java.io.Closeable; import java.sql.Connection; import java.util.List; import java.util.Map; /** * The primary Java interface for working with mybatis-wheel. * Through this interface you can execute commands, get mappers nad manage transactions. * * @author intrack */ public interface SqlSession extends Closeable { /** * Retrieve a simple row mapped from the statement key. * <T> The return object type. */ <T> T selectOne(String statement); /** * Retrieve a simple row mapped from the statement key and parameter. * <T> The return object type. */ <T> T selectOne(String statement, Object parameter); /** * Retrieve a list of mapped objects from the statement key. * <E> The return list element type. */ <E> List<E> selectList(String statement); /** * Retrieve a list of mapped objects from the statement key and parameter. * <E> The return list element type. */ <E> List<E> selectList(String statement, Object parameter); /** * Retrieve a list of mapped objects from the statement key and parameter, * within the specified row bounds. * <E> The return list element type. */ <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds); /** * THe selectMap is a special case in that ti is designed to convert a list of results * into a Map based on one of the properties in the resulting objects. * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") * <K> the returned Map keys type * <V> the returned Map values tpe */ <K, V> Map<K, V> selectMap(String statement, String mapKey); /** * THe selectMap is a special case in that ti is designed to convert a list of results * into a Map based on one of the properties in the resulting objects with parameter. * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") * <K> the returned Map keys type * <V> the returned Map values tpe */ <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey); /** * THe selectMap is a special case in that ti is designed to convert a list of results * into a Map based on one of the properties in the resulting objects with parameter. * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") * <K> the returned Map keys type * <V> the returned Map values tpe */ <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds); /** * A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. */ <T> Cursor<T> selectCursor(String statement); /** * A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. */ <T> Cursor<T> selectCursor(String statement, Object parameter); /** * A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. */ <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds); /** * Retrieve a single row mapped from the statement key * using a ResultHandler. */ void select(String statement, ResultHandler resultHandler); /** * Retrieve a single row mapped from the statement key and parameter * using a ResultHandler. */ void select(String statement, Object parameter, ResultHandler resultHandler); /** * Retrieve a single row mapped from the statement key and parameter using * a ResultHandler and RowBounds. */ void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler resultHandler); /** * Execute an insert statement. */ int insert(String statement); /** * Execute an insert statement with parameter. */ int insert(String statement, Object parameter); /** * Execute an update statement. */ int update(String statement); /** * Execute on update statement with parameter. */ int update(String statement, Object parameter); /** * Execute an delete statement. */ int delete(String statement); /** * Execute an delete statement with parameter. */ int delete(String statement, Object parameter); /** * Flushes batch statement and commits database connection. */ void commit(); /** * Discards pending batch statements and rolls database connection back. */ void rollback(); /** * Flushes batch statements. */ // List<BatchResult> flushStatements(); /** * Close the session. */ @Override void close(); /** * Clears local session cache. */ void clearCache(); /** * Retrieves current configuration. */ Configuration getConfiguration(); /** * Retrieves a mapper. */ <T> T getMapper(Class<T> type); /** * Retrieves inner database connection. */ Connection getConnection(); }
src/main/java/com/intrack/session/SqlSession.java
package com.intrack.session; import com.intrack.cursor.Cursor; import java.io.Closeable; import java.util.List; import java.util.Map; /** * The primary Java interface for working with mybatis-wheel. * Through this interface you can execute commands, get mappers nad manage transactions. * * @author intrack */ public interface SqlSession extends Closeable { /** * Retrieve a simple row mapped from the statement key. * <T> The return object type. */ <T> T selectOne(String statement); /** * Retrieve a simple row mapped from the statement key and parameter. * <T> The return object type. */ <T> T selectOne(String statement, Object parameter); /** * Retrieve a list of mapped objects from the statement key. * <E> The return list element type. */ <E> List<E> selectList(String statement); /** * Retrieve a list of mapped objects from the statement key and parameter. * <E> The return list element type. */ <E> List<E> selectList(String statement, Object parameter); /** * Retrieve a list of mapped objects from the statement key and parameter, * within the specified row bounds. * <E> The return list element type. */ <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds); /** * THe selectMap is a special case in that ti is designed to convert a list of results * into a Map based on one of the properties in the resulting objects. * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") * <K> the returned Map keys type * <V> the returned Map values tpe */ <K, V> Map<K, V> selectMap(String statement, String mapKey); /** * THe selectMap is a special case in that ti is designed to convert a list of results * into a Map based on one of the properties in the resulting objects with parameter. * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") * <K> the returned Map keys type * <V> the returned Map values tpe */ <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey); /** * THe selectMap is a special case in that ti is designed to convert a list of results * into a Map based on one of the properties in the resulting objects with parameter. * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") * <K> the returned Map keys type * <V> the returned Map values tpe */ <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds); /** * A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. */ <T> Cursor<T> selectCursor(String statement); /** * A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. */ <T> Cursor<T> selectCursor(String statement, Object parameter); /** * A Cursor offers the same results as a List, except it fetches data lazily using an Iterator. */ <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds); /** * Retrieve a single row mapped from the statement key * using a ResultHandler. */ void select(String statement, ResultHandler resultHandler); /** * Retrieve a single row mapped from the statement key and parameter * using a ResultHandler. */ void select(String statement, Object parameter, ResultHandler resultHandler); @Override void close(); }
update SqlSession
src/main/java/com/intrack/session/SqlSession.java
update SqlSession
<ide><path>rc/main/java/com/intrack/session/SqlSession.java <ide> import com.intrack.cursor.Cursor; <ide> <ide> import java.io.Closeable; <add>import java.sql.Connection; <ide> import java.util.List; <ide> import java.util.Map; <ide> <ide> */ <ide> void select(String statement, Object parameter, ResultHandler resultHandler); <ide> <add> /** <add> * Retrieve a single row mapped from the statement key and parameter using <add> * a ResultHandler and RowBounds. <add> */ <add> void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler resultHandler); <add> <add> /** <add> * Execute an insert statement. <add> */ <add> int insert(String statement); <add> <add> /** <add> * Execute an insert statement with parameter. <add> */ <add> int insert(String statement, Object parameter); <add> <add> /** <add> * Execute an update statement. <add> */ <add> int update(String statement); <add> <add> /** <add> * Execute on update statement with parameter. <add> */ <add> int update(String statement, Object parameter); <add> <add> /** <add> * Execute an delete statement. <add> */ <add> int delete(String statement); <add> <add> /** <add> * Execute an delete statement with parameter. <add> */ <add> int delete(String statement, Object parameter); <add> <add> /** <add> * Flushes batch statement and commits database connection. <add> */ <add> void commit(); <add> <add> /** <add> * Discards pending batch statements and rolls database connection back. <add> */ <add> void rollback(); <add> <add> /** <add> * Flushes batch statements. <add> */ <add>// List<BatchResult> flushStatements(); <add> <add> /** <add> * Close the session. <add> */ <ide> @Override <ide> void close(); <ide> <add> /** <add> * Clears local session cache. <add> */ <add> void clearCache(); <add> <add> /** <add> * Retrieves current configuration. <add> */ <add> Configuration getConfiguration(); <add> <add> /** <add> * Retrieves a mapper. <add> */ <add> <T> T getMapper(Class<T> type); <add> <add> /** <add> * Retrieves inner database connection. <add> */ <add> Connection getConnection(); <add> <ide> }
JavaScript
apache-2.0
0e781df50a603e6e519d8ca62a07e1372a155b17
0
cafjs/caf_pull
/*! Copyright 2013 Hewlett-Packard Development Company, L.P. 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. */ "use strict"; /* * Loads external resources and caches them in the local filesystem. * * The name of this component in framework.json should be pull_mux * * @name caf_pull/plug_pull * @namespace * @augments gen_plug */ var caf = require('caf_core'); var genPlug = caf.gen_plug; var async = caf.async; var helper = require('./plug_pull_helper'); /** * Factory method to create a pull service connector. */ exports.newInstance = function(context, spec, secrets, cb) { var $ = context; /* Type of all is {<CA Id> : {alias : {fileName : <string>, url : <string> ,version: <string>, caId: <string>, alias: <string>, updateF: <function>, queue : <worker>}} */ var all = {}; var home = $.cf.getHome(); var subdir = spec.env.subdir || 'pull_cache'; var that = genPlug.constructor(spec, secrets); var newAddResourceQueue = function() { return async.queue( function(meta, cb0) { async.waterfall([ function(cb1) { // load head $.log && $.log.trace('begin head caid:' + meta.caId + ' alias:' + meta.alias); helper.loadHead(meta, cb1); }, function(newVersion, cb1) { meta.version = newVersion; $.log && $.log.trace('begin load caid:' + meta.caId + ' alias:' + meta.alias); // nop if locally cached helper.loadBody(meta, home, subdir, cb1); }, function(fileName, cb1) { $.log && $.log.trace('begin update caid:' + meta.caId + ' alias:' + meta.alias); meta.fileName = fileName; // updateF should be idempotent meta.updateF(fileName, meta.version, cb1); } ], function(err, data) { $.log && $.log.trace('done update caid:' + meta.caId + ' alias:' + meta.alias); cb0(err, data); }); },1); // serialized }; that.addResource = function(caId, alias, url, updateF) { all[caId] = all[caId] || {}; all[caId][alias] = all[caId][alias] || {}; var meta = all[caId][alias]; meta.url = url; meta.updateF = updateF; meta.caId = caId; meta.alias = alias; // queue per resource to serialize file system access meta.queue = meta.queue || newAddResourceQueue(); var cb0 = function(err, data) { // log if (err) { $.log && $.log.debug('cannot load url:' + url + ' caId:' + caId + ' alias: ' + alias + ' got error:' + err); } else { $.log && $.log.trace('+'); } }; meta.queue.push(meta, cb0); }; that.removeResource = function(caId, alias) { /* we don't cleanup the file system, when the node.js process dies, * cloud foundry eventually will remove all the files associated to * that process. */ delete all[caId][alias]; }; that.refreshResource = function(caId, alias) { var meta = all[caId] && all[caId][alias]; if (!meta) { $.log && $.log.warn('Cannot refresh non-loaded resource:' + alias + ' for CA:' + caId); } else { that.addResource(caId, alias, meta.url, meta.updateF); } }; $.log && $.log.debug('New pull plug'); cb(null, that); };
lib/plug_pull.js
/*! Copyright 2013 Hewlett-Packard Development Company, L.P. 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. */ "use strict"; /* * Loads external resources and caches them in the local filesystem. * * The name of this component in framework.json should be pull_mux * * @name caf_pull/plug_pull * @namespace * @augments gen_plug */ var caf = require('caf_core'); var genPlug = caf.gen_plug; var async = caf.async; var helper = require('./plug_pull_helper'); /** * Factory method to create a pull service connector. */ exports.newInstance = function(context, spec, secrets, cb) { var $ = context; /* Type of all is {<CA Id> : {alias : {fileName : <string>, url : <string> ,version: <string>, caId: <string>, alias: <string>, updateF: <function>, queue : <worker>}} */ var all = {}; var home = $.cf.getHome(); var subdir = spec.env.subdir || 'pull_cache'; var that = genPlug.constructor(spec, secrets); var newAddResourceQueue = function() { return async.queue( function(meta, cb0) { async.waterfall([ function(cb1) { // load head $.log.trace('begin head caid:' + meta.caId + ' alias:' + meta.alias); helper.loadHead(meta, cb1); }, function(newVersion, cb1) { meta.version = newVersion; $.log.trace('begin load caid:' + meta.caId + ' alias:' + meta.alias); // nop if locally cached helper.loadBody(meta, home, subdir, cb1); }, function(fileName, cb1) { $.log.trace('begin update caid:' + meta.caId + ' alias:' + meta.alias); meta.fileName = fileName; // updateF should be idempotent meta.updateF(fileName, meta.version, cb1); } ], function(err, data) { $.log.trace('done update caid:' + meta.caId + ' alias:' + meta.alias); cb0(err, data); }); },1); // serialized }; that.addResource = function(caId, alias, url, updateF) { all[caId] = all[caId] || {}; all[caId][alias] = all[caId][alias] || {}; var meta = all[caId][alias]; meta.url = url; meta.updateF = updateF; meta.caId = caId; meta.alias = alias; // queue per resource to serialize file system access meta.queue = meta.queue || newAddResourceQueue(); var cb0 = function(err, data) { // log if (err) { $.log.debug('cannot load url:' + url + ' caId:' + caId + ' alias: ' + alias + ' got error:' + err); } else { $.log.trace('+'); } }; meta.queue.push(meta, cb0); }; that.removeResource = function(caId, alias) { /* we don't cleanup the file system, when the node.js process dies, * cloud foundry eventually will remove all the files associated to * that process. */ delete all[caId][alias]; }; that.refreshResource = function(caId, alias) { var meta = all[caId] && all[caId][alias]; if (!meta) { $.log.warn('Cannot refresh non-loaded resource:' + alias + ' for CA:' + caId); } else { that.addResource(caId, alias, meta.url, meta.updateF); } }; $.log.debug('New pull plug'); cb(null, that); };
Fix logging
lib/plug_pull.js
Fix logging
<ide><path>ib/plug_pull.js <ide> async.waterfall([ <ide> function(cb1) { <ide> // load head <del> $.log.trace('begin head caid:' + <del> meta.caId + ' alias:' + <del> meta.alias); <add> $.log && $.log.trace('begin head caid:' + <add> meta.caId + <add> ' alias:' + <add> meta.alias); <ide> helper.loadHead(meta, cb1); <ide> }, <ide> function(newVersion, cb1) { <ide> meta.version = newVersion; <del> $.log.trace('begin load caid:' + <del> meta.caId + ' alias:' + <del> meta.alias); <add> $.log && $.log.trace('begin load caid:' + <add> meta.caId + <add> ' alias:' + <add> meta.alias); <ide> <ide> // nop if locally cached <ide> helper.loadBody(meta, home, subdir, cb1); <ide> }, <ide> function(fileName, cb1) { <del> $.log.trace('begin update caid:' + <del> meta.caId + ' alias:' + <del> meta.alias); <add> $.log && $.log.trace('begin update caid:' <add> + meta.caId + <add> ' alias:' + <add> meta.alias); <ide> meta.fileName = fileName; <ide> // updateF should be idempotent <ide> meta.updateF(fileName, meta.version, cb1); <ide> } <ide> ], <ide> function(err, data) { <del> $.log.trace('done update caid:' + <del> meta.caId + ' alias:' + <del> meta.alias); <add> $.log && $.log.trace('done update caid:' + <add> meta.caId + ' alias:' + <add> meta.alias); <ide> cb0(err, data); <ide> }); <ide> },1); // serialized <ide> var cb0 = function(err, data) { <ide> // log <ide> if (err) { <del> $.log.debug('cannot load url:' + url + ' caId:' + caId + <del> ' alias: ' + alias + ' got error:' + err); <add> $.log && $.log.debug('cannot load url:' + url + ' caId:' + <add> caId + ' alias: ' + alias + ' got error:' <add> + err); <ide> } else { <del> $.log.trace('+'); <add> $.log && $.log.trace('+'); <ide> } <ide> }; <ide> meta.queue.push(meta, cb0); <ide> that.refreshResource = function(caId, alias) { <ide> var meta = all[caId] && all[caId][alias]; <ide> if (!meta) { <del> $.log.warn('Cannot refresh non-loaded resource:' + alias + <del> ' for CA:' + caId); <add> $.log && $.log.warn('Cannot refresh non-loaded resource:' + alias + <add> ' for CA:' + caId); <ide> } else { <ide> that.addResource(caId, alias, meta.url, meta.updateF); <ide> } <ide> }; <ide> <del> $.log.debug('New pull plug'); <add> $.log && $.log.debug('New pull plug'); <ide> cb(null, that); <ide> };
JavaScript
mit
8f27b539d2e25af744550c4714177b3828a881b2
0
tangentstorm/ok-bot
// An IRC bot for the k5 programming language, // using oK from : https://github.com/JohnEarnest/ok "use strict"; var irc = require('irc'); var ok = require('./lib/ok/oK'); const MAXLINES = 8; var client = new irc.Client('irc.freenode.net', 'ok-bot', { channels: ['#jsoftware', '#learnprogramming', '#kq', '#lpmc'] }); var env = ok.baseEnv(); function runK(src) { return ok.format(ok.run(ok.parse(src), env)); } client.addListener('message', (from, to, msg)=> { if (to.startsWith('#') && msg.startsWith('k) ')) { var result; try { result = runK(msg.substring(2)); } catch (err) { result = 'ERROR: ' + err.message; } var line, lines = result.split("\n"); for (var i=0; i<lines.length; i++) { if (i >= MAXLINES && lines.length != MAXLINES) { line = '...'; break; } else line = lines[i]; client.say(to, `${from}: ${line}`); } } });
ok-bot.js
// An IRC bot for the k5 programming language, // using oK from : https://github.com/JohnEarnest/ok "use strict"; var irc = require('irc'); var ok = require('./lib/ok/oK'); const MAXLINES = 8; var client = new irc.Client('irc.freenode.net', 'ok-bot', { channels: ['#jsoftware', '#learnprogramming', '#kq'] }); var env = ok.baseEnv(); function runK(src) { return ok.format(ok.run(ok.parse(src), env)); } client.addListener('message', (from, to, msg)=> { if (to.startsWith('#') && msg.startsWith('k) ')) { var result; try { result = runK(msg.substring(2)); } catch (err) { result = 'ERROR: ' + err.message; } var line, lines = result.split("\n"); for (var i=0; i<lines.length; i++) { if (i >= MAXLINES && lines.length != MAXLINES) { line = '...'; break; } else line = lines[i]; client.say(to, `${from}: ${line}`); } } });
add #lpmc
ok-bot.js
add #lpmc
<ide><path>k-bot.js <ide> const MAXLINES = 8; <ide> <ide> var client = new irc.Client('irc.freenode.net', 'ok-bot', { <del> channels: ['#jsoftware', '#learnprogramming', '#kq'] <add> channels: ['#jsoftware', '#learnprogramming', '#kq', '#lpmc'] <ide> }); <ide> <ide> var env = ok.baseEnv();
Java
mit
0c4de1303e0d75e4479cb001f111b5403fe7aa4e
0
125m125/ktapi-java,125m125/ktapi-java
package de._125m125.kt.ktapi.smartCache; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.function.Supplier; import de._125m125.kt.ktapi.core.BUY_SELL; import de._125m125.kt.ktapi.core.BUY_SELL_BOTH; import de._125m125.kt.ktapi.core.KtCachingRequester; import de._125m125.kt.ktapi.core.KtNotificationManager; import de._125m125.kt.ktapi.core.KtRequester; import de._125m125.kt.ktapi.core.NotificationListener; import de._125m125.kt.ktapi.core.PAYOUT_TYPE; import de._125m125.kt.ktapi.core.entities.HistoryEntry; import de._125m125.kt.ktapi.core.entities.Item; import de._125m125.kt.ktapi.core.entities.Message; import de._125m125.kt.ktapi.core.entities.Notification; import de._125m125.kt.ktapi.core.entities.OrderBookEntry; import de._125m125.kt.ktapi.core.entities.Payout; import de._125m125.kt.ktapi.core.entities.Permissions; import de._125m125.kt.ktapi.core.entities.PusherResult; import de._125m125.kt.ktapi.core.entities.Trade; import de._125m125.kt.ktapi.core.results.Callback; import de._125m125.kt.ktapi.core.results.Result; import de._125m125.kt.ktapi.core.results.WriteResult; import de._125m125.kt.ktapi.core.users.UserKey; import de._125m125.kt.ktapi.smartCache.objects.TimestampedList; import de._125m125.kt.ktapi.smartCache.objects.TimestampedObjectFactory; /** * */ public class KtCachingRequesterIml<U extends UserKey<?>> implements KtRequester<U>, NotificationListener, KtCachingRequester<U> { public static final int CACHE_HIT_STATUS_CODE = 299; private static final String ITEMS = "items-"; private static final String TRADES = "trades-"; private static final String PAYOUTS = "payouts-"; private static final String MESSAGES = "messages-"; private static final String ORDERBOOK = "orderbook-"; private static final String HISTORY = "history-"; private final Map<String, CacheData<?>> cache; private final KtRequester<U> requester; private KtNotificationManager<U> ktNotificationManager; private final TimestampedObjectFactory factory; public KtCachingRequesterIml(final KtRequester<U> requester, final KtNotificationManager<U> ktNotificationManager) { this(requester, ktNotificationManager, new TimestampedObjectFactory()); } public KtCachingRequesterIml(final KtRequester<U> requester, final KtNotificationManager<U> ktNotificationManager, final TimestampedObjectFactory factory) { this.ktNotificationManager = ktNotificationManager; this.cache = new ConcurrentHashMap<>(); this.requester = requester; this.factory = factory != null ? factory : new TimestampedObjectFactory(); } @Override public void invalidateHistory(final String itemid) { invalidate(KtCachingRequesterIml.HISTORY + itemid); } @Override public void invalidateOrderBook(final String itemid) { invalidate(KtCachingRequesterIml.ORDERBOOK + itemid); } @Override public void invalidateMessages(final U userKey) { invalidate(KtCachingRequesterIml.MESSAGES + userKey.getUserId()); } @Override public void invalidatePayouts(final U userKey) { invalidate(KtCachingRequesterIml.PAYOUTS + userKey.getUserId()); } @Override public void invalidateTrades(final U userKey) { invalidate(KtCachingRequesterIml.TRADES + userKey.getUserId()); } @Override public void invalidateItemList(final U userKey) { invalidate(KtCachingRequesterIml.ITEMS + userKey.getUserId()); } private void invalidate(final String key) { final CacheData<?> cacheData = this.cache.get(key); if (cacheData != null) { cacheData.invalidate(); } } @Override public boolean isValidHistory(final String itemid, final List<HistoryEntry> historyEntries) { return isValid(KtCachingRequesterIml.HISTORY + itemid, historyEntries); } @Override public boolean isValidOrderBook(final String itemid, final List<OrderBookEntry> orderBook) { return isValid(KtCachingRequesterIml.ORDERBOOK + itemid, orderBook); } @Override public boolean isValidMessageList(final U userKey, final List<Message> messages) { return isValid(KtCachingRequesterIml.MESSAGES + userKey.getUserId(), messages); } @Override public boolean isValidPayoutList(final U userKey, final List<Payout> payouts) { return isValid(KtCachingRequesterIml.PAYOUTS + userKey.getUserId(), payouts); } @Override public boolean isValidTradeList(final U userKey, final List<Trade> trades) { return isValid(KtCachingRequesterIml.TRADES + userKey.getUserId(), trades); } @Override public boolean isValidItemList(final U userKey, final List<Item> items) { return isValid(KtCachingRequesterIml.ITEMS + userKey.getUserId(), items); } private <T> boolean isValid(final String key, final List<T> historyEntries) { if (!(historyEntries instanceof TimestampedList)) { return false; } final CacheData<?> cacheData = this.cache.get(key); return cacheData != null && ((TimestampedList<?>) historyEntries) .getTimestamp() >= cacheData.getLastInvalidationTime(); } @Override public void update(final Notification notification) { final String key = notification.getDetails().get("source") + "-" + notification.getDetails().get("key"); invalidate(key); } @Override public Result<List<HistoryEntry>> getHistory(final String itemid, final int limit, final int offset) { this.ktNotificationManager.subscribeToHistory(this); return getOrFetch(KtCachingRequesterIml.HISTORY + itemid, offset, offset + limit, () -> this.requester.getHistory(itemid, limit, offset)); } @Override public Result<HistoryEntry> getLatestHistory(final String itemid) { this.ktNotificationManager.subscribeToHistory(this); return this.getOrFetch(KtCachingRequesterIml.HISTORY + itemid, 0, () -> this.requester.getLatestHistory(itemid)); } @Override public Result<List<OrderBookEntry>> getOrderBook(final String itemid, final int limit, final BUY_SELL_BOTH mode, final boolean summarizeRemaining) { // TODO caching return this.requester.getOrderBook(itemid, limit, mode, summarizeRemaining); } @Override public Result<List<OrderBookEntry>> getBestOrderBookEntries(final String itemid, final BUY_SELL_BOTH mode) { // TODO caching return this.requester.getBestOrderBookEntries(itemid, mode); } @Override public Result<Permissions> getPermissions(final U userKey) { // TODO caching? return this.requester.getPermissions(userKey); } @Override public Result<List<Item>> getItems(final U userKey) { this.ktNotificationManager.subscribeToItems(this, userKey, false); this.ktNotificationManager.subscribeToItems(this, userKey, true); return getAllOrFetch(KtCachingRequesterIml.ITEMS + userKey.getUserId(), () -> this.requester.getItems(userKey)); } @Override public Result<Item> getItem(final U userKey, final String itemid) { this.ktNotificationManager.subscribeToItems(this, userKey, false); this.ktNotificationManager.subscribeToItems(this, userKey, true); return getOrFetch(KtCachingRequesterIml.ITEMS + userKey.getUserId(), item -> item.getId().equals(itemid), () -> this.requester.getItem(userKey, itemid)); } @Override public Result<List<Message>> getMessages(final U userKey) { this.ktNotificationManager.subscribeToMessages(this, userKey, false); this.ktNotificationManager.subscribeToMessages(this, userKey, true); return getAllOrFetch(KtCachingRequesterIml.MESSAGES + userKey.getUserId(), () -> this.requester.getMessages(userKey)); } @Override public Result<List<Payout>> getPayouts(final U userKey) { this.ktNotificationManager.subscribeToPayouts(this, userKey, false); this.ktNotificationManager.subscribeToPayouts(this, userKey, true); return getAllOrFetch(KtCachingRequesterIml.PAYOUTS + userKey.getUserId(), () -> this.requester.getPayouts(userKey)); } @Override public Result<WriteResult<Payout>> createPayout(final U userKey, final PAYOUT_TYPE type, final String itemid, final String amount) { final Result<WriteResult<Payout>> result = this.requester.createPayout(userKey, type, itemid, amount); result.addCallback(new InvalidationCallback<WriteResult<Payout>>(this.cache, KtCachingRequesterIml.PAYOUTS + userKey.getUserId())); return result; } @Override public Result<WriteResult<Payout>> cancelPayout(final U userKey, final long payoutid) { final Result<WriteResult<Payout>> result = this.requester.cancelPayout(userKey, payoutid); result.addCallback(new InvalidationCallback<WriteResult<Payout>>(this.cache, KtCachingRequesterIml.PAYOUTS + userKey.getUserId())); return result; } @Override public Result<WriteResult<Payout>> takeoutPayout(final U userKey, final long payoutid) { final Result<WriteResult<Payout>> result = this.requester.takeoutPayout(userKey, payoutid); result.addCallback(new InvalidationCallback<WriteResult<Payout>>(this.cache, KtCachingRequesterIml.PAYOUTS + userKey.getUserId())); return result; } @Override public Result<PusherResult> authorizePusher(final U userKey, final String channel_name, final String socketId) { return this.requester.authorizePusher(userKey, channel_name, socketId); } @Override public Result<List<Trade>> getTrades(final U userKey) { this.ktNotificationManager.subscribeToTrades(this, userKey, false); this.ktNotificationManager.subscribeToTrades(this, userKey, true); return getAllOrFetch(KtCachingRequesterIml.TRADES + userKey.getUserId(), () -> this.requester.getTrades(userKey)); } @Override public Result<WriteResult<Trade>> createTrade(final U userKey, final BUY_SELL mode, final String item, final int amount, final String pricePerItem) { final Result<WriteResult<Trade>> result = this.requester.createTrade(userKey, mode, item, amount, pricePerItem); result.addCallback(new InvalidationCallback<WriteResult<Trade>>(this.cache, KtCachingRequesterIml.TRADES + userKey.getUserId())); return result; } @Override public Result<WriteResult<Trade>> cancelTrade(final U userKey, final long tradeId) { final Result<WriteResult<Trade>> result = this.requester.cancelTrade(userKey, tradeId); result.addCallback(new InvalidationCallback<WriteResult<Trade>>(this.cache, KtCachingRequesterIml.TRADES + userKey.getUserId())); return result; } @Override public Result<WriteResult<Trade>> takeoutTrade(final U userKey, final long tradeId) { final Result<WriteResult<Trade>> result = this.requester.takeoutTrade(userKey, tradeId); result.addCallback(new InvalidationCallback<WriteResult<Trade>>(this.cache, KtCachingRequesterIml.TRADES + userKey.getUserId())); return result; } private <T> Result<List<T>> getOrFetch(final String key, final int start, final int end, final Supplier<Result<List<T>>> fetcher) { @SuppressWarnings("unchecked") final CacheData<T> cacheEntry = (CacheData<T>) this.cache.computeIfAbsent(key, s -> new CacheData<T>()); final Optional<TimestampedList<T>> all = cacheEntry.get(start, end); if (all.isPresent()) { return new ImmediateResult<>(KtCachingRequesterIml.CACHE_HIT_STATUS_CODE, all.get()); } else { final Result<List<T>> result = fetcher.get(); final ExposedResult<List<T>> returnResult = new ExposedResult<>(); result.addCallback(new Callback<List<T>>() { @Override public void onSuccess(final int status, final List<T> result) { final TimestampedList<T> timestampedList = cacheEntry.set(result, start, start + result.size()); returnResult.setSuccessResult(status, timestampedList); } @Override public void onFailure(final int status, final String message, final String humanReadableMessage) { returnResult.setErrorResult(status, message, humanReadableMessage); } @Override public void onError(final Throwable t) { returnResult.setFailureResult(t); } }); return returnResult; } } private <T> Result<T> getOrFetch(final String key, final int index, final Supplier<Result<T>> fetcher) { @SuppressWarnings("unchecked") final CacheData<T> cacheEntry = (CacheData<T>) this.cache.computeIfAbsent(key, s -> new CacheData<T>()); final Optional<T> all = cacheEntry.get(index); if (all.isPresent()) { return new ImmediateResult<>(KtCachingRequesterIml.CACHE_HIT_STATUS_CODE, KtCachingRequesterIml.this.factory.create(all.get(), cacheEntry.getLastInvalidationTime(), true)); } else { final Result<T> result = fetcher.get(); final ExposedResult<T> returnResult = new ExposedResult<>(); result.addCallback(new Callback<T>() { @Override public void onSuccess(final int status, final T result) { returnResult.setSuccessResult(status, KtCachingRequesterIml.this.factory .create(result, cacheEntry.getLastInvalidationTime(), false)); } @Override public void onFailure(final int status, final String message, final String humanReadableMessage) { returnResult.setErrorResult(status, message, humanReadableMessage); } @Override public void onError(final Throwable t) { returnResult.setFailureResult(t); } }); return returnResult; } } private <T> Result<T> getOrFetch(final String key, final Predicate<T> index, final Supplier<Result<T>> fetcher) { @SuppressWarnings("unchecked") final CacheData<T> cacheEntry = (CacheData<T>) this.cache.computeIfAbsent(key, s -> new CacheData<T>()); final Optional<T> all = cacheEntry.getAny(index); if (all.isPresent()) { return new ImmediateResult<>(KtCachingRequesterIml.CACHE_HIT_STATUS_CODE, KtCachingRequesterIml.this.factory.create(all.get(), cacheEntry.getLastInvalidationTime(), true)); } else { final Result<T> result = fetcher.get(); final ExposedResult<T> returnResult = new ExposedResult<>(); result.addCallback(new Callback<T>() { @Override public void onSuccess(final int status, final T result) { returnResult.setSuccessResult(status, KtCachingRequesterIml.this.factory .create(result, cacheEntry.getLastInvalidationTime(), false)); } @Override public void onFailure(final int status, final String message, final String humanReadableMessage) { returnResult.setErrorResult(status, message, humanReadableMessage); } @Override public void onError(final Throwable t) { returnResult.setFailureResult(t); } }); return returnResult; } } private <T> Result<List<T>> getAllOrFetch(final String key, final Supplier<Result<List<T>>> fetcher) { @SuppressWarnings("unchecked") final CacheData<T> cacheEntry = (CacheData<T>) this.cache.computeIfAbsent(key, s -> new CacheData<T>()); final Optional<TimestampedList<T>> all = cacheEntry.getAll(); if (all.isPresent()) { return new ImmediateResult<>(KtCachingRequesterIml.CACHE_HIT_STATUS_CODE, all.get()); } else { final Result<List<T>> result = fetcher.get(); final ExposedResult<List<T>> returnResult = new ExposedResult<>(); result.addCallback(new Callback<List<T>>() { @Override public void onSuccess(final int status, final List<T> result) { final TimestampedList<T> timestampedList = cacheEntry.set(result, 0, result.size()); returnResult.setSuccessResult(status, timestampedList); } @Override public void onFailure(final int status, final String message, final String humanReadableMessage) { returnResult.setErrorResult(status, message, humanReadableMessage); } @Override public void onError(final Throwable t) { returnResult.setFailureResult(t); } }); return returnResult; } } protected static class ExposedResult<T> extends Result<T> { @Override protected void setSuccessResult(final int status, final T content) { super.setSuccessResult(status, content); } @Override protected void setFailureResult(final Throwable t) { super.setFailureResult(t); } @Override protected void setErrorResult(final int status, final String errorMessage, final String humanReadableErrorMessage) { super.setErrorResult(status, errorMessage, humanReadableErrorMessage); } } @Override public void close() throws IOException { this.requester.close(); } }
ktapi-smartCache/src/main/java/de/_125m125/kt/ktapi/smartCache/KtCachingRequesterIml.java
package de._125m125.kt.ktapi.smartCache; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.function.Supplier; import de._125m125.kt.ktapi.core.BUY_SELL; import de._125m125.kt.ktapi.core.BUY_SELL_BOTH; import de._125m125.kt.ktapi.core.KtCachingRequester; import de._125m125.kt.ktapi.core.KtNotificationManager; import de._125m125.kt.ktapi.core.KtRequester; import de._125m125.kt.ktapi.core.NotificationListener; import de._125m125.kt.ktapi.core.PAYOUT_TYPE; import de._125m125.kt.ktapi.core.entities.HistoryEntry; import de._125m125.kt.ktapi.core.entities.Item; import de._125m125.kt.ktapi.core.entities.Message; import de._125m125.kt.ktapi.core.entities.Notification; import de._125m125.kt.ktapi.core.entities.OrderBookEntry; import de._125m125.kt.ktapi.core.entities.Payout; import de._125m125.kt.ktapi.core.entities.Permissions; import de._125m125.kt.ktapi.core.entities.PusherResult; import de._125m125.kt.ktapi.core.entities.Trade; import de._125m125.kt.ktapi.core.results.Callback; import de._125m125.kt.ktapi.core.results.Result; import de._125m125.kt.ktapi.core.results.WriteResult; import de._125m125.kt.ktapi.core.users.UserKey; import de._125m125.kt.ktapi.smartCache.objects.TimestampedList; import de._125m125.kt.ktapi.smartCache.objects.TimestampedObjectFactory; /** * */ public class KtCachingRequesterIml<U extends UserKey<?>> implements KtRequester<U>, NotificationListener, KtCachingRequester<U> { public static final int CACHE_HIT_STATUS_CODE = 299; private static final String ITEMS = "items-"; private static final String TRADES = "trades-"; private static final String PAYOUTS = "payouts-"; private static final String MESSAGES = "messages-"; private static final String ORDERBOOK = "orderbook-"; private static final String HISTORY = "history-"; private final Map<String, CacheData<?>> cache; private final KtRequester<U> requester; private final TimestampedObjectFactory factory; public KtCachingRequesterIml(final KtRequester<U> requester, final KtNotificationManager<U> ktNotificationManager) { this(requester, ktNotificationManager, new TimestampedObjectFactory()); } public KtCachingRequesterIml(final KtRequester<U> requester, final KtNotificationManager<U> ktNotificationManager, final TimestampedObjectFactory factory) { this.cache = new ConcurrentHashMap<>(); this.requester = requester; this.factory = factory != null ? factory : new TimestampedObjectFactory(); // ktNotificationManager.subscribeToAll(this, false); // ktNotificationManager.subscribeToAll(this, true); ktNotificationManager.subscribeToAll(this); } @Override public void invalidateHistory(final String itemid) { invalidate(KtCachingRequesterIml.HISTORY + itemid); } @Override public void invalidateOrderBook(final String itemid) { invalidate(KtCachingRequesterIml.ORDERBOOK + itemid); } @Override public void invalidateMessages(final U userKey) { invalidate(KtCachingRequesterIml.MESSAGES + userKey.getUserId()); } @Override public void invalidatePayouts(final U userKey) { invalidate(KtCachingRequesterIml.PAYOUTS + userKey.getUserId()); } @Override public void invalidateTrades(final U userKey) { invalidate(KtCachingRequesterIml.TRADES + userKey.getUserId()); } @Override public void invalidateItemList(final U userKey) { invalidate(KtCachingRequesterIml.ITEMS + userKey.getUserId()); } private void invalidate(final String key) { final CacheData<?> cacheData = this.cache.get(key); if (cacheData != null) { cacheData.invalidate(); } } @Override public boolean isValidHistory(final String itemid, final List<HistoryEntry> historyEntries) { return isValid(KtCachingRequesterIml.HISTORY + itemid, historyEntries); } @Override public boolean isValidOrderBook(final String itemid, final List<OrderBookEntry> orderBook) { return isValid(KtCachingRequesterIml.ORDERBOOK + itemid, orderBook); } @Override public boolean isValidMessageList(final U userKey, final List<Message> messages) { return isValid(KtCachingRequesterIml.MESSAGES + userKey.getUserId(), messages); } @Override public boolean isValidPayoutList(final U userKey, final List<Payout> payouts) { return isValid(KtCachingRequesterIml.PAYOUTS + userKey.getUserId(), payouts); } @Override public boolean isValidTradeList(final U userKey, final List<Trade> trades) { return isValid(KtCachingRequesterIml.TRADES + userKey.getUserId(), trades); } @Override public boolean isValidItemList(final U userKey, final List<Item> items) { return isValid(KtCachingRequesterIml.ITEMS + userKey.getUserId(), items); } private <T> boolean isValid(final String key, final List<T> historyEntries) { if (!(historyEntries instanceof TimestampedList)) { return false; } final CacheData<?> cacheData = this.cache.get(key); return cacheData != null && ((TimestampedList<?>) historyEntries) .getTimestamp() >= cacheData.getLastInvalidationTime(); } @Override public void update(final Notification notification) { final String key = notification.getDetails().get("source") + "-" + notification.getDetails().get("key"); invalidate(key); } @Override public Result<List<HistoryEntry>> getHistory(final String itemid, final int limit, final int offset) { return getOrFetch(KtCachingRequesterIml.HISTORY + itemid, offset, offset + limit, () -> this.requester.getHistory(itemid, limit, offset)); } @Override public Result<HistoryEntry> getLatestHistory(final String itemid) { return this.getOrFetch(KtCachingRequesterIml.HISTORY + itemid, 0, () -> this.requester.getLatestHistory(itemid)); } @Override public Result<List<OrderBookEntry>> getOrderBook(final String itemid, final int limit, final BUY_SELL_BOTH mode, final boolean summarizeRemaining) { // TODO caching return this.requester.getOrderBook(itemid, limit, mode, summarizeRemaining); } @Override public Result<List<OrderBookEntry>> getBestOrderBookEntries(final String itemid, final BUY_SELL_BOTH mode) { // TODO caching return this.requester.getBestOrderBookEntries(itemid, mode); } @Override public Result<Permissions> getPermissions(final U userKey) { // TODO caching? return this.requester.getPermissions(userKey); } @Override public Result<List<Item>> getItems(final U userKey) { return getAllOrFetch(KtCachingRequesterIml.PAYOUTS + userKey.getUserId(), () -> this.requester.getItems(userKey)); } @Override public Result<Item> getItem(final U userKey, final String itemid) { return getOrFetch(KtCachingRequesterIml.ITEMS + userKey.getUserId(), item -> item.getId().equals(itemid), () -> this.requester.getItem(userKey, itemid)); } @Override public Result<List<Message>> getMessages(final U userKey) { return getAllOrFetch(KtCachingRequesterIml.PAYOUTS + userKey.getUserId(), () -> this.requester.getMessages(userKey)); } @Override public Result<List<Payout>> getPayouts(final U userKey) { return getAllOrFetch(KtCachingRequesterIml.PAYOUTS + userKey.getUserId(), () -> this.requester.getPayouts(userKey)); } @Override public Result<WriteResult<Payout>> createPayout(final U userKey, final PAYOUT_TYPE type, final String itemid, final String amount) { final Result<WriteResult<Payout>> result = this.requester.createPayout(userKey, type, itemid, amount); result.addCallback(new InvalidationCallback<WriteResult<Payout>>(this.cache, KtCachingRequesterIml.PAYOUTS + userKey.getUserId())); return result; } @Override public Result<WriteResult<Payout>> cancelPayout(final U userKey, final long payoutid) { final Result<WriteResult<Payout>> result = this.requester.cancelPayout(userKey, payoutid); result.addCallback(new InvalidationCallback<WriteResult<Payout>>(this.cache, KtCachingRequesterIml.PAYOUTS + userKey.getUserId())); return result; } @Override public Result<WriteResult<Payout>> takeoutPayout(final U userKey, final long payoutid) { final Result<WriteResult<Payout>> result = this.requester.takeoutPayout(userKey, payoutid); result.addCallback(new InvalidationCallback<WriteResult<Payout>>(this.cache, KtCachingRequesterIml.PAYOUTS + userKey.getUserId())); return result; } @Override public Result<PusherResult> authorizePusher(final U userKey, final String channel_name, final String socketId) { return this.requester.authorizePusher(userKey, channel_name, socketId); } @Override public Result<List<Trade>> getTrades(final U userKey) { return getAllOrFetch(KtCachingRequesterIml.TRADES + userKey.getUserId(), () -> this.requester.getTrades(userKey)); } @Override public Result<WriteResult<Trade>> createTrade(final U userKey, final BUY_SELL mode, final String item, final int amount, final String pricePerItem) { final Result<WriteResult<Trade>> result = this.requester.createTrade(userKey, mode, item, amount, pricePerItem); result.addCallback(new InvalidationCallback<WriteResult<Trade>>(this.cache, KtCachingRequesterIml.TRADES + userKey.getUserId())); return result; } @Override public Result<WriteResult<Trade>> cancelTrade(final U userKey, final long tradeId) { final Result<WriteResult<Trade>> result = this.requester.cancelTrade(userKey, tradeId); result.addCallback(new InvalidationCallback<WriteResult<Trade>>(this.cache, KtCachingRequesterIml.TRADES + userKey.getUserId())); return result; } @Override public Result<WriteResult<Trade>> takeoutTrade(final U userKey, final long tradeId) { final Result<WriteResult<Trade>> result = this.requester.takeoutTrade(userKey, tradeId); result.addCallback(new InvalidationCallback<WriteResult<Trade>>(this.cache, KtCachingRequesterIml.TRADES + userKey.getUserId())); return result; } private <T> Result<List<T>> getOrFetch(final String key, final int start, final int end, final Supplier<Result<List<T>>> fetcher) { @SuppressWarnings("unchecked") final CacheData<T> cacheEntry = (CacheData<T>) this.cache.computeIfAbsent(key, s -> new CacheData<T>()); final Optional<TimestampedList<T>> all = cacheEntry.get(start, end); if (all.isPresent()) { return new ImmediateResult<>(KtCachingRequesterIml.CACHE_HIT_STATUS_CODE, all.get()); } else { final Result<List<T>> result = fetcher.get(); final ExposedResult<List<T>> returnResult = new ExposedResult<>(); result.addCallback(new Callback<List<T>>() { @Override public void onSuccess(final int status, final List<T> result) { final TimestampedList<T> timestampedList = cacheEntry.set(result, start, start + result.size()); returnResult.setSuccessResult(status, timestampedList); } @Override public void onFailure(final int status, final String message, final String humanReadableMessage) { returnResult.setErrorResult(status, message, humanReadableMessage); } @Override public void onError(final Throwable t) { returnResult.setFailureResult(t); } }); return returnResult; } } private <T> Result<T> getOrFetch(final String key, final int index, final Supplier<Result<T>> fetcher) { @SuppressWarnings("unchecked") final CacheData<T> cacheEntry = (CacheData<T>) this.cache.computeIfAbsent(key, s -> new CacheData<T>()); final Optional<T> all = cacheEntry.get(index); if (all.isPresent()) { return new ImmediateResult<>(KtCachingRequesterIml.CACHE_HIT_STATUS_CODE, KtCachingRequesterIml.this.factory.create(all.get(), cacheEntry.getLastInvalidationTime(), true)); } else { final Result<T> result = fetcher.get(); final ExposedResult<T> returnResult = new ExposedResult<>(); result.addCallback(new Callback<T>() { @Override public void onSuccess(final int status, final T result) { returnResult.setSuccessResult(status, KtCachingRequesterIml.this.factory .create(result, cacheEntry.getLastInvalidationTime(), false)); } @Override public void onFailure(final int status, final String message, final String humanReadableMessage) { returnResult.setErrorResult(status, message, humanReadableMessage); } @Override public void onError(final Throwable t) { returnResult.setFailureResult(t); } }); return returnResult; } } private <T> Result<T> getOrFetch(final String key, final Predicate<T> index, final Supplier<Result<T>> fetcher) { @SuppressWarnings("unchecked") final CacheData<T> cacheEntry = (CacheData<T>) this.cache.computeIfAbsent(key, s -> new CacheData<T>()); final Optional<T> all = cacheEntry.getAny(index); if (all.isPresent()) { return new ImmediateResult<>(KtCachingRequesterIml.CACHE_HIT_STATUS_CODE, KtCachingRequesterIml.this.factory.create(all.get(), cacheEntry.getLastInvalidationTime(), true)); } else { final Result<T> result = fetcher.get(); final ExposedResult<T> returnResult = new ExposedResult<>(); result.addCallback(new Callback<T>() { @Override public void onSuccess(final int status, final T result) { returnResult.setSuccessResult(status, KtCachingRequesterIml.this.factory .create(result, cacheEntry.getLastInvalidationTime(), false)); } @Override public void onFailure(final int status, final String message, final String humanReadableMessage) { returnResult.setErrorResult(status, message, humanReadableMessage); } @Override public void onError(final Throwable t) { returnResult.setFailureResult(t); } }); return returnResult; } } private <T> Result<List<T>> getAllOrFetch(final String key, final Supplier<Result<List<T>>> fetcher) { @SuppressWarnings("unchecked") final CacheData<T> cacheEntry = (CacheData<T>) this.cache.computeIfAbsent(key, s -> new CacheData<T>()); final Optional<TimestampedList<T>> all = cacheEntry.getAll(); if (all.isPresent()) { return new ImmediateResult<>(KtCachingRequesterIml.CACHE_HIT_STATUS_CODE, all.get()); } else { final Result<List<T>> result = fetcher.get(); final ExposedResult<List<T>> returnResult = new ExposedResult<>(); result.addCallback(new Callback<List<T>>() { @Override public void onSuccess(final int status, final List<T> result) { final TimestampedList<T> timestampedList = cacheEntry.set(result, 0, result.size()); returnResult.setSuccessResult(status, timestampedList); } @Override public void onFailure(final int status, final String message, final String humanReadableMessage) { returnResult.setErrorResult(status, message, humanReadableMessage); } @Override public void onError(final Throwable t) { returnResult.setFailureResult(t); } }); return returnResult; } } protected static class ExposedResult<T> extends Result<T> { @Override protected void setSuccessResult(final int status, final T content) { super.setSuccessResult(status, content); } @Override protected void setFailureResult(final Throwable t) { super.setFailureResult(t); } @Override protected void setErrorResult(final int status, final String errorMessage, final String humanReadableErrorMessage) { super.setErrorResult(status, errorMessage, humanReadableErrorMessage); } } @Override public void close() throws IOException { this.requester.close(); } }
use correct cache-prefixes for KtCachingRequesterImpl (fix #23) and subscribe to updates on get (fix #24)
ktapi-smartCache/src/main/java/de/_125m125/kt/ktapi/smartCache/KtCachingRequesterIml.java
use correct cache-prefixes for KtCachingRequesterImpl (fix #23) and subscribe to updates on get (fix #24)
<ide><path>tapi-smartCache/src/main/java/de/_125m125/kt/ktapi/smartCache/KtCachingRequesterIml.java <ide> <ide> private final Map<String, CacheData<?>> cache; <ide> private final KtRequester<U> requester; <add> private KtNotificationManager<U> ktNotificationManager; <ide> private final TimestampedObjectFactory factory; <ide> <ide> public KtCachingRequesterIml(final KtRequester<U> requester, <ide> public KtCachingRequesterIml(final KtRequester<U> requester, <ide> final KtNotificationManager<U> ktNotificationManager, <ide> final TimestampedObjectFactory factory) { <add> this.ktNotificationManager = ktNotificationManager; <ide> this.cache = new ConcurrentHashMap<>(); <ide> this.requester = requester; <ide> this.factory = factory != null ? factory : new TimestampedObjectFactory(); <del> <del> // ktNotificationManager.subscribeToAll(this, false); <del> // ktNotificationManager.subscribeToAll(this, true); <del> ktNotificationManager.subscribeToAll(this); <ide> } <ide> <ide> @Override <ide> @Override <ide> public Result<List<HistoryEntry>> getHistory(final String itemid, final int limit, <ide> final int offset) { <add> this.ktNotificationManager.subscribeToHistory(this); <ide> return getOrFetch(KtCachingRequesterIml.HISTORY + itemid, offset, offset + limit, <ide> () -> this.requester.getHistory(itemid, limit, offset)); <ide> } <ide> <ide> @Override <ide> public Result<HistoryEntry> getLatestHistory(final String itemid) { <add> this.ktNotificationManager.subscribeToHistory(this); <ide> return this.getOrFetch(KtCachingRequesterIml.HISTORY + itemid, 0, <ide> () -> this.requester.getLatestHistory(itemid)); <ide> } <ide> <ide> @Override <ide> public Result<List<Item>> getItems(final U userKey) { <del> return getAllOrFetch(KtCachingRequesterIml.PAYOUTS + userKey.getUserId(), <add> this.ktNotificationManager.subscribeToItems(this, userKey, false); <add> this.ktNotificationManager.subscribeToItems(this, userKey, true); <add> return getAllOrFetch(KtCachingRequesterIml.ITEMS + userKey.getUserId(), <ide> () -> this.requester.getItems(userKey)); <ide> } <ide> <ide> @Override <ide> public Result<Item> getItem(final U userKey, final String itemid) { <add> this.ktNotificationManager.subscribeToItems(this, userKey, false); <add> this.ktNotificationManager.subscribeToItems(this, userKey, true); <ide> return getOrFetch(KtCachingRequesterIml.ITEMS + userKey.getUserId(), <ide> item -> item.getId().equals(itemid), () -> this.requester.getItem(userKey, itemid)); <ide> } <ide> <ide> @Override <ide> public Result<List<Message>> getMessages(final U userKey) { <del> return getAllOrFetch(KtCachingRequesterIml.PAYOUTS + userKey.getUserId(), <add> this.ktNotificationManager.subscribeToMessages(this, userKey, false); <add> this.ktNotificationManager.subscribeToMessages(this, userKey, true); <add> return getAllOrFetch(KtCachingRequesterIml.MESSAGES + userKey.getUserId(), <ide> () -> this.requester.getMessages(userKey)); <ide> } <ide> <ide> @Override <ide> public Result<List<Payout>> getPayouts(final U userKey) { <add> this.ktNotificationManager.subscribeToPayouts(this, userKey, false); <add> this.ktNotificationManager.subscribeToPayouts(this, userKey, true); <ide> return getAllOrFetch(KtCachingRequesterIml.PAYOUTS + userKey.getUserId(), <ide> () -> this.requester.getPayouts(userKey)); <ide> } <ide> <ide> @Override <ide> public Result<List<Trade>> getTrades(final U userKey) { <add> this.ktNotificationManager.subscribeToTrades(this, userKey, false); <add> this.ktNotificationManager.subscribeToTrades(this, userKey, true); <ide> return getAllOrFetch(KtCachingRequesterIml.TRADES + userKey.getUserId(), <ide> () -> this.requester.getTrades(userKey)); <ide> }
Java
apache-2.0
069103a9e0b533f34d26e335075b64b06f87bf25
0
Cognifide/AET,Cognifide/AET,Cognifide/AET,Cognifide/AET
/** * AET * * Copyright (C) 2013 Cognifide Limited * * 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.cognifide.aet.job.api.collector; import java.io.IOException; /** * A Http request logic wrapper, that enables executing request with defined headers and cookies. */ public interface HttpRequestExecutor { HttpRequestExecutor addHeader(String key, String value); HttpRequestExecutor addCookie(String key, String value); HttpRequestExecutor removeCookie(String key); /** * Executes a GET request to the given <b>url</b> and returns {@link ResponseObject} * * @param url - an url the request should be done to * @param timeoutInMs - number of milliseconds after which connection will be timed out */ ResponseObject executeGetRequest(String url, int timeoutInMs) throws IOException; }
api/jobs-api/src/main/java/com/cognifide/aet/job/api/collector/HttpRequestExecutor.java
/** * AET * * Copyright (C) 2013 Cognifide Limited * * 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.cognifide.aet.job.api.collector; import java.io.IOException; /** * A Http request logic wrapper, that enables executing request with defined headers and cookies. */ public interface HttpRequestExecutor { HttpRequestExecutor addHeader(String key, String value); HttpRequestExecutor addCookie(String key, String value); HttpRequestExecutor removeCookie(String key); /** * Executes a GET request to the given <bb>url</bb> and returns {@link ResponseObject} * * @param url - an url the request should be done to * @param timeoutInMs - number of milliseconds after which connection will be timed out */ ResponseObject executeGetRequest(String url, int timeoutInMs) throws IOException; }
fix for incorrect JAVADOC
api/jobs-api/src/main/java/com/cognifide/aet/job/api/collector/HttpRequestExecutor.java
fix for incorrect JAVADOC
<ide><path>pi/jobs-api/src/main/java/com/cognifide/aet/job/api/collector/HttpRequestExecutor.java <ide> HttpRequestExecutor removeCookie(String key); <ide> <ide> /** <del> * Executes a GET request to the given <bb>url</bb> and returns {@link ResponseObject} <add> * Executes a GET request to the given <b>url</b> and returns {@link ResponseObject} <ide> * <ide> * @param url - an url the request should be done to <ide> * @param timeoutInMs - number of milliseconds after which connection will be timed out
Java
mit
86853cf9151789435f7eaca26408a4215084cadb
0
JCPedroza/XochiJava
import static org.junit.Assert.*; import java.util.*; public class Test{ // Instance variables for use with testing Note aNoteA = new Note("A", 440, 60, 1, 1, 127, 1); Note aNoteC = new Note("C", 450, 61, 2, 4, 125, 6); Note aNoteE = new Note("E", 460, 62, 3, 5, 126, 7); Note aNoteG = new Note("G", 470, 66, 6, 6, 6, 6); Note[] aNoteArray = {aNoteA, aNoteC, aNoteE}; List<Note> aNoteList = Arrays.asList(aNoteA, aNoteC, aNoteE); List<String> aPool = Arrays.asList("A", "B", "C", "D"); String[] aPool2 = {"Ab", "A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G"}; List<String> aPool3 = new ArrayList<String>(Arrays.asList(aPool2)); Chord aChord1 = new Chord(aNoteArray, "Am"); Chord aChord2 = new Chord(aNoteArray); Scale aScale1 = new Scale(aNoteList, "A aeolian"); Scale aScale2 = new Scale(aNoteList); Scale aScale3 = new Scale(aNoteArray); List<Chord> aChList = new ArrayList<Chord>(Arrays.asList(aChord1, aChord2)); ChordGroup aChG1 = new ChordGroup(aChList); // Instances Process aProcess = new Process(); Formulas formulas = new Formulas(); public void runTests(){ // Class Tests assertEquals(aNoteA.getName(), "A"); assertEquals(aScale1.getName(), "A aeolian"); assertEquals(aChord1.getName(), "Am"); // Misc method tests --------------------------- assertEquals(aChord2.getName(), "ACE"); assertEquals(aScale2.getName(), "ACE"); assertEquals(aScale3.getName(), "ACE"); assertEquals(Arrays.toString(aChG1.getChordsAsStringArray()), Arrays.toString(new String[] {"Am", "ACE"})); // Process Tests ------------------------------- // stepCount() assertEquals(aProcess.stepCount("C","Eb"), 3); assertEquals(aProcess.stepCount(aNoteA, aNoteC), 3); assertEquals(aProcess.stepCount(aNoteG, aNoteA), 2); assertEquals(aProcess.stepCount("C","Eb", aPool3), 3); assertEquals(aProcess.stepCount("Gb", "B", aPool2), 5); assertEquals(aProcess.stepCount(aNoteA, aNoteC, aPool), 2); assertEquals(aProcess.stepCount(aNoteA, aNoteC, aPool2), 3); // scalize() assertEquals(Arrays.toString(aProcess.scalize(aNoteA, formulas.aeolian).getNotesAsStringArray()), Arrays.toString(new String[] {"A", "B", "C", "D", "E", "F", "G"})); assertEquals(Arrays.toString(aProcess.scalize(aNoteA, formulas.aeolian, aPool2).getNotesAsStringArray()), Arrays.toString(new String[] {"A", "B", "C", "D", "E", "F", "G"})); assertEquals(Arrays.toString(aProcess.scalize(aNoteC, formulas.ionian).getNotesAsStringArray()), Arrays.toString(new String[] {"C", "D", "E", "F", "G", "A", "B"})); assertEquals(Arrays.toString(aProcess.scalize(aNoteC, formulas.ionian, aPool).getNotesAsStringArray()), Arrays.toString(new String[] {"C", "A", "C", "D", "B", "D", "B"})); assertEquals(Arrays.toString(aProcess.scalize("F", formulas.ionian).getNotesAsStringArray()), Arrays.toString(new String[] {"F", "G", "A", "Bb", "C", "D", "E"})); assertEquals(Arrays.toString(aProcess.scalize("D", formulas.aeolian, aPool2).getNotesAsStringArray()), Arrays.toString(new String[] {"D", "E", "F", "G", "A", "Bb", "C"})); // harmonize() & scalize() assertEquals(Arrays.toString(aProcess.harmonize(aProcess.scalize(aNoteA, formulas.aeolian)).getChordsAsStringArray()), Arrays.toString(new String[] {"ACE", "BDF", "CEG", "DFA", "EGB", "FAC", "GBD"})); // :D System.out.println("All test passed! :D"); } }
Test.java
import static org.junit.Assert.*; import java.util.*; public class Test{ // Instance variables for use with testing Note aNoteA = new Note("A", 440, 60, 1, 1, 127, 1); Note aNoteC = new Note("C", 450, 61, 2, 4, 125, 6); Note aNoteE = new Note("E", 460, 62, 3, 5, 126, 7); Note aNoteG = new Note("G", 470, 66, 6, 6, 6, 6); Note[] aNoteArray = {aNoteA, aNoteC, aNoteE}; List<Note> aNoteList = Arrays.asList(aNoteA, aNoteC, aNoteE); List<String> aPool = Arrays.asList("A", "B", "C", "D"); String[] aPool2 = {"Ab", "A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G"}; List<String> aPool3 = new ArrayList<String>(Arrays.asList(aPool2)); Chord aChord1 = new Chord(aNoteArray, "Am"); Scale aScale1 = new Scale(aNoteList, "A aeolian"); // Instances Process aProcess = new Process(); Formulas formulas = new Formulas(); public void runTests(){ // Class Tests assertEquals(aNoteA.getName(), "A"); assertEquals(aScale1.getName(), "A aeolian"); assertEquals(aChord1.getName(), "Am"); // Process Tests //stepCount() assertEquals(aProcess.stepCount("C","Eb"), 3); assertEquals(aProcess.stepCount(aNoteA, aNoteC), 3); assertEquals(aProcess.stepCount(aNoteG, aNoteA), 2); assertEquals(aProcess.stepCount("C","Eb", aPool3), 3); assertEquals(aProcess.stepCount("Gb", "B", aPool2), 5); assertEquals(aProcess.stepCount(aNoteA, aNoteC, aPool), 2); assertEquals(aProcess.stepCount(aNoteA, aNoteC, aPool2), 3); //scalize() assertEquals(Arrays.toString(aProcess.scalize(aNoteA, formulas.aeolian).getNotesAsString()), Arrays.toString(new String[] {"A", "B", "C", "D", "E", "F", "G"})); assertEquals(Arrays.toString(aProcess.scalize(aNoteA, formulas.aeolian, aPool2).getNotesAsString()), Arrays.toString(new String[] {"A", "B", "C", "D", "E", "F", "G"})); assertEquals(Arrays.toString(aProcess.scalize(aNoteC, formulas.ionian).getNotesAsString()), Arrays.toString(new String[] {"C", "D", "E", "F", "G", "A", "B"})); assertEquals(Arrays.toString(aProcess.scalize(aNoteC, formulas.ionian, aPool).getNotesAsString()), Arrays.toString(new String[] {"C", "A", "C", "D", "B", "D", "B"})); assertEquals(Arrays.toString(aProcess.scalize("F", formulas.ionian).getNotesAsString()), Arrays.toString(new String[] {"F", "G", "A", "Bb", "C", "D", "E"})); assertEquals(Arrays.toString(aProcess.scalize("D", formulas.aeolian, aPool2).getNotesAsString()), Arrays.toString(new String[] {"D", "E", "F", "G", "A", "Bb", "C"})); // :D System.out.println("All test passed! :D"); } }
added tests for harmonize() and ChordGroup.getChordsAsStringArray()
Test.java
added tests for harmonize() and ChordGroup.getChordsAsStringArray()
<ide><path>est.java <ide> String[] aPool2 = {"Ab", "A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G"}; <ide> List<String> aPool3 = new ArrayList<String>(Arrays.asList(aPool2)); <ide> Chord aChord1 = new Chord(aNoteArray, "Am"); <add> Chord aChord2 = new Chord(aNoteArray); <ide> Scale aScale1 = new Scale(aNoteList, "A aeolian"); <del> <add> Scale aScale2 = new Scale(aNoteList); <add> Scale aScale3 = new Scale(aNoteArray); <add> List<Chord> aChList = new ArrayList<Chord>(Arrays.asList(aChord1, aChord2)); <add> ChordGroup aChG1 = new ChordGroup(aChList); <ide> // Instances <ide> Process aProcess = new Process(); <ide> Formulas formulas = new Formulas(); <ide> assertEquals(aScale1.getName(), "A aeolian"); <ide> assertEquals(aChord1.getName(), "Am"); <ide> <del> // Process Tests <add> // Misc method tests --------------------------- <add> assertEquals(aChord2.getName(), "ACE"); <add> assertEquals(aScale2.getName(), "ACE"); <add> assertEquals(aScale3.getName(), "ACE"); <add> assertEquals(Arrays.toString(aChG1.getChordsAsStringArray()), Arrays.toString(new String[] {"Am", "ACE"})); <ide> <del> //stepCount() <add> // Process Tests ------------------------------- <add> <add> // stepCount() <ide> assertEquals(aProcess.stepCount("C","Eb"), 3); <ide> assertEquals(aProcess.stepCount(aNoteA, aNoteC), 3); <ide> assertEquals(aProcess.stepCount(aNoteG, aNoteA), 2); <ide> assertEquals(aProcess.stepCount("Gb", "B", aPool2), 5); <ide> assertEquals(aProcess.stepCount(aNoteA, aNoteC, aPool), 2); <ide> assertEquals(aProcess.stepCount(aNoteA, aNoteC, aPool2), 3); <add> <ide> <del> //scalize() <del> assertEquals(Arrays.toString(aProcess.scalize(aNoteA, formulas.aeolian).getNotesAsString()), <add> // scalize() <add> assertEquals(Arrays.toString(aProcess.scalize(aNoteA, formulas.aeolian).getNotesAsStringArray()), <ide> Arrays.toString(new String[] {"A", "B", "C", "D", "E", "F", "G"})); <del> assertEquals(Arrays.toString(aProcess.scalize(aNoteA, formulas.aeolian, aPool2).getNotesAsString()), <add> assertEquals(Arrays.toString(aProcess.scalize(aNoteA, formulas.aeolian, aPool2).getNotesAsStringArray()), <ide> Arrays.toString(new String[] {"A", "B", "C", "D", "E", "F", "G"})); <del> assertEquals(Arrays.toString(aProcess.scalize(aNoteC, formulas.ionian).getNotesAsString()), <add> assertEquals(Arrays.toString(aProcess.scalize(aNoteC, formulas.ionian).getNotesAsStringArray()), <ide> Arrays.toString(new String[] {"C", "D", "E", "F", "G", "A", "B"})); <del> assertEquals(Arrays.toString(aProcess.scalize(aNoteC, formulas.ionian, aPool).getNotesAsString()), <add> assertEquals(Arrays.toString(aProcess.scalize(aNoteC, formulas.ionian, aPool).getNotesAsStringArray()), <ide> Arrays.toString(new String[] {"C", "A", "C", "D", "B", "D", "B"})); <del> assertEquals(Arrays.toString(aProcess.scalize("F", formulas.ionian).getNotesAsString()), <add> assertEquals(Arrays.toString(aProcess.scalize("F", formulas.ionian).getNotesAsStringArray()), <ide> Arrays.toString(new String[] {"F", "G", "A", "Bb", "C", "D", "E"})); <del> assertEquals(Arrays.toString(aProcess.scalize("D", formulas.aeolian, aPool2).getNotesAsString()), <add> assertEquals(Arrays.toString(aProcess.scalize("D", formulas.aeolian, aPool2).getNotesAsStringArray()), <ide> Arrays.toString(new String[] {"D", "E", "F", "G", "A", "Bb", "C"})); <add> <add> // harmonize() & scalize() <add> assertEquals(Arrays.toString(aProcess.harmonize(aProcess.scalize(aNoteA, formulas.aeolian)).getChordsAsStringArray()), <add> Arrays.toString(new String[] {"ACE", "BDF", "CEG", "DFA", "EGB", "FAC", "GBD"})); <ide> <del> <ide> // :D <ide> System.out.println("All test passed! :D"); <ide> }
Java
apache-2.0
4f83bc8f7d9bb5456f0784f39c623377905a7542
0
Tamicer/Novate,NeglectedByBoss/Novate
package com.tamic.novate; import android.content.Context; import android.support.annotation.NonNull; import android.util.Log; import com.google.gson.Gson; import com.tamic.novate.util.Utils; import java.io.File; import java.io.InputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.Proxy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; import okhttp3.Cache; import okhttp3.CertificatePinner; import okhttp3.ConnectionPool; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.BaseUrl; import retrofit2.Call; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Novate adapts a Java interface to Retrofit call by using annotations on the declared methods to * define how requests are made. Create instances using {@linkplain Builder * the builder} and pass your interface to {@link #} to generate an implementation. * <p/> * For example, * <pre>{@code * Novate novate = new Novate.Builder() * .baseUrl("http://api.example.com") * .addConverterFactory(GsonConverterFactory.create()) * .build(); * <p/> * MyApi api = Novate.create(MyApi.class); * Response<User> user = api.getUser().execute(); * }</pre> * * @author Tamic ([email protected]) */ public final class Novate { private static Map<String, String> headers; private static Map<String, String> parameters; private static Retrofit.Builder retrofitBuilder; private static Retrofit retrofit; private static OkHttpClient.Builder okhttpBuilder; public static BaseApiService apiManager; private static OkHttpClient okHttpClient; private static Context mContext; private final okhttp3.Call.Factory callFactory; private final String baseUrl; private final List<Converter.Factory> converterFactories; private final List<CallAdapter.Factory> adapterFactories; private final Executor callbackExecutor; private final boolean validateEagerly; private NovateSubscriber novateSubscriber; private Observable<ResponseBody> downObservable; private Map<String, Observable<ResponseBody>> downMaps = new HashMap<String, Observable<ResponseBody>>(){}; public static final String TAG = "Novate"; /** * Mandatory constructor for the Novate */ Novate(okhttp3.Call.Factory callFactory, String baseUrl, Map<String, String> headers, Map<String, String> parameters, BaseApiService apiManager, List<Converter.Factory> converterFactories, List<CallAdapter.Factory> adapterFactories, Executor callbackExecutor, boolean validateEagerly) { this.callFactory = callFactory; this.baseUrl = baseUrl; this.headers = headers; this.parameters = parameters; this.apiManager = apiManager; this.converterFactories = converterFactories; this.adapterFactories = adapterFactories; this.callbackExecutor = callbackExecutor; this.validateEagerly = validateEagerly; } /** * create ApiService */ public <T> T create(final Class<T> service) { return retrofit.create(service); } /** * @param subscriber */ public <T> T call(Observable<T> observable, Subscriber<T> subscriber) { observable.compose(schedulersTransformer) .subscribe(subscriber); return null; } /** * Retroift execute get * * return parsed data * * you don't need to parse ResponseBody * */ public <T> T executeGet(final String url, final Map<String, String> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null && MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d("dd", "-->:" + "Type:" + types[0]); apiManager.executeGet(url, maps) .compose(schedulersTransformer) .subscribe(new NovateSubscriber<T>(mContext, finalNeedType, callBack)); return null; } /** * MethodHandler */ private List<Type> MethodHandler(Type[] types) { Log.d(TAG, "types size: " + types.length); List<Type> needtypes = new ArrayList<>(); Type needParentType = null; for (Type paramType : types) { System.out.println(" " + paramType); // if Type is T if (paramType instanceof ParameterizedType) { Type[] parentypes = ((ParameterizedType) paramType).getActualTypeArguments(); Log.d(TAG, "TypeArgument: "); for (Type childtype : parentypes) { Log.d(TAG, "childtype:" + childtype); needtypes.add(childtype); //needParentType = childtype; if (childtype instanceof ParameterizedType) { Type[] childtypes = ((ParameterizedType) childtype).getActualTypeArguments(); for (Type type : childtypes) { needtypes.add(type); //needChildType = type; Log.d(TAG, "type:" + childtype); } } } } } return needtypes; } final Observable.Transformer schedulersTransformer = new Observable.Transformer() { @Override public Object call(Object observable) { return ((Observable) observable).subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }; /** * Retroift get * @param url * @param maps * @param subscriber * @param <T> * @return no parse data */ public <T> T get(String url, Map<String, String> maps, BaseSubscriber<ResponseBody> subscriber) { apiManager.executeGet(url, maps) .compose(schedulersTransformer) .subscribe(subscriber); return null; } /** * /** * Retroift executePost * * @return no parse data * * you must to be parse ResponseBody * * <p/> * For example, * <pre>{@code * Novate novate = new Novate.Builder() * .baseUrl("http://api.example.com") * .addConverterFactory(GsonConverterFactory.create()) * .build(); * * novate.post("url", parameters, new BaseSubscriber<ResponseBody>(context) { * @Override * public void onError(Throwable e) { * * } * * @Override * public void onNext(ResponseBody responseBody) { * * // todo you need to parse responseBody * * } * }); * <p/> * * }</pre> */ public void post(String url, Map<String, String> parameters, Subscriber<ResponseBody> subscriber) { apiManager.executePost(url, parameters) .compose(schedulersTransformer) .subscribe(subscriber); } /** * Retroift executePost * * @return parsed data * you don't need to parse ResponseBody * */ public <T> T executePost(final String url, final Map<String, String> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null && MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); apiManager.executePost(url, maps) .compose(schedulersTransformer) .subscribe(new NovateSubscriber<T>(mContext, finalNeedType, callBack)); return null; } /** * Execute http by Delete * @return parsed data * you don't need to parse ResponseBody * */ public <T> T executeDelete(final String url, final Map<String, String> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null && MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); apiManager.executeDelete(url, maps) .compose(schedulersTransformer) .subscribe(new NovateSubscriber<T>(mContext, finalNeedType, callBack)); return null; } /** * Execute Http by Put * @return parsed data * you don't need to parse ResponseBody * */ public <T> T executePut(final String url, final Map<String, String> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null && MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); apiManager.executePut(url, maps) .compose(schedulersTransformer) .subscribe(new NovateSubscriber<T>(mContext, finalNeedType, callBack)); return null; } /** * Test * @param url url * @param maps maps * @param subscriber subscriber * @param <T> T * @return */ public <T> T test(String url, Map<String, String> maps, Subscriber<ResponseBody> subscriber) { apiManager.getTest(url, maps) .compose(schedulersTransformer) .subscribe(subscriber); return null; } /** * upload * @param url * @param requestBody requestBody * @param subscriber subscriber * @param <T> T * @return */ public <T> T upload(String url, RequestBody requestBody, Subscriber<ResponseBody> subscriber) { apiManager.upLoadFile(url, requestBody) .compose(schedulersTransformer) .subscribe(subscriber); return null; } /** * download * @param url * @param callBack */ public void download(String url, DownLoadCallBack callBack) { if (downMaps.get(url) == null) { downObservable = apiManager.downloadFile(url); downMaps.put(url, downObservable); } else { downObservable = downMaps.get(url); } if (NovateDownLoadManager.isDownLoading) { downObservable.unsubscribeOn(Schedulers.io()); NovateDownLoadManager.isDownLoading = false; NovateDownLoadManager.isCancel = true; return; } NovateDownLoadManager.isDownLoading = true; downObservable.compose(schedulersTransformer) .subscribe(new DownSubscriber<ResponseBody>(callBack, mContext)); } /** * Mandatory Builder for the Builder */ public static final class Builder { private static final int DEFAULT_TIMEOUT = 5; private static final int DEFAULT_MAXIDLE_CONNECTIONS = 5; private static final long DEFAULT_KEEP_ALIVEDURATION = 8; private static final long caheMaxSize = 10 * 1024 * 1024; private okhttp3.Call.Factory callFactory; private String baseUrl; private Boolean isLog = false; private List<InputStream> certificateList; private HostnameVerifier hostnameVerifier; private CertificatePinner certificatePinner; private List<Converter.Factory> converterFactories = new ArrayList<>(); private List<CallAdapter.Factory> adapterFactories = new ArrayList<>(); private Executor callbackExecutor; private boolean validateEagerly; private Context context; private NovateCookieManger cookieManager; private Cache cache = null; private Proxy proxy; private File httpCacheDirectory; private SSLSocketFactory sslSocketFactory; private ConnectionPool connectionPool; private Converter.Factory converterFactory; private CallAdapter.Factory callAdapterFactory; public Builder(Context context) { // Add the base url first. This prevents overriding its behavior but also // ensures correct behavior when using novate that consume all types. okhttpBuilder = new OkHttpClient.Builder(); retrofitBuilder = new Retrofit.Builder(); this.context = context; } /** * The HTTP client used for requests. default OkHttpClient * <p/> * This is a convenience method for calling {@link #callFactory}. * <p/> * Note: This method <b>does not</b> make a defensive copy of {@code client}. Changes to its * settings will affect subsequent requests. Pass in a {@linkplain OkHttpClient#clone() cloned} * instance to prevent this if desired. */ @NonNull public Builder client(OkHttpClient client) { retrofitBuilder.client(Utils.checkNotNull(client, "client == null")); return this; } /** * Add ApiManager for serialization and deserialization of objects. *//* public Builder addApiManager(final Class<ApiManager> service) { apiManager = retrofit.create((Utils.checkNotNull(service, "apiManager == null"))); //return retrofit.create(service); return this; }*/ /** * Specify a custom call factory for creating {@link } instances. * <p/> * Note: Calling {@link #client} automatically sets this value. */ public Builder callFactory(okhttp3.Call.Factory factory) { this.callFactory = Utils.checkNotNull(factory, "factory == null"); return this; } /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to * milliseconds. */ public Builder connectTimeout(int timeout) { return connectTimeout(timeout, TimeUnit.SECONDS); } /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to * milliseconds. */ public Builder writeTimeout(int timeout) { return writeTimeout(timeout, TimeUnit.SECONDS); } public Builder addLog(boolean isLog) { this.isLog = isLog; return this; } public Builder proxy(Proxy proxy) { okhttpBuilder.proxy(Utils.checkNotNull(proxy, "proxy == null")); return this; } /** * Sets the default write timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link TimeUnit #MAX_VALUE} when converted to * milliseconds. */ public Builder writeTimeout(int timeout, TimeUnit unit) { if (timeout != -1) { okhttpBuilder.writeTimeout(timeout, unit); } else { okhttpBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); } return this; } /** * Sets the connection pool used to recycle HTTP and HTTPS connections. * * <p>If unset, a new connection pool will be used. */ public Builder connectionPool(ConnectionPool connectionPool) { if (connectionPool == null) throw new NullPointerException("connectionPool == null"); this.connectionPool = connectionPool; return this; } /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link TimeUnit #MAX_VALUE} when converted to * milliseconds. */ public Builder connectTimeout(int timeout, TimeUnit unit) { if (timeout != -1) { okhttpBuilder.connectTimeout(timeout, unit); } else { okhttpBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); } return this; } /** * Set an API base URL which can change over time. * * @see BaseUrl(HttpUrl) */ public Builder baseUrl(String baseUrl) { this.baseUrl = Utils.checkNotNull(baseUrl, "baseUrl == null"); return this; } /** * Add converter factory for serialization and deserialization of objects. */ public Builder addConverterFactory(Converter.Factory factory) { this.converterFactory = factory; return this; } /** * Add a call adapter factory for supporting service method return types other than {@link CallAdapter * }. */ public Builder addCallAdapterFactory(CallAdapter.Factory factory) { this.callAdapterFactory = factory; return this; } /** * Add Header for serialization and deserialization of objects. */ public Builder addHeader(Map<String, String> headers) { okhttpBuilder.addInterceptor(new BaseInterceptor((Utils.checkNotNull(headers, "header == null")))); return this; } /** * Add parameters for serialization and deserialization of objects. */ public Builder addParameters(Map<String, String> parameters) { okhttpBuilder.addInterceptor(new BaseInterceptor((Utils.checkNotNull(parameters, "parameters == null")))); return this; } /** * Returns a modifiable list of interceptors that observe a single network request and response. * These interceptors must call {@link Interceptor.Chain#proceed} exactly once: it is an error * for a network interceptor to short-circuit or repeat a network request. */ public Builder addInterceptor(Interceptor interceptor) { okhttpBuilder.addInterceptor(Utils.checkNotNull(interceptor, "interceptor == null")); return this; } /** * The executor on which {@link Call} methods are invoked when returning {@link Call} from * your service method. * <p/> * Note: {@code executor} is not used for {@linkplain #addCallAdapterFactory custom method * return types}. */ public Builder callbackExecutor(Executor executor) { this.callbackExecutor = Utils.checkNotNull(executor, "executor == null"); return this; } /** * When calling {@link #create} on the resulting {@link Retrofit} instance, eagerly validate * the configuration of all methods in the supplied interface. */ public Builder validateEagerly(boolean validateEagerly) { this.validateEagerly = validateEagerly; return this; } /** * Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to * outgoing HTTP requests. * <p/> * <p>If unset, {@linkplain NovateCookieManger#NO_COOKIES no cookies} will be accepted nor provided. */ public Builder cookieManager(NovateCookieManger cookie) { if (cookie == null) throw new NullPointerException("cookieManager == null"); this.cookieManager = cookie; return this; } /** * */ public Builder addSSLSocketFactory(SSLSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; return this; } public Builder addHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; return this; } public Builder addCertificatePinner(CertificatePinner certificatePinner) { this.certificatePinner = certificatePinner; return this; } /** * Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to * outgoing HTTP requests. * <p/> * <p>If unset, {@linkplain NovateCookieManger#NO_COOKIES no cookies} will be accepted nor provided. */ public Builder addSSL(String[] hosts, int[] certificates) { if (hosts == null) throw new NullPointerException("hosts == null"); if (certificates == null) throw new NullPointerException("ids == null"); addSSLSocketFactory(NovateHttpsFactroy.getSSLSocketFactory(context, certificates)); addHostnameVerifier(NovateHttpsFactroy.getHostnameVerifier(hosts)); return this; } public Builder addNetworkInterceptor(Interceptor interceptor) { okhttpBuilder.addNetworkInterceptor(interceptor); return this; } /** * setCache * @param cache cahe * @return Builder */ public Builder addCache(Cache cache) { int maxStale = 60 * 60 * 24 * 3; return addCacheAge(cache, maxStale); } /** * @return */ public Builder addCacheAge(Cache cache, final int cacheTime) { addCache(cache, String.format("max-age=%d", cacheTime)); return this; } /** * @param cache * @param cacheTime ms * @return */ public Builder addCacheStale(Cache cache, final int cacheTime) { addCache(cache, String.format("max-stale=%d", cacheTime)); return this; } /** * @param cache * @param cacheControlValue Cache-Control值 * @return */ public Builder addCache(Cache cache, final String cacheControlValue) { Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new CaheInterceptor(mContext, cacheControlValue); addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR); addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR); this.cache = cache; return this; } /** * Create the {@link Retrofit} instance using the configured values. * <p/> * Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link * OkHttpClient} will be created and used. */ public Novate build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } if (okhttpBuilder == null) { throw new IllegalStateException("okhttpBuilder required."); } if (retrofitBuilder == null) { throw new IllegalStateException("retrofitBuilder required."); } /** set Context. */ mContext = context; /** * Set a fixed API base URL. * * @see #baseUrl(HttpUrl) */ retrofitBuilder.baseUrl(baseUrl); /** Add converter factory for serialization and deserialization of objects. */ if (converterFactory == null) { converterFactory = GsonConverterFactory.create(); } ; retrofitBuilder.addConverterFactory(converterFactory); /** * Add a call adapter factory for supporting service method return types other than {@link * Call}. */ if (callAdapterFactory == null) { callAdapterFactory = RxJavaCallAdapterFactory.create(); } retrofitBuilder.addCallAdapterFactory(callAdapterFactory); if (isLog) { okhttpBuilder.addNetworkInterceptor( new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS)); } if(sslSocketFactory != null) { okhttpBuilder.sslSocketFactory(sslSocketFactory); } if (hostnameVerifier != null) { okhttpBuilder.hostnameVerifier(hostnameVerifier); } if ( httpCacheDirectory == null) { httpCacheDirectory = new File(mContext.getCacheDir(), "Novate_Http_cache"); } try { if (cache == null) { cache = new Cache(httpCacheDirectory, caheMaxSize); } } catch (Exception e) { Log.e("OKHttp", "Could not create http cache", e); } okhttpBuilder.cache(cache); addCache(cache); /** * Sets the connection pool used to recycle HTTP and HTTPS connections. * * <p>If unset, a new connection pool will be used. */ if (connectionPool == null) { connectionPool = new ConnectionPool(DEFAULT_MAXIDLE_CONNECTIONS, DEFAULT_KEEP_ALIVEDURATION, TimeUnit.SECONDS); } okhttpBuilder.connectionPool(connectionPool); /** * Sets the HTTP proxy that will be used by connections created by this client. This takes * precedence over {@link #proxySelector}, which is only honored when this proxy is null (which * it is by default). To disable proxy use completely, call {@code setProxy(Proxy.NO_PROXY)}. */ if (proxy == null) { okhttpBuilder.proxy(proxy); } /** * Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to * outgoing HTTP requests. * * <p>If unset, {@link Novate CookieManager#NO_COOKIES no cookies} will be accepted nor provided. */ if (cookieManager == null) { cookieManager = new NovateCookieManger(context); } okhttpBuilder.cookieJar(new NovateCookieManger(context)); /** *okhttp3.Call.Factory callFactory = this.callFactory; */ if (callFactory != null) { retrofitBuilder.callFactory(callFactory); } /** * create okHttpClient */ okHttpClient = okhttpBuilder.build(); /** * set Retrofit client */ retrofitBuilder.client(okHttpClient); /** * create Retrofit */ retrofit = retrofitBuilder.build(); /** *create BaseApiService; */ apiManager = retrofit.create(BaseApiService.class); return new Novate(callFactory, baseUrl, headers, parameters, apiManager, converterFactories, adapterFactories, callbackExecutor, validateEagerly); } } /** * NovateSubscriber * @param <T> */ class NovateSubscriber<T> extends BaseSubscriber<ResponseBody> { private ResponseCallBack<T> callBack; private Type finalNeedType; public NovateSubscriber(Context context, Type finalNeedType, ResponseCallBack<T> callBack) { super(context); this.callBack = callBack; this.finalNeedType = finalNeedType; } @Override public void onStart() { super.onStart(); // todo some common as show loadding and check netWork is NetworkAvailable if (callBack != null) { callBack.onStart(); } } @Override public void onCompleted() { // todo some common as dismiss loadding if (callBack != null) { callBack.onCompleted(); } } @Override public void onError(Throwable e) { Log.e("novate", "-->:" + e.getMessage()); if (callBack != null) { callBack.onError(e); } } @Override public void onNext(ResponseBody responseBody) { try { byte[] bytes = responseBody.bytes(); String jsStr = new String(bytes); Log.d("OkHttp", "ResponseBody:" + jsStr); if (callBack != null) { try { /** * if need parse baseRespone<T> use ParentType, if parse T use childType . defult parse baseRespone<T> * * callBack.onSuccee((T) JSON.parseArray(jsStr, (Class<Object>) finalNeedType)); * Type finalNeedType = needChildType; */ NovateResponse<T> baseResponse = new Gson().fromJson(jsStr, finalNeedType); if (baseResponse.isOk()) { callBack.onSuccee((T) new Gson().fromJson(jsStr, finalNeedType)); } } catch (Exception e) { e.printStackTrace(); if (callBack != null) { callBack.onError(e); } } } } catch (Exception e) { e.printStackTrace(); if (callBack != null) { callBack.onError(e); } } } } /** * ResponseCallBack <T> Support your custom data model * * */ public interface ResponseCallBack<T> { public void onStart(); public void onCompleted(); public abstract void onError(Throwable e); public abstract void onSuccee(T response); } }
novate/src/main/java/com/tamic/novate/Novate.java
package com.tamic.novate; import android.content.Context; import android.support.annotation.NonNull; import android.util.Log; import com.google.gson.Gson; import com.tamic.novate.util.Utils; import java.io.File; import java.io.InputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.Proxy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; import okhttp3.Cache; import okhttp3.CertificatePinner; import okhttp3.ConnectionPool; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.BaseUrl; import retrofit2.Call; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Novate adapts a Java interface to Retrofit call by using annotations on the declared methods to * define how requests are made. Create instances using {@linkplain Builder * the builder} and pass your interface to {@link #} to generate an implementation. * <p/> * For example, * <pre>{@code * Novate novate = new Novate.Builder() * .baseUrl("http://api.example.com") * .addConverterFactory(GsonConverterFactory.create()) * .build(); * <p/> * MyApi api = Novate.create(MyApi.class); * Response<User> user = api.getUser().execute(); * }</pre> * * @author Tamic ([email protected]) */ public final class Novate { private static Map<String, String> headers; private static Map<String, String> parameters; private static Retrofit.Builder retrofitBuilder; private static Retrofit retrofit; private static OkHttpClient.Builder okhttpBuilder; public static BaseApiService apiManager; private static OkHttpClient okHttpClient; private static Context mContext; private final okhttp3.Call.Factory callFactory; private final String baseUrl; private final List<Converter.Factory> converterFactories; private final List<CallAdapter.Factory> adapterFactories; private final Executor callbackExecutor; private final boolean validateEagerly; private NovateSubscriber novateSubscriber; private Observable<ResponseBody> downObservable; private Map<String, Observable<ResponseBody>> downMaps = new HashMap<String, Observable<ResponseBody>>(){}; public static final String TAG = "Novate"; /** * Mandatory constructor for the Novate */ Novate(okhttp3.Call.Factory callFactory, String baseUrl, Map<String, String> headers, Map<String, String> parameters, BaseApiService apiManager, List<Converter.Factory> converterFactories, List<CallAdapter.Factory> adapterFactories, Executor callbackExecutor, boolean validateEagerly) { this.callFactory = callFactory; this.baseUrl = baseUrl; this.headers = headers; this.parameters = parameters; this.apiManager = apiManager; this.converterFactories = converterFactories; this.adapterFactories = adapterFactories; this.callbackExecutor = callbackExecutor; this.validateEagerly = validateEagerly; } /** * create ApiService */ public <T> T create(final Class<T> service) { return retrofit.create(service); } /** * @param subscriber */ public <T> T call(Observable<T> observable, Subscriber<T> subscriber) { observable.compose(schedulersTransformer) .subscribe(subscriber); return null; } /** * Retroift execute get * * return parsed data * * you don't need to parse ResponseBody * */ public <T> T executeGet(final String url, final Map<String, String> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null && MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d("dd", "-->:" + "Type:" + types[0]); apiManager.executeGet(url, maps) .compose(schedulersTransformer) .subscribe(new NovateSubscriber<T>(mContext, finalNeedType, callBack)); return null; } /** * MethodHandler */ private List<Type> MethodHandler(Type[] types) { Log.d(TAG, "types size: " + types.length); List<Type> needtypes = new ArrayList<>(); Type needParentType = null; for (Type paramType : types) { System.out.println(" " + paramType); // if Type is T if (paramType instanceof ParameterizedType) { Type[] parentypes = ((ParameterizedType) paramType).getActualTypeArguments(); Log.d(TAG, "TypeArgument: "); for (Type childtype : parentypes) { Log.d(TAG, "childtype:" + childtype); needtypes.add(childtype); //needParentType = childtype; if (childtype instanceof ParameterizedType) { Type[] childtypes = ((ParameterizedType) childtype).getActualTypeArguments(); for (Type type : childtypes) { needtypes.add(type); //needChildType = type; Log.d(TAG, "type:" + childtype); } } } } } return needtypes; } final Observable.Transformer schedulersTransformer = new Observable.Transformer() { @Override public Object call(Object observable) { return ((Observable) observable).subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }; /** * Retroift get * @param url * @param maps * @param subscriber * @param <T> * @return no parse data */ public <T> T get(String url, Map<String, String> maps, BaseSubscriber<ResponseBody> subscriber) { apiManager.executeGet(url, maps) .compose(schedulersTransformer) .subscribe(subscriber); return null; } /** * /** * Retroift executePost * * @return no parse data * * you must to be parse ResponseBody * * <p/> * For example, * <pre>{@code * Novate novate = new Novate.Builder() * .baseUrl("http://api.example.com") * .addConverterFactory(GsonConverterFactory.create()) * .build(); * * novate.post("url", parameters, new BaseSubscriber<ResponseBody>(context) { * @Override * public void onError(Throwable e) { * * } * * @Override * public void onNext(ResponseBody responseBody) { * * // todo you need to parse responseBody * * } * }); * <p/> * * }</pre> */ public void post(String url, Map<String, String> parameters, Subscriber<ResponseBody> subscriber) { apiManager.executePost(url, parameters) .compose(schedulersTransformer) .subscribe(subscriber); } /** * Retroift executePost * * @return parsed data * you don't need to parse ResponseBody * */ public <T> T executePost(final String url, final Map<String, String> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null && MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); apiManager.executePost(url, maps) .compose(schedulersTransformer) .subscribe(new NovateSubscriber<T>(mContext, finalNeedType, callBack)); return null; } /** * Execute http by Delete * @return parsed data * you don't need to parse ResponseBody * */ public <T> T executeDelete(final String url, final Map<String, String> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null && MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); apiManager.executeDelete(url, maps) .compose(schedulersTransformer) .subscribe(new NovateSubscriber<T>(mContext, finalNeedType, callBack)); return null; } /** * Execute Http by Put * @return parsed data * you don't need to parse ResponseBody * */ public <T> T executePut(final String url, final Map<String, String> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null && MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); apiManager.executePut(url, maps) .compose(schedulersTransformer) .subscribe(new NovateSubscriber<T>(mContext, finalNeedType, callBack)); return null; } /** * Test * @param url url * @param maps maps * @param subscriber subscriber * @param <T> T * @return */ public <T> T test(String url, Map<String, String> maps, Subscriber<ResponseBody> subscriber) { apiManager.getTest(url, maps) .compose(schedulersTransformer) .subscribe(subscriber); return null; } /** * upload * @param url * @param requestBody requestBody * @param subscriber subscriber * @param <T> T * @return */ public <T> T upload(String url, RequestBody requestBody, Subscriber<ResponseBody> subscriber) { apiManager.upLoadFile(url, requestBody) .compose(schedulersTransformer) .subscribe(subscriber); return null; } /** * download * @param url * @param callBack */ public void download(String url, DownLoadCallBack callBack) { if (downMaps.get(url) == null) { downObservable = apiManager.downloadFile(url); downMaps.put(url, downObservable); } else { downObservable = downMaps.get(url); } if (NovateDownLoadManager.isDownLoading) { downObservable.unsubscribeOn(Schedulers.io()); NovateDownLoadManager.isDownLoading = false; NovateDownLoadManager.isCancel = true; return; } NovateDownLoadManager.isDownLoading = true; downObservable.compose(schedulersTransformer) .subscribe(new DownSubscriber<ResponseBody>(callBack, mContext)); } /** * Mandatory Builder for the Builder */ public static final class Builder { private static final int DEFAULT_TIMEOUT = 5; private static final int DEFAULT_MAXIDLE_CONNECTIONS = 5; private static final long DEFAULT_KEEP_ALIVEDURATION = 8; private static final long caheMaxSize = 10 * 1024 * 1024; private okhttp3.Call.Factory callFactory; private String baseUrl; private Boolean isLog = false; private List<InputStream> certificateList; private HostnameVerifier hostnameVerifier; private CertificatePinner certificatePinner; private List<Converter.Factory> converterFactories = new ArrayList<>(); private List<CallAdapter.Factory> adapterFactories = new ArrayList<>(); private Executor callbackExecutor; private boolean validateEagerly; private Context context; private NovateCookieManger cookieManager; private Cache cache = null; private Proxy proxy; private File httpCacheDirectory; private SSLSocketFactory sslSocketFactory; private ConnectionPool connectionPool; private Converter.Factory converterFactory; private CallAdapter.Factory callAdapterFactory; public Builder(Context context) { // Add the base url first. This prevents overriding its behavior but also // ensures correct behavior when using novate that consume all types. okhttpBuilder = new OkHttpClient.Builder(); retrofitBuilder = new Retrofit.Builder(); this.context = context; } /** * The HTTP client used for requests. default OkHttpClient * <p/> * This is a convenience method for calling {@link #callFactory}. * <p/> * Note: This method <b>does not</b> make a defensive copy of {@code client}. Changes to its * settings will affect subsequent requests. Pass in a {@linkplain OkHttpClient#clone() cloned} * instance to prevent this if desired. */ @NonNull public Builder client(OkHttpClient client) { retrofitBuilder.client(Utils.checkNotNull(client, "client == null")); return this; } /** * Add ApiManager for serialization and deserialization of objects. *//* public Builder addApiManager(final Class<ApiManager> service) { apiManager = retrofit.create((Utils.checkNotNull(service, "apiManager == null"))); //return retrofit.create(service); return this; }*/ /** * Specify a custom call factory for creating {@link } instances. * <p/> * Note: Calling {@link #client} automatically sets this value. */ public Builder callFactory(okhttp3.Call.Factory factory) { this.callFactory = Utils.checkNotNull(factory, "factory == null"); return this; } /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to * milliseconds. */ public Builder connectTimeout(int timeout) { return connectTimeout(timeout, TimeUnit.SECONDS); } /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to * milliseconds. */ public Builder writeTimeout(int timeout) { return writeTimeout(timeout, TimeUnit.SECONDS); } public Builder addLog(boolean isLog) { this.isLog = isLog; return this; } public Builder proxy(Proxy proxy) { okhttpBuilder.proxy(Utils.checkNotNull(proxy, "proxy == null")); return this; } /** * Sets the default write timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link TimeUnit #MAX_VALUE} when converted to * milliseconds. */ public Builder writeTimeout(int timeout, TimeUnit unit) { if (timeout != -1) { okhttpBuilder.writeTimeout(timeout, unit); } else { okhttpBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); } return this; } /** * Sets the connection pool used to recycle HTTP and HTTPS connections. * * <p>If unset, a new connection pool will be used. */ public Builder connectionPool(ConnectionPool connectionPool) { if (connectionPool == null) throw new NullPointerException("connectionPool == null"); this.connectionPool = connectionPool; return this; } /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link TimeUnit #MAX_VALUE} when converted to * milliseconds. */ public Builder connectTimeout(int timeout, TimeUnit unit) { if (timeout != -1) { okhttpBuilder.connectTimeout(timeout, unit); } else { okhttpBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); } return this; } /** * Set an API base URL which can change over time. * * @see BaseUrl(HttpUrl) */ public Builder baseUrl(String baseUrl) { this.baseUrl = Utils.checkNotNull(baseUrl, "baseUrl == null"); return this; } /** * Add converter factory for serialization and deserialization of objects. */ public Builder addConverterFactory(Converter.Factory factory) { this.converterFactory = factory; return this; } /** * Add a call adapter factory for supporting service method return types other than {@link CallAdapter * }. */ public Builder addCallAdapterFactory(CallAdapter.Factory factory) { this.callAdapterFactory = factory; return this; } /** * Add Header for serialization and deserialization of objects. */ public Builder addHeader(Map<String, String> headers) { okhttpBuilder.addInterceptor(new BaseInterceptor((Utils.checkNotNull(headers, "header == null")))); return this; } /** * Add parameters for serialization and deserialization of objects. */ public Builder addParameters(Map<String, String> parameters) { okhttpBuilder.addInterceptor(new BaseInterceptor((Utils.checkNotNull(parameters, "parameters == null")))); return this; } /** * Returns a modifiable list of interceptors that observe a single network request and response. * These interceptors must call {@link Interceptor.Chain#proceed} exactly once: it is an error * for a network interceptor to short-circuit or repeat a network request. */ public Builder addInterceptor(Interceptor interceptor) { okhttpBuilder.addInterceptor(Utils.checkNotNull(interceptor, "interceptor == null")); return this; } /** * The executor on which {@link Call} methods are invoked when returning {@link Call} from * your service method. * <p/> * Note: {@code executor} is not used for {@linkplain #addCallAdapterFactory custom method * return types}. */ public Builder callbackExecutor(Executor executor) { this.callbackExecutor = Utils.checkNotNull(executor, "executor == null"); return this; } /** * When calling {@link #create} on the resulting {@link Retrofit} instance, eagerly validate * the configuration of all methods in the supplied interface. */ public Builder validateEagerly(boolean validateEagerly) { this.validateEagerly = validateEagerly; return this; } /** * Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to * outgoing HTTP requests. * <p/> * <p>If unset, {@linkplain NovateCookieManger#NO_COOKIES no cookies} will be accepted nor provided. */ public Builder cookieManager(NovateCookieManger cookie) { if (cookie == null) throw new NullPointerException("cookieManager == null"); this.cookieManager = cookie; return this; } /** * */ public Builder addSSLSocketFactory(SSLSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; return this; } public Builder addHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; return this; } public Builder addCertificatePinner(CertificatePinner certificatePinner) { this.certificatePinner = certificatePinner; return this; } /** * Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to * outgoing HTTP requests. * <p/> * <p>If unset, {@linkplain NovateCookieManger#NO_COOKIES no cookies} will be accepted nor provided. */ public Builder addSSL(String[] hosts, int[] certificates) { if (hosts == null) throw new NullPointerException("hosts == null"); if (certificates == null) throw new NullPointerException("ids == null"); addSSLSocketFactory(NovateHttpsFactroy.getSSLSocketFactory(context, certificates)); addHostnameVerifier(NovateHttpsFactroy.getHostnameVerifier(hosts)); return this; } public Builder addNetworkInterceptor(Interceptor interceptor) { okhttpBuilder.addNetworkInterceptor(interceptor); return this; } /** * setCache * @param cache cahe * @return Builder */ public Builder addCache(Cache cache) { int maxStale = 60 * 60 * 24 * 3; return addCacheAge(cache, maxStale); } /** * @return */ public Builder addCacheAge(Cache cache, final int cacheTime) { addCache(cache, String.format("max-age=%d", cacheTime)); return this; } /** * @param cache * @param cacheTime ms * @return */ public Builder addCacheStale(Cache cache, final int cacheTime) { addCache(cache, String.format("max-stale=%d", cacheTime)); return this; } /** * @param cache * @param cacheControlValue Cache-Control值 * @return */ public Builder addCache(Cache cache, final String cacheControlValue) { Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new CaheInterceptor(mContext, cacheControlValue); addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR); addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR); this.cache = cache; return this; } /** * Create the {@link Retrofit} instance using the configured values. * <p/> * Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link * OkHttpClient} will be created and used. */ public Novate build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } if (okhttpBuilder == null) { throw new IllegalStateException("okhttpBuilder required."); } if (retrofitBuilder == null) { throw new IllegalStateException("retrofitBuilder required."); } /** set Context. */ mContext = context; /** * Set a fixed API base URL. * * @see #baseUrl(HttpUrl) */ retrofitBuilder.baseUrl(baseUrl); /** Add converter factory for serialization and deserialization of objects. */ if (converterFactory == null) { converterFactory = GsonConverterFactory.create(); } ; retrofitBuilder.addConverterFactory(converterFactory); /** * Add a call adapter factory for supporting service method return types other than {@link * Call}. */ if (callAdapterFactory == null) { callAdapterFactory = RxJavaCallAdapterFactory.create(); } retrofitBuilder.addCallAdapterFactory(callAdapterFactory); if (isLog) { okhttpBuilder.addNetworkInterceptor( new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS)); } if(sslSocketFactory != null) { okhttpBuilder.sslSocketFactory(sslSocketFactory); } if (hostnameVerifier != null) { okhttpBuilder.hostnameVerifier(hostnameVerifier); } if ( httpCacheDirectory == null) { httpCacheDirectory = new File(mContext.getCacheDir(), "Novate_Http_cache"); } try { if (cache == null) { cache = new Cache(httpCacheDirectory, caheMaxSize); } } catch (Exception e) { Log.e("OKHttp", "Could not create http cache", e); } okhttpBuilder.cache(cache); addCache(cache); /** * Sets the connection pool used to recycle HTTP and HTTPS connections. * * <p>If unset, a new connection pool will be used. */ if (connectionPool == null) { connectionPool = new ConnectionPool(DEFAULT_MAXIDLE_CONNECTIONS, DEFAULT_KEEP_ALIVEDURATION, TimeUnit.SECONDS); } okhttpBuilder.connectionPool(connectionPool); /** * Sets the HTTP proxy that will be used by connections created by this client. This takes * precedence over {@link #proxySelector}, which is only honored when this proxy is null (which * it is by default). To disable proxy use completely, call {@code setProxy(Proxy.NO_PROXY)}. */ if (proxy == null) { okhttpBuilder.proxy(proxy); } /** * Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to * outgoing HTTP requests. * * <p>If unset, {@link Novate CookieManager#NO_COOKIES no cookies} will be accepted nor provided. */ if (cookieManager == null) { cookieManager = new NovateCookieManger(context); } okhttpBuilder.cookieJar(new NovateCookieManger(context)); /** *okhttp3.Call.Factory callFactory = this.callFactory; */ if (callFactory != null) { retrofitBuilder.callFactory(callFactory); } /** * create okHttpClient */ okHttpClient = okhttpBuilder.build(); /** * set Retrofit client */ retrofitBuilder.client(okHttpClient); /** * create Retrofit */ retrofit = retrofitBuilder.build(); /** *create BaseApiService; */ apiManager = retrofit.create(BaseApiService.class); return new Novate(callFactory, baseUrl, headers, parameters, apiManager, converterFactories, adapterFactories, callbackExecutor, validateEagerly); } } /** * NovateSubscriber * @param <T> */ class NovateSubscriber<T> extends BaseSubscriber<ResponseBody> { private ResponseCallBack<T> callBack; private Type finalNeedType; public NovateSubscriber(Context context, Type finalNeedType, ResponseCallBack<T> callBack) { super(context); this.callBack = callBack; this.finalNeedType = finalNeedType; } @Override public void onError(Throwable e) { Log.e("novate", "-->:" + e.getMessage()); if (callBack != null) { callBack.onError(e); } } @Override public void onNext(ResponseBody responseBody) { try { byte[] bytes = responseBody.bytes(); String jsStr = new String(bytes); Log.d("OkHttp", "ResponseBody:" + jsStr); if (callBack != null) { try { /** * if need parse baseRespone<T> use ParentType, if parse T use childType . defult parse baseRespone<T> * * callBack.onSuccee((T) JSON.parseArray(jsStr, (Class<Object>) finalNeedType)); * Type finalNeedType = needChildType; */ NovateResponse<T> baseResponse = new Gson().fromJson(jsStr, finalNeedType); if (baseResponse.isOk()) { callBack.onSuccee((T) new Gson().fromJson(jsStr, finalNeedType)); } } catch (Exception e) { e.printStackTrace(); if (callBack != null) { callBack.onError(e); } } } } catch (Exception e) { e.printStackTrace(); if (callBack != null) { callBack.onError(e); } } } } /** * ResponseCallBack <T> Support your custom data model * * */ public interface ResponseCallBack<T> { public void onStart(); public void onCompleted(); public abstract void onError(Throwable e); public abstract void onSuccee(T response); } }
增加开始和完成被遗漏的回调
novate/src/main/java/com/tamic/novate/Novate.java
增加开始和完成被遗漏的回调
<ide><path>ovate/src/main/java/com/tamic/novate/Novate.java <ide> } <ide> <ide> @Override <add> public void onStart() { <add> super.onStart(); <add> // todo some common as show loadding and check netWork is NetworkAvailable <add> if (callBack != null) { <add> callBack.onStart(); <add> } <add> <add> } <add> <add> @Override <add> public void onCompleted() { <add> // todo some common as dismiss loadding <add> if (callBack != null) { <add> callBack.onCompleted(); <add> } <add> } <add> <add> @Override <ide> public void onError(Throwable e) { <ide> Log.e("novate", "-->:" + e.getMessage()); <ide> if (callBack != null) {