repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
tombujok/hazelcast
hazelcast/src/main/java/com/hazelcast/config/CollectionConfig.java
9298
/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.config; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.hazelcast.internal.serialization.impl.SerializationUtil.readNullableList; import static com.hazelcast.internal.serialization.impl.SerializationUtil.writeNullableList; import static com.hazelcast.util.Preconditions.checkAsyncBackupCount; import static com.hazelcast.util.Preconditions.checkBackupCount; /** * Provides configuration service for Collection. * * @param <T> Type of Collection such as List, Set */ public abstract class CollectionConfig<T extends CollectionConfig> implements IdentifiedDataSerializable { /** * Default maximum size for the Configuration. */ public static final int DEFAULT_MAX_SIZE = 0; /** * The default number of synchronous backups */ public static final int DEFAULT_SYNC_BACKUP_COUNT = 1; /** * The default number of asynchronous backups */ public static final int DEFAULT_ASYNC_BACKUP_COUNT = 0; private String name; private List<ItemListenerConfig> listenerConfigs; private int backupCount = DEFAULT_SYNC_BACKUP_COUNT; private int asyncBackupCount = DEFAULT_ASYNC_BACKUP_COUNT; private int maxSize = DEFAULT_MAX_SIZE; private boolean statisticsEnabled = true; protected CollectionConfig() { } protected CollectionConfig(CollectionConfig config) { this.name = config.name; this.listenerConfigs = new ArrayList<ItemListenerConfig>(config.getItemListenerConfigs()); this.backupCount = config.backupCount; this.asyncBackupCount = config.asyncBackupCount; this.maxSize = config.maxSize; this.statisticsEnabled = config.statisticsEnabled; } public abstract T getAsReadOnly(); /** * Gets the name of this collection. * * @return the name of this collection */ public String getName() { return name; } /** * Sets the name of this collection. * * @param name the name of this collection * @return the updated collection configuration */ public T setName(String name) { this.name = name; return (T) this; } /** * Gets the list of ItemListenerConfigs. * * @return the list of ItemListenerConfigs */ public List<ItemListenerConfig> getItemListenerConfigs() { if (listenerConfigs == null) { listenerConfigs = new ArrayList<ItemListenerConfig>(); } return listenerConfigs; } /** * Sets the list of ItemListenerConfigs. * * @param listenerConfigs the list of ItemListenerConfigs to set * @return this collection configuration */ public T setItemListenerConfigs(List<ItemListenerConfig> listenerConfigs) { this.listenerConfigs = listenerConfigs; return (T) this; } /** * Gets the total number of synchronous and asynchronous backups for this collection. * * @return the total number of synchronous and asynchronous backups for this collection */ public int getTotalBackupCount() { return backupCount + asyncBackupCount; } /** * Gets the number of synchronous backups for this collection. * * @return the number of synchronous backups for this collection */ public int getBackupCount() { return backupCount; } /** * Sets the number of synchronous backups for this collection. * * @param backupCount the number of synchronous backups to set for this collection * @return the current CollectionConfig * @throws IllegalArgumentException if backupCount smaller than 0, * or larger than the maximum number of backup * or the sum of the backups and async backups is larger than the maximum number of backups * @see #setAsyncBackupCount(int) */ public T setBackupCount(int backupCount) { this.backupCount = checkBackupCount(backupCount, asyncBackupCount); return (T) this; } /** * Gets the number of asynchronous backups. * * @return the number of asynchronous backups */ public int getAsyncBackupCount() { return asyncBackupCount; } /** * Sets the number of asynchronous backups. * * @param asyncBackupCount the number of asynchronous synchronous backups to set * @return the updated CollectionConfig * @throws IllegalArgumentException if asyncBackupCount is smaller than 0, * or larger than the maximum number of backups, * or the sum of the backups and async backups is larger than the maximum number of backups. * @see #setBackupCount(int) * @see #getAsyncBackupCount() */ public T setAsyncBackupCount(int asyncBackupCount) { this.asyncBackupCount = checkAsyncBackupCount(asyncBackupCount, asyncBackupCount); return (T) this; } /** * Gets the maximum size for the Configuration. * * @return the maximum size for the Configuration */ public int getMaxSize() { return maxSize == 0 ? Integer.MAX_VALUE : maxSize; } /** * Sets the maximum size for the collection. * * @return the current CollectionConfig */ public T setMaxSize(int maxSize) { this.maxSize = maxSize; return (T) this; } /** * Checks if collection statistics are enabled. * * @return {@code true} if collection statistics are enabled, {@code false} otherwise */ public boolean isStatisticsEnabled() { return statisticsEnabled; } /** * Sets collection statistics to enabled or disabled. * * @param statisticsEnabled {@code true} to enable collection statistics, {@code false} to disable * @return the current collection config instance */ public T setStatisticsEnabled(boolean statisticsEnabled) { this.statisticsEnabled = statisticsEnabled; return (T) this; } /** * Adds an item listener to this collection (listens for when items are added or removed). * * @param itemListenerConfig the item listener to add to this collection */ public void addItemListenerConfig(ItemListenerConfig itemListenerConfig) { getItemListenerConfigs().add(itemListenerConfig); } @Override public int getFactoryId() { return ConfigDataSerializerHook.F_ID; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); writeNullableList(listenerConfigs, out); out.writeInt(backupCount); out.writeInt(asyncBackupCount); out.writeInt(maxSize); out.writeBoolean(statisticsEnabled); } @Override public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); listenerConfigs = readNullableList(in); backupCount = in.readInt(); asyncBackupCount = in.readInt(); maxSize = in.readInt(); statisticsEnabled = in.readBoolean(); } @Override @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"}) public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CollectionConfig<?> that = (CollectionConfig<?>) o; if (backupCount != that.backupCount) { return false; } if (asyncBackupCount != that.asyncBackupCount) { return false; } if (getMaxSize() != that.getMaxSize()) { return false; } if (statisticsEnabled != that.statisticsEnabled) { return false; } if (name != null ? !name.equals(that.name) : that.name != null) { return false; } return getItemListenerConfigs().equals(that.getItemListenerConfigs()); } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + getItemListenerConfigs().hashCode(); result = 31 * result + backupCount; result = 31 * result + asyncBackupCount; result = 31 * result + getMaxSize(); result = 31 * result + (statisticsEnabled ? 1 : 0); return result; } }
apache-2.0
ernestp/consulo
platform/remote-servers-impl/src/com/intellij/remoteServer/impl/configuration/deploySource/ArtifactDeploymentSourceType.java
2832
/* * Copyright 2000-2013 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.remoteServer.impl.configuration.deploySource; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.project.Project; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.artifacts.ArtifactPointerUtil; import com.intellij.packaging.impl.run.BuildArtifactsBeforeRunTaskProvider; import com.intellij.remoteServer.configuration.deployment.ArtifactDeploymentSource; import com.intellij.remoteServer.configuration.deployment.DeploymentSourceType; import com.intellij.remoteServer.impl.configuration.deploySource.impl.ArtifactDeploymentSourceImpl; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import javax.swing.*; /** * @author nik */ public class ArtifactDeploymentSourceType extends DeploymentSourceType<ArtifactDeploymentSource> { private static final String NAME_ATTRIBUTE = "name"; public ArtifactDeploymentSourceType() { super("artifact"); } @NotNull @Override public ArtifactDeploymentSource load(@NotNull Element tag, @NotNull Project project) { return new ArtifactDeploymentSourceImpl(ArtifactPointerUtil.getPointerManager(project).create(tag.getAttributeValue(NAME_ATTRIBUTE))); } @Override public void save(@NotNull ArtifactDeploymentSource source, @NotNull Element tag) { tag.setAttribute(NAME_ATTRIBUTE, source.getArtifactPointer().getName()); } @Override public void setBuildBeforeRunTask(@NotNull RunConfiguration configuration, @NotNull ArtifactDeploymentSource source) { Artifact artifact = source.getArtifact(); if (artifact != null) { BuildArtifactsBeforeRunTaskProvider.setBuildArtifactBeforeRun(configuration.getProject(), configuration, artifact); } } @Override public void updateBuildBeforeRunOption(@NotNull JComponent runConfigurationEditorComponent, @NotNull Project project, @NotNull ArtifactDeploymentSource source, boolean select) { Artifact artifact = source.getArtifact(); if (artifact != null) { BuildArtifactsBeforeRunTaskProvider.setBuildArtifactBeforeRunOption(runConfigurationEditorComponent, project, artifact, select); } } }
apache-2.0
openfurther/further-open-core
core/core-api/src/main/java/edu/utah/further/core/api/math/SimpleInterval.java
6621
/** * Copyright (C) [2013] [The FURTHeR 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 edu.utah.further.core.api.math; import static edu.utah.further.core.api.message.Messages.illegalValueMessage; import org.apache.commons.lang.builder.HashCodeBuilder; import edu.utah.further.core.api.context.Api; import edu.utah.further.core.api.exception.BusinessRuleException; /** * An immutable interval <code>[a,b]</code>, where a and b are integers. * <p> * -----------------------------------------------------------------------------------<br> * (c) 2008-2013 FURTHeR Project, AVP Health Sciences IT Office, University of Utah<br> * Contact: {@code <further@utah.edu>}<br> * Biomedical Informatics, 26 South 2000 East<br> * Room 5775 HSEB, Salt Lake City, UT 84112<br> * Day Phone: 1-801-581-4080<br> * ----------------------------------------------------------------------------------- * * @author Oren E. Livne {@code <oren.livne@utah.edu>} * @version Mar 23, 2009 */ @Api public final class SimpleInterval<D extends Comparable<? super D>> implements Interval<D, SimpleInterval<D>> { // ========================= CONSTANTS ================================= // ========================= FIELDS ==================================== /** * Lower bound of the interval. */ protected final D low; /** * Upper bound of the interval. */ protected final D high; // ========================= CONSTRUCTORS ============================== /** * Construct an interval from bounds. * * @param low * Lower bound of the interval * @param high * Upper bound of the interval */ public SimpleInterval(final D low, final D high) { if (low.compareTo(high) <= 0) { this.low = low; this.high = high; } else { throw new BusinessRuleException(illegalValueMessage("interval")); } } // ========================= IMPLEMENTATION: Object ==================== /** * Print an interval. */ @Override public String toString() { return "[" + low + "," + high + "]"; } /** * Must be overridden when <code>equals()</code> is. * * @see java.lang.Object#hashCode() */ @Override public final int hashCode() { return new HashCodeBuilder(17, 37).append(low).append(high).toHashCode(); } // ========================= IMPLEMENTATION: PubliclyCloneable ========= /** * Return a deep copy of this object. Must be implemented for example for this object * to serve as a target of an assembly. * <p> * WARNING: the parameter class E must be immutable for this class to properly be * cloned (and serve as part of a parser's target). * * @return a deep copy of this object * @see edu.utah.further.core.api.lang.PubliclyCloneable#copy() */ @Override public SimpleInterval<D> copy() { return new SimpleInterval<>(low, high); } // ========================= IMPLEMENTATION: Comparable ================ /** * Result of comparing two intervals [a,b], [c,d]. They are equal if and only if a=c * and b=d. [a,b] is less than [c,d] if a &lt; c or if a = c and b &lt; d. Otherwise, * [a,b] is greater than [c,d] (lexicographic ordering). * * @param obj * the other <code>Interval</code> * @return the result of comparison */ @Override public int compareTo(final SimpleInterval<D> other) { return (low.equals(other.getLow()) && high.equals(other.getHigh())) ? 0 : (((low .compareTo(other.getLow()) < 0) || (low.equals(other.getLow()) && high .compareTo(other.getHigh()) < 0))) ? -1 : 1; } /** * Result of equality of two intervals. They are equal if and only if their * <code>low,high</code> fields are equal up to a relative tolerance of 1e-16. * * @param o * The other <code>Interval</code> object. * @return boolean The result of equality. */ @Override public boolean equals(final Object obj) { // Standard checks to ensure the adherence to the general contract of // the equals() method if (this == obj) { return true; } if ((obj == null) || (obj.getClass() != this.getClass())) { return false; } // Cast to friendlier version final SimpleInterval<?> other = (SimpleInterval<?>) obj; // Do not use compareTo() == 0 for a generic type because of unchecked // warning return low.equals(other.getLow()) && high.equals(other.getHigh()); } // // ========================= IMPLEMENTATION: TolerantlyComparable ====== // // /** // * Result of equality of two interval. They are equal if and only if their // * <code>low,high</code> fields are equal up to a relative tolerance of 1e-16, // * regardless of <code>tol</code>. This is an implementation of the // * <code>TolerantlyComparable</code> interface. // * // * @param obj // * The other <code>Interval</code> object. // * @param tol // * tolerance of equality; ignored // * @return the result of equality // */ // public int tolerantlyEquals(final SimpleInterval<D> obj, final double tol) // { // return (this.equals(obj) ? TolerantlyComparable.EQUAL // : TolerantlyComparable.NOT_EQUAL); // } // ========================= PUBLIC METHODS ============================ /** * Does this interval a intersect another interval * * @param b * another interval * @return true iff this intersects b */ @Override public boolean intersects(final SimpleInterval<D> b) { if (((b.getLow().compareTo(high) <= 0 && b.getLow().compareTo(low) >= 0)) || ((low.compareTo(b.getHigh()) <= 0 && low.compareTo(b.getLow()) >= 0))) { return true; } return false; } /** * Does this interval a intersect another interval * * @param b * an element * @return true iff this intersects b */ @Override public boolean contains(final D b) { return (low.compareTo(b) <= 0) && (high.compareTo(b) >= 0); } // ========================= GETTERS & SETTERS ========================= /** * @return Returns the high. */ @Override public D getHigh() { return high; } /** * @return Returns the low. */ @Override public D getLow() { return low; } }
apache-2.0
open-adk/OpenADK-java
adk-library/src/main/java/openadk/library/impl/LifecycleException.java
384
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // package openadk.library.impl; /** * Thrown to signal an object has not been initialized or started, or that it * has been closed or shut down */ public class LifecycleException extends RuntimeException { public LifecycleException( String msg ) { super( msg ); } }
apache-2.0
open-telemetry/opentelemetry-java
sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableSpanExporterProvider.java
1405
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.sdk.autoconfigure; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.SpanExporter; import java.util.Collection; public class TestConfigurableSpanExporterProvider implements ConfigurableSpanExporterProvider { @Override public SpanExporter createExporter(ConfigProperties config) { return new TestSpanExporter(config); } @Override public String getName() { return "testExporter"; } public static class TestSpanExporter implements SpanExporter { private final ConfigProperties config; public TestSpanExporter(ConfigProperties config) { this.config = config; } @Override public CompletableResultCode export(Collection<SpanData> spans) { return CompletableResultCode.ofSuccess(); } @Override public CompletableResultCode flush() { return CompletableResultCode.ofSuccess(); } @Override public CompletableResultCode shutdown() { return CompletableResultCode.ofSuccess(); } public ConfigProperties getConfig() { return config; } } }
apache-2.0
nagyistoce/camunda-engine-dmn
scriptengine-juel/src/test/java/org/camunda/bpm/dmn/juel/TestJuelScriptEngine.java
2552
/* 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.camunda.bpm.dmn.juel; import static org.assertj.core.api.Assertions.assertThat; import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.junit.BeforeClass; import org.junit.Test; public class TestJuelScriptEngine { protected static ScriptEngineManager scriptEngineManager; @BeforeClass public static void createScriptEngineManager() { scriptEngineManager = new ScriptEngineManager(); } @Test public void shouldFindScriptEngineByName() { ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("juel"); assertScriptEngine(scriptEngine); scriptEngine = scriptEngineManager.getEngineByName("Juel"); assertScriptEngine(scriptEngine); scriptEngine = scriptEngineManager.getEngineByName("JUEL"); assertScriptEngine(scriptEngine); } @Test public void shouldFindScriptEngineByExtension() { ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension("juel"); assertScriptEngine(scriptEngine); } @Test public void shouldEvaluateConstant() throws ScriptException { ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("juel"); String test = (String) scriptEngine.eval("${'test'}"); assertThat(test).isEqualTo(test); } @Test public void shouldEvaluateExpression() throws ScriptException { ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("juel"); Bindings bindings = scriptEngine.createBindings(); bindings.put("test", "ok"); Boolean result = (Boolean) scriptEngine.eval("${test == 'ok'}", bindings); assertThat(result).isTrue(); bindings.put("test", "notok"); result = (Boolean) scriptEngine.eval("${test == 'ok'}", bindings); assertThat(result).isFalse(); } protected void assertScriptEngine(ScriptEngine scriptEngine) { assertThat(scriptEngine) .isNotNull() .isInstanceOf(JuelScriptEngine.class); } }
apache-2.0
Tankernn/TankernnGameServer
src/main/java/eu/tankernn/game/server/entities/player/ServerPlayer.java
692
package eu.tankernn.game.server.entities.player; import eu.tankernn.game.server.entities.ServerEntity; import eu.tankernn.gameEngine.entities.EntityState; import io.netty.channel.Channel; public class ServerPlayer extends ServerEntity { private final Channel channel; private String username; public ServerPlayer(Channel channel) { super(new EntityState()); state.setModelId(0); this.channel = channel; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Channel getChannel() { return channel; } public int getId() { return state.getId(); } }
apache-2.0
kdwink/intellij-community
plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackRepository.java
12337
/* * Copyright 2000-2014 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.tasks.youtrack; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.tasks.*; import com.intellij.tasks.impl.BaseRepository; import com.intellij.tasks.impl.BaseRepositoryImpl; import com.intellij.tasks.impl.LocalTaskImpl; import com.intellij.tasks.impl.TaskUtil; import com.intellij.util.Function; import com.intellij.util.NullableFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.VersionComparatorUtil; import com.intellij.util.xmlb.annotations.Tag; import org.apache.axis.utils.XMLChar; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.io.InputStream; import java.io.StringReader; import java.util.Date; import java.util.List; import java.util.Set; /** * @author Dmitry Avdeev */ @Tag("YouTrack") public class YouTrackRepository extends BaseRepositoryImpl { private String myDefaultSearch = "Assignee: me sort by: updated #Unresolved"; /** * for serialization */ @SuppressWarnings({"UnusedDeclaration"}) public YouTrackRepository() { } public YouTrackRepository(TaskRepositoryType type) { super(type); } @NotNull @Override public BaseRepository clone() { return new YouTrackRepository(this); } private YouTrackRepository(YouTrackRepository other) { super(other); myDefaultSearch = other.getDefaultSearch(); } public Task[] getIssues(@Nullable String request, int max, long since) throws Exception { String query = getDefaultSearch(); if (StringUtil.isNotEmpty(request)) { query += " " + request; } String requestUrl = "/rest/project/issues/?filter=" + encodeUrl(query) + "&max=" + max + "&updatedAfter" + since; HttpMethod method = doREST(requestUrl, false); try { InputStream stream = method.getResponseBodyAsStream(); // todo workaround for http://youtrack.jetbrains.net/issue/JT-7984 String s = StreamUtil.readText(stream, CharsetToolkit.UTF8_CHARSET); for (int i = 0; i < s.length(); i++) { if (!XMLChar.isValid(s.charAt(i))) { s = s.replace(s.charAt(i), ' '); } } Element element; try { //InputSource source = new InputSource(stream); //source.setEncoding("UTF-8"); //element = new SAXBuilder(false).build(source).getRootElement(); element = new SAXBuilder(false).build(new StringReader(s)).getRootElement(); } catch (JDOMException e) { LOG.error("Can't parse YouTrack response for " + requestUrl, e); throw e; } if ("error".equals(element.getName())) { throw new Exception("Error from YouTrack for " + requestUrl + ": '" + element.getText() + "'"); } List<Element> children = element.getChildren("issue"); final List<Task> tasks = ContainerUtil.mapNotNull(children, new NullableFunction<Element, Task>() { public Task fun(Element o) { return createIssue(o); } }); return tasks.toArray(new Task[tasks.size()]); } finally { method.releaseConnection(); } } @Nullable @Override public CancellableConnection createCancellableConnection() { PostMethod method = new PostMethod(getUrl() + "/rest/user/login"); return new HttpTestConnection<PostMethod>(method) { @Override protected void doTest(PostMethod method) throws Exception { login(method); } }; } private HttpClient login(PostMethod method) throws Exception { HttpClient client = getHttpClient(); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(getUsername(), getPassword())); configureHttpMethod(method); method.addParameter("login", getUsername()); method.addParameter("password", getPassword()); client.getParams().setContentCharset("UTF-8"); client.executeMethod(method); String response; try { if (method.getStatusCode() != 200) { throw new Exception("Cannot login: HTTP status code " + method.getStatusCode()); } response = method.getResponseBodyAsString(1000); } finally { method.releaseConnection(); } if (response == null) { throw new NullPointerException(); } if (!response.contains("<login>ok</login>")) { int pos = response.indexOf("</error>"); int length = "<error>".length(); if (pos > length) { response = response.substring(length, pos); } throw new Exception("Cannot login: " + response); } return client; } @Nullable public Task findTask(@NotNull String id) throws Exception { final Element element = fetchRequestAsElement(id); return element.getName().equals("issue") ? createIssue(element) : null; } @TestOnly @NotNull public Element fetchRequestAsElement(@NotNull String id) throws Exception { final HttpMethod method = doREST("/rest/issue/byid/" + id, false); try { final InputStream stream = method.getResponseBodyAsStream(); return new SAXBuilder(false).build(stream).getRootElement(); } finally { method.releaseConnection(); } } HttpMethod doREST(String request, boolean post) throws Exception { HttpClient client = login(new PostMethod(getUrl() + "/rest/user/login")); String uri = getUrl() + request; HttpMethod method = post ? new PostMethod(uri) : new GetMethod(uri); configureHttpMethod(method); int status = client.executeMethod(method); if (status == 400) { InputStream string = method.getResponseBodyAsStream(); Element element = new SAXBuilder(false).build(string).getRootElement(); TaskUtil.prettyFormatXmlToLog(LOG, element); if ("error".equals(element.getName())) { throw new Exception(element.getText()); } } return method; } @Override public void setTaskState(@NotNull Task task, @NotNull CustomTaskState state) throws Exception { doREST("/rest/issue/execute/" + task.getId() + "?command=" + encodeUrl("state " + state.getId()), true).releaseConnection(); } @NotNull @Override public Set<CustomTaskState> getAvailableTaskStates(@NotNull Task task) throws Exception { final HttpMethod method = doREST("/rest/issue/" + task.getId() + "/execute/intellisense?command=" + encodeUrl("state "), false); try { final InputStream stream = method.getResponseBodyAsStream(); final Element element = new SAXBuilder(false).build(stream).getRootElement(); return ContainerUtil.map2Set(element.getChild("suggest").getChildren("item"), new Function<Element, CustomTaskState>() { @Override public CustomTaskState fun(Element element) { final String stateName = element.getChildText("option"); return new CustomTaskState(stateName, stateName); } }); } finally { method.releaseConnection(); } } @Nullable private Task createIssue(Element element) { final String id = element.getAttributeValue("id"); if (id == null) return null; final String summary = element.getAttributeValue("summary"); if (summary == null) return null; final String description = element.getAttributeValue("description"); String type = element.getAttributeValue("type"); TaskType taskType = TaskType.OTHER; if (type != null) { try { taskType = TaskType.valueOf(type.toUpperCase()); } catch (IllegalArgumentException e) { // do nothing } } final TaskType finalTaskType = taskType; final Date updated = new Date(Long.parseLong(element.getAttributeValue("updated"))); final Date created = new Date(Long.parseLong(element.getAttributeValue("created"))); final boolean resolved = element.getAttribute("resolved") != null; return new Task() { @Override public boolean isIssue() { return true; } @Override public String getIssueUrl() { return getUrl() + "/issue/" + getId(); } @NotNull @Override public String getId() { return id; } @NotNull @Override public String getSummary() { return summary; } public String getDescription() { return description; } @NotNull @Override public Comment[] getComments() { return Comment.EMPTY_ARRAY; } @NotNull @Override public Icon getIcon() { return LocalTaskImpl.getIconFromType(getType(), isIssue()); } @NotNull @Override public TaskType getType() { return finalTaskType; } @Nullable @Override public Date getUpdated() { return updated; } @Nullable @Override public Date getCreated() { return created; } @Override public boolean isClosed() { // IDEA-118605 return resolved; } @Override public TaskRepository getRepository() { return YouTrackRepository.this; } }; } public String getDefaultSearch() { return myDefaultSearch; } public void setDefaultSearch(String defaultSearch) { if (defaultSearch != null) { myDefaultSearch = defaultSearch; } } @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"}) @Override public boolean equals(Object o) { if (!super.equals(o)) return false; YouTrackRepository repository = (YouTrackRepository)o; return Comparing.equal(repository.getDefaultSearch(), getDefaultSearch()); } private static final Logger LOG = Logger.getInstance("#com.intellij.tasks.youtrack.YouTrackRepository"); @Override public void updateTimeSpent(@NotNull LocalTask task, @NotNull String timeSpent, @NotNull String comment) throws Exception { checkVersion(); String command = encodeUrl(String.format("work Today %s %s", timeSpent, comment)); final HttpMethod method = doREST("/rest/issue/execute/" + task.getId() + "?command=" + command, true); try { if (method.getStatusCode() != 200) { InputStream stream = method.getResponseBodyAsStream(); String message = new SAXBuilder(false).build(stream).getRootElement().getText(); throw new Exception(message); } } finally { method.releaseConnection(); } } private void checkVersion() throws Exception { HttpMethod method = doREST("/rest/workflow/version", false); try { InputStream stream = method.getResponseBodyAsStream(); Element element = new SAXBuilder(false).build(stream).getRootElement(); final boolean timeTrackingAvailable = element.getName().equals("version") && VersionComparatorUtil.compare(element.getChildText("version"), "4.1") >= 0; if (!timeTrackingAvailable) { throw new Exception("Time tracking is not supported in this version of Youtrack"); } } finally { method.releaseConnection(); } } @Override protected int getFeatures() { return super.getFeatures() | TIME_MANAGEMENT | STATE_UPDATING; } }
apache-2.0
codsoul/java-learn
java-learn/src/main/java/com/latteyan/learn/java/progress/thread/线程_Test.java
7243
package com.latteyan.learn.java.progress.thread; public class 线程_Test { /** * 【一】线程的概念 * 下面是在一个单独的线程中执行一个任务的简单过程 * 1)将任务代码移到实现了Runnable接口类的run方法中。这个接口非常简单,只有一个方法 * public interface Runnable{ * void run(); * } * 可以如下所示实现一个类: * class MyRunnable implements Runnable{ * public void run() * { * task Code...... * ............... * } * } * * 2)创建一个类对象: * Runnable r = MyRunnable(); * * 3)由Runnable创建一个Thread对象 * Tread t = new Tread(r); * * *也可以通过构建一个Thread类的子类定义一个线程,如下所示: * Class MyTread extends Thread{ * public void run() * { * task code * } * } * * 警告:不要调用Thread类或Runnable对象的run方法。直接调用run方法,只会执行同一个线程 * 中的任务,而不会启动新线程。应该调用Tread.start方法。这个方法将创建一个执行run * 方法的新线程。 * * * * * * 【二】中断线程 * java的早期版本中,有一个stop方法,其它线程可以调用它终止线程。 * 但是,这个方法现在已经被弃用了。 * * 有一种可以强制线程终止的方法。然而,interrupt方法可以用来请求终止线程。 * 当一个线程调用interrupt方法时,线程的中断状态将被置空。 * 这是每一个线程都具有的boolean标志。每个线程都应该不时地检查这个标志,以判断线程是不被 中断。 * 要想弄清中断状态是否被置空,首先调用静态的Thread.currentThread方法获得当前线程, * 然后调用isInterrupted()方法。 * while(!Tread.currentThread.isInterrupted() && more work to do) * { * do more work * } * 但是,如果线程被阻塞,就无法检测中断状态。这是产生InterruptedException异常的地方。 * 当一个被阻塞的线程(调用sleep或wait)上调用interrupt方法时,阻塞调用将会被InterruptedException * 异常中断。 * * * 【三】线程的状态 * --线程可以有如下6种状态 * New (新生) * Runnable (可运行) * Blocked (被阻塞) * Waiting (等待) * Timed waiting (计时等待) * Terminated (被终止) * 要确定一个线程的状态,可调用getState方法。 * * 1、新生线程 * 当用new操作符创建一个新线程时,如new Thread(r),该线程还没有开始运行。 * 这意味着它的状态是new.当一个线程处于新生状态,程序还没有开始运行线程中的代码。 * 在运行之前还有一些薄记工作要做。 * 2、可运行线程 * 一旦调用start方法,线程处于runnable状态。 * 一个可运行的线程可能正在运行也可能没有运行,这取决于操作系统给线程提供运行的时间。 * 。。。。 * * 3、被阻塞线程和等待线程 * 当线程处于被阻塞或等待状时,它暂时不活动。它不运行任何代码且消耗最少的资源。 * 直到线程调试器重新激活它。细节取决于它是怎样达到非活动状态的。 * ○当一个线程试图获取一个内部的锁,而该锁被其他线程持有,则该线程进入阻塞状态。 * 当所有其它线程释放该锁,并且线程调试器允许本线程徒有它的时候,该线程将变成非阻塞状态。 * ○当线程等待另一个线程通知调度器一个条件时,它自己进入等待状态。 * 在调用Object.wait方法或Thread.join方法,或者是等待java.util.concurrent库中的Lock或Condition时, * 就会出现这种情况。 * 实际上,被阻塞状态和等待状态是有很大不同的。 * ○有几个方法有一个超时参数。调用它们导致线程进入计时等待状态。 * 这一状态将一直保持到超时期满或者收到适当的通知。 * 带有超时参数的方法有Thread.sleep和Thread.join \Lock.tryLock以及Condition.await的计时版 * 4、被终止的线程 * 线程因如下两个原因之一被终止: * A:因为run方法正常退出而自然死亡 * B:因为一个没有捕获的异常终止了run方法而意外死亡。 * 特别是,可以调用线程的stop方法杀死一个线程。该方法抛出ThreadDeath错误对象, * 由此杀死线程。但是,stop方法已过时,不要在自己的代码中调用它。 * * 【四】线程属性 * 1、线程优先级 * 每一个线程有一个优先级。默认情况下,一个线程继承它的父线程的优先级。 * 可以用setPriority方法提高或降低任何一个线程的优先级。 * 2、守护线程 * 通过调用 * t.setDaemon(true); * 将线程转换为守护线程。 * 守护线程的唯一用途是为其它线程提供服务。 * 计时线程就是一个例子,它定时地发送“时间嘀嗒”信号给其它线程或清空过时的调整缓存项的线程。 * 当只剩下守护线程时,虚拟机就退出了,由于如果只剩下守护线程,没必要继续运行程序了。 * 3、未捕获异常处理器 * 线程的run方法不能抛出任何被检测的异常。但是,不被检测的异常会导致线程终止。 * 在这种情况下,线程就死亡了。 * 但是,不需要任何catch子句来处理可以被传播的这。相反,就在线程死亡之前,异常被传递到一个用于 * 未捕获异常的处理器。 * 该处理器必须属于一个实现一个Thread.UncaughExceptionHandleer接口的类。这个接口只有一个方法 * void uncaughException(Thread t,Throwable e) * * * * sleep()与wait()的不同 * 【1】这两个方法来自不同的类分别是,sleep来自Thread类,而wait来自Object类 * sleep是Thread的静态类方法,谁调用的谁去睡觉,即使在a线程里调用了b的sleep方法,实际上还是a去睡觉,要让b线程睡觉要在b的代码中调用sleep。 * * 【2】最主要是sleep方法没有释放锁,而wait方法释放了锁,使得其他线程可以使用同步控制块或者方法 * sleep不出让系统资源;wait是进入线程等待池等待,出让系统资源,其他线程可以占用CPU。 * 一般wait不会加时间限制,因为如果wait线程的运行资源不够,再出来也没用, * 要等待其他线程调用notify/notifyAll唤醒等待池中的所有线程,才会进入就绪队列等待OS分配系统资源。 * sleep(milliseconds)可以用时间指定使它自动唤醒过来,如果时间不到只能调用interrupt()强行打断。 * Thread.Sleep(0)的作用是“触发操作系统立刻重新进行一次CPU竞争”。 * * 【3】使用范围:wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,而sleep可以在任何地方使用 synchronized(x){ x.notify() /或者wait() } */ }
apache-2.0
alexeev/jboss-fuse-mirror
fabric/fabric-itests/basic/src/test/java/io/fabric8/itests/basic/mq/MQProfileTest.java
11633
package io.fabric8.itests.basic.mq; import io.fabric8.api.Container; import io.fabric8.api.FabricService; import io.fabric8.api.Profile; import io.fabric8.api.ServiceProxy; import io.fabric8.itests.paxexam.support.ContainerBuilder; import io.fabric8.itests.paxexam.support.ContainerProxy; import io.fabric8.itests.paxexam.support.FabricTestSupport; import io.fabric8.itests.paxexam.support.Provision; import java.util.Arrays; import java.util.LinkedList; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.management.ObjectName; import org.apache.activemq.broker.jmx.BrokerViewMBean; import org.apache.activemq.command.DiscoveryEvent; import org.apache.activemq.transport.discovery.DiscoveryListener; import org.apache.curator.framework.CuratorFramework; import org.fusesource.mq.fabric.FabricDiscoveryAgent; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.ExamReactorStrategy; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.exam.options.DefaultCompositeOption; import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory; @RunWith(JUnit4TestRunner.class) @ExamReactorStrategy(AllConfinedStagedReactorFactory.class) public class MQProfileTest extends FabricTestSupport { @Test public void testLocalChildCreation() throws Exception { System.err.println(executeCommand("fabric:create -n")); ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class); try { Set<ContainerProxy> containers= ContainerBuilder.create(fabricProxy, 2).withName("child").withProfiles("default").assertProvisioningResult().build(); try { LinkedList<Container> containerList = new LinkedList<Container>(containers); Container broker = containerList.removeLast(); Profile brokerProfile = broker.getVersion().getProfile("mq-default"); broker.setProfiles(new Profile[]{brokerProfile}); Provision.provisioningSuccess(Arrays.asList(broker), PROVISION_TIMEOUT); waitForBroker("default"); // check jmx stats final BrokerViewMBean bean = (BrokerViewMBean)Provision.getMBean(broker, new ObjectName("org.apache.activemq:type=Broker,brokerName=" + broker.getId()), BrokerViewMBean.class, 120000); Assert.assertEquals("Producer not present", 0, bean.getTotalProducerCount()); Assert.assertEquals("Consumer not present", 0, bean.getTotalConsumerCount()); for (Container c : containerList) { Profile exampleProfile = broker.getVersion().getProfile("example-mq"); c.setProfiles(new Profile[]{exampleProfile}); } Provision.provisioningSuccess(containers, PROVISION_TIMEOUT); Provision.waitForCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { while(bean.getTotalProducerCount() == 0 || bean.getTotalConsumerCount() == 0) { Thread.sleep(1000); } return true; } }, 120000L); Assert.assertEquals("Producer not present", 1, bean.getTotalProducerCount()); Assert.assertEquals("Consumer not present", 1, bean.getTotalConsumerCount()); } finally { ContainerBuilder.destroy(containers); } } finally { fabricProxy.close(); } } @Test public void testMQCreateBasic() throws Exception { System.err.println(executeCommand("fabric:create -n")); System.err.println(executeCommand("mq-create --jmx-user admin --jmx-password admin --minimumInstances 1 mq")); ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class); try { Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 2).withName("child").withProfiles("default").assertProvisioningResult().build(); try { LinkedList<Container> containerList = new LinkedList<Container>(containers); Container broker = containerList.removeLast(); Profile brokerProfile = broker.getVersion().getProfile("mq-broker-default.mq"); broker.setProfiles(new Profile[]{brokerProfile}); Provision.provisioningSuccess(Arrays.asList(broker), PROVISION_TIMEOUT); waitForBroker("default"); final BrokerViewMBean bean = (BrokerViewMBean)Provision.getMBean(broker, new ObjectName("org.apache.activemq:type=Broker,brokerName=mq"), BrokerViewMBean.class, 120000); System.err.println(executeCommand("container-list")); for (Container c : containerList) { Profile exampleProfile = broker.getVersion().getProfile("example-mq"); c.setProfiles(new Profile[]{exampleProfile}); } Provision.provisioningSuccess(containers, PROVISION_TIMEOUT); Provision.waitForCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { while(bean.getTotalProducerCount() == 0 || bean.getTotalConsumerCount() == 0) { Thread.sleep(1000); } return true; } }, 120000L); Assert.assertEquals("Producer not present", 1, bean.getTotalProducerCount()); Assert.assertEquals("Consumer not present", 1, bean.getTotalConsumerCount()); } finally { ContainerBuilder.destroy(containers); } } finally { fabricProxy.close(); } } @Test public void testMQCreateNetwork() throws Exception { System.err.println(executeCommand("fabric:create -n")); executeCommand("mq-create --group us-east --networks us-west --jmx-user admin --jmx-password admin --networks-username admin --networks-password admin --minimumInstances 1 us-east"); executeCommand("mq-create --group us-west --networks us-east --jmx-user admin --jmx-password admin --networks-username admin --networks-password admin --minimumInstances 1 us-west"); ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class); try { Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 4).withName("child").withProfiles("default").assertProvisioningResult().build(); try { LinkedList<Container> containerList = new LinkedList<Container>(containers); Container eastBroker = containerList.removeLast(); Container westBroker = containerList.removeLast(); Profile eastBrokerProfile = eastBroker.getVersion().getProfile("mq-broker-us-east.us-east"); eastBroker.setProfiles(new Profile[]{eastBrokerProfile}); Profile westBrokerProfile = eastBroker.getVersion().getProfile("mq-broker-us-west.us-west"); westBroker.setProfiles(new Profile[]{westBrokerProfile}); Provision.provisioningSuccess(Arrays.asList(westBroker, eastBroker), PROVISION_TIMEOUT); waitForBroker("us-east"); waitForBroker("us-west"); final BrokerViewMBean brokerEast = (BrokerViewMBean)Provision.getMBean(eastBroker, new ObjectName("org.apache.activemq:type=Broker,brokerName=us-east"), BrokerViewMBean.class, 120000); final BrokerViewMBean brokerWest = (BrokerViewMBean)Provision.getMBean(westBroker, new ObjectName("org.apache.activemq:type=Broker,brokerName=us-west"), BrokerViewMBean.class, 120000); Container eastProducer = containerList.removeLast(); executeCommand("container-add-profile " + eastProducer.getId()+" example-mq-producer mq-client-us-east"); Container westConsumer = containerList.removeLast(); executeCommand("container-add-profile " + westConsumer.getId() + " example-mq-consumer mq-client-us-west"); Provision.provisioningSuccess(Arrays.asList(eastProducer, westConsumer), PROVISION_TIMEOUT); System.out.println(executeCommand("fabric:container-list")); Provision.waitForCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { while(brokerEast.getTotalEnqueueCount() == 0 || brokerWest.getTotalDequeueCount() == 0) { Thread.sleep(1000); } return true; } }, 120000L); System.out.println(executeCommand("fabric:container-connect -u admin -p admin " + eastBroker.getId() + " bstat")); System.out.println(executeCommand("fabric:container-connect -u admin -p admin " + westBroker.getId() + " bstat")); Assert.assertFalse("Messages not sent", brokerEast.getTotalEnqueueCount() == 0); Assert.assertFalse("Messages not received", brokerWest.getTotalDequeueCount() == 0); } finally { ContainerBuilder.destroy(containers); } } finally { fabricProxy.close(); } } protected void waitForBroker(String groupName) throws Exception { ServiceProxy<CuratorFramework> curatorProxy = ServiceProxy.createServiceProxy(bundleContext, CuratorFramework.class); try { CuratorFramework curator = curatorProxy.getService(); final CountDownLatch serviceLatch = new CountDownLatch(1); final FabricDiscoveryAgent discoveryAgent = new FabricDiscoveryAgent(); discoveryAgent.setCurator(curator); discoveryAgent.setGroupName(groupName); discoveryAgent.setDiscoveryListener( new DiscoveryListener() { @Override public void onServiceAdd(DiscoveryEvent discoveryEvent) { System.out.println("Service added:" + discoveryEvent.getServiceName()); serviceLatch.countDown(); try { discoveryAgent.stop(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onServiceRemove(DiscoveryEvent discoveryEvent) { System.out.println("Service removed:" + discoveryEvent.getServiceName()); } }); discoveryAgent.start(); Assert.assertTrue(serviceLatch.await(15, TimeUnit.MINUTES)); } finally { curatorProxy.close(); } } @Configuration public Option[] config() { return new Option[]{ new DefaultCompositeOption(fabricDistributionConfiguration()), CoreOptions.scanFeatures("default", "mq-fabric").start() }; } }
apache-2.0
tatemura/strudel
session/src/main/java/com/nec/strudel/session/LocalParam.java
842
/******************************************************************************* * Copyright 2015 Junichi Tatemura * * 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.nec.strudel.session; public interface LocalParam extends ParamName { }
apache-2.0
ehcache/ehcache3-samples
fullstack/src/main/java/org/ehcache/sample/web/rest/util/PaginationUtil.java
1748
package org.ehcache.sample.web.rest.util; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; import org.springframework.web.util.UriComponentsBuilder; /** * Utility class for handling pagination. * * <p> * Pagination uses the same principles as the <a href="https://developer.github.com/v3/#pagination">GitHub API</a>, * and follow <a href="http://tools.ietf.org/html/rfc5988">RFC 5988 (Link header)</a>. */ public final class PaginationUtil { private PaginationUtil() { } public static <T> HttpHeaders generatePaginationHttpHeaders(Page<T> page, String baseUrl) { HttpHeaders headers = new HttpHeaders(); headers.add("X-Total-Count", Long.toString(page.getTotalElements())); String link = ""; if ((page.getNumber() + 1) < page.getTotalPages()) { link = "<" + generateUri(baseUrl, page.getNumber() + 1, page.getSize()) + ">; rel=\"next\","; } // prev link if ((page.getNumber()) > 0) { link += "<" + generateUri(baseUrl, page.getNumber() - 1, page.getSize()) + ">; rel=\"prev\","; } // last and first link int lastPage = 0; if (page.getTotalPages() > 0) { lastPage = page.getTotalPages() - 1; } link += "<" + generateUri(baseUrl, lastPage, page.getSize()) + ">; rel=\"last\","; link += "<" + generateUri(baseUrl, 0, page.getSize()) + ">; rel=\"first\""; headers.add(HttpHeaders.LINK, link); return headers; } private static String generateUri(String baseUrl, int page, int size) { return UriComponentsBuilder.fromUriString(baseUrl).queryParam("page", page).queryParam("size", size).toUriString(); } }
apache-2.0
ZenHarbinger/l2fprod-properties-editor
src/main/java/com/l2fprod/common/swing/UserPreferences.java
11577
/* * Copyright 2015 Matthew Aguirre * * 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.l2fprod.common.swing; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.prefs.Preferences; import javax.swing.DefaultButtonModel; import javax.swing.JFileChooser; import javax.swing.JRadioButton; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.event.ChangeEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableColumnModelListener; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.text.JTextComponent; import com.l2fprod.common.util.converter.ConverterRegistry; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.BackingStoreException; /** * UserPreferences. <BR> * */ public final class UserPreferences { private static final ComponentListener WINDOW_DIMENSIONS = new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { store((Window) e.getComponent()); } @Override public void componentResized(ComponentEvent e) { store((Window) e.getComponent()); } private void store(Window w) { String bounds = (String) ConverterRegistry.instance().convert( String.class, w.getBounds()); node().node("Windows").put(w.getName() + ".bounds", bounds); } }; private static final PropertyChangeListener SPLIT_PANE_LISTENER = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { JSplitPane split = (JSplitPane) evt.getSource(); node().node("JSplitPane").put(split.getName() + ".dividerLocation", String.valueOf(split.getDividerLocation())); } }; private UserPreferences() { } /** * Gets the default file chooser. Its current directory will be tracked and * restored on subsequent calls. * * @return the default file chooser */ public static JFileChooser getDefaultFileChooser() { return getFileChooser("default"); } /** * Gets the default directory chooser. Its current directory will be tracked * and restored on subsequent calls. * * @return the default directory chooser */ public static JFileChooser getDefaultDirectoryChooser() { return getDirectoryChooser("default"); } /** * Gets the file chooser with the given id. Its current directory will be * tracked and restored on subsequent calls. * * @param id * @return the file chooser with the given id */ public static JFileChooser getFileChooser(final String id) { JFileChooser chooser = new JFileChooser(); track(chooser, "FileChooser." + id + ".path"); return chooser; } /** * Gets the directory chooser with the given id. Its current directory will * be tracked and restored on subsequent calls. * * @param id * @return the directory chooser with the given id */ public static JFileChooser getDirectoryChooser(String id) { JFileChooser chooser; Class<?> directoryChooserClass; try { directoryChooserClass = Class .forName("com.l2fprod.common.swing.JDirectoryChooser"); chooser = (JFileChooser) directoryChooserClass.newInstance(); } catch (ClassNotFoundException ex) { chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } catch (InstantiationException ex) { chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } catch (IllegalAccessException ex) { chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } track(chooser, "DirectoryChooser." + id + ".path"); return chooser; } private static void track(JFileChooser chooser, final String key) { // get the path for the given filechooser String path = node().get(key, null); if (path != null) { File file = new File(path); if (file.exists()) { chooser.setCurrentDirectory(file); } } PropertyChangeListener trackPath = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { /* everytime the path change, update the preferences */ if (evt.getNewValue() instanceof File) { node().put(key, ((File) evt.getNewValue()).getAbsolutePath()); } } }; chooser.addPropertyChangeListener(JFileChooser.DIRECTORY_CHANGED_PROPERTY, trackPath); } public static void track(final JRadioButton button) { final Preferences prefs = node().node("Buttons"); boolean selected = prefs.getBoolean(button.getName() + ".selected", button .isSelected()); ((DefaultButtonModel) button.getModel()).getGroup().setSelected( button.getModel(), selected);// .setSelected(selected); button.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { prefs.putBoolean(button.getName() + ".selected", button.isSelected()); } }); } /** * Restores the window size, position and state if possible. Tracks the * window size, position and state. * * @param window */ public static void track(Window window) { Preferences prefs = node().node("Windows"); String bounds = prefs.get(window.getName() + ".bounds", null); if (bounds != null) { Rectangle rect = (Rectangle) ConverterRegistry.instance().convert( Rectangle.class, bounds); window.setBounds(rect); } window.addComponentListener(WINDOW_DIMENSIONS); } private static class TableWidthTracker implements TableColumnModelListener { private final JTable table; TableWidthTracker(JTable table) { this.table = table; } void saveColumnWidths() { try { Preferences prefs = node().node("Tables").node(table.getName() + ".columnWidths"); prefs.clear(); TableColumnModel model = table.getTableHeader().getColumnModel(); for (int i = 0, c = model.getColumnCount(); i < c; i++) { TableColumn column = model.getColumn(i); prefs.putInt(table.getColumnName(i), column.getWidth()); } } catch (BackingStoreException e) { Logger.getLogger(UserPreferences.class.getName()).log(Level.SEVERE, null, e); } } @Override public void columnAdded(TableColumnModelEvent event) { saveColumnWidths(); } @Override public void columnMarginChanged(ChangeEvent event) { saveColumnWidths(); } @Override public void columnMoved(TableColumnModelEvent event) { saveColumnWidths(); } @Override public void columnRemoved(TableColumnModelEvent event) { saveColumnWidths(); } @Override public void columnSelectionChanged(ListSelectionEvent event) { saveColumnWidths(); } } public static void track(JTable table) { // first try to restore the widths try { Preferences prefs = node().node("Tables").node(table.getName() + ".columnWidths"); TableColumnModel model = table.getTableHeader().getColumnModel(); for (int i = 0, c = model.getColumnCount(); i < c; i++) { TableColumn column = model.getColumn(i); int width = prefs.getInt(table.getColumnName(i), -1); if (width != -1) { column.setPreferredWidth(width); } } table.getTableHeader().resizeAndRepaint(); } catch (Throwable e) { Logger.getLogger(UserPreferences.class.getName()).log(Level.SEVERE, null, e); } // then plug the listener to track them try { TableHelper.addColumnModelTracker(table, new TableWidthTracker(table)); } catch (Throwable e) { Logger.getLogger(UserPreferences.class.getName()).log(Level.SEVERE, null, e); } } /** * Restores the text. Stores the text. * * @param text */ public static void track(JTextComponent text) { TextListener textListener = new TextListener(text); } private static final class TextListener implements DocumentListener { private final JTextComponent text; TextListener(JTextComponent text) { this.text = text; restore(); text.getDocument().addDocumentListener((DocumentListener) this); } @Override public void changedUpdate(javax.swing.event.DocumentEvent e) { store(); } @Override public void insertUpdate(javax.swing.event.DocumentEvent e) { store(); } @Override public void removeUpdate(javax.swing.event.DocumentEvent e) { store(); } void restore() { Preferences prefs = node().node("JTextComponent"); text.setText(prefs.get(text.getName(), "")); } void store() { Preferences prefs = node().node("JTextComponent"); prefs.put(text.getName(), text.getText()); } }; public static void track(JSplitPane split) { Preferences prefs = node().node("JSplitPane"); // restore the previous location int dividerLocation = prefs .getInt(split.getName() + ".dividerLocation", -1); if (dividerLocation >= 0) { split.setDividerLocation(dividerLocation); } // track changes split.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, SPLIT_PANE_LISTENER); } /** * @return the Preference node where User Preferences are stored. */ private static Preferences node() { return Preferences.userNodeForPackage(UserPreferences.class).node( "UserPreferences"); } }
apache-2.0
mkl87/AllPlay
allplaylibrary/src/main/java/eu/applabs/allplaylibrary/Player.java
13261
package eu.applabs.allplaylibrary; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.media.AudioManager; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import android.util.Log; import com.bumptech.glide.Glide; import java.util.ArrayList; import java.util.List; import java.util.Observer; import javax.inject.Inject; import eu.applabs.allplaylibrary.data.Observable; import eu.applabs.allplaylibrary.data.SettingsManager; import eu.applabs.allplaylibrary.data.Song; import eu.applabs.allplaylibrary.event.Event; import eu.applabs.allplaylibrary.event.PlayerEvent; import eu.applabs.allplaylibrary.event.ServiceConnectionEvent; import eu.applabs.allplaylibrary.services.ServicePlayer; import eu.applabs.allplaylibrary.services.ServicePlaylist; import eu.applabs.allplaylibrary.services.ServiceType; import eu.applabs.allplaylibrary.services.deezer.DeezerPlayer; import eu.applabs.allplaylibrary.services.spotify.SpotifyPlayer; public class Player extends Observable implements Observer, AudioManager.OnAudioFocusChangeListener { private static final String TAG = Player.class.getSimpleName(); @Inject protected Activity mActivity; @Inject protected MusicCatalog mMusicCatalog; @Inject protected SettingsManager mSettingsManager; @Inject protected Playlist mPlaylist; private List<ServicePlayer> mServicePlayerList = new ArrayList<>(); private ServicePlayer mActiveServicePlayer; private boolean mMediaSessionCompatInitialized = false; private MediaSessionCompat mMediaSessionCompat; public Player() { AllPlayLibrary.getInstance().component().inject(this); mPlaylist.addObserver(this); for(ServiceType serviceType : mSettingsManager.getConnectedServiceTypes()) { connectServiceType(mActivity, serviceType); } } public void clearPlayer() { mActivity = null; // Clear all initialized player if(mServicePlayerList != null) { for (ServicePlayer player : mServicePlayerList) { player.clearPlayer(); } } mServicePlayerList.clear(); mServicePlayerList = null; mPlaylist.deleteObserver(this); mPlaylist.clear(); mPlaylist = null; if(mMediaSessionCompat != null && mMediaSessionCompat.isActive()) { mMediaSessionCompat.setActive(false); mMediaSessionCompat = null; } } public void setServicePlaylist(ServicePlaylist servicePlaylist) { mPlaylist.setServicePlaylist(servicePlaylist); } public ServicePlaylist getServicePlaylist() { return mPlaylist.getServicePlaylist(); } /** * Method to connect a ServiceType * * Access level not specified to provide package only access ! * * @param activity Activity (Used to connect the ServiceType) * @param serviceType ServiceType * * @return boolean (true = Connect started) */ boolean connectServiceType(Activity activity, ServiceType serviceType) { ServicePlayer player = null; switch(serviceType) { case SPOTIFY: player = new SpotifyPlayer(); break; case GOOGLE_MUSIC: return false; case DEEZER: player = new DeezerPlayer(); break; } if(player != null) { player.addObserver(this); player.login(activity); mServicePlayerList.add(player); } return true; } /** * Method to disconnect a ServiceType * * Access level not specified to provide package only access ! * * @param serviceType ServiceType * * @return boolean (true = Disconnect started) */ boolean disconnectServiceType(ServiceType serviceType) { ServicePlayer player = null; for(ServicePlayer iplayer : mServicePlayerList) { if(iplayer.getServiceType() == serviceType) { player = iplayer; break; } } if(player != null) { List<ServiceType> connectedServices = mSettingsManager.getConnectedServiceTypes(); connectedServices.remove(player.getServiceType()); mSettingsManager.setConnectedServices(connectedServices); player.deleteObserver(this); player.logout(); ServiceConnectionEvent serviceConnectionEvent = new ServiceConnectionEvent(ServiceConnectionEvent.ServiceConnectionEventType.DISCONNECTED, player.getServiceType()); handleServiceConnectionEvent(serviceConnectionEvent); player.clearPlayer(); mServicePlayerList.remove(player); } return true; } /** * Method to check if the login was successful * * Access level not specified to provide package only access ! * * @param requestCode Integer (Code of the request) * @param resultCode Integer (Code of the result) * @param intent Intent (Provides addition data) * * @return boolean (true = Event handled) */ boolean checkActivityResult(int requestCode, int resultCode, Intent intent) { for(ServicePlayer player : mServicePlayerList) { if(player.checkActivityResult(requestCode, resultCode, intent)) { return true; } } return false; } public Playlist getPlaylist() { return mPlaylist; } public ServicePlayer.PlayerState getPlayerState() { if(mActiveServicePlayer != null) { return mActiveServicePlayer.getPlayerState(); } return ServicePlayer.PlayerState.IDLE; } public void play() { Song song = mPlaylist.getCurrentSong(); if(song != null) { for(ServicePlayer player : mServicePlayerList) { if(player.play(song)) { // Save the active player if(!mMediaSessionCompatInitialized) { initializeMediaSession(); } mActiveServicePlayer = player; break; } } } } public void resume() { Song song = mPlaylist.getCurrentSong(); if(mActiveServicePlayer != null && song != null) { mActiveServicePlayer.resume(song); } } public void pause() { Song song = mPlaylist.getCurrentSong(); if(mActiveServicePlayer != null && song != null) { mActiveServicePlayer.pause(song); } } public void stop() { Song song = mPlaylist.getCurrentSong(); if(mActiveServicePlayer != null && song != null) { mActiveServicePlayer.stop(song); } } public void next() { Song song = mPlaylist.getNextSong(); if(song != null) { for(ServicePlayer player : mServicePlayerList) { if(player.play(song)) { // Save the active player if(!mMediaSessionCompatInitialized) { initializeMediaSession(); } mActiveServicePlayer = player; break; } } } } public void prev() { Song song = mPlaylist.getPrevSong(); if(song != null) { for(ServicePlayer player : mServicePlayerList) { if(player.play(song)) { // Save the active player if(!mMediaSessionCompatInitialized) { initializeMediaSession(); } mActiveServicePlayer = player; break; } } } } private void initializeMediaSession() { mMediaSessionCompatInitialized = true; ComponentName cn = new ComponentName("eu.applabs.allplay", "eu.applabs.allplay.player.Player"); Intent intent = new Intent(mActivity, mActivity.getClass()); PendingIntent pi = PendingIntent.getActivity(mActivity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); mMediaSessionCompat = new MediaSessionCompat(mActivity, TAG, cn, pi); mMediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS); AudioManager am = (AudioManager) mActivity.getSystemService(Context.AUDIO_SERVICE); // Request audio focus for playback int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { if(mMediaSessionCompat != null) { PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder().setActions(getAvailableActions()); stateBuilder.setState(0, 100, 1.0f); mMediaSessionCompat.setPlaybackState(stateBuilder.build()); new NowPlayingCardUpdater(mPlaylist.getCurrentSong()).start(); mMediaSessionCompat.setActive(true); } } } private long getAvailableActions() { return PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH; } @Override public void onAudioFocusChange(int focusChange) { } @Override public void update(java.util.Observable observable, Object o) { if(o instanceof Event) { Event event = (Event) o; switch (event.getEventType()) { case PLAYLIST_EVENT: new NowPlayingCardUpdater(mPlaylist.getCurrentSong()).start(); break; case SERVICE_CONNECTION_EVENT: ServiceConnectionEvent serviceConnectionEvent = (ServiceConnectionEvent) event; handleServiceConnectionEvent(serviceConnectionEvent); break; case PLAYER_EVENT: PlayerEvent playerEvent = (PlayerEvent) event; handlePlayerEvent(playerEvent); break; } } } private void handleServiceConnectionEvent(ServiceConnectionEvent serviceConnectionEvent) { List<ServiceType> connectedServices = mSettingsManager.getConnectedServiceTypes(); switch (serviceConnectionEvent.getServiceConnectionEventType()) { case CONNECTED: connectedServices.add(serviceConnectionEvent.getServiceType()); mSettingsManager.setConnectedServices(connectedServices); break; case DISCONNECTED: connectedServices.remove(serviceConnectionEvent.getServiceType()); mSettingsManager.setConnectedServices(connectedServices); break; } for(Observer observer : mObserverList) { observer.update(this, serviceConnectionEvent); } } private void handlePlayerEvent(PlayerEvent playerEvent) { switch (playerEvent.getPlayerEventType()) { case STATE_CHANGED: for (Observer observer : mObserverList) { observer.update(this, playerEvent); } break; case PLAYBACK_POSITION_CHANGED: for (Observer observer : mObserverList) { observer.update(this, playerEvent); } break; case TRACK_END: next(); break; case ERROR: mPlaylist.remove(mPlaylist.getCurrentSong()); next(); break; } } private class NowPlayingCardUpdater extends Thread { private Song mSong = null; public NowPlayingCardUpdater(Song song) { mSong = song; } @Override public void run() { super.run(); if(mSong != null) { MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder(); metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, mSong.getTitle()); metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, mSong.getArtist()); try { Bitmap bitmap = Glide.with(mActivity).load(mSong.getCoverBig()).asBitmap().into(800, 800).get(); metadataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, bitmap); } catch (Exception e) { Log.e(TAG, "Error during cover load"); } if(mMediaSessionCompat != null) { mMediaSessionCompat.setMetadata(metadataBuilder.build()); } } } } }
apache-2.0
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.tasks.ui.view/src/org/jkiss/dbeaver/tasks/ui/DataSourceToolsContributor.java
11857
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * 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.jkiss.dbeaver.tasks.ui; import org.eclipse.jface.action.*; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.*; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.connection.DBPEditorContribution; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.navigator.meta.DBXTreeNode; import org.jkiss.dbeaver.model.navigator.meta.DBXTreeObject; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.tasks.ui.view.DatabaseTasksView; import org.jkiss.dbeaver.tools.registry.ToolDescriptor; import org.jkiss.dbeaver.tools.registry.ToolGroupDescriptor; import org.jkiss.dbeaver.tools.registry.ToolsRegistry; import org.jkiss.dbeaver.ui.ActionUtils; import org.jkiss.dbeaver.ui.DBeaverIcons; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.actions.EmptyListAction; import org.jkiss.dbeaver.ui.actions.datasource.DataSourceMenuContributor; import org.jkiss.dbeaver.ui.editors.IDatabaseEditorInput; import org.jkiss.dbeaver.ui.navigator.NavigatorUtils; import org.jkiss.dbeaver.utils.RuntimeUtils; import org.jkiss.utils.CommonUtils; import java.util.*; public class DataSourceToolsContributor extends DataSourceMenuContributor { private static final boolean SHOW_GROUPS_AS_SUBMENU = false; @Override protected void fillContributionItems(List<IContributionItem> menuItems) { IWorkbenchPage activePage = UIUtils.getActiveWorkbenchWindow().getActivePage(); IWorkbenchPart activePart = activePage.getActivePart(); if (activePart == null) { return; } DBSObject selectedObject = null; { final ISelectionProvider selectionProvider = activePart.getSite().getSelectionProvider(); if (selectionProvider != null) { ISelection selection = selectionProvider.getSelection(); if (selection instanceof IStructuredSelection && !selection.isEmpty()) { selectedObject = RuntimeUtils.getObjectAdapter(((IStructuredSelection) selection).getFirstElement(), DBSObject.class); List<ToolDescriptor> tools = getAvailableTools((IStructuredSelection) selection); fillToolsMenu(menuItems, tools, selection); } } } if (activePart instanceof IEditorPart) { IEditorInput editorInput = ((IEditorPart) activePart).getEditorInput(); if (editorInput instanceof IDatabaseEditorInput) { selectedObject = ((IDatabaseEditorInput) editorInput).getDatabaseObject(); } else if (activePart instanceof IDataSourceContainerProvider) { selectedObject = ((IDataSourceContainerProvider) activePart).getDataSourceContainer(); } } if (selectedObject != null) { // Contribute standard tools like session manager DBPDataSource dataSource = selectedObject.getDataSource(); if (dataSource != null) { DBPDataSourceContainer dataSourceContainer = dataSource.getContainer(); DBPEditorContribution[] contributedEditors = DBWorkbench.getPlatform().getDataSourceProviderRegistry().getContributedEditors(DBPEditorContribution.MB_CONNECTION_EDITOR, dataSourceContainer); if (contributedEditors.length > 0) { menuItems.add(new Separator()); for (DBPEditorContribution ec : contributedEditors) { menuItems.add(new ActionContributionItem(new OpenToolsEditorAction(activePage, dataSource, ec))); } } } } // Tasks management { menuItems.add(new Separator()); menuItems.add(ActionUtils.makeCommandContribution(activePart.getSite(), DatabaseTasksView.CREATE_TASK_CMD_ID)); } } private List<ToolDescriptor> getAvailableTools(IStructuredSelection selection) { List<DBSObject> objects = NavigatorUtils.getSelectedObjects(selection); List<ToolDescriptor> result = new ArrayList<>(); if (!objects.isEmpty()) { for (ToolDescriptor descriptor : ToolsRegistry.getInstance().getTools()) { if (descriptor.isSingleton() && objects.size() > 1) { continue; } boolean applies = true; for (DBSObject object : objects) { if (!descriptor.appliesTo(object)) { applies = false; break; } } if (applies) { result.add(descriptor); } } } return result; } private void findObjectNodes(DBXTreeNode meta, List<DBXTreeObject> editors, Set<DBXTreeNode> processedNodes) { if (processedNodes.contains(meta)) { return; } if (meta instanceof DBXTreeObject) { editors.add((DBXTreeObject) meta); } processedNodes.add(meta); if (meta.getRecursiveLink() != null) { return; } List<DBXTreeNode> children = meta.getChildren(null); if (children != null) { for (DBXTreeNode child : children) { findObjectNodes(child, editors, processedNodes); } } } private static void fillToolsMenu(List<IContributionItem> menuItems, List<ToolDescriptor> tools, ISelection selection) { boolean hasTools = false; if (!CommonUtils.isEmpty(tools)) { IWorkbenchWindow workbenchWindow = UIUtils.getActiveWorkbenchWindow(); if (workbenchWindow.getActivePage() != null) { IWorkbenchPart activePart = workbenchWindow.getActivePage().getActivePart(); if (activePart != null) { Map<ToolGroupDescriptor, IMenuManager> groupsMap = new HashMap<>(); Set<ToolGroupDescriptor> groupSet = new HashSet<>(); for (ToolDescriptor tool : tools) { hasTools = true; IMenuManager parentMenu = null; if (tool.getGroup() != null) { if (SHOW_GROUPS_AS_SUBMENU) { parentMenu = getGroupMenu(menuItems, groupsMap, tool.getGroup()); } else { if (!groupSet.contains(tool.getGroup())) { groupSet.add(tool.getGroup()); menuItems.add(new Separator(tool.getGroup().getId())); } } } IAction action = ActionUtils.makeAction( new ExecuteToolHandler(workbenchWindow, tool), activePart.getSite(), selection, tool.getLabel(), tool.getIcon() == null ? null : DBeaverIcons.getImageDescriptor(tool.getIcon()), tool.getDescription()); if (parentMenu == null) { menuItems.add(new ActionContributionItem(action)); } else { parentMenu.add(new ActionContributionItem(action)); } } } } } if (!hasTools) { menuItems.add(new ActionContributionItem(new EmptyListAction())); } } private static IMenuManager getGroupMenu(List<IContributionItem> rootItems, Map<ToolGroupDescriptor, IMenuManager> groupsMap, ToolGroupDescriptor group) { IMenuManager item = groupsMap.get(group); if (item == null) { item = new MenuManager(group.getLabel(), null, group.getId()); if (group.getParent() != null) { IMenuManager parentMenu = getGroupMenu(rootItems, groupsMap, group.getParent()); parentMenu.add(item); } else { rootItems.add(item); } } groupsMap.put(group, item); return item; } private class OpenToolsEditorAction extends Action { private final IWorkbenchPage workbenchPage; private final DBPDataSource dataSource; private final DBPEditorContribution editor; public OpenToolsEditorAction(IWorkbenchPage workbenchPage, DBPDataSource dataSource, DBPEditorContribution editor) { super(editor.getLabel(), DBeaverIcons.getImageDescriptor(editor.getIcon())); this.workbenchPage = workbenchPage; this.dataSource = dataSource; this.editor = editor; } @Override public void run() { try { workbenchPage.openEditor( new DataSourceEditorInput(dataSource, editor), editor.getEditorId()); } catch (PartInitException e) { DBWorkbench.getPlatformUI().showError("Editor open", "Error opening tool editor '" + editor.getEditorId() + "'", e.getStatus()); } } } public static class DataSourceEditorInput implements IEditorInput, IDataSourceContainerProvider, DBPContextProvider { private final DBPDataSource dataSource; private final DBPEditorContribution editor; public DataSourceEditorInput(DBPDataSource dataSource, DBPEditorContribution editor) { this.dataSource = dataSource; this.editor = editor; } @Override public boolean exists() { return false; } @Override public ImageDescriptor getImageDescriptor() { return DBeaverIcons.getImageDescriptor(editor.getIcon()); } @Override public String getName() { return editor.getLabel(); } @Override public IPersistableElement getPersistable() { return null; } @Override public String getToolTipText() { return editor.getDescription(); } @Override public <T> T getAdapter(Class<T> adapter) { return null; } @Override public DBPDataSourceContainer getDataSourceContainer() { return dataSource.getContainer(); } @Override public DBCExecutionContext getExecutionContext() { return DBUtils.getDefaultContext(dataSource, false); } @Override public boolean equals(Object obj) { return obj == this || (obj instanceof DataSourceEditorInput && ((DataSourceEditorInput) obj).dataSource == dataSource && ((DataSourceEditorInput) obj).editor == editor); } } }
apache-2.0
pmk2429/investickation
app/src/main/java/com/sfsu/map/InfoWindowItem.java
326
package com.sfsu.map; /** * Holds the info window for each of the marker/bubble on the map. The info window displays the Observation recorded by the * user and on click of the window allows the user to open a details fragment. * <p> * Created by Pavitra on 11/14/2015. */ public class InfoWindowItem { }
apache-2.0
ljr/OnlineBroker
src/br/usp/icmc/lasdpc/cloudsim/Demand.java
276
package br.usp.icmc.lasdpc.cloudsim; import java.util.ArrayList; import java.util.List; public abstract class Demand { protected List<Event> events; public Demand() { events = new ArrayList<Event>(); } public abstract List<Event> update(List<Double> values); }
apache-2.0
jdahlstrom/vaadin.react
server/src/test/java/com/vaadin/tests/server/component/colorpicker/AbstractColorPickerDeclarativeTest.java
3531
/* * Copyright 2000-2014 Vaadin 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 com.vaadin.tests.server.component.colorpicker; import org.junit.Test; import com.vaadin.shared.ui.colorpicker.Color; import com.vaadin.tests.design.DeclarativeTestBase; import com.vaadin.ui.AbstractColorPicker; import com.vaadin.ui.AbstractColorPicker.PopupStyle; import com.vaadin.ui.ColorPicker; import com.vaadin.ui.ColorPickerArea; public class AbstractColorPickerDeclarativeTest extends DeclarativeTestBase<AbstractColorPicker> { @Test public void testAllAbstractColorPickerFeatures() { String design = "<vaadin-color-picker color='#fafafa' default-caption-enabled position='100,100'" + " popup-style='simple' rgb-visibility='false' hsv-visibility='false'" + " history-visibility=false textfield-visibility=false />"; ColorPicker colorPicker = new ColorPicker(); int colorInt = Integer.parseInt("fafafa", 16); colorPicker.setColor(new Color(colorInt)); colorPicker.setDefaultCaptionEnabled(true); colorPicker.setPosition(100, 100); colorPicker.setPopupStyle(PopupStyle.POPUP_SIMPLE); colorPicker.setRGBVisibility(false); colorPicker.setHSVVisibility(false); colorPicker.setSwatchesVisibility(true); colorPicker.setHistoryVisibility(false); colorPicker.setTextfieldVisibility(false); testWrite(design, colorPicker); testRead(design, colorPicker); } @Test public void testEmptyColorPicker() { String design = "<vaadin-color-picker />"; ColorPicker colorPicker = new ColorPicker(); testRead(design, colorPicker); testWrite(design, colorPicker); } @Test public void testAllAbstractColorPickerAreaFeatures() { String design = "<vaadin-color-picker-area color='#fafafa' default-caption-enabled position='100,100'" + " popup-style='simple' rgb-visibility='false' hsv-visibility='false'" + " history-visibility=false textfield-visibility=false />"; AbstractColorPicker colorPicker = new ColorPickerArea(); int colorInt = Integer.parseInt("fafafa", 16); colorPicker.setColor(new Color(colorInt)); colorPicker.setDefaultCaptionEnabled(true); colorPicker.setPosition(100, 100); colorPicker.setPopupStyle(PopupStyle.POPUP_SIMPLE); colorPicker.setRGBVisibility(false); colorPicker.setHSVVisibility(false); colorPicker.setSwatchesVisibility(true); colorPicker.setHistoryVisibility(false); colorPicker.setTextfieldVisibility(false); testWrite(design, colorPicker); testRead(design, colorPicker); } @Test public void testEmptyColorPickerArea() { String design = "<vaadin-color-picker-area />"; AbstractColorPicker colorPicker = new ColorPickerArea(); testRead(design, colorPicker); testWrite(design, colorPicker); } }
apache-2.0
googleinterns/calcite
core/src/main/java/org/apache/calcite/sql/SqlBinaryStringLiteral.java
2328
/* * 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.calcite.sql; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.sql.type.SqlTypeName; import org.apache.calcite.util.BitString; import org.apache.calcite.util.Util; import java.util.List; /** * A binary (or hexadecimal) string literal. * * <p>The {@link #value} field is a {@link BitString} and {@link #typeName} is * {@link SqlTypeName#BINARY}. */ public class SqlBinaryStringLiteral extends SqlAbstractStringLiteral { //~ Constructors ----------------------------------------------------------- protected SqlBinaryStringLiteral( BitString val, SqlParserPos pos) { super(val, SqlTypeName.BINARY, pos); } //~ Methods ---------------------------------------------------------------- /** * @return the underlying BitString */ public BitString getBitString() { return (BitString) value; } @Override public SqlBinaryStringLiteral clone(SqlParserPos pos) { return new SqlBinaryStringLiteral((BitString) value, pos); } public void unparse( SqlWriter writer, int leftPrec, int rightPrec) { assert value instanceof BitString; writer.literal("X'" + ((BitString) value).toHexString() + "'"); } protected SqlAbstractStringLiteral concat1(List<SqlLiteral> literals) { return new SqlBinaryStringLiteral( BitString.concat( Util.transform(literals, literal -> ((SqlBinaryStringLiteral) literal).getBitString())), literals.get(0).getParserPosition()); } }
apache-2.0
vinothchandar/hoodie
hoodie-utilities/src/main/java/com/uber/hoodie/utilities/sources/InputBatch.java
1595
/* * Copyright (c) 2018 Uber Technologies, Inc. (hoodie-dev-group@uber.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 com.uber.hoodie.utilities.sources; import com.uber.hoodie.utilities.schema.SchemaProvider; import java.util.Optional; public class InputBatch<T> { private final Optional<T> batch; private final String checkpointForNextBatch; private final SchemaProvider schemaProvider; public InputBatch(Optional<T> batch, String checkpointForNextBatch, SchemaProvider schemaProvider) { this.batch = batch; this.checkpointForNextBatch = checkpointForNextBatch; this.schemaProvider = schemaProvider; } public InputBatch(Optional<T> batch, String checkpointForNextBatch) { this.batch = batch; this.checkpointForNextBatch = checkpointForNextBatch; this.schemaProvider = null; } public Optional<T> getBatch() { return batch; } public String getCheckpointForNextBatch() { return checkpointForNextBatch; } public SchemaProvider getSchemaProvider() { return schemaProvider; } }
apache-2.0
DariusX/camel
core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MetricsComponentBuilderFactory.java
4899
/* * 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.camel.builder.component.dsl; import javax.annotation.Generated; import org.apache.camel.Component; import org.apache.camel.builder.component.AbstractComponentBuilder; import org.apache.camel.builder.component.ComponentBuilder; import org.apache.camel.component.metrics.MetricsComponent; /** * Collect various metrics directly from Camel routes using the DropWizard * metrics library. * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.ComponentDslMojo") public interface MetricsComponentBuilderFactory { /** * Metrics (camel-metrics) * Collect various metrics directly from Camel routes using the DropWizard * metrics library. * * Category: monitoring * Since: 2.14 * Maven coordinates: org.apache.camel:camel-metrics */ static MetricsComponentBuilder metrics() { return new MetricsComponentBuilderImpl(); } /** * Builder for the Metrics component. */ interface MetricsComponentBuilder extends ComponentBuilder<MetricsComponent> { /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer */ default MetricsComponentBuilder lazyStartProducer( boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the component should use basic property binding (Camel 2.x) * or the newer property binding with additional capabilities. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default MetricsComponentBuilder basicPropertyBinding( boolean basicPropertyBinding) { doSetProperty("basicPropertyBinding", basicPropertyBinding); return this; } /** * To use a custom configured MetricRegistry. * * The option is a: <code>com.codahale.metrics.MetricRegistry</code> * type. * * Group: advanced */ default MetricsComponentBuilder metricRegistry( com.codahale.metrics.MetricRegistry metricRegistry) { doSetProperty("metricRegistry", metricRegistry); return this; } } class MetricsComponentBuilderImpl extends AbstractComponentBuilder<MetricsComponent> implements MetricsComponentBuilder { @Override protected MetricsComponent buildConcreteComponent() { return new MetricsComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "lazyStartProducer": ((MetricsComponent) component).setLazyStartProducer((boolean) value); return true; case "basicPropertyBinding": ((MetricsComponent) component).setBasicPropertyBinding((boolean) value); return true; case "metricRegistry": ((MetricsComponent) component).setMetricRegistry((com.codahale.metrics.MetricRegistry) value); return true; default: return false; } } } }
apache-2.0
leapframework/framework
base/lang/src/main/java/leap/lang/http/ContentTypes.java
835
/* * Copyright 2015 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 leap.lang.http; public class ContentTypes extends MimeTypes { public static String create(String mimeType,String charset){ return mimeType + ";charset=" + charset; } protected ContentTypes() { } }
apache-2.0
sweble/osr-common
parser-toolkit-parent/ptk-common/src/main/java/de/fau/cs/osr/ptk/common/test/nodes/CtnBuilder.java
3196
/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * 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 de.fau.cs.osr.ptk.common.test.nodes; public class CtnBuilder { public static CtnText ctnText() { return new CtnText("Default text"); } public static CtnText ctnText(String text) { return new CtnText(text); } public static CtnNodeList ctnList() { return new CtnNodeList(); } public static CtnNodeList ctnList(CtnNode... children) { return new CtnNodeList(children); } public static SectionBuilder ctnSection() { return new SectionBuilder(); } public static CtnTitle ctnTitle(CtnNode... children) { return new CtnTitle.CtnTitleImpl(children); } public static CtnBody ctnBody(CtnNode... children) { return new CtnBody.CtnBodyImpl(children); } public static CtnDocument ctnDoc(CtnNode... children) { return new CtnDocument(children); } public static CtnIdNode ctnId(int i) { return new CtnIdNode(i); } public static UrlBuilder ctnUrl() { return new UrlBuilder(); } public static CtnNodeWithObjProp ctnObjProp(Object prop) { return new CtnNodeWithObjProp(prop); } public static CtnNodeWithPropAndContent ctnPropContent( Object prop, String content) { return new CtnNodeWithPropAndContent(prop, content); } // ========================================================================= public static final class SectionBuilder { private int level = 0; private CtnTitle title = new CtnTitle.CtnTitleImpl(ctnText("Default section title")); private CtnBody body = new CtnBody.CtnBodyImpl(ctnText("Default section body")); public SectionBuilder withLevel(int level) { this.level = level; return this; } public SectionBuilder withTitle(CtnTitle title) { this.title = title; return this; } public SectionBuilder withTitle(CtnNode... children) { this.title = new CtnTitle.CtnTitleImpl(children); return this; } public SectionBuilder withBody(CtnBody body) { this.body = body; return this; } public SectionBuilder withBody(CtnNode... children) { this.body = new CtnBody.CtnBodyImpl(children); return this; } public CtnSection build() { return new CtnSection(level, title, body); } } public static final class UrlBuilder { private String protocol = "http"; private String path = "example.org"; public UrlBuilder withProtocol(String protocol) { this.protocol = protocol; return this; } public UrlBuilder withPath(String path) { this.path = path; return this; } public CtnUrl build() { return new CtnUrl(protocol, path); } } }
apache-2.0
Mageswaran1989/aja
src/main/scala/org/aja/dhira/src/main/scala/org/dhira/core/nnet/conf/preprocessor/FeedForwardToCnnPreProcessor.java
6904
/* * * * Copyright 2015 Skymind,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.deeplearning4j.nn.conf.preprocessor; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AccessLevel; import lombok.Data; import lombok.Getter; import lombok.Setter; import org.deeplearning4j.nn.conf.InputPreProcessor; import org.deeplearning4j.nn.conf.inputs.InputType; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.shape.Shape; import org.nd4j.linalg.util.ArrayUtil; import java.util.Arrays; /** * A preprocessor to allow CNN and standard feed-forward network layers to be used together.<br> * For example, DenseLayer -> CNN<br> * This does two things:<br> * (a) Reshapes activations out of FeedFoward layer (which is 2D or 3D with shape * [numExamples, inputHeight*inputWidth*numChannels]) into 4d activations (with shape * [numExamples, numChannels, inputHeight, inputWidth]) suitable to feed into CNN layers.<br> * (b) Reshapes 4d epsilons (weights*deltas) from CNN layer, with shape * [numExamples, numChannels, inputHeight, inputWidth]) into 2d epsilons (with shape * [numExamples, inputHeight*inputWidth*numChannels]) for use in feed forward layer * Note: numChannels is equivalent to depth or featureMaps referenced in different literature * * @author Adam Gibson * @see CnnToFeedForwardPreProcessor for opposite case (i.e., CNN -> DenseLayer etc) */ @Data public class FeedForwardToCnnPreProcessor implements InputPreProcessor { private int inputHeight; private int inputWidth; private int numChannels; @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private int[] shape; /** * Reshape to a channels x rows x columns tensor * * @param inputHeight the columns * @param inputWidth the rows * @param numChannels the channels */ @JsonCreator public FeedForwardToCnnPreProcessor(@JsonProperty("inputHeight") int inputHeight, @JsonProperty("inputWidth") int inputWidth, @JsonProperty("numChannels") int numChannels) { this.inputHeight = inputHeight; this.inputWidth = inputWidth; this.numChannels = numChannels; } public FeedForwardToCnnPreProcessor(int inputWidth, int inputHeight) { this.inputHeight = inputHeight; this.inputWidth = inputWidth; this.numChannels = 1; } @Override public INDArray preProcess(INDArray input, int miniBatchSize) { if (input.ordering() != 'c' || !Shape.strideDescendingCAscendingF(input)) input = input.dup('c'); this.shape = input.shape(); if (input.shape().length == 4) return input; if (input.columns() != inputWidth * inputHeight * numChannels) throw new IllegalArgumentException("Invalid input: expect output columns must be equal to rows " + inputHeight + " x columns " + inputWidth + " x channels " + numChannels + " but was instead " + Arrays.toString(input.shape())); return input.reshape('c', input.size(0), numChannels, inputHeight, inputWidth); } @Override // return 4 dimensions public INDArray backprop(INDArray epsilons, int miniBatchSize) { if (epsilons.ordering() != 'c' || !Shape.strideDescendingCAscendingF(epsilons)) epsilons = epsilons.dup('c'); if (shape == null || ArrayUtil.prod(shape) != epsilons.length()) { if (epsilons.rank() == 2) return epsilons; //should never happen return epsilons.reshape('c', epsilons.size(0), numChannels, inputHeight, inputWidth); } return epsilons.reshape('c', shape); } @Override public FeedForwardToCnnPreProcessor clone() { try { FeedForwardToCnnPreProcessor clone = (FeedForwardToCnnPreProcessor) super.clone(); if (clone.shape != null) clone.shape = clone.shape.clone(); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } @Override public InputType getOutputType(InputType inputType) { switch (inputType.getType()) { case FF: InputType.InputTypeFeedForward c = (InputType.InputTypeFeedForward) inputType; int expSize = inputHeight * inputWidth * numChannels; if (c.getSize() != expSize) { throw new IllegalStateException("Invalid input: expected FeedForward input of size " + expSize + " = (d=" + numChannels + " * w=" + inputWidth + " * h=" + inputHeight + "), got " + inputType); } return InputType.convolutional(inputHeight, inputWidth, numChannels); case CNN: InputType.InputTypeConvolutional c2 = (InputType.InputTypeConvolutional) inputType; if (c2.getDepth() != numChannels || c2.getHeight() != inputHeight || c2.getWidth() != inputWidth) { throw new IllegalStateException("Invalid input: Got CNN input type with (d,w,h)=(" + c2.getDepth() + "," + c2.getWidth() + "," + c2.getHeight() + ") but expected (" + numChannels + "," + inputHeight + "," + inputWidth + ")"); } return c2; case CNNFlat: InputType.InputTypeConvolutionalFlat c3 = (InputType.InputTypeConvolutionalFlat) inputType; if (c3.getDepth() != numChannels || c3.getHeight() != inputHeight || c3.getWidth() != inputWidth) { throw new IllegalStateException("Invalid input: Got CNN input type with (d,w,h)=(" + c3.getDepth() + "," + c3.getWidth() + "," + c3.getHeight() + ") but expected (" + numChannels + "," + inputHeight + "," + inputWidth + ")"); } return c3.getUnflattenedType(); default: throw new IllegalStateException("Invalid input type: got " + inputType); } } }
apache-2.0
Selventa/model-builder
tools/groovy/src/src/main/org/codehaus/groovy/runtime/NullObject.java
4491
/* * Copyright 2003-2007 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 org.codehaus.groovy.runtime; import java.util.Collections; import java.util.Iterator; import groovy.lang.GroovyObjectSupport; public class NullObject extends GroovyObjectSupport { private static final NullObject INSTANCE = new NullObject(); /** * private constructor */ private NullObject() { } /** * get the NullObject reference * * @return the null object */ public static NullObject getNullObject() { return INSTANCE; } /** * Since this is implemented as a singleton, we should avoid the * use of the clone method */ public Object clone() { throw new NullPointerException("Cannot invoke method clone() on null object"); } /** * Tries to get a property on null, which will always fail * * @param property - the property to get * @return a NPE */ public Object getProperty(String property) { throw new NullPointerException("Cannot get property '" + property + "' on null object"); } /** * Tries to set a property on null, which will always fail * * @param property - the proprty to set * @param newValue - the new value of the property */ public void setProperty(String property, Object newValue) { throw new NullPointerException("Cannot set property '" + property + "' on null object"); } /** * Tries to invoke a method on null, which will always fail * * @param name the name of the method to invoke * @param args - arguments to the method * @return a NPE */ public Object invokeMethod(String name, Object args) { throw new NullPointerException("Cannot invoke method " + name + "() on null object"); } /** * null is only equal to null * * @param to - the reference object with which to compare * @return - true if this object is the same as the to argument */ public boolean equals(Object to) { return to == null; } /** * iterator() method to be able to iterate on null. * Note: this part is from Invoker * * @return an iterator for an empty list */ public Iterator iterator() { return Collections.EMPTY_LIST.iterator(); } /** * Allows to add a String to null. * The result is concatenated String of the result of calling * toString() on this object and the String in the parameter. * * @param s - the String to concatenate * @return the concatenated string */ public Object plus(String s) { return getMetaClass().invokeMethod(this, "toString", new Object[]{}) + s; } /** * Fallback for null+null. * The result is always a NPE. The plus(String) version will catch * the case of adding a non null String to null. * * @param o - the Object * @return nothing */ public Object plus(Object o) { throw new NullPointerException("Cannot execute null+null"); } /** * The method "is" is used to test for equal references. * This method will return true only if the given parameter * is null * * @param other - the object to test * @return true if other is null */ public boolean is(Object other) { return other == null; } /** * Type conversion method for null. * * @param c - the class to convert to * @return always null */ public Object asType(Class c) { return null; } /** * A null object always coerces to false. * * @return false */ public boolean asBoolean() { return false; } public String toString() { return "null"; } public int hashCode() { throw new NullPointerException("Cannot invoke method hashCode() on null object"); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/CreateTrustRequest.java
20122
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.directory.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * AWS Directory Service for Microsoft Active Directory allows you to configure trust relationships. For example, you * can establish a trust between your AWS Managed Microsoft AD directory, and your existing on-premises Microsoft Active * Directory. This would allow you to provide users and groups access to resources in either domain, with a single set * of credentials. * </p> * <p> * This action initiates the creation of the AWS side of a trust relationship between an AWS Managed Microsoft AD * directory and an external domain. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CreateTrust" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateTrustRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The Directory ID of the AWS Managed Microsoft AD directory for which to establish the trust relationship. * </p> */ private String directoryId; /** * <p> * The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship. * </p> */ private String remoteDomainName; /** * <p> * The trust password. The must be the same password that was used when creating the trust relationship on the * external domain. * </p> */ private String trustPassword; /** * <p> * The direction of the trust relationship. * </p> */ private String trustDirection; /** * <p> * The trust relationship type. <code>Forest</code> is the default. * </p> */ private String trustType; /** * <p> * The IP addresses of the remote DNS server associated with RemoteDomainName. * </p> */ private com.amazonaws.internal.SdkInternalList<String> conditionalForwarderIpAddrs; /** * <p> * Optional parameter to enable selective authentication for the trust. * </p> */ private String selectiveAuth; /** * <p> * The Directory ID of the AWS Managed Microsoft AD directory for which to establish the trust relationship. * </p> * * @param directoryId * The Directory ID of the AWS Managed Microsoft AD directory for which to establish the trust relationship. */ public void setDirectoryId(String directoryId) { this.directoryId = directoryId; } /** * <p> * The Directory ID of the AWS Managed Microsoft AD directory for which to establish the trust relationship. * </p> * * @return The Directory ID of the AWS Managed Microsoft AD directory for which to establish the trust relationship. */ public String getDirectoryId() { return this.directoryId; } /** * <p> * The Directory ID of the AWS Managed Microsoft AD directory for which to establish the trust relationship. * </p> * * @param directoryId * The Directory ID of the AWS Managed Microsoft AD directory for which to establish the trust relationship. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateTrustRequest withDirectoryId(String directoryId) { setDirectoryId(directoryId); return this; } /** * <p> * The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship. * </p> * * @param remoteDomainName * The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship. */ public void setRemoteDomainName(String remoteDomainName) { this.remoteDomainName = remoteDomainName; } /** * <p> * The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship. * </p> * * @return The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship. */ public String getRemoteDomainName() { return this.remoteDomainName; } /** * <p> * The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship. * </p> * * @param remoteDomainName * The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateTrustRequest withRemoteDomainName(String remoteDomainName) { setRemoteDomainName(remoteDomainName); return this; } /** * <p> * The trust password. The must be the same password that was used when creating the trust relationship on the * external domain. * </p> * * @param trustPassword * The trust password. The must be the same password that was used when creating the trust relationship on * the external domain. */ public void setTrustPassword(String trustPassword) { this.trustPassword = trustPassword; } /** * <p> * The trust password. The must be the same password that was used when creating the trust relationship on the * external domain. * </p> * * @return The trust password. The must be the same password that was used when creating the trust relationship on * the external domain. */ public String getTrustPassword() { return this.trustPassword; } /** * <p> * The trust password. The must be the same password that was used when creating the trust relationship on the * external domain. * </p> * * @param trustPassword * The trust password. The must be the same password that was used when creating the trust relationship on * the external domain. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateTrustRequest withTrustPassword(String trustPassword) { setTrustPassword(trustPassword); return this; } /** * <p> * The direction of the trust relationship. * </p> * * @param trustDirection * The direction of the trust relationship. * @see TrustDirection */ public void setTrustDirection(String trustDirection) { this.trustDirection = trustDirection; } /** * <p> * The direction of the trust relationship. * </p> * * @return The direction of the trust relationship. * @see TrustDirection */ public String getTrustDirection() { return this.trustDirection; } /** * <p> * The direction of the trust relationship. * </p> * * @param trustDirection * The direction of the trust relationship. * @return Returns a reference to this object so that method calls can be chained together. * @see TrustDirection */ public CreateTrustRequest withTrustDirection(String trustDirection) { setTrustDirection(trustDirection); return this; } /** * <p> * The direction of the trust relationship. * </p> * * @param trustDirection * The direction of the trust relationship. * @see TrustDirection */ public void setTrustDirection(TrustDirection trustDirection) { withTrustDirection(trustDirection); } /** * <p> * The direction of the trust relationship. * </p> * * @param trustDirection * The direction of the trust relationship. * @return Returns a reference to this object so that method calls can be chained together. * @see TrustDirection */ public CreateTrustRequest withTrustDirection(TrustDirection trustDirection) { this.trustDirection = trustDirection.toString(); return this; } /** * <p> * The trust relationship type. <code>Forest</code> is the default. * </p> * * @param trustType * The trust relationship type. <code>Forest</code> is the default. * @see TrustType */ public void setTrustType(String trustType) { this.trustType = trustType; } /** * <p> * The trust relationship type. <code>Forest</code> is the default. * </p> * * @return The trust relationship type. <code>Forest</code> is the default. * @see TrustType */ public String getTrustType() { return this.trustType; } /** * <p> * The trust relationship type. <code>Forest</code> is the default. * </p> * * @param trustType * The trust relationship type. <code>Forest</code> is the default. * @return Returns a reference to this object so that method calls can be chained together. * @see TrustType */ public CreateTrustRequest withTrustType(String trustType) { setTrustType(trustType); return this; } /** * <p> * The trust relationship type. <code>Forest</code> is the default. * </p> * * @param trustType * The trust relationship type. <code>Forest</code> is the default. * @see TrustType */ public void setTrustType(TrustType trustType) { withTrustType(trustType); } /** * <p> * The trust relationship type. <code>Forest</code> is the default. * </p> * * @param trustType * The trust relationship type. <code>Forest</code> is the default. * @return Returns a reference to this object so that method calls can be chained together. * @see TrustType */ public CreateTrustRequest withTrustType(TrustType trustType) { this.trustType = trustType.toString(); return this; } /** * <p> * The IP addresses of the remote DNS server associated with RemoteDomainName. * </p> * * @return The IP addresses of the remote DNS server associated with RemoteDomainName. */ public java.util.List<String> getConditionalForwarderIpAddrs() { if (conditionalForwarderIpAddrs == null) { conditionalForwarderIpAddrs = new com.amazonaws.internal.SdkInternalList<String>(); } return conditionalForwarderIpAddrs; } /** * <p> * The IP addresses of the remote DNS server associated with RemoteDomainName. * </p> * * @param conditionalForwarderIpAddrs * The IP addresses of the remote DNS server associated with RemoteDomainName. */ public void setConditionalForwarderIpAddrs(java.util.Collection<String> conditionalForwarderIpAddrs) { if (conditionalForwarderIpAddrs == null) { this.conditionalForwarderIpAddrs = null; return; } this.conditionalForwarderIpAddrs = new com.amazonaws.internal.SdkInternalList<String>(conditionalForwarderIpAddrs); } /** * <p> * The IP addresses of the remote DNS server associated with RemoteDomainName. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setConditionalForwarderIpAddrs(java.util.Collection)} or * {@link #withConditionalForwarderIpAddrs(java.util.Collection)} if you want to override the existing values. * </p> * * @param conditionalForwarderIpAddrs * The IP addresses of the remote DNS server associated with RemoteDomainName. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateTrustRequest withConditionalForwarderIpAddrs(String... conditionalForwarderIpAddrs) { if (this.conditionalForwarderIpAddrs == null) { setConditionalForwarderIpAddrs(new com.amazonaws.internal.SdkInternalList<String>(conditionalForwarderIpAddrs.length)); } for (String ele : conditionalForwarderIpAddrs) { this.conditionalForwarderIpAddrs.add(ele); } return this; } /** * <p> * The IP addresses of the remote DNS server associated with RemoteDomainName. * </p> * * @param conditionalForwarderIpAddrs * The IP addresses of the remote DNS server associated with RemoteDomainName. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateTrustRequest withConditionalForwarderIpAddrs(java.util.Collection<String> conditionalForwarderIpAddrs) { setConditionalForwarderIpAddrs(conditionalForwarderIpAddrs); return this; } /** * <p> * Optional parameter to enable selective authentication for the trust. * </p> * * @param selectiveAuth * Optional parameter to enable selective authentication for the trust. * @see SelectiveAuth */ public void setSelectiveAuth(String selectiveAuth) { this.selectiveAuth = selectiveAuth; } /** * <p> * Optional parameter to enable selective authentication for the trust. * </p> * * @return Optional parameter to enable selective authentication for the trust. * @see SelectiveAuth */ public String getSelectiveAuth() { return this.selectiveAuth; } /** * <p> * Optional parameter to enable selective authentication for the trust. * </p> * * @param selectiveAuth * Optional parameter to enable selective authentication for the trust. * @return Returns a reference to this object so that method calls can be chained together. * @see SelectiveAuth */ public CreateTrustRequest withSelectiveAuth(String selectiveAuth) { setSelectiveAuth(selectiveAuth); return this; } /** * <p> * Optional parameter to enable selective authentication for the trust. * </p> * * @param selectiveAuth * Optional parameter to enable selective authentication for the trust. * @see SelectiveAuth */ public void setSelectiveAuth(SelectiveAuth selectiveAuth) { withSelectiveAuth(selectiveAuth); } /** * <p> * Optional parameter to enable selective authentication for the trust. * </p> * * @param selectiveAuth * Optional parameter to enable selective authentication for the trust. * @return Returns a reference to this object so that method calls can be chained together. * @see SelectiveAuth */ public CreateTrustRequest withSelectiveAuth(SelectiveAuth selectiveAuth) { this.selectiveAuth = selectiveAuth.toString(); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDirectoryId() != null) sb.append("DirectoryId: ").append(getDirectoryId()).append(","); if (getRemoteDomainName() != null) sb.append("RemoteDomainName: ").append(getRemoteDomainName()).append(","); if (getTrustPassword() != null) sb.append("TrustPassword: ").append("***Sensitive Data Redacted***").append(","); if (getTrustDirection() != null) sb.append("TrustDirection: ").append(getTrustDirection()).append(","); if (getTrustType() != null) sb.append("TrustType: ").append(getTrustType()).append(","); if (getConditionalForwarderIpAddrs() != null) sb.append("ConditionalForwarderIpAddrs: ").append(getConditionalForwarderIpAddrs()).append(","); if (getSelectiveAuth() != null) sb.append("SelectiveAuth: ").append(getSelectiveAuth()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateTrustRequest == false) return false; CreateTrustRequest other = (CreateTrustRequest) obj; if (other.getDirectoryId() == null ^ this.getDirectoryId() == null) return false; if (other.getDirectoryId() != null && other.getDirectoryId().equals(this.getDirectoryId()) == false) return false; if (other.getRemoteDomainName() == null ^ this.getRemoteDomainName() == null) return false; if (other.getRemoteDomainName() != null && other.getRemoteDomainName().equals(this.getRemoteDomainName()) == false) return false; if (other.getTrustPassword() == null ^ this.getTrustPassword() == null) return false; if (other.getTrustPassword() != null && other.getTrustPassword().equals(this.getTrustPassword()) == false) return false; if (other.getTrustDirection() == null ^ this.getTrustDirection() == null) return false; if (other.getTrustDirection() != null && other.getTrustDirection().equals(this.getTrustDirection()) == false) return false; if (other.getTrustType() == null ^ this.getTrustType() == null) return false; if (other.getTrustType() != null && other.getTrustType().equals(this.getTrustType()) == false) return false; if (other.getConditionalForwarderIpAddrs() == null ^ this.getConditionalForwarderIpAddrs() == null) return false; if (other.getConditionalForwarderIpAddrs() != null && other.getConditionalForwarderIpAddrs().equals(this.getConditionalForwarderIpAddrs()) == false) return false; if (other.getSelectiveAuth() == null ^ this.getSelectiveAuth() == null) return false; if (other.getSelectiveAuth() != null && other.getSelectiveAuth().equals(this.getSelectiveAuth()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDirectoryId() == null) ? 0 : getDirectoryId().hashCode()); hashCode = prime * hashCode + ((getRemoteDomainName() == null) ? 0 : getRemoteDomainName().hashCode()); hashCode = prime * hashCode + ((getTrustPassword() == null) ? 0 : getTrustPassword().hashCode()); hashCode = prime * hashCode + ((getTrustDirection() == null) ? 0 : getTrustDirection().hashCode()); hashCode = prime * hashCode + ((getTrustType() == null) ? 0 : getTrustType().hashCode()); hashCode = prime * hashCode + ((getConditionalForwarderIpAddrs() == null) ? 0 : getConditionalForwarderIpAddrs().hashCode()); hashCode = prime * hashCode + ((getSelectiveAuth() == null) ? 0 : getSelectiveAuth().hashCode()); return hashCode; } @Override public CreateTrustRequest clone() { return (CreateTrustRequest) super.clone(); } }
apache-2.0
reactor/reactor-netty
reactor-netty-examples/src/main/java/reactor/netty/examples/documentation/udp/server/address/Application.java
1089
/* * Copyright (c) 2020-2021 VMware, Inc. or its affiliates, All Rights Reserved. * * 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 * * https://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 reactor.netty.examples.documentation.udp.server.address; import reactor.netty.Connection; import reactor.netty.udp.UdpServer; import java.time.Duration; public class Application { public static void main(String[] args) { Connection server = UdpServer.create() .host("localhost") //<1> .port(8080) //<2> .bindNow(Duration.ofSeconds(30)); server.onDispose() .block(); } }
apache-2.0
ConsecroMUD/ConsecroMUD
com/suscipio_solutions/consecro_mud/core/intermud/i3/packets/ChannelAdd.java
1720
package com.suscipio_solutions.consecro_mud.core.intermud.i3.packets; import java.util.Vector; import com.suscipio_solutions.consecro_mud.core.intermud.i3.server.I3Server; /** * Copyright (c) 1996 George Reese * 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. * */ @SuppressWarnings("rawtypes") public class ChannelAdd extends Packet { public String channel = null; public ChannelAdd() { super(); type = Packet.CHAN_ADD; } public ChannelAdd(Vector v) throws InvalidPacketException { super(v); try { type = Packet.CHAN_ADD; channel = (String)v.elementAt(6); } catch( final ClassCastException e ) { throw new InvalidPacketException(); } } public ChannelAdd(int t, String chan, String who) { super(); type = t; channel = chan; sender_name = who; } @Override public void send() throws InvalidPacketException { if( channel == null ) { throw new InvalidPacketException(); } super.send(); } @Override public String toString() { final NameServer n = Intermud.getNameServer(); final String cmd= "({\"channel-add\",5,\"" + I3Server.getMudName() + "\",\"" + sender_name + "\",\""+n.name+"\",0,\"" + channel + "\",0,})"; return cmd; } }
apache-2.0
kevinzh64/CoolWeather
app/src/main/java/com/coolweather/android/ChooseAreaFragment.java
8616
package com.coolweather.android; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.coolweather.android.db.City; import com.coolweather.android.db.County; import com.coolweather.android.db.Province; import com.coolweather.android.util.HttpUtil; import com.coolweather.android.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by kevin on 2017/3/22 0022. */ public class ChooseAreaFragment extends Fragment { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private Button backButton; private ListView listView; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); private List<Province> provinceList; private List<City> cityList; private List<County> countyList; private Province selectedProvince; private City selectedCity; //private County selectedCounty; private int currentLevel; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View view = inflater.inflate(R.layout.choose_area, container, false); titleText = (TextView)view.findViewById(R.id.title_text); backButton = (Button)view.findViewById(R.id.back_button); listView = (ListView)view.findViewById(R.id.list_view); adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); return view; } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(position); queryCities(); }else if (currentLevel == LEVEL_CITY){ selectedCity = cityList.get(position); queryCounties(); }else if (currentLevel == LEVEL_COUNTY) { String weatherId = countyList.get(position).getWeatherId(); if (getActivity() instanceof MainActivity) { Intent intent = new Intent(getActivity(), WeatherActivity.class); intent.putExtra("weather_id", weatherId); startActivity(intent); getActivity().finish(); } else if (getActivity() instanceof WeatherActivity) { WeatherActivity activity = (WeatherActivity)getActivity(); activity.drawerLayout.closeDrawers(); activity.swipeRefresh.setRefreshing(true); activity.requestWeather(weatherId); } } } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentLevel == LEVEL_COUNTY){ queryCities(); }else if (currentLevel == LEVEL_CITY){ queryProvinces(); } } }); queryProvinces(); } private void queryProvinces(){ titleText.setText("中国"); backButton.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); if (provinceList.size() > 0){ dataList.clear(); for (Province province : provinceList){ dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; }else { String address = "http://guolin.tech/api/china"; queryFromServer(address, "province"); } } private void queryCities(){ titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class); if (cityList.size() > 0){ dataList.clear(); for (City city : cityList){ dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_CITY; }else { int provinceCode = selectedProvince.getProvinceCode(); String address = "http://guolin.tech/api/china/" + provinceCode; queryFromServer(address, "city"); } } private void queryCounties(){ titleText.setText((selectedCity.getCityName())); backButton.setVisibility(View.VISIBLE); countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class); if(countyList.size() > 0){ dataList.clear(); for (County county : countyList){ dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_COUNTY; }else { int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode; queryFromServer(address, "county"); } } private void queryFromServer(String address, final String type){ showProgressDialog(); HttpUtil.sendOkHttpRequest(address, new Callback() { @Override public void onFailure(Call call, IOException e) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(), "loading failed", Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String responseText = response.body().string(); boolean result = false; if ("province".equals(type)){ result = Utility.handleProvinceResponse(responseText); }else if ("city".equals(type)){ result = Utility.handleCityResponse(responseText, selectedProvince.getId()); }else if ("county".equals(type)){ result = Utility.handleCountyResponse(responseText, selectedCity.getId()); } if (result){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)){ queryProvinces(); }else if ("city".equals(type)){ queryCities(); }else if("county".equals(type)){ queryCounties(); } } }); } } }); } private void showProgressDialog(){ if(progressDialog == null){ progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("loading"); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } private void closeProgressDialog(){ if (progressDialog != null){ progressDialog.dismiss(); } } }
apache-2.0
flylzd/RelaxedReader
app/src/main/java/com/lemon/reader/api/ApiClient.java
587
package com.lemon.reader.api; import com.lemon.kohttp.KOHttpClientManager; import com.lemon.kohttp.callback.ResponseCallback; import com.lemon.reader.AppContext; public class ApiClient { static { KOHttpClientManager.setUserAgent(ApiClientHelper.getUserAgent(AppContext.getInstance())); } public static void getImagesList(String requestTag, String keywords, int page, ResponseCallback responseCallback) { String url = UriHelper.getInstance().getImagesListUrl(keywords, page); KOHttpClientManager.get(requestTag, url, responseCallback); } }
apache-2.0
LyLuo/message-center
mc-core/src/main/java/cc/ly/mc/core/message/DefaultMessage.java
6026
package cc.ly.mc.core.message; import cc.ly.mc.core.attribute.Attribute; import cc.ly.mc.core.attribute.Attributes; import cc.ly.mc.core.event.EventBus; import cc.ly.mc.core.util.NumberUtils; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Created by ly on 9/8/15. */ public class DefaultMessage implements Message { private byte version; private int length = Messages.MESSAGE_FIELDS_LENGTH; private MessageFlag flag; private int code; private int hopByHop; private int endToEnd; private Map<Integer, Attribute<?>> attributes = new HashMap<>(); private Map<Object, Object> attachs = new HashMap<>(); @Override public byte version() { return version; } @Override public void version(byte version) { this.version = version; } @Override public int length() { return length; } @Override public MessageFlag flag() { return flag; } @Override public void flag(MessageFlag flag) { this.flag = flag; } @Override public int code() { return code; } @Override public void code(int code) { this.code = code; } @Override public int hopByHop() { return hopByHop; } @Override public void hopByHop(int hopByHop) { this.hopByHop = hopByHop; } @Override public int endToEnd() { return endToEnd; } @Override public void endToEnd(int endToEnd) { this.endToEnd = endToEnd; } @Override public Attribute<?> attribute(int code) { return attributes.get(code); } @Override public boolean hasAttribute(int... codes) { if(codes == null){ throw new NullPointerException("codes must not be null"); } Set<Integer> keySet = attributes.keySet(); for(int i = 0, size = codes.length; i < size; i++) { if(!keySet.contains(codes[i])){ return false; } } return true; } @Override public Map<Integer, Attribute<?>> attributes() { return attributes; } @Override public void addAttribute(Attribute<?> attribute) { if (attribute == null) { throw new NullPointerException("attribute must not be null"); } if (! attribute.valid()) { throw new IllegalArgumentException("attribute is invalid"); } if (attributes.containsKey(attribute.code())){ throw new IllegalArgumentException("attribute already exits"); } attributes.put(attribute.code(), attribute); length += attribute.length(); } @Override public Attribute<?> removeAttribute(int code) { if(attributes().containsKey(code)){ Attribute<?> attribute = attributes().remove(code); this.length = length() - attribute.length(); return attribute; } return null; } @Override public void attach(Object key, Object value) { if (key == null) { throw new NullPointerException("key must not be null"); } attachs.put(key, value); } @Override public Object attach(Object key) { if (key == null) { throw new NullPointerException("key must not be null"); } return attachs.get(key); } @Override public boolean valid() { return true; } /** * verison(1) + length(3) + flag(1) + code(3) + hopByHop(4) + endToEnd(4) + attributes * * @param payload 二进制数据 */ @Override public void fromBinary(byte[] payload) { if (payload.length < Messages.MESSAGE_FIELDS_LENGTH){ throw new IllegalArgumentException("payload's length must bigger than " + Messages.MESSAGE_FIELDS_LENGTH + " but it's " + length); } byte[] lengthPayload = new byte[Messages.LENGTH_FIELD_LENGTH]; byte[] codePayload = new byte[Messages.CODE_FIELD_LENGTH]; byte[] attributesPayload; int length; ByteBuffer buffer = ByteBuffer.wrap(payload); //parse version version(buffer.get()); //parse length buffer.get(lengthPayload); length = NumberUtils.bytes3ToInt(lengthPayload); if (length < Messages.MESSAGE_FIELDS_LENGTH){ throw new IllegalArgumentException("message's length must bigger than " + Messages.MESSAGE_FIELDS_LENGTH + " but it's " + length); } if (payload.length < length) { throw new IllegalArgumentException("message length " + length + " must less than payload's length " + payload.length); } //parse flag flag(MessageFlag.fromBinary(buffer.get())); //parse code buffer.get(codePayload); code(NumberUtils.bytes3ToInt(codePayload)); //parse hopByHop hopByHop(buffer.getInt()); //parse endToEnd endToEnd(buffer.getInt()); attributesPayload = new byte[length - Messages.MESSAGE_FIELDS_LENGTH]; buffer.get(attributesPayload); //parse attributes Attributes.parse(attributesPayload).forEach(attribute -> addAttribute(attribute)); } @Override public byte[] toBinary() { ByteBuffer buffer = ByteBuffer.allocate(length()); buffer.put(version()); buffer.put(NumberUtils.intToBytes3(length())); buffer.put(flag().value()); buffer.put(NumberUtils.intToBytes3(code())); buffer.putInt(hopByHop()); buffer.putInt(endToEnd()); attributes().forEach((integer, attribute) -> buffer.put(attribute.toBinary())); buffer.flip(); return buffer.array(); } /** * notify以当前对象类名注册名的观察者,并将自身作为event source传入 */ @Override public void onReceived() { EventBus.getInstance().notify(String.valueOf(this.code()), this); } }
apache-2.0
Yingzheng1995/CoolWeather
app/src/main/java/hitwh/xyz/coolweatherbyxyz/gson/Suggestion.java
607
package hitwh.xyz.coolweatherbyxyz.gson; import com.google.gson.annotations.SerializedName; /** * Created by ASUS on 2017/2/16. */ public class Suggestion { @SerializedName("comf") public Comfort comfort; @SerializedName("cw") public CarWash carWash; @SerializedName("sport") public Sport sport; public class Comfort { @SerializedName("txt") public String info; } public class CarWash { @SerializedName("txt") public String info; } public class Sport { @SerializedName("txt") public String info; } }
apache-2.0
Gaia3D/mago3d
mago3d-user/src/main/java/gaia3d/domain/issue/Issue.java
2761
package gaia3d.domain.issue; import java.math.BigDecimal; import java.time.LocalDateTime; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.multipart.MultipartFile; import gaia3d.domain.common.Search; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; /** * Issue * @author jeongdae * */ @ToString(callSuper = true) @Builder @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Issue extends Search { // 이슈 상세 고유번호 private Long issueDetailId; // 댓글 개수 private Integer commentCount; // 데이터 그룹명 private String dataGroupName; // 사용자명 private String userName; // 이슈 내용 private String contents; // 이슈 댓글 고유번호 private Long issueCommentId; // comment private String comment; // 조회수 private Integer viewCount; // 대리자 private String assignee; // 레포트 private String reporter; // 첨부파일 private String fileName; private MultipartFile multipartFile; /****** validator ********/ private String methodMode; /************* 업무 처리 ***********/ // 고유번호 private Long issueId; // 데이터 그룹 고유 번호 private Integer dataGroupId; // 데이터 고유 번호 private Long dataId; // 데이터 키 private String dataKey; // 오브젝트 키 private String objectKey; // 사용자 아이디 private String userId; // 이슈명 private String title; // 우선순위. common_code 동적 생성 private String priority; private String priorityName; private String priorityCssClass; private String priorityImage; // 예정일. 마감일 private String dueDate; private String dueDay; private String dueHour; private String dueMinute; // 이슈 유형. common_code 동적 생성 private String issueType; private String issueTypeName; private String issueTypeCssClass; private String issueTypeImages; // 상태. common_code 동적 생성 private String status; // location(위도, 경도) private String location; // 위도 private BigDecimal latitude; // 경도 private BigDecimal longitude; // 높이 private BigDecimal altitude; // 요청 IP private String clientIp; // 년도 private String year; // 월 private String month; // 일 private String day; // 일년중 몇주 private String yearWeek; // 이번달 몇주 private String week; // 시간 private String hour; // 분 private String minute; // 수정일 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private LocalDateTime updateDate; // 등록일 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private LocalDateTime insertDate; }
apache-2.0
mikokitty/iMed
java-wrapper-master/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/model/Voice.java
4193
/** * Copyright 2015 IBM Corp. All Rights Reserved. * * 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.ibm.watson.developer_cloud.text_to_speech.v1.model; import com.ibm.watson.developer_cloud.service.model.GenericModel; /** * The Class Voice. * * @author German Attanasio Ruiz (germanatt@us.ibm.com) */ public class Voice extends GenericModel { /** The Constant ES_ENRIQUE. */ public static final Voice ES_ENRIQUE = new Voice("es-ES_EnriqueVoice", "male", "es-ES"); /** The Constant ES_LAURA. */ public static final Voice ES_LAURA = new Voice("es-ES_LauraVoice", "female", "es-US"); /** The Constant ES_SOFIA. */ public static final Voice ES_SOFIA = new Voice("es-US_SofiaVoice", "female", "es-US"); /** The Constant EN_MICHAEL. */ public static final Voice EN_MICHAEL = new Voice("en-US_MichaelVoice", "male", "en-US"); /** The Constant EN_LISA. */ public static final Voice EN_LISA = new Voice("en-US_LisaVoice", "female", "en-US"); /** The Constant EN_ALLISON. */ public static final Voice EN_ALLISON = new Voice("en-US_AllisonVoice", "female", "en-US"); /** The Constant IT_FRANCESCA. */ public static final Voice IT_FRANCESCA = new Voice("it-IT_FrancescaVoice", "female", "it-IT"); /** The Constant FR_RENEE. */ public static final Voice FR_RENEE = new Voice("fr-FR_ReneeVoice", "female", "fr-FR"); /** The Constant DE_DIETER. */ public static final Voice DE_DIETER = new Voice("de-DE_DieterVoice", "male", "de-DE"); /** The Constant DE_GIRGIT. */ public static final Voice DE_GIRGIT = new Voice("de-DE_BirgitVoice", "female", "de-DE"); /** The Constant GB_KATE. */ public static final Voice GB_KATE = new Voice("en-GB_KateVoice", "female", "en-GB"); /** The name. */ private String name; /** The language. */ private String language; /** The gender. */ private String gender; /** The url. */ private String url; /** The description. */ private String description; /** * Instantiates a new voice. */ public Voice() { } /** * Instantiates a new voice. * * @param name * the name * @param gender * the gender * @param language * the language */ public Voice(final String name, final String gender, final String language) { this.name = name; this.gender = gender; this.language = language; } /** * Gets the description. * * @return the description */ public String getDescription() { return description; } /** * Sets the description. * * @param description the new description */ public void setDescription(String description) { this.description = description; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name * the new name */ public void setName(final String name) { this.name = name; } /** * Gets the language. * * @return the language */ public String getLanguage() { return language; } /** * Sets the language. * * @param language * the new language */ public void setLanguage(final String language) { this.language = language; } /** * Gets the gender. * * @return the gender */ public String getGender() { return gender; } /** * Sets the gender. * * @param gender * the new gender */ public void setGender(final String gender) { this.gender = gender; } /** * Gets the url. * * @return the url */ public String getUrl() { return url; } /** * Sets the url. * * @param url * the new url */ public void setUrl(final String url) { this.url = url; } }
apache-2.0
jezamoraa/oracle
src/test/java/mx/zetta/adf/business/salesorder/SalesOrderService_GetAllWithCustomer_Test.java
674
package mx.zetta.adf.business.salesorder; import java.util.List; import java.util.logging.Level; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import mx.zetta.adf.SpringTest; import mx.zetta.adf.business.salesorder.SalesOrderService; import mx.zetta.adf.commons.business.entities.SalesOrder; public class SalesOrderService_GetAllWithCustomer_Test extends SpringTest { @Autowired SalesOrderService salesOrderService; @Test public void test() { List<SalesOrder> salesOrders = salesOrderService.getAllWithCustomer(); for (SalesOrder salesOrder : salesOrders) { LOGGER.log(Level.INFO, salesOrder.toString()); } } }
apache-2.0
scify/JThinkFreedom
jthinkfreedom-leap/src/main/java/org/scify/jthinkfreedom/leap/stimuli/CircularGestureStimulus.java
1510
/* * Copyright 2014 SciFY. * * 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.scify.jthinkfreedom.leap.stimuli; import com.leapmotion.leap.Gesture; import static com.leapmotion.leap.Gesture.State.STATE_STOP; import org.scify.jthinkfreedom.skeleton.stimuli.StimulusAnnotation; /** * * @author peustr */ @StimulusAnnotation(sensorClass = "org.scify.jthinkfreedom.leap.sensors.LeapMotionSensor") public class CircularGestureStimulus extends LeapMotionGestureStimulus { public CircularGestureStimulus() { super(); } @Override public boolean shouldReact() { for (Gesture gesture : frame.gestures()) { return gesture.type() == Gesture.Type.TYPE_CIRCLE && gesture.state() == STATE_STOP; } return false; } @Override public String getCanonicalString() { return "Circle"; } @Override public String getDescription() { return "Detecting a circular gesture"; } }
apache-2.0
feedzai/pdb
src/test/java/com/feedzai/commons/sql/abstraction/engine/impl/h2/H2EngineSchemaTest.java
3863
/* * Copyright 2014 Feedzai * * 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.feedzai.commons.sql.abstraction.engine.impl.h2; import com.feedzai.commons.sql.abstraction.engine.DatabaseEngine; import com.feedzai.commons.sql.abstraction.engine.DatabaseEngineException; import com.feedzai.commons.sql.abstraction.engine.DatabaseFactory; import com.feedzai.commons.sql.abstraction.engine.impl.abs.AbstractEngineSchemaTest; import com.feedzai.commons.sql.abstraction.engine.testconfig.DatabaseConfiguration; import com.feedzai.commons.sql.abstraction.engine.testconfig.DatabaseTestUtil; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Collection; import static com.feedzai.commons.sql.abstraction.engine.impl.abs.AbstractEngineSchemaTest.Ieee754Support.SUPPORTED_STRINGS; /** * @author Joao Silva (joao.silva@feedzai.com) * @since 2.0.0 */ @RunWith(Parameterized.class) public class H2EngineSchemaTest extends AbstractEngineSchemaTest { @Parameterized.Parameters public static Collection<DatabaseConfiguration> data() throws Exception { return DatabaseTestUtil.loadConfigurations("h2"); } @Override protected Ieee754Support getIeee754Support() { return SUPPORTED_STRINGS; } @Override @Test @Ignore("H2 respects the fetch size, but takes a *very* long time to timeout on closing the DatabaseEngine/ResultSet") public void testFetchSize() { } @Override protected void defineUDFGetOne(final DatabaseEngine engine) throws DatabaseEngineException { engine.executeUpdate("DROP ALIAS IF EXISTS GetOne"); engine.executeUpdate("CREATE ALIAS IF NOT EXISTS GetOne FOR \"" + this.getClass().getName() + ".GetOne\""); } @Override protected void defineUDFTimesTwo(final DatabaseEngine engine) throws DatabaseEngineException { engine.executeUpdate("DROP ALIAS IF EXISTS \"" + getTestSchema() + "\".TimesTwo"); engine.executeUpdate( "CREATE ALIAS IF NOT EXISTS \"" + getTestSchema() + "\".TimesTwo FOR \"" + this.getClass().getName() + ".TimesTwo\"" ); } @Override protected void createSchema(final DatabaseEngine engine, final String schema) throws DatabaseEngineException { engine.executeUpdate("CREATE SCHEMA IF NOT EXISTS \"" + schema + "\""); } @Override protected void dropSchema(final DatabaseEngine engine, final String schema) throws DatabaseEngineException { engine.executeUpdate("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); } /** * Checks whether the current connection to H2 is local or to a remote server. * * This method won't throw exceptions, if there is any problem the connection will be considered local. * * @return {@code true} if the connection is local, {@code false} otherwise. */ private boolean checkIsLocalH2() { try (final DatabaseEngine engine = DatabaseFactory.getConnection(properties)) { return "0".equals(engine.getConnection().getClientInfo("numServers")); } catch (final Exception ex) { return true; } } public static int GetOne() { return 1; } public static int TimesTwo(int value) { return value * 2; } }
apache-2.0
tfeiner/proxybuilder
modules/static/generated/testusage/src/main/java/junit/org/rapidpm/proxybuilder/staticgenerated/processors/v010/MyClass.java
283
package junit.org.rapidpm.proxybuilder.staticgenerated.processors.v010; import org.rapidpm.proxybuilder.staticgenerated.annotations.StaticLoggingProxy; @StaticLoggingProxy public interface MyClass { default void doSomething() { System.out.println("I did something"); } }
apache-2.0
javadev/jaxb-like-message-parser
src/main/java/edi/parser/engine/Separator.java
433
package edi.parser.engine; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Documented public @interface Separator { String before() default ""; String after() default ""; String between() default ""; }
apache-2.0
ymggt/tenwell
tenwell-identity/tenwell-identity-core/src/main/java/org/tenwell/identity/core/saml2/SAMLEntityResolver.java
511
package org.tenwell.identity.core.saml2; import java.io.IOException; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class SAMLEntityResolver implements EntityResolver { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { throw new SAXException("SAML request contains invalid elements. Possible XML External Entity (XXE) attack."); } }
apache-2.0
18380460383/eshare
app/src/main/java/com/kzmen/sczxjf/bean/returned/OrderForm.java
1317
package com.kzmen.sczxjf.bean.returned; import java.io.Serializable; /** * Created by Administrator on 2016/1/27. */ public class OrderForm implements Serializable{ /** * uid : 93364 * order : 2016012716535443283 * money : 2100 * title : 韩国新品潮流女包 * balance : 600 * score :积分 */ private String uid; private String order; private double money; private String title; private double balance; private String score; public void setUid(String uid) { this.uid = uid; } public void setOrder(String order) { this.order = order; } public void setMoney(double money) { this.money = money; } public void setTitle(String title) { this.title = title; } public void setBalance(double balance) { this.balance = balance; } public String getUid() { return uid; } public String getOrder() { return order; } public double getMoney() { return money; } public String getTitle() { return title; } public double getBalance() { return balance; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } }
apache-2.0
gxa/gxa
atlas-index-api/src/main/java/uk/ac/ebi/gxa/index/StatisticsStorageFactory.java
1919
package uk.ac.ebi.gxa.index; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.gxa.statistics.StatisticsStorage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import static com.google.common.io.Closeables.closeQuietly; /** * This factory class returns de-serialized bit index of gene expression data */ public class StatisticsStorageFactory { final private Logger log = LoggerFactory.getLogger(getClass()); private File atlasIndex; private String indexFileName; private StatisticsStorage statisticsStorage = null; public StatisticsStorageFactory(String indexFileName) { this.indexFileName = indexFileName; } public void setAtlasIndex(File atlasIndexDir) { this.atlasIndex = atlasIndexDir; } /** * @return StatisticsStorage containing indexes of all types in StatisticType enum * @throws IOException in case of I/O problems */ public StatisticsStorage createStatisticsStorage() throws IOException { File indexFile = new File(atlasIndex, indexFileName); if (indexFile.exists()) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream(indexFile)); readStatisticsStorage(ois); log.info("De-serialized " + indexFile.getAbsolutePath() + " successfully"); } catch (ClassNotFoundException cnfe) { log.error("Failed to de-serialize: " + indexFile.getAbsolutePath()); } finally { closeQuietly(ois); } } return statisticsStorage; } @SuppressWarnings("unchecked") private void readStatisticsStorage(ObjectInputStream ois) throws IOException, ClassNotFoundException { statisticsStorage = (StatisticsStorage) ois.readObject(); } }
apache-2.0
tduehr/cas
support/cas-server-support-couchbase-ticket-registry/src/main/java/org/apereo/cas/ticket/registry/CouchbaseTicketRegistry.java
8181
package org.apereo.cas.ticket.registry; import org.apereo.cas.couchbase.core.CouchbaseClientFactory; import org.apereo.cas.ticket.ServiceTicket; import org.apereo.cas.ticket.Ticket; import org.apereo.cas.ticket.TicketCatalog; import org.apereo.cas.ticket.TicketGrantingTicket; import org.apereo.cas.util.CollectionUtils; import com.couchbase.client.java.document.SerializableDocument; import com.couchbase.client.java.view.DefaultView; import com.couchbase.client.java.view.View; import com.couchbase.client.java.view.ViewQuery; import com.couchbase.client.java.view.ViewResult; import com.couchbase.client.java.view.ViewRow; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.DisposableBean; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; /** * A Ticket Registry storage backend which uses the memcached protocol. * CouchBase is a multi host NoSQL database with a memcached interface * to persistent storage which also is quite usable as a replicated * ticket storage engine for multiple front end CAS servers. * * @author Fredrik Jönsson "fjo@kth.se" * @author Misagh Moayyed * @since 4.2.0 */ @Slf4j @RequiredArgsConstructor public class CouchbaseTicketRegistry extends AbstractTicketRegistry implements DisposableBean { /** * The all tickets view name. */ public static final String VIEW_NAME_ALL_TICKETS = "all_tickets"; /** * All tickets view. */ public static final View ALL_TICKETS_VIEW = DefaultView.create( VIEW_NAME_ALL_TICKETS, "function(d,m) {emit(m.id);}", "_count"); /** * Views available. */ public static final Collection<View> ALL_VIEWS = CollectionUtils.wrap(ALL_TICKETS_VIEW); /** * "statistics" document. */ public static final String UTIL_DOCUMENT = "statistics"; private static final long MAX_EXP_TIME_IN_DAYS = 30; private static final String END_TOKEN = "\u02ad"; private final TicketCatalog ticketCatalog; private final CouchbaseClientFactory couchbase; private static int getViewRowCountFromViewResultIterator(final Iterator<ViewRow> iterator) { if (iterator.hasNext()) { val res = iterator.next(); val count = (Integer) res.value(); LOGGER.debug("Found [{}] rows", count); return count; } LOGGER.debug("No rows could be found by the query iterator."); return 0; } /** * Get the expiration policy value of the ticket in seconds. * * @param ticket the ticket * @return the exp value * @see <a href="http://docs.couchbase.com/developer/java-2.0/documents-basics.html">Couchbase Docs</a> */ private static int getTimeToLive(final Ticket ticket) { val expTime = ticket.getExpirationPolicy().getTimeToLive().intValue(); if (TimeUnit.SECONDS.toDays(expTime) >= MAX_EXP_TIME_IN_DAYS) { LOGGER.warn("Any expiration time larger than [{}] days in seconds is considered absolute (as in a Unix time stamp) " + "anything smaller is considered relative in seconds.", MAX_EXP_TIME_IN_DAYS); } return expTime; } @Override public Ticket updateTicket(final Ticket ticket) { addTicket(ticket); return ticket; } @Override public void addTicket(final Ticket ticketToAdd) { LOGGER.debug("Adding ticket [{}]", ticketToAdd); try { val ticket = encodeTicket(ticketToAdd); val document = SerializableDocument.create(ticket.getId(), getTimeToLive(ticketToAdd), ticket); val bucket = this.couchbase.getBucket(); LOGGER.debug("Created document for ticket [{}]. Upserting into bucket [{}]", ticketToAdd, bucket.name()); bucket.upsert(document); } catch (final Exception e) { LOGGER.error("Failed adding [{}]: [{}]", ticketToAdd, e); } } @Override public Ticket getTicket(final String ticketId, final Predicate<Ticket> predicate) { try { LOGGER.debug("Locating ticket id [{}]", ticketId); val encTicketId = encodeTicketId(ticketId); if (encTicketId == null) { LOGGER.debug("Ticket id [{}] could not be found", ticketId); return null; } val document = this.couchbase.getBucket().get(encTicketId, SerializableDocument.class); if (document != null) { val t = (Ticket) document.content(); LOGGER.debug("Got ticket [{}] from the registry.", t); val decoded = decodeTicket(t); if (predicate.test(decoded)) { return decoded; } return null; } LOGGER.debug("Ticket [{}] not found in the registry.", encTicketId); return null; } catch (final Exception e) { LOGGER.error("Failed fetching [{}]: [{}]", ticketId, e); return null; } } /** * Stops the couchbase client. */ @SneakyThrows @Override public void destroy() { LOGGER.debug("Shutting down Couchbase"); this.couchbase.shutdown(); } @Override public Collection<? extends Ticket> getTickets() { return this.ticketCatalog.findAll().stream().flatMap(t -> getViewResultIteratorForPrefixedTickets(t.getPrefix() + '-').allRows().stream()) .filter(row -> StringUtils.isNotBlank(row.id())).map(row -> { val ticket = (Ticket) row.document().content(); LOGGER.debug("Got ticket [{}] from the registry.", ticket); return decodeTicket(ticket); }).map(decoded -> { if (decoded == null || decoded.isExpired()) { LOGGER.warn("Ticket has expired or cannot be decoded"); return null; } else { return decoded; } }).collect(Collectors.toList()); } @Override public long sessionCount() { return runQuery(TicketGrantingTicket.PREFIX + '-'); } @Override public long serviceTicketCount() { return runQuery(ServiceTicket.PREFIX + '-'); } @Override public boolean deleteSingleTicket(final String ticketIdToDelete) { val ticketId = encodeTicketId(ticketIdToDelete); LOGGER.debug("Deleting ticket [{}]", ticketId); try { return this.couchbase.getBucket().remove(ticketId) != null; } catch (final Exception e) { LOGGER.error("Failed deleting [{}]: [{}]", ticketId, e); return false; } } @Override public long deleteAll() { val remove = (Consumer<? super ViewRow>) t -> this.couchbase.getBucket().remove(t.document()); return this.ticketCatalog.findAll() .stream() .mapToLong(t -> { val it = getViewResultIteratorForPrefixedTickets(t.getPrefix() + '-').iterator(); val count = getViewRowCountFromViewResultIterator(it); it.forEachRemaining(remove); return count; }) .sum(); } private int runQuery(final String prefix) { val iterator = getViewResultIteratorForPrefixedTickets(prefix).iterator(); return getViewRowCountFromViewResultIterator(iterator); } private ViewResult getViewResultIteratorForPrefixedTickets(final String prefix) { LOGGER.debug("Running query on document [{}] and view [{}] with prefix [{}]", UTIL_DOCUMENT, VIEW_NAME_ALL_TICKETS, prefix); return this.couchbase.getBucket().query( ViewQuery.from(UTIL_DOCUMENT, VIEW_NAME_ALL_TICKETS) .startKey(prefix) .endKey(prefix + END_TOKEN) .reduce()); } }
apache-2.0
ech1965/colosseum
app/play/modules/rabbitmq/RabbitMQPlugin.java
12441
/** * Copyright 2011 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. * * @author Felipe Oliveira (http://mashup.fm) * */ package play.modules.rabbitmq; import java.io.IOException; //import java.net.URI; //import java.net.URISyntaxException; import org.apache.commons.lang.StringUtils; import play.*; import play.modules.rabbitmq.util.ExceptionUtil; import play.modules.rabbitmq.util.MsgMapper; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.Address; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.MessageProperties; import java.util.ArrayList; import java.util.List; // TODO: Auto-generated Javadoc /** * The Class RabbitMQPlugin. */ public class RabbitMQPlugin extends Plugin { public RabbitMQPlugin(Application app) { this.app = app; } Application app; /** The Constant factory. */ public static final ConnectionFactory factory = new ConnectionFactory(); /** The mapper. */ private static MsgMapper mapper = null; /** The stats service. */ // private static StatsService statsService = new StatsService(); /** The consumers running. */ private static boolean consumersActive = true; /** * On application start. */ @Override public void onStart() { // Connection Factory factory.setUsername(getUserName()); factory.setPassword(getPassword()); factory.setVirtualHost(getVhost()); } /** * Consumers running. * * @return true, if successful */ public static boolean areConsumersActive() { return consumersActive; } /** * Consumers running. * * @param b the b */ public static void consumersActive(boolean b) { consumersActive = b; } /** * Stats service. * * @return the stats service */ // public static StatsService statsService() { // return statsService; // } /** * Mapper. * * @return the msg mapper */ public static MsgMapper mapper() { if ( mapper != null ) { return mapper; } String s = Play.application().configuration().getString("rabbitmq.msgmapper"); if ((s != null) && StringUtils.isNotBlank(s)) { try { mapper = MsgMapper.Type.valueOf(s).get(); } catch (Throwable t) { Logger.error(ExceptionUtil.getStackTrace(t)); mapper = MsgMapper.Type.json.get(); } } else { mapper = MsgMapper.Type.json.get(); } Logger.info("RabbitMQ Message Mapper: %s", mapper); if ( mapper == null ) { throw new RuntimeException( "RabbitMQ Message Mapper is null! Config Parameter 'rabbitmq.msgmapper': " + s ); } return mapper; } /** * Gets the task channel. * * @return the task channel */ protected Channel createChannel() { Channel channel = null; int attempts = 0; while (true) { attempts++; Logger.info("Attempting to connect to queue: attempt " + attempts); try { Connection connection = this.getConnection(); channel = connection.createChannel(); break; } catch (IOException e) { Logger.error("Error creating RabbitMQ channel, retrying in 5 secs - Exception: %s", ExceptionUtil.getStackTrace(e)); try { Thread.sleep(1000 * 5); } catch (InterruptedException ex) { } } } return channel; } /** * Creates the channel. * * @param queue * the queue * @return the channel * @throws Exception * the exception */ public Channel createChannel(String queue, String routingKey) throws Exception { // Counter that keeps track of number of retries int attempts = 0; // Get Plugin RabbitMQPlugin plugin = Play.application().plugin(RabbitMQPlugin.class); // Create Channel Channel channel = this.createChannel(); // Basic Qos if (RabbitMQPlugin.isBasicQos()) { int prefetchCount = 1; channel.basicQos(prefetchCount); } // Start Daemon while (true) { // Add to the number of retries attempts++; // Log Debug Logger.debug("Retry " + attempts); // Get Next Delivery Message try { // http://www.rabbitmq.com/api-guide.html // channel.exchangeDeclare(exchangeName, "direct", true); // String queueName = channel.queueDeclare().getQueue(); // channel.queueBind(queueName, exchangeName, routingKey); channel.exchangeDeclare(queue, plugin.getExchangeType(), true); channel.queueDeclare(queue, plugin.isDurable(), false, false, null); channel.queueBind(queue, queue, routingKey); // Log Debug Logger.info("RabbitMQ Task Channel Available: " + channel); // Return Channel return channel; } catch (Throwable t) { // Log Debug Logger.error("Error establishing a connection to RabbitMQ, will keep retrying - Exception: %s", ExceptionUtil.getStackTrace(t)); // Sleep a little while before retrying try { Thread.sleep(1000 * 10); } catch (InterruptedException ex) { } } } } /** * Creates the channel for a subscriber to consume messages from an exchange * (Exchange is created. Subscribers queue and binding by routing key are created) * * @param exchangeName * the exchange name * @param queue * the queue * @param routingKey * the routing key * @return the channel * @throws Exception * the exception */ public Channel createSubscribersChannel(String exchangeName, String queue, String routingKey) throws Exception { // Counter that keeps track of number of retries int attempts = 0; // Get Plugin RabbitMQPlugin plugin = Play.application().plugin(RabbitMQPlugin.class); // Create Channel Channel channel = this.createChannel(); // Basic Qos if (RabbitMQPlugin.isBasicQos()) { int prefetchCount = 1; channel.basicQos(prefetchCount); } // Start Daemon while (true) { // Add to the number of retries attempts++; // Log Debug Logger.debug("Retry " + attempts); // Get Next Delivery Message try { // http://www.rabbitmq.com/api-guide.html channel.exchangeDeclare(exchangeName, plugin.getExchangeType(), true); channel.queueDeclare(queue, plugin.isDurable(), false, false, null); channel.queueBind(queue, exchangeName, routingKey); // Log Debug Logger.info("RabbitMQ Task Channel Available: " + channel); // Return Channel return channel; } catch (Throwable t) { // Log Debug Logger.error("Error establishing a connection to RabbitMQ, will keep retrying - Exception: %s", ExceptionUtil.getStackTrace(t)); // Sleep a little while before retrying try { Thread.sleep(1000 * 10); } catch (InterruptedException ex) { } } } } /** * Creates the channel to publish messages to an exchange * (Exchange is created. Queue and bindings are NOT created) * * @param exchangeName * the exchange name * @return the channel * @throws Exception * the exception */ public Channel createPublishersChannel(String exchangeName) throws Exception { // Counter that keeps track of number of retries int attempts = 0; // Get Plugin RabbitMQPlugin plugin = Play.application().plugin(RabbitMQPlugin.class); // Create Channel Channel channel = this.createChannel(); // Basic Qos if (RabbitMQPlugin.isBasicQos()) { int prefetchCount = 1; channel.basicQos(prefetchCount); } // Start Daemon while (true) { // Add to the number of retries attempts++; // Log Debug Logger.debug("Retry " + attempts); // Get Next Delivery Message try { // http://www.rabbitmq.com/api-guide.html channel.exchangeDeclare(exchangeName, plugin.getExchangeType(), true); // Log Debug Logger.info("RabbitMQ Task Channel Available: " + channel); // Return Channel return channel; } catch (Throwable t) { // Log Debug Logger.error("Error establishing a connection to RabbitMQ, will keep retrying - Exception: %s", ExceptionUtil.getStackTrace(t)); // Sleep a little while before retrying try { Thread.sleep(1000 * 10); } catch (InterruptedException ex) { } } } } /** * Gets the user name. * * @return the user name */ public static String getUserName() { String s = Play.application().configuration().getString("rabbitmq.username"); if (s == null) { return "guest"; } return s; } /** * Gets the password. * * @return the password */ public static String getPassword() { String s = Play.application().configuration().getString("rabbitmq.password"); if (s == null) { return "guest"; } return s; } /** * Checks if is auto ack. * * @return true, if is auto ack */ public static boolean isAutoAck() { boolean autoAck = false; Boolean b = Play.application().configuration().getBoolean("rabbitmq.autoAck"); if (b == null) { return autoAck; } return b; } /** * Checks if is basic qos. * * @return true, if is basic qos */ public static boolean isBasicQos() { boolean basicQos = true; Boolean b = Play.application().configuration().getBoolean("rabbitmq.basicQos"); if (b == null) { return basicQos; } return b; } /** * Retries. * * @return the int */ public static int retries() { int defaultRetries = 5; try { Integer retries = Play.application().configuration().getInt("rabbitmq.retries"); return retries; } catch (Throwable t) { Logger.error(ExceptionUtil.getStackTrace(t)); return defaultRetries; } } /** * Checks if is durable. * * @return true, if is durable */ public static boolean isDurable() { boolean durable = true; Boolean b = Play.application().configuration().getBoolean("rabbitmq.durable"); if (b == null) { return durable; } return b; } /** * Gets the basic properties. * * @return the basic properties */ public static BasicProperties getBasicProperties() { if (isDurable() == false) { return null; } BasicProperties b = MessageProperties.PERSISTENT_TEXT_PLAIN; return b; } /** * Gets the exchange type. * * @return the exchange type */ public static String getExchangeType() { String s = Play.application().configuration().getString("rabbitmq.exchangeType"); if (s == null) { return "direct"; } return s; } /** * Gets the vhost. * * @return the vhost */ public static String getVhost() { String s = Play.application().configuration().getString("rabbitmq.vhost"); if (s == null) { return "/"; } return s; } /** * Gets address using conf rabbitmq.seeds=host1[:port1];host2[:port2]... * * @return */ public Address[] getAddress(String seeds) { List<Address> addresses = new ArrayList<>(); if (seeds == null || seeds.isEmpty()) { addresses.add(new Address("localhost", 5672)); return addresses.toArray(new Address[0]); } String[] stringArray = seeds.split("[;,\\s]"); for (String s : stringArray) { String[] hostPort = s.split(":"); if (0 == hostPort.length) { continue; } String host = hostPort[0]; int port = 5672; if (hostPort.length > 1) { port = Integer.parseInt(hostPort[1]); } addresses.add(new Address(host, port)); } return addresses.toArray(new Address[0]); } /** * Gets the connection. * * @return the connection * @throws IOException * Signals that an I/O exception has occurred. */ public Connection getConnection() throws IOException { String seeds = Play.application().configuration().getString("rabbitmq.seeds"); return factory.newConnection(getAddress(seeds)); } }
apache-2.0
julianhyde/phoenix
phoenix-core/src/it/java/org/apache/phoenix/end2end/SpillableGroupByIT.java
6799
/* * 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.phoenix.end2end; import static org.apache.phoenix.util.TestUtil.GROUPBYTEST_NAME; import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Map; import java.util.Properties; import org.apache.phoenix.query.QueryServices; import org.apache.phoenix.util.PhoenixRuntime; import org.apache.phoenix.util.PropertiesUtil; import org.apache.phoenix.util.ReadOnlyProps; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import com.google.common.collect.Maps; /* * Run in own cluster since it updates QueryServices.MAX_MEMORY_SIZE_ATTRIB * and we wouldn't want that to be set for other tests sharing the same * cluster. */ @Category(NeedsOwnMiniClusterTest.class) public class SpillableGroupByIT extends BaseOwnClusterHBaseManagedTimeIT { private static final int NUM_ROWS_INSERTED = 1000; // covers: COUNT, COUNT(DISTINCT) SUM, AVG, MIN, MAX private static String GROUPBY1 = "select " + "count(*), count(distinct uri), sum(appcpu), avg(appcpu), uri, min(id), max(id) from " + GROUPBYTEST_NAME + " group by uri"; private int id; @BeforeClass public static void doSetup() throws Exception { Map<String, String> props = Maps.newHashMapWithExpectedSize(1); // Set a very small cache size to force plenty of spilling props.put(QueryServices.GROUPBY_MAX_CACHE_SIZE_ATTRIB, Integer.toString(1)); props.put(QueryServices.GROUPBY_SPILLABLE_ATTRIB, String.valueOf(true)); props.put(QueryServices.GROUPBY_SPILL_FILES_ATTRIB, Integer.toString(1)); // Large enough to not run out of memory, but small enough to spill props.put(QueryServices.MAX_MEMORY_SIZE_ATTRIB, Integer.toString(40000)); setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator())); } private long createTable() throws Exception { long ts = nextTimestamp(); ensureTableCreated(getUrl(), GROUPBYTEST_NAME, null, ts - 2); return ts; } private void loadData(long ts) throws SQLException { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts)); Connection conn = DriverManager.getConnection(getUrl(), props); int groupFactor = NUM_ROWS_INSERTED / 2; for (int i = 0; i < NUM_ROWS_INSERTED; i++) { insertRow(conn, Integer.toString(i % (groupFactor)), 10); if ((i % 1000) == 0) { conn.commit(); } } conn.commit(); conn.close(); } private void insertRow(Connection conn, String uri, int appcpu) throws SQLException { PreparedStatement statement = conn.prepareStatement("UPSERT INTO " + GROUPBYTEST_NAME + "(id, uri, appcpu) values (?,?,?)"); statement.setString(1, String.valueOf(id)); statement.setString(2, uri); statement.setInt(3, appcpu); statement.executeUpdate(); id++; } @Test public void testScanUri() throws Exception { SpillableGroupByIT spGpByT = new SpillableGroupByIT(); long ts = spGpByT.createTable(); spGpByT.loadData(ts); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); Connection conn = DriverManager.getConnection(getUrl(), props); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(GROUPBY1); int count = 0; while (rs.next()) { String uri = rs.getString(5); assertEquals(2, rs.getInt(1)); assertEquals(1, rs.getInt(2)); assertEquals(20, rs.getInt(3)); assertEquals(10, rs.getInt(4)); int a = Integer.valueOf(rs.getString(6)).intValue(); int b = Integer.valueOf(rs.getString(7)).intValue(); assertEquals(Integer.valueOf(uri).intValue(), Math.min(a, b)); assertEquals(NUM_ROWS_INSERTED / 2 + Integer.valueOf(uri), Math.max(a, b)); count++; } assertEquals(NUM_ROWS_INSERTED / 2, count); } finally { conn.close(); } // Test group by with limit that will exit after first row props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); conn = DriverManager.getConnection(getUrl(), props); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT appcpu FROM " + GROUPBYTEST_NAME + " group by appcpu limit 1"); assertTrue(rs.next()); assertEquals(10,rs.getInt(1)); assertFalse(rs.next()); } finally { conn.close(); } // Test group by with limit that will do spilling before exiting props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); conn = DriverManager.getConnection(getUrl(), props); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT to_number(uri) FROM " + GROUPBYTEST_NAME + " group by to_number(uri) limit 100"); int count = 0; while (rs.next()) { count++; } assertEquals(100, count); } finally { conn.close(); } } }
apache-2.0
dbiir/rainbow
rainbow-parser/src/main/java/cn/edu/ruc/iir/rainbow/parser/sql/tree/Relation.java
932
/* * 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 cn.edu.ruc.iir.rainbow.parser.sql.tree; import java.util.Optional; public abstract class Relation extends Node { protected Relation(Optional<NodeLocation> location) { super(location); } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitRelation(this, context); } }
apache-2.0
reboundsoftware/shinobi
src/main/java/ch/reboundsoft/shinobi/authstore/realm/JdbcRealmFactory.java
1704
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.reboundsoft.shinobi.authstore.realm; import ch.reboundsoft.shinobi.authstore.ds.RealmDataSource; import com.google.inject.Inject; import com.google.inject.Singleton; import ninja.utils.NinjaProperties; import org.apache.shiro.authc.credential.DefaultPasswordService; import org.apache.shiro.authc.credential.PasswordMatcher; import org.apache.shiro.authc.credential.PasswordService; import org.apache.shiro.realm.jdbc.JdbcRealm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author rmaire */ @Singleton public class JdbcRealmFactory implements ShinobiRealm { private static final transient Logger log = LoggerFactory.getLogger(JdbcRealmFactory.class); private final JdbcRealm realm; @Inject public JdbcRealmFactory(NinjaProperties ninjaProperties, RealmDataSource ds) { realm = new JdbcRealm(); realm.setDataSource(ds.getDataSource()); realm.setAuthenticationQuery(ninjaProperties.get("shinobi.db.authenticationQuery")); realm.setUserRolesQuery(ninjaProperties.get("shinobi.db.userRolesQuery")); realm.setPermissionsQuery(ninjaProperties.get("shinobi.db.permissionsQuery")); realm.setPermissionsLookupEnabled(true); PasswordMatcher pm = new PasswordMatcher(); pm.setPasswordService(new DefaultPasswordService()); realm.setCredentialsMatcher(pm); } @Override public JdbcRealm getRealm() { log.info("Shinobi jdbc realm created"); return realm; } }
apache-2.0
ppicas/android-clean-architecture-mvp
app/src/main/java/cat/ppicas/cleanarch/ui/vista/CityListItemVista.java
954
/* * Copyright (C) 2015 Pau Picas Sans <pau.picas@gmail.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 cat.ppicas.cleanarch.ui.vista; import cat.ppicas.framework.ui.Vista; public interface CityListItemVista extends Vista { void setCityName(String name); void setCountry(String country); void setCurrentTemp(String temp); void setLoadingElevation(boolean loading); void setElevation(int elevation); }
apache-2.0
Enotron/EnergySimulator
EnergySimulator/src/main/java/org/enotron/simulator/services/DataService.java
3190
package org.enotron.simulator.services; import java.nio.ByteBuffer; import java.util.Date; import java.util.List; import java.util.logging.Logger; import org.enotron.simulator.api.GroupByTime; import org.enotron.simulator.api.MeasurementImpl; import org.enotron.simulator.api.Simulator; import org.enotron.simulator.api.SimulatorException; import org.enotron.simulator.api.ValuesMode; import org.enotron.simulator.impl.simulator.AbstractSimulator; import org.enotron.simulator.utility.ByteArrayHelper; /** * A Spring service that is designed to be injected in to the simulator * where needed. * * This groups methods related to data, like: * Get Measurements * * @author scondon * @copyright 2015 Enotron 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. * */ public class DataService { private Logger _logger = Logger.getLogger(DataService.class.getName()); private ConfigurationService configService; public DataService() { } public List<MeasurementImpl> getMeaurementList( byte[] simulatorId, String[] parameterList, ValuesMode valuesmode, Date startTime, Date endTime, GroupByTime groupByTime) throws SimulatorException { //Check that this is a valid simulator ID AbstractSimulator sim = (AbstractSimulator) getSimulator(simulatorId); String simulatorIdHex = ByteArrayHelper.toHexString(simulatorId); _logger.fine("Received GetData request for " + simulatorIdHex + " and " + parameterList + " for " + valuesmode + " grouped by "); if (parameterList == null || parameterList.length == 0) { _logger.warning("No Parameter List specified - " + "will return all parameters"); } if (valuesmode == null) { _logger.warning("No Values mode specified - assuming " + ValuesMode.AVERAGE); valuesmode = ValuesMode.AVERAGE; } return sim.getMeasurements(valuesmode, startTime, endTime, groupByTime, parameterList); } public ConfigurationService getConfigService() { return configService; } public void setConfigService(ConfigurationService configService) { this.configService = configService; } private Simulator getSimulator(byte[] simulatorUid) throws SimulatorException { ByteBuffer simKey; try { simKey = ByteBuffer.wrap(simulatorUid); } catch (Exception ex) { throw new SimulatorException("Invalid value passed as Simulator ID", -141); } Simulator sim = configService.getSimList().get(simKey); if (sim == null) { String simulatorIdHex = ByteArrayHelper.toHexString(simulatorUid); throw new SimulatorException( "Failed to find simulator with ID " + simulatorIdHex, -139); } return sim; } }
apache-2.0
tatemura/congenio
src/test/java/com/nec/congenio/impl/ExtendMixinTest.java
1618
/******************************************************************************* * Copyright 2015, 2016 Junichi Tatemura * * 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.nec.congenio.impl; import org.junit.Test; import org.w3c.dom.Element; import com.nec.congenio.test.TestDataSet; import com.nec.congenio.xml.Xml; public class ExtendMixinTest { private TestDataSet set = new TestDataSet("extendxml"); @Test public void testMixin() { successCases("mixin"); } private void successCases(String name) { for (Element e : set.testSet(name)) { Element test = Xml.getSingleElement("test", e); Element base = Xml.getSingleElement("base", e); ConfigResource res = set.createResource(e); ExtendXml.resolve(base, res); ExtendXml.resolve(test, base, res); Element expectedResult = Xml.getSingleElement("success", e); XmlValueUtil.assertEq(expectedResult, test); } } }
apache-2.0
CraigAndrew/titanium4j
src/com/emitrom/ti4j/mobile/client/core/handlers/ui/ListViewItemClickHandler.java
319
package com.emitrom.ti4j.mobile.client.core.handlers.ui; import com.emitrom.ti4j.mobile.client.core.events.ui.ListViewItemClickEvent; import com.google.gwt.event.shared.EventHandler; public interface ListViewItemClickHandler extends EventHandler { public void onListViewItemClick(ListViewItemClickEvent event); }
apache-2.0
evictedSaint/mels-cool-project
Design.java
4995
package behemoths; import java.util.HashMap; import behemoths.run.Season; import behemoths.run.Theatre; import behemoths.run.uniqueResources; public class Design { private String name = ""; private HashMap<String, Integer> theatreMap = new HashMap<String, Integer>(); private int ore = 0; private int oil = 0; private HashMap<uniqueResources, Integer> uniRes = new HashMap<uniqueResources, Integer>(); private boolean illegal = false; private String desc = ""; private boolean smallImpact = false; private boolean complex = false; private boolean obsolete = false; private String type = ""; private String status = ""; //for heroes; mia, kia, etc. public Design(String name) { this.name = name; for (uniqueResources resource : uniqueResources.values()) { this.uniRes.put(resource, 0); } } public void setType(String newType) { this.type = newType; } public String getType() { return this.type; } public void setStatus(String status) { this.status = status; } public String getStatus() { return this.status; } public boolean getComplex() { return complex; } public void setComplex(boolean complex) { this.complex = complex; } public boolean getObsolete() { return obsolete; } public void setObsolete(boolean obsolete) { this.obsolete = obsolete; } public void setUniqueResource(uniqueResources resource, int amount) { this.uniRes.put(resource, amount); } public int getUniqueResource(uniqueResources resource) { return this.uniRes.get(resource); } public double getExpenseNum(int oreAvailable, int oilAvailable, HashMap<uniqueResources, Integer> resourceAvailable) { double expense = 1; int totalDeficit = 0; int oreDeficit = ore - oreAvailable; int oilDeficit = oil - oilAvailable; for (uniqueResources resource : uniqueResources.values()) { int deficitHolder = uniRes.get(resource) - resourceAvailable.get(resource); if (deficitHolder > 0) { oreDeficit += deficitHolder; } } if (oreDeficit > 0) { totalDeficit += oreDeficit; } if (oilDeficit > 0) { totalDeficit += oilDeficit; } if (totalDeficit == 0) { expense = 1; } if (totalDeficit > 0) { expense = 0.75; } if (totalDeficit > 2) { expense = 0.5; } if (totalDeficit > 5) { expense = 0.25; } if (totalDeficit > 9) { expense = 0.0; } if (this.complex = true && expense != 0.0) { expense -= 0.25; } return expense; } public String getExpense(int oreAvailable, int oilAvailable, HashMap<uniqueResources, Integer> resourceAvailable) { String expenseWord = "Cheap"; double expense = 1; int totalDeficit = 0; int oreDeficit = ore - oreAvailable; int oilDeficit = oil - oilAvailable; for (uniqueResources resource : uniqueResources.values()) { int deficitHolder = uniRes.get(resource) - resourceAvailable.get(resource); if (deficitHolder > 0) { oreDeficit += deficitHolder; } } if (oreDeficit > 0) { totalDeficit += oreDeficit; } if (oilDeficit > 0) { totalDeficit += oilDeficit; } if (totalDeficit == 0) { expense = 1; } if (totalDeficit > 0 && totalDeficit < 3) { expense = 0.75; } if (totalDeficit > 2 && totalDeficit < 6) { expense = 0.5; } if (totalDeficit > 5 && totalDeficit < 10) { expense = 0.25; } if (totalDeficit > 9) { expense = 0.0; } if (this.complex = true && expense != 0.0) { expense -= 0.25; } // convert to word if (expense == 1) { expenseWord = "Cheap"; } if (expense == 0.75) { expenseWord = "Expensive"; } if (expense == 0.5) { expenseWord = "Very Expensive"; } if (expense == 0.25) { expenseWord = "National Effort"; } if (expense == 0.0) { expenseWord = "Theoretical"; } return expenseWord; } public int getTheatreBonus(Theatre theatre, Season season) { return this.theatreMap.get(theatre.toString() + season.toString()); } public void setTheatreBonus(Theatre theatre, Season season, int bonus) { this.theatreMap.put(theatre.toString() + season.toString(), bonus); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getOre() { return ore; } public void setOre(int ore) { this.ore = ore; } public int getOil() { return oil; } public void setOil(int oil) { this.oil = oil; } public boolean getIllegal() { return illegal; } public void setIllegal(boolean illegal) { this.illegal = illegal; } public boolean getImpact() { return smallImpact; } public void setImpact(boolean impact) { this.smallImpact = impact; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
apache-2.0
datasynctools/sync-tools-prototype
data-sync-tools-core/src/test/java/tools/datasync/core/sampleapp/SyncStateTableCreator.java
417
package tools.datasync.core.sampleapp; import java.sql.Connection; import tools.datasync.utils.SqlUtils; public class SyncStateTableCreator { public static void createDb(Connection conn) { // TODO Remove hard coding of sql statement String path = "src/test/resources/create_table_framework.sql"; try { SqlUtils.runSQLScript(conn, path); } catch (Exception e) { e.printStackTrace(); } } }
apache-2.0
hasithalakmal/RIP
RIP_API/Swagger_REST_API/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java
2671
package io.swagger.codegen.options; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.languages.PhpClientCodegen; import com.google.common.collect.ImmutableMap; import java.util.Map; public class PhpClientOptionsProvider implements OptionsProvider { public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String VARIABLE_NAMING_CONVENTION_VALUE = "snake_case"; public static final String INVOKER_PACKAGE_VALUE = "Swagger\\Client\\Php"; public static final String PACKAGE_PATH_VALUE = "SwaggerClient-php"; public static final String SRC_BASE_PATH_VALUE = "libPhp"; public static final String COMPOSER_VENDOR_NAME_VALUE = "swaggerPhp"; public static final String COMPOSER_PROJECT_NAME_VALUE = "swagger-client-php"; public static final String GIT_USER_ID_VALUE = "gitSwaggerPhp"; public static final String GIT_REPO_ID_VALUE = "git-swagger-client-php"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; @Override public String getLanguage() { return "php"; } @Override public Map<String, String> createOptions() { ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>(); return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(PhpClientCodegen.VARIABLE_NAMING_CONVENTION, VARIABLE_NAMING_CONVENTION_VALUE) .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) .put(PhpClientCodegen.PACKAGE_PATH, PACKAGE_PATH_VALUE) .put(PhpClientCodegen.SRC_BASE_PATH, SRC_BASE_PATH_VALUE) .put(PhpClientCodegen.COMPOSER_VENDOR_NAME, COMPOSER_VENDOR_NAME_VALUE) .put(CodegenConstants.GIT_USER_ID, GIT_USER_ID_VALUE) .put(PhpClientCodegen.COMPOSER_PROJECT_NAME, COMPOSER_PROJECT_NAME_VALUE) .put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .build(); } @Override public boolean isServer() { return false; } }
apache-2.0
vespa-engine/vespa
container-search/src/main/java/com/yahoo/search/dispatch/ResponseMonitor.java
427
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.dispatch; /** * Classes implementing ResponseMonitor can be informed by monitored objects * that a response is available for processing. The responseAvailable method * must be thread-safe. * * @author ollivir */ public interface ResponseMonitor<T> { void responseAvailable(T from); }
apache-2.0
dmutti/masters
CodeForest/src/br/usp/each/saeg/code/forest/metaphor/Branch.java
5728
package br.usp.each.saeg.code.forest.metaphor; import java.util.*; import javax.media.j3d.*; import javax.vecmath.*; import org.apache.commons.lang3.*; import br.usp.each.saeg.code.forest.image.*; import br.usp.each.saeg.code.forest.metaphor.assembler.*; import br.usp.each.saeg.code.forest.metaphor.data.*; import br.usp.each.saeg.code.forest.primitive.*; import com.sun.j3d.utils.geometry.*; public class Branch extends CodeGeometry { public static final int PROPORTION = 2; public static final float OUTSIDE = .97f; private double angle; private int signal; private int index; private LeafDistribution distribution; private LeafAssembler assembler; private CodeCylinder body; private CodeCone tip; private Trunk trunk; private BranchData data; private final ForestRestrictions restrictions; public Branch(Trunk trunk, BranchData data, ForestRestrictions restr, int index) { appearance = ImageUtils.getBranchAppearance(getMaterial(trunk.getColor())); this.index = index; this.trunk = trunk; this.data = data; this.restrictions = restr; if (isLeft()) { signal = -1; angle = Math.toRadians(90); } else { signal = 1; angle = Math.toRadians(270); } distribution = new LeafDistribution(data, trunk.getHeight()); calculateTranslation(); changeAlign(); calculateBranchBody(); createBranch(); createTip(); assembler = new LeafAssembler(distribution, translation, trunk, data.getLeafData(), this, restrictions); addInformation(); } private void createBranch() { Transform3D tr = getTransform3D(); tr.setTranslation(translation); GroupDataItem item = new GroupDataItem(tr, body); groupData.add(item); trunk.add(item.getTransformGroup()); } private void createTip() { Transform3D tr = getTransform3D(); Vector3d tipTranslation = new Vector3d(translation); tipTranslation.setX((signal * body.getHeight() / 2) + tipTranslation.getX() + signal * body.getRadius() / 2); tr.setTranslation(tipTranslation); tip = new CodeCone(body.getRadius(), body.getRadius(), Cone.GENERATE_NORMALS | Cone.GENERATE_TEXTURE_COORDS, appearance); GroupDataItem item = new GroupDataItem(tr, tip); groupData.add(item); trunk.add(item.getTransformGroup()); } private void calculateBranchBody() { body = new CodeCylinder(trunk.getRadius()/3, (float) distribution.getSize(), Cylinder.GENERATE_NORMALS | Cylinder.GENERATE_TEXTURE_COORDS, appearance); } private void calculateTranslation() { double x = signal * (trunk.getRadius()) + signal * (distribution.getSize()/PROPORTION) * OUTSIDE; double y = (trunk.getOffset() * trunk.getStep()) + ((trunk.getStep() / 2 - trunk.getRadius() / 4) * index); translation = new Vector3d(x, y, 0); } private void changeAlign() { translation.setY(translation.getY() + translation.getY()/(10 + random.nextInt(20))); } private void addInformation() { body.setGeometry(this); tip.setGeometry(this); } @Override public void changeStatus() { if (isEnabled()) { disable(); for (Leaf leaf : assembler.getLeaves()) { leaf.disable(); } } else { refresh(); } } private Transform3D getTransform3D() { Transform3D tr = new Transform3D(); tr.rotZ(angle); return tr; } public boolean isLeft() { return index % 2 == 0; } public double getSize() { return body.getHeight() + tip.getHeight(); } public List<Leaf> getLeaves() { return assembler.getLeaves(); } public BranchData getData() { return data; } @Override public void refresh() { if (!containsTerm() || !containsScore()) { disable(); for (Leaf leaf : assembler.getLeaves()) { leaf.disable(); } return; } enable(); for (Leaf leaf : assembler.getLeaves()) { leaf.refresh(); } } private boolean containsTerm() { if (StringUtils.isBlank(restrictions.getTerm())) { return true; } if (restrictions.isBranches()) { if (StringUtils.isNotBlank(restrictions.getTerm()) && StringUtils.containsIgnoreCase(data.getValue(), StringUtils.trim(restrictions.getTerm()))) { return true; } } if (restrictions.isLeaves()) { for (Leaf leaf : assembler.getLeaves()) { if (StringUtils.isNotBlank(restrictions.getTerm()) && StringUtils.containsIgnoreCase(leaf.getData().getValue(), StringUtils.trim(restrictions.getTerm()))) { return true; } } } return false; } private boolean containsScore() { if (restrictions.isBranches()) { if (data.isScoreBetween(restrictions.getMinScore(), restrictions.getMaxScore())) { return true; } } if (restrictions.isLeaves()) { for (Leaf leaf : assembler.getLeaves()) { if (leaf.getData().isScoreBetween(restrictions.getMinScore(), restrictions.getMaxScore())) { return true; } } } return false; } public int getSignal() { return signal; } @Override public Trunk getTrunk() { return trunk; } }
apache-2.0
emre-aydin/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/ByteArrayObjectDataInput.java
21387
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.internal.serialization.impl; import com.hazelcast.internal.nio.Bits; import com.hazelcast.internal.nio.BufferObjectDataInput; import com.hazelcast.internal.serialization.Data; import com.hazelcast.internal.serialization.InternalSerializationService; import com.hazelcast.internal.util.collection.ArrayUtils; import javax.annotation.Nullable; import java.io.EOFException; import java.io.IOException; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import static com.hazelcast.internal.nio.Bits.CHAR_SIZE_IN_BYTES; import static com.hazelcast.internal.nio.Bits.INT_SIZE_IN_BYTES; import static com.hazelcast.internal.nio.Bits.LONG_SIZE_IN_BYTES; import static com.hazelcast.internal.nio.Bits.NULL_ARRAY_LENGTH; import static com.hazelcast.internal.nio.Bits.SHORT_SIZE_IN_BYTES; import static com.hazelcast.version.Version.UNKNOWN; class ByteArrayObjectDataInput extends VersionedObjectDataInput implements BufferObjectDataInput { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; byte[] data; int size; int pos; int mark; char[] charBuffer; private final InternalSerializationService service; private final boolean bigEndian; ByteArrayObjectDataInput(byte[] data, InternalSerializationService service, ByteOrder byteOrder) { this(data, 0, service, byteOrder); } ByteArrayObjectDataInput(byte[] data, int offset, InternalSerializationService service, ByteOrder byteOrder) { this.data = data; this.size = data != null ? data.length : 0; this.pos = offset; this.service = service; this.bigEndian = byteOrder == ByteOrder.BIG_ENDIAN; } @Override public void init(byte[] data, int offset) { this.data = data; this.size = data != null ? data.length : 0; this.pos = offset; } @Override public void clear() { data = null; size = 0; pos = 0; mark = 0; if (charBuffer != null && charBuffer.length > UTF_BUFFER_SIZE * 8) { charBuffer = new char[UTF_BUFFER_SIZE * 8]; } version = UNKNOWN; wanProtocolVersion = UNKNOWN; } @Override public int read() throws EOFException { return (pos < size) ? (data[pos++] & 0xff) : -1; } @Override public int read(int position) throws EOFException { return (position < size) ? (data[position] & 0xff) : -1; } @Override public final int read(byte[] b, int off, int len) throws EOFException { if (b == null) { throw new NullPointerException(); } else { ArrayUtils.boundsCheck(b.length, off, len); } if (len == 0) { return 0; } if (pos >= size) { return -1; } if (pos + len > size) { len = size - pos; } System.arraycopy(data, pos, b, off, len); pos += len; return len; } @Override public final boolean readBoolean() throws EOFException { final int ch = read(); if (ch < 0) { throw new EOFException(); } return (ch != 0); } @Override public final boolean readBoolean(int position) throws EOFException { final int ch = read(position); if (ch < 0) { throw new EOFException(); } return (ch != 0); } /** * See the general contract of the {@code readByte} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return the next byte of this input stream as a signed 8-bit * {@code byte}. * @throws java.io.EOFException if this input stream has reached the end * @throws java.io.IOException if an I/O error occurs * @see java.io.FilterInputStream#in */ @Override public final byte readByte() throws EOFException { final int ch = read(); if (ch < 0) { throw new EOFException(); } return (byte) (ch); } @Override public final byte readByte(int position) throws EOFException { final int ch = read(position); if (ch < 0) { throw new EOFException(); } return (byte) (ch); } /** * See the general contract of the {@code readChar} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return the next two bytes of this input stream as a Unicode character * @throws java.io.EOFException if this input stream reaches the end before reading two bytes * @throws java.io.IOException if an I/O error occurs * @see java.io.FilterInputStream#in */ @Override public final char readChar() throws EOFException { final char c = readChar(pos); pos += CHAR_SIZE_IN_BYTES; return c; } @Override public char readChar(int position) throws EOFException { checkAvailable(position, CHAR_SIZE_IN_BYTES); return Bits.readChar(data, position, bigEndian); } /** * See the general contract of the {@code readDouble} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return the next eight bytes of this input stream, interpreted as a {@code double} * @throws java.io.EOFException if this input stream reaches the end before reading eight bytes * @throws java.io.IOException if an I/O error occurs * @see java.io.DataInputStream#readLong() * @see Double#longBitsToDouble(long) */ @Override public double readDouble() throws EOFException { return Double.longBitsToDouble(readLong()); } @Override public double readDouble(int position) throws EOFException { return Double.longBitsToDouble(readLong(position)); } @Override public double readDouble(ByteOrder byteOrder) throws EOFException { return Double.longBitsToDouble(readLong(byteOrder)); } @Override public double readDouble(int position, ByteOrder byteOrder) throws EOFException { return Double.longBitsToDouble(readLong(position, byteOrder)); } /** * See the general contract of the {@code readFloat} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return the next four bytes of this input stream, interpreted as a {@code float} * @throws java.io.EOFException if this input stream reaches the end before reading four bytes * @throws java.io.IOException if an I/O error occurs * @see java.io.DataInputStream#readInt() * @see Float#intBitsToFloat(int) */ @Override public float readFloat() throws EOFException { return Float.intBitsToFloat(readInt()); } @Override public float readFloat(int position) throws EOFException { return Float.intBitsToFloat(readInt(position)); } @Override public float readFloat(ByteOrder byteOrder) throws EOFException { return Float.intBitsToFloat(readInt(byteOrder)); } @Override public float readFloat(int position, ByteOrder byteOrder) throws EOFException { return Float.intBitsToFloat(readInt(position, byteOrder)); } @Override public void readFully(final byte[] b) throws IOException { if (read(b) == -1) { throw new EOFException("End of stream reached"); } } @Override public void readFully(final byte[] b, final int off, final int len) throws EOFException { if (read(b, off, len) == -1) { throw new EOFException("End of stream reached"); } } /** * See the general contract of the {@code readInt} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return the next four bytes of this input stream, interpreted as an {@code int} * @throws java.io.EOFException if this input stream reaches the end before reading four bytes * @throws java.io.IOException if an I/O error occurs * @see java.io.FilterInputStream#in */ @Override public final int readInt() throws EOFException { final int i = readInt(pos); pos += INT_SIZE_IN_BYTES; return i; } public int readInt(int position) throws EOFException { checkAvailable(position, INT_SIZE_IN_BYTES); return Bits.readInt(data, position, bigEndian); } @Override public final int readInt(ByteOrder byteOrder) throws EOFException { final int i = readInt(pos, byteOrder); pos += INT_SIZE_IN_BYTES; return i; } @Override public int readInt(int position, ByteOrder byteOrder) throws EOFException { checkAvailable(position, INT_SIZE_IN_BYTES); return Bits.readInt(data, position, byteOrder == ByteOrder.BIG_ENDIAN); } @Override public final String readLine() { throw new UnsupportedOperationException(); } /** * See the general contract of the {@code readLong} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return the next eight bytes of this input stream, interpreted as a {@code long} * @throws java.io.EOFException if this input stream reaches the end before reading eight bytes * @throws java.io.IOException if an I/O error occurs * @see java.io.FilterInputStream#in */ @Override public final long readLong() throws EOFException { final long l = readLong(pos); pos += LONG_SIZE_IN_BYTES; return l; } public long readLong(int position) throws EOFException { checkAvailable(position, LONG_SIZE_IN_BYTES); return Bits.readLong(data, position, bigEndian); } @Override public final long readLong(ByteOrder byteOrder) throws EOFException { final long l = readLong(pos, byteOrder); pos += LONG_SIZE_IN_BYTES; return l; } @Override public long readLong(int position, ByteOrder byteOrder) throws EOFException { checkAvailable(position, LONG_SIZE_IN_BYTES); return Bits.readLong(data, position, byteOrder == ByteOrder.BIG_ENDIAN); } /** * See the general contract of the {@code readShort} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return the next two bytes of this input stream, interpreted as a signed 16-bit number * @throws java.io.EOFException if this input stream reaches the end before reading two bytes * @throws java.io.IOException if an I/O error occurs * @see java.io.FilterInputStream#in */ @Override public final short readShort() throws EOFException { short s = readShort(pos); pos += SHORT_SIZE_IN_BYTES; return s; } @Override public short readShort(int position) throws EOFException { checkAvailable(position, SHORT_SIZE_IN_BYTES); return Bits.readShort(data, position, bigEndian); } @Override public final short readShort(ByteOrder byteOrder) throws EOFException { short s = readShort(pos, byteOrder); pos += SHORT_SIZE_IN_BYTES; return s; } @Override public short readShort(int position, ByteOrder byteOrder) throws EOFException { checkAvailable(position, SHORT_SIZE_IN_BYTES); return Bits.readShort(data, position, byteOrder == ByteOrder.BIG_ENDIAN); } @Override @Nullable public byte[] readByteArray() throws IOException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { byte[] b = new byte[len]; readFully(b); return b; } return EMPTY_BYTE_ARRAY; } @Override @Nullable public boolean[] readBooleanArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { boolean[] values = new boolean[len]; for (int i = 0; i < len; i++) { values[i] = readBoolean(); } return values; } return new boolean[0]; } @Override @Nullable public char[] readCharArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { char[] values = new char[len]; for (int i = 0; i < len; i++) { values[i] = readChar(); } return values; } return new char[0]; } @Override @Nullable public int[] readIntArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { int[] values = new int[len]; for (int i = 0; i < len; i++) { values[i] = readInt(); } return values; } return new int[0]; } @Override @Nullable public long[] readLongArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { long[] values = new long[len]; for (int i = 0; i < len; i++) { values[i] = readLong(); } return values; } return new long[0]; } @Override @Nullable public double[] readDoubleArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { double[] values = new double[len]; for (int i = 0; i < len; i++) { values[i] = readDouble(); } return values; } return new double[0]; } @Override @Nullable public float[] readFloatArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { float[] values = new float[len]; for (int i = 0; i < len; i++) { values[i] = readFloat(); } return values; } return new float[0]; } @Override @Nullable public short[] readShortArray() throws EOFException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { short[] values = new short[len]; for (int i = 0; i < len; i++) { values[i] = readShort(); } return values; } return new short[0]; } @Override @Nullable @Deprecated public String[] readUTFArray() throws IOException { return readStringArray(); } @Override @Nullable public String[] readStringArray() throws IOException { int len = readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len > 0) { String[] values = new String[len]; for (int i = 0; i < len; i++) { values[i] = readString(); } return values; } return new String[0]; } /** * See the general contract of the {@code readUnsignedByte} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return the next byte of this input stream, interpreted as an unsigned 8-bit number * @throws java.io.EOFException if this input stream has reached the end * @throws java.io.IOException if an I/O error occurs * @see java.io.FilterInputStream#in */ @Override public int readUnsignedByte() throws EOFException { return readByte() & 0xFF; } /** * See the general contract of the {@code readUnsignedShort} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return the next two bytes of this input stream, interpreted as an unsigned 16-bit integer * @throws java.io.EOFException if this input stream reaches the end before reading two bytes * @throws java.io.IOException if an I/O error occurs * @see java.io.FilterInputStream#in */ @Override public int readUnsignedShort() throws EOFException { return readShort() & 0xffff; } /** * See the general contract of the {@code readUTF} method of {@code DataInput}. * <p> * Bytes for this operation are read from the contained input stream. * * @return a Unicode string. * @throws java.io.EOFException if this input stream reaches the end before reading all the bytes * @throws java.io.IOException if an I/O error occurs * @throws java.io.UTFDataFormatException if the bytes do not represent a valid modified UTF-8 encoding of a string * @see java.io.DataInputStream#readUTF(java.io.DataInput) */ @Override @Deprecated public final String readUTF() throws IOException { return readString(); } @Nullable @Override public String readString() throws IOException { int numberOfBytes = readInt(); if (numberOfBytes == NULL_ARRAY_LENGTH) { return null; } String result = new String(data, pos, numberOfBytes, StandardCharsets.UTF_8); pos += numberOfBytes; return result; } @Override @Nullable public final Object readObject() throws EOFException { return service.readObject(this); } @Override @Nullable public <T> T readObject(Class aClass) throws IOException { return service.readObject(this, aClass); } @Override @Nullable public <T> T readDataAsObject() throws IOException { // a future optimization would be to skip the construction of the Data object Data data = readData(); return data == null ? null : (T) service.toObject(data); } @Override @Nullable public final Data readData() throws IOException { byte[] bytes = readByteArray(); return bytes == null ? null : new HeapData(bytes); } @Override public final long skip(long n) { if (n <= 0 || n >= Integer.MAX_VALUE) { return 0L; } return skipBytes((int) n); } @Override public final int skipBytes(final int n) { if (n <= 0) { return 0; } int skip = n; final int pos = position(); if (pos + skip > size) { skip = size - pos; } position(pos + skip); return skip; } /** * Returns this buffer's position. */ @Override public final int position() { return pos; } @Override public final void position(int newPos) { if ((newPos > size) || (newPos < 0)) { throw new IllegalArgumentException(); } pos = newPos; if (mark > pos) { mark = -1; } } final void checkAvailable(int pos, int k) throws EOFException { if (pos < 0) { throw new IllegalArgumentException("Negative pos! -> " + pos); } if ((size - pos) < k) { throw new EOFException("Cannot read " + k + " bytes!"); } } @Override public final int available() { return size - pos; } @Override public final boolean markSupported() { return true; } @Override public final void mark(int readlimit) { mark = pos; } @Override public final void reset() { pos = mark; } @Override public final void close() { data = null; charBuffer = null; } @Override public final ClassLoader getClassLoader() { return service.getClassLoader(); } @Override public InternalSerializationService getSerializationService() { return service; } public ByteOrder getByteOrder() { return bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; } @Override public String toString() { return "ByteArrayObjectDataInput{" + "size=" + size + ", pos=" + pos + ", mark=" + mark + '}'; } }
apache-2.0
groupe-sii/ogham
ogham-test-classpath/src/main/java/fr/sii/ogham/test/classpath/runner/util/SourceUtils.java
1293
package fr.sii.ogham.test.classpath.runner.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; public class SourceUtils { public static void copy(String resourceFolder, Path generatedProjectPath) throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceFolder + "/**"); for (Resource resource : resources) { if (resource.exists() && resource.isReadable() && resource.contentLength() > 0) { URL url = resource.getURL(); String urlString = url.toExternalForm(); String targetName = urlString.substring(urlString.indexOf(resourceFolder) + resourceFolder.length() + 1); Path destination = generatedProjectPath.resolve(targetName); Files.createDirectories(destination.getParent()); try (InputStream source = resource.getInputStream()) { Files.copy(source, destination); } } } } private SourceUtils() { super(); } }
apache-2.0
luiz/vraptor-html-dsl
src/main/java/br/com/caelum/vraptor/html/tags/P.java
1124
package br.com.caelum.vraptor.html.tags; import br.com.caelum.vraptor.html.attributes.Attribute; import br.com.caelum.vraptor.html.tags.interfaces.NestedElement; import br.com.caelum.vraptor.html.tags.interfaces.Tag; import br.com.caelum.vraptor.html.transformers.DefaultTagTransformer; import br.com.caelum.vraptor.html.transformers.TagTransformer; public class P implements Tag { private NestedElement[] children = new NestedElement[0]; private final Attribute[] attributes; private final TagTransformer tagTransformer = new DefaultTagTransformer(); public P(Attribute... attributes) { this.attributes = attributes; } public Attribute[] getAttributes() { return this.attributes; } public NestedElement[] getChildren() { return this.children; } public String toHtml() { return tagTransformer.transform(this); } public Tag with(NestedElement... children) { this.children = children; return this; } public Tag with(java.lang.Object content) { return with(new Text(content)); } public Tag with(NestedElement child) { this.children = new NestedElement[] { child }; return this; } }
apache-2.0
messaginghub/pooled-jms
pooled-jms/src/main/java/org/messaginghub/pooled/jms/JmsPoolQueueBrowser.java
2840
/* * 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.messaginghub.pooled.jms; import java.util.Enumeration; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.IllegalStateException; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueBrowser; /** * A {@link QueueBrowser} which was created by {@link JmsPoolSession}. */ public class JmsPoolQueueBrowser implements QueueBrowser, AutoCloseable { private final AtomicBoolean closed = new AtomicBoolean(); private final JmsPoolSession session; private final QueueBrowser delegate; /** * Wraps the QueueBrowser. * * @param session * the pooled session that created this object. * @param delegate * the created QueueBrowser to wrap. */ public JmsPoolQueueBrowser(JmsPoolSession session, QueueBrowser delegate) { this.session = session; this.delegate = delegate; } @Override public Queue getQueue() throws JMSException { checkClosed(); return delegate.getQueue(); } @Override public String getMessageSelector() throws JMSException { checkClosed(); return delegate.getMessageSelector(); } @Override public Enumeration<?> getEnumeration() throws JMSException { checkClosed(); return delegate.getEnumeration(); } @Override public void close() throws JMSException { if (closed.compareAndSet(false, true)) { // ensure session removes browser from it's list of managed resources. session.onQueueBrowserClose(this); delegate.close(); } } @Override public String toString() { return getClass().getSimpleName() + " { " + delegate + " }"; } public QueueBrowser getQueueBrowser() throws JMSException { checkClosed(); return delegate; } private void checkClosed() throws IllegalStateException { if (closed.get()) { throw new IllegalStateException("The QueueBrowser is closed"); } } }
apache-2.0
Kiosani/OpenGTS
src/org/opengts/db/GeoEvent.java
18000
// ---------------------------------------------------------------------------- // Copyright 2007-2017, GeoTelematic Solutions, Inc. // All rights reserved // ---------------------------------------------------------------------------- // // 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. // // ---------------------------------------------------------------------------- // Description: // A container for a generic GPS event // ---------------------------------------------------------------------------- // Change History: // 2010/07/18 Martin D. Flynn // -Initial release // ---------------------------------------------------------------------------- package org.opengts.db; import java.util.*; import org.opengts.util.*; import org.opengts.dbtools.*; import org.opengts.db.tables.*; /** *** A container for a single generic GPS event **/ public class GeoEvent implements Cloneable, GeoPointProvider { // ------------------------------------------------------------------------ /** *** Interface for GeoEvent handler call-backs **/ public static interface GeoEventHandler { public int handleGeoEvent(GeoEvent gev); } // ------------------------------------------------------------------------ /* standard event field types */ public static final String KEY_mobileID = "mobileID"; public static final String KEY_accountID = EventData.FLD_accountID; public static final String KEY_account = "account"; public static final String KEY_deviceID = EventData.FLD_deviceID; public static final String KEY_device = "device"; public static final String KEY_geozoneID = EventData.FLD_geozoneID; public static final String KEY_geozone = "geozone"; public static final String KEY_timestamp = EventData.FLD_timestamp; public static final String KEY_statusCode = EventData.FLD_statusCode; public static final String KEY_latitude = EventData.FLD_latitude; public static final String KEY_longitude = EventData.FLD_longitude; public static final String KEY_geoPoint = "geoPoint"; public static final String KEY_speedKPH = EventData.FLD_speedKPH; public static final String KEY_heading = EventData.FLD_heading; public static final String KEY_altitude = EventData.FLD_altitude; public static final String KEY_odometerKM = EventData.FLD_odometerKM; // ------------------------------------------------------------------------ private Map<String,Object> fieldValues = null; /** *** Constructor **/ public GeoEvent() { this.fieldValues = new HashMap<String,Object>(); } /** *** Copy Constructor **/ public GeoEvent(GeoEvent other) { this(); if (other != null) { this.fieldValues.putAll(other.getFieldValues()); } } // ------------------------------------------------------------------------ /** *** Retruns a clone of this GeoEvent instance *** @return A clone of this GeoEvent **/ public Object clone() { return new GeoEvent(this); } // ------------------------------------------------------------------------ /** *** Gets a String representation of this instance **/ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[" + new DateTime(this.getTimestamp()) + "] "); sb.append(StringTools.format(this.getLatitude(),"0.00000")); sb.append("/"); sb.append(StringTools.format(this.getLongitude(),"0.00000")); sb.append(" "); sb.append(StringTools.format(this.getAltitudeMeters(),"0") + " m"); return sb.toString(); } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ /** *** Gets the field keys **/ public Set<String> getFieldKeys() { return this.fieldValues.keySet(); } /** *** Gets the field values **/ public Map<String,Object> getFieldValues() { return this.fieldValues; } /** *** Sets a field value **/ public void setFieldValue(String key, Object val) { if (!StringTools.isBlank(key)) { Map<String,Object> fv = this.getFieldValues(); if (val != null) { fv.put(key, val); } else { fv.remove(key); } } } /** *** Gets a Object field value **/ public Object getFieldValue(String key, Object dft) { Object fv = (key != null)? this.getFieldValues().get(key) : null; if (fv != null) { return (dft instanceof String)? fv.toString() : fv; } else { return dft; } } /** *** Returns true if the field value has been defined **/ public boolean hasFieldValue(String key) { return this.fieldValues.containsKey(key); } // ------------------------------------------------------------------------ /** *** Sets a Integer field value **/ public void setFieldValue(String key, int val) { this.setFieldValue(key, (Object)(new Integer(val))); } /** *** Gets a Integer field value **/ public int getFieldValue(String key, int dft) { Object fv = this.getFieldValue(key,null); return (fv instanceof Number)? ((Number)fv).intValue() : dft; } /** *** Sets a Long field value **/ public void setFieldValue(String key, long val) { this.setFieldValue(key, (Object)(new Long(val))); } /** *** Gets a Long field value **/ public long getFieldValue(String key, long dft) { Object fv = this.getFieldValue(key,null); return (fv instanceof Number)? ((Number)fv).longValue() : dft; } /** *** Sets a Double field value **/ public void setFieldValue(String key, double val) { this.setFieldValue(key, (Object)(new Double(val))); } /** *** Gets a Double field value **/ public double getFieldValue(String key, double dft) { Object fv = this.getFieldValue(key,null); return (fv instanceof Number)? ((Number)fv).doubleValue() : dft; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ /** *** Sets the MobileID **/ public void setMobileID(String mobileID) { this.setFieldValue(KEY_mobileID, mobileID); } /** *** Gets the MobileID **/ public String getMobileID() { return (String)this.getFieldValue(KEY_mobileID, null); } /** *** Returns true if an MobileID has been defined **/ public boolean hasMobileID() { return this.hasFieldValue(KEY_mobileID); } // ------------------------------------------------------------------------ /** *** Sets the AccountID **/ public void setAccountID(String accountID) { this.setFieldValue(KEY_accountID, accountID); if (StringTools.isBlank(accountID)) { this.setAccount(null); this.setDevice(null); this.setGeozone(null); } else { Account acct = this.getAccount(); if ((acct != null) && !accountID.equals(acct.getAccountID())) { this.setAccount(null); this.setDevice(null); this.setGeozone(null); } } } /** *** Gets the AccountID **/ public String getAccountID() { return (String)this.getFieldValue(KEY_accountID, null); } /** *** Returns true if an AccountID has been defined **/ public boolean hasAccountID() { return this.hasFieldValue(KEY_accountID); } /** *** Sets the Account **/ public void setAccount(Account account) { this.setFieldValue(KEY_account, account); if (account != null) { this.setFieldValue(KEY_accountID, account.getAccountID()); } } /** *** Gets the Account **/ public Account getAccount() { return (Account)this.getFieldValue(KEY_account, null); } /** *** Returns true if an Account has been defined **/ public boolean hasAccount() { return this.hasFieldValue(KEY_account); } // ------------------------------------------------------------------------ /** *** Sets the DeviceID **/ public void setDeviceID(String deviceID) { this.setFieldValue(KEY_deviceID, deviceID); if (StringTools.isBlank(deviceID)) { this.setDevice(null); } else { Device dev = this.getDevice(); if ((dev != null) && !deviceID.equals(dev.getDeviceID())) { this.setDevice(null); } } } /** *** Gets the DeviceID **/ public String getDeviceID() { return (String)this.getFieldValue(KEY_deviceID, null); } /** *** Returns true if a DeviceID has been defined **/ public boolean hasDeviceID() { return this.hasFieldValue(KEY_deviceID); } /** *** Sets the Device **/ public void setDevice(Device device) { this.setFieldValue(KEY_device, device); if (device != null) { this.setFieldValue(KEY_accountID, device.getAccountID()); this.setFieldValue(KEY_deviceID , device.getDeviceID()); } } /** *** Gets the Device **/ public Device getDevice() { return (Device)this.getFieldValue(KEY_device, null); } /** *** Returns true if a Device has been defined **/ public boolean hasDevice() { return this.hasFieldValue(KEY_device); } // ------------------------------------------------------------------------ /** *** Sets the GeozoneID **/ public void setGeozoneID(String geozoneID) { this.setFieldValue(KEY_geozoneID, geozoneID); if (StringTools.isBlank(geozoneID)) { this.setGeozone(null); } else { Geozone geoz = this.getGeozone(); if ((geoz != null) && !geozoneID.equals(geoz.getGeozoneID())) { this.setGeozone(null); } } } /** *** Gets the GeozoneID **/ public String getGeozoneID() { return (String)this.getFieldValue(KEY_geozoneID, null); } /** *** Returns true if a GeozoneID has been defined **/ public boolean hasGeozoneID() { return this.hasFieldValue(KEY_geozoneID); } /** *** Sets the Geozone **/ public void setGeozone(Geozone geozone) { this.setFieldValue(KEY_geozone, geozone); if (geozone != null) { this.setFieldValue(KEY_geozoneID, geozone.getGeozoneID()); } } /** *** Gets the Geozone **/ public Geozone getGeozone() { return (Geozone)this.getFieldValue(KEY_geozone, null); } /** *** Returns true if a Geozone has been defined **/ public boolean hasGeozone() { return this.hasFieldValue(KEY_geozone); } // ------------------------------------------------------------------------ /** *** Sets the timestamp **/ public void setTimestamp(long ts) { this.setFieldValue(KEY_timestamp, ((ts > 0L)? ts : 0L)); } /** *** Gets the timestamp **/ public long getTimestamp() { return this.getFieldValue(KEY_timestamp, 0L); } /** *** Returns true if a timestamp has been defined **/ public boolean hasTimestamp() { return this.hasFieldValue(KEY_timestamp); } // ------------------------------------------------------------------------ /** *** Sets the StatusCode **/ public void setStatusCode(int sc) { this.setFieldValue(KEY_statusCode, ((sc > 0)? sc : 0)); } /** *** Gets the StatusCode **/ public int getStatusCode() { return this.getFieldValue(KEY_statusCode, 0); } /** *** Returns true if a StatusCode has been defined **/ public boolean hasStatusCode() { return this.hasFieldValue(KEY_statusCode); } // ------------------------------------------------------------------------ /** *** Sets the GeoPoint **/ public void setGeoPoint(double lat, double lon) { this.setFieldValue(KEY_latitude , lat); this.setFieldValue(KEY_longitude, lon); this.setFieldValue(KEY_geoPoint , null); } /** *** Sets the GeoPoint **/ public void setGeoPoint(GeoPoint gp) { if (gp != null) { this.setFieldValue(KEY_latitude , gp.getLatitude()); this.setFieldValue(KEY_longitude, gp.getLongitude()); this.setFieldValue(KEY_geoPoint , gp); } else { this.setFieldValue(KEY_latitude , null); this.setFieldValue(KEY_longitude, null); this.setFieldValue(KEY_geoPoint , null); } } /** *** Returns true if the current GeoPoint is valie **/ public boolean isGeoPointValid() { if (this.hasGeoPoint()) { return GeoPoint.isValid(this.getLatitude(),this.getLongitude()); } else { return false; } } /** *** Sets the latitude **/ public void setLatitude(double lat) { this.setFieldValue(KEY_latitude , lat); this.setFieldValue(KEY_geoPoint , null); } /** *** Gets the latitude **/ public double getLatitude() { return this.getFieldValue(KEY_latitude, 0.0); } /** *** Returns true if a latitude has been defined **/ public boolean hasLatitude() { return this.hasFieldValue(KEY_latitude); } /** *** Sets the longitude **/ public void setLongitude(double lon) { this.setFieldValue(KEY_longitude, lon); this.setFieldValue(KEY_geoPoint , null); } /** *** Gets the longitude **/ public double getLongitude() { return this.getFieldValue(KEY_longitude, 0.0); } /** *** Returns true if a longitude has been defined **/ public boolean hasLongitude() { return this.hasFieldValue(KEY_longitude); } /** *** Gets the GeoPoint **/ public GeoPoint getGeoPoint() { GeoPoint gp = (GeoPoint)this.getFieldValue(KEY_geoPoint, null); if (gp == null) { gp = new GeoPoint(this.getLatitude(),this.getLongitude()); this.setFieldValue(KEY_geoPoint, gp); } return gp; } /** *** Returns true if a latitude/longitude has been defined **/ public boolean hasGeoPoint() { return this.hasLatitude() && this.hasLongitude(); } // ------------------------------------------------------------------------ /** *** Sets the Speed **/ public void setSpeedKPH(double kph) { this.setFieldValue(KEY_speedKPH, ((kph >= 0.0)? kph : 0.0)); } /** *** Gets the Speed **/ public double getSpeedKPH() { return this.getFieldValue(KEY_speedKPH, 0.0); } /** *** Returns true if a speed has been defined **/ public boolean hasSpeedKPH() { return this.hasFieldValue(KEY_speedKPH); } // ------------------------------------------------------------------------ /** *** Sets the Heading **/ public void setHeading(double deg) { this.setFieldValue(KEY_heading, ((deg >= 0.0)? deg : 0.0)); } /** *** Gets the Heading **/ public double getHeading() { return this.getFieldValue(KEY_heading, 0.0); } /** *** Returns true if a speed has been defined **/ public boolean hasHeading() { return this.hasFieldValue(KEY_heading); } // ------------------------------------------------------------------------ /** *** Sets the Altitude **/ public void setAltitudeMeters(double altM) { this.setFieldValue(KEY_altitude, altM); } /** *** Gets the Altitude **/ public double getAltitudeMeters() { return this.getFieldValue(KEY_altitude, 0.0); } /** *** Returns true if a speed has been defined **/ public boolean hasAltitudeMeters() { return this.hasFieldValue(KEY_altitude); } // ------------------------------------------------------------------------ /** *** Sets the Odometer **/ public void setOdometerKM(double km) { this.setFieldValue(KEY_odometerKM, km); } /** *** Gets the Odometer **/ public double getOdometerKM() { return this.getFieldValue(KEY_odometerKM, 0.0); } /** *** Returns true if an Odometer has been defined **/ public boolean hasOdometerKM() { return this.hasFieldValue(KEY_odometerKM); } // ------------------------------------------------------------------------ }
apache-2.0
weiwenqiang/GitHub
ListView/MultiTypeAdapter-master/app/src/androidTest/java/com/wenld/multitypeadapter/ExampleInstrumentedTest.java
756
package com.wenld.multitypeadapter; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.wenld.multitypeadapter", appContext.getPackageName()); } }
apache-2.0
weiwenqiang/GitHub
expert/greenDAO/tests/DaoTestBase/src/main/java/org/greenrobot/greendao/daotest/customtype/MyTimestampConverter.java
546
package org.greenrobot.greendao.daotest.customtype; import org.greenrobot.greendao.converter.PropertyConverter; public class MyTimestampConverter implements PropertyConverter<MyTimestamp, Long> { @Override public MyTimestamp convertToEntityProperty(Long databaseValue) { MyTimestamp myTimestamp = new MyTimestamp(); myTimestamp.timestamp=databaseValue; return myTimestamp; } @Override public Long convertToDatabaseValue(MyTimestamp entityProperty) { return entityProperty.timestamp; } }
apache-2.0
cboehme/metafacture-core
metafacture-io/src/test/java/org/metafacture/io/ObjectStdoutWriterTest.java
1438
/* * Copyright 2016 Christoph Böhme * * 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.metafacture.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import org.junit.Before; /** * Tests for class {@link ObjectStdoutWriter}. * * @author Christoph Böhme * */ public final class ObjectStdoutWriterTest extends AbstractConfigurableObjectWriterTest { private ObjectStdoutWriter<String> writer; private ByteArrayOutputStream stdoutBuffer; @Before public void setup() { writer = new ObjectStdoutWriter<String>(); // Redirect standard out: stdoutBuffer = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdoutBuffer)); } @Override protected ConfigurableObjectWriter<String> getWriter() { return writer; } @Override protected String getOutput() throws IOException { System.out.flush(); return stdoutBuffer.toString(); } }
apache-2.0
akarnokd/RxJava
src/main/java/io/reactivex/parallel/ParallelFlowable.java
41225
/** * Copyright (c) 2016-present, RxJava 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. */ package io.reactivex.parallel; import java.util.*; import java.util.concurrent.Callable; import io.reactivex.*; import io.reactivex.annotations.*; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.*; import io.reactivex.internal.functions.*; import io.reactivex.internal.operators.parallel.*; import io.reactivex.internal.subscriptions.EmptySubscription; import io.reactivex.internal.util.*; import io.reactivex.plugins.RxJavaPlugins; import org.reactivestreams.*; /** * Abstract base class for Parallel publishers that take an array of Subscribers. * <p> * Use {@code from()} to start processing a regular Publisher in 'rails'. * Use {@code runOn()} to introduce where each 'rail' should run on thread-vise. * Use {@code sequential()} to merge the sources back into a single Flowable. * * <p>History: 2.0.5 - experimental * @param <T> the value type * @since 2.1 - beta */ @Beta public abstract class ParallelFlowable<T> { /** * Subscribes an array of Subscribers to this ParallelFlowable and triggers * the execution chain for all 'rails'. * * @param subscribers the subscribers array to run in parallel, the number * of items must be equal to the parallelism level of this ParallelFlowable * @see #parallelism() */ public abstract void subscribe(@NonNull Subscriber<? super T>[] subscribers); /** * Returns the number of expected parallel Subscribers. * @return the number of expected parallel Subscribers */ public abstract int parallelism(); /** * Validates the number of subscribers and returns true if their number * matches the parallelism level of this ParallelFlowable. * * @param subscribers the array of Subscribers * @return true if the number of subscribers equals to the parallelism level */ protected final boolean validate(@NonNull Subscriber<?>[] subscribers) { int p = parallelism(); if (subscribers.length != p) { Throwable iae = new IllegalArgumentException("parallelism = " + p + ", subscribers = " + subscribers.length); for (Subscriber<?> s : subscribers) { EmptySubscription.error(iae, s); } return false; } return true; } /** * Take a Publisher and prepare to consume it on multiple 'rails' (number of CPUs) * in a round-robin fashion. * @param <T> the value type * @param source the source Publisher * @return the ParallelFlowable instance */ @CheckReturnValue public static <T> ParallelFlowable<T> from(@NonNull Publisher<? extends T> source) { return from(source, Runtime.getRuntime().availableProcessors(), Flowable.bufferSize()); } /** * Take a Publisher and prepare to consume it on parallelism number of 'rails' in a round-robin fashion. * @param <T> the value type * @param source the source Publisher * @param parallelism the number of parallel rails * @return the new ParallelFlowable instance */ @CheckReturnValue public static <T> ParallelFlowable<T> from(@NonNull Publisher<? extends T> source, int parallelism) { return from(source, parallelism, Flowable.bufferSize()); } /** * Take a Publisher and prepare to consume it on parallelism number of 'rails' , * possibly ordered and round-robin fashion and use custom prefetch amount and queue * for dealing with the source Publisher's values. * @param <T> the value type * @param source the source Publisher * @param parallelism the number of parallel rails * @param prefetch the number of values to prefetch from the source * the source until there is a rail ready to process it. * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public static <T> ParallelFlowable<T> from(@NonNull Publisher<? extends T> source, int parallelism, int prefetch) { ObjectHelper.requireNonNull(source, "source"); ObjectHelper.verifyPositive(parallelism, "parallelism"); ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new ParallelFromPublisher<T>(source, parallelism, prefetch)); } /** * Calls the specified converter function during assembly time and returns its resulting value. * <p> * This allows fluent conversion to any other type. * * @param <R> the resulting object type * @param converter the function that receives the current ParallelFlowable instance and returns a value * @return the converted value * @throws NullPointerException if converter is null * @since 2.1.7 - experimental */ @Experimental @CheckReturnValue @NonNull public final <R> R as(@NonNull ParallelFlowableConverter<T, R> converter) { return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); } /** * Maps the source values on each 'rail' to another value. * <p> * Note that the same mapper function may be called from multiple threads concurrently. * @param <R> the output value type * @param mapper the mapper function turning Ts into Us. * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> map(@NonNull Function<? super T, ? extends R> mapper) { ObjectHelper.requireNonNull(mapper, "mapper"); return RxJavaPlugins.onAssembly(new ParallelMap<T, R>(this, mapper)); } /** * Maps the source values on each 'rail' to another value and * handles errors based on the given {@link ParallelFailureHandling} enumeration value. * <p> * Note that the same mapper function may be called from multiple threads concurrently. * @param <R> the output value type * @param mapper the mapper function turning Ts into Us. * @param errorHandler the enumeration that defines how to handle errors thrown * from the mapper function * @return the new ParallelFlowable instance * @since 2.0.8 - experimental */ @CheckReturnValue @Experimental @NonNull public final <R> ParallelFlowable<R> map(@NonNull Function<? super T, ? extends R> mapper, @NonNull ParallelFailureHandling errorHandler) { ObjectHelper.requireNonNull(mapper, "mapper"); ObjectHelper.requireNonNull(errorHandler, "errorHandler is null"); return RxJavaPlugins.onAssembly(new ParallelMapTry<T, R>(this, mapper, errorHandler)); } /** * Maps the source values on each 'rail' to another value and * handles errors based on the returned value by the handler function. * <p> * Note that the same mapper function may be called from multiple threads concurrently. * @param <R> the output value type * @param mapper the mapper function turning Ts into Us. * @param errorHandler the function called with the current repeat count and * failure Throwable and should return one of the {@link ParallelFailureHandling} * enumeration values to indicate how to proceed. * @return the new ParallelFlowable instance * @since 2.0.8 - experimental */ @CheckReturnValue @Experimental @NonNull public final <R> ParallelFlowable<R> map(@NonNull Function<? super T, ? extends R> mapper, @NonNull BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { ObjectHelper.requireNonNull(mapper, "mapper"); ObjectHelper.requireNonNull(errorHandler, "errorHandler is null"); return RxJavaPlugins.onAssembly(new ParallelMapTry<T, R>(this, mapper, errorHandler)); } /** * Filters the source values on each 'rail'. * <p> * Note that the same predicate may be called from multiple threads concurrently. * @param predicate the function returning true to keep a value or false to drop a value * @return the new ParallelFlowable instance */ @CheckReturnValue public final ParallelFlowable<T> filter(@NonNull Predicate<? super T> predicate) { ObjectHelper.requireNonNull(predicate, "predicate"); return RxJavaPlugins.onAssembly(new ParallelFilter<T>(this, predicate)); } /** * Filters the source values on each 'rail' and * handles errors based on the given {@link ParallelFailureHandling} enumeration value. * <p> * Note that the same predicate may be called from multiple threads concurrently. * @param predicate the function returning true to keep a value or false to drop a value * @param errorHandler the enumeration that defines how to handle errors thrown * from the predicate * @return the new ParallelFlowable instance * @since 2.0.8 - experimental */ @CheckReturnValue @Experimental public final ParallelFlowable<T> filter(@NonNull Predicate<? super T> predicate, @NonNull ParallelFailureHandling errorHandler) { ObjectHelper.requireNonNull(predicate, "predicate"); ObjectHelper.requireNonNull(errorHandler, "errorHandler is null"); return RxJavaPlugins.onAssembly(new ParallelFilterTry<T>(this, predicate, errorHandler)); } /** * Filters the source values on each 'rail' and * handles errors based on the returned value by the handler function. * <p> * Note that the same predicate may be called from multiple threads concurrently. * @param predicate the function returning true to keep a value or false to drop a value * @param errorHandler the function called with the current repeat count and * failure Throwable and should return one of the {@link ParallelFailureHandling} * enumeration values to indicate how to proceed. * @return the new ParallelFlowable instance * @since 2.0.8 - experimental */ @CheckReturnValue @Experimental public final ParallelFlowable<T> filter(@NonNull Predicate<? super T> predicate, @NonNull BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { ObjectHelper.requireNonNull(predicate, "predicate"); ObjectHelper.requireNonNull(errorHandler, "errorHandler is null"); return RxJavaPlugins.onAssembly(new ParallelFilterTry<T>(this, predicate, errorHandler)); } /** * Specifies where each 'rail' will observe its incoming values with * no work-stealing and default prefetch amount. * <p> * This operator uses the default prefetch size returned by {@code Flowable.bufferSize()}. * <p> * The operator will call {@code Scheduler.createWorker()} as many * times as this ParallelFlowable's parallelism level is. * <p> * No assumptions are made about the Scheduler's parallelism level, * if the Scheduler's parallelism level is lower than the ParallelFlowable's, * some rails may end up on the same thread/worker. * <p> * This operator doesn't require the Scheduler to be trampolining as it * does its own built-in trampolining logic. * * @param scheduler the scheduler to use * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> runOn(@NonNull Scheduler scheduler) { return runOn(scheduler, Flowable.bufferSize()); } /** * Specifies where each 'rail' will observe its incoming values with * possibly work-stealing and a given prefetch amount. * <p> * This operator uses the default prefetch size returned by {@code Flowable.bufferSize()}. * <p> * The operator will call {@code Scheduler.createWorker()} as many * times as this ParallelFlowable's parallelism level is. * <p> * No assumptions are made about the Scheduler's parallelism level, * if the Scheduler's parallelism level is lower than the ParallelFlowable's, * some rails may end up on the same thread/worker. * <p> * This operator doesn't require the Scheduler to be trampolining as it * does its own built-in trampolining logic. * * @param scheduler the scheduler to use * that rail's worker has run out of work. * @param prefetch the number of values to request on each 'rail' from the source * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> runOn(@NonNull Scheduler scheduler, int prefetch) { ObjectHelper.requireNonNull(scheduler, "scheduler"); ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new ParallelRunOn<T>(this, scheduler, prefetch)); } /** * Reduces all values within a 'rail' and across 'rails' with a reducer function into a single * sequential value. * <p> * Note that the same reducer function may be called from multiple threads concurrently. * @param reducer the function to reduce two values into one. * @return the new Flowable instance emitting the reduced value or empty if the ParallelFlowable was empty */ @CheckReturnValue @NonNull public final Flowable<T> reduce(@NonNull BiFunction<T, T, T> reducer) { ObjectHelper.requireNonNull(reducer, "reducer"); return RxJavaPlugins.onAssembly(new ParallelReduceFull<T>(this, reducer)); } /** * Reduces all values within a 'rail' to a single value (with a possibly different type) via * a reducer function that is initialized on each rail from an initialSupplier value. * <p> * Note that the same mapper function may be called from multiple threads concurrently. * @param <R> the reduced output type * @param initialSupplier the supplier for the initial value * @param reducer the function to reduce a previous output of reduce (or the initial value supplied) * with a current source value. * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> reduce(@NonNull Callable<R> initialSupplier, @NonNull BiFunction<R, ? super T, R> reducer) { ObjectHelper.requireNonNull(initialSupplier, "initialSupplier"); ObjectHelper.requireNonNull(reducer, "reducer"); return RxJavaPlugins.onAssembly(new ParallelReduce<T, R>(this, initialSupplier, reducer)); } /** * Merges the values from each 'rail' in a round-robin or same-order fashion and * exposes it as a regular Publisher sequence, running with a default prefetch value * for the rails. * <p> * This operator uses the default prefetch size returned by {@code Flowable.bufferSize()}. * <img width="640" height="602" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/parallelflowable.sequential.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequential} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new Flowable instance * @see ParallelFlowable#sequential(int) * @see ParallelFlowable#sequentialDelayError() */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue public final Flowable<T> sequential() { return sequential(Flowable.bufferSize()); } /** * Merges the values from each 'rail' in a round-robin or same-order fashion and * exposes it as a regular Publisher sequence, running with a give prefetch value * for the rails. * <img width="640" height="602" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/parallelflowable.sequential.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequential} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param prefetch the prefetch amount to use for each rail * @return the new Flowable instance * @see ParallelFlowable#sequential() * @see ParallelFlowable#sequentialDelayError(int) */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue @NonNull public final Flowable<T> sequential(int prefetch) { ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new ParallelJoin<T>(this, prefetch, false)); } /** * Merges the values from each 'rail' in a round-robin or same-order fashion and * exposes it as a regular Flowable sequence, running with a default prefetch value * for the rails and delaying errors from all rails till all terminate. * <p> * This operator uses the default prefetch size returned by {@code Flowable.bufferSize()}. * <img width="640" height="602" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/parallelflowable.sequential.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequentialDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @return the new Flowable instance * @see ParallelFlowable#sequentialDelayError(int) * @see ParallelFlowable#sequential() * @since 2.0.7 - experimental */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue @Experimental @NonNull public final Flowable<T> sequentialDelayError() { return sequentialDelayError(Flowable.bufferSize()); } /** * Merges the values from each 'rail' in a round-robin or same-order fashion and * exposes it as a regular Publisher sequence, running with a give prefetch value * for the rails and delaying errors from all rails till all terminate. * <img width="640" height="602" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/parallelflowable.sequential.png" alt=""> * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The operator honors backpressure.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequentialDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param prefetch the prefetch amount to use for each rail * @return the new Flowable instance * @see ParallelFlowable#sequential() * @see ParallelFlowable#sequentialDelayError() * @since 2.0.7 - experimental */ @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) @CheckReturnValue @NonNull public final Flowable<T> sequentialDelayError(int prefetch) { ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new ParallelJoin<T>(this, prefetch, true)); } /** * Sorts the 'rails' of this ParallelFlowable and returns a Publisher that sequentially * picks the smallest next value from the rails. * <p> * This operator requires a finite source ParallelFlowable. * * @param comparator the comparator to use * @return the new Flowable instance */ @CheckReturnValue @NonNull public final Flowable<T> sorted(@NonNull Comparator<? super T> comparator) { return sorted(comparator, 16); } /** * Sorts the 'rails' of this ParallelFlowable and returns a Publisher that sequentially * picks the smallest next value from the rails. * <p> * This operator requires a finite source ParallelFlowable. * * @param comparator the comparator to use * @param capacityHint the expected number of total elements * @return the new Flowable instance */ @CheckReturnValue @NonNull public final Flowable<T> sorted(@NonNull Comparator<? super T> comparator, int capacityHint) { ObjectHelper.requireNonNull(comparator, "comparator is null"); ObjectHelper.verifyPositive(capacityHint, "capacityHint"); int ch = capacityHint / parallelism() + 1; ParallelFlowable<List<T>> railReduced = reduce(Functions.<T>createArrayList(ch), ListAddBiConsumer.<T>instance()); ParallelFlowable<List<T>> railSorted = railReduced.map(new SorterFunction<T>(comparator)); return RxJavaPlugins.onAssembly(new ParallelSortedJoin<T>(railSorted, comparator)); } /** * Sorts the 'rails' according to the comparator and returns a full sorted list as a Publisher. * <p> * This operator requires a finite source ParallelFlowable. * * @param comparator the comparator to compare elements * @return the new Flowable instance */ @CheckReturnValue @NonNull public final Flowable<List<T>> toSortedList(@NonNull Comparator<? super T> comparator) { return toSortedList(comparator, 16); } /** * Sorts the 'rails' according to the comparator and returns a full sorted list as a Publisher. * <p> * This operator requires a finite source ParallelFlowable. * * @param comparator the comparator to compare elements * @param capacityHint the expected number of total elements * @return the new Flowable instance */ @CheckReturnValue @NonNull public final Flowable<List<T>> toSortedList(@NonNull Comparator<? super T> comparator, int capacityHint) { ObjectHelper.requireNonNull(comparator, "comparator is null"); ObjectHelper.verifyPositive(capacityHint, "capacityHint"); int ch = capacityHint / parallelism() + 1; ParallelFlowable<List<T>> railReduced = reduce(Functions.<T>createArrayList(ch), ListAddBiConsumer.<T>instance()); ParallelFlowable<List<T>> railSorted = railReduced.map(new SorterFunction<T>(comparator)); Flowable<List<T>> merged = railSorted.reduce(new MergerBiFunction<T>(comparator)); return RxJavaPlugins.onAssembly(merged); } /** * Call the specified consumer with the current element passing through any 'rail'. * * @param onNext the callback * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> doOnNext(@NonNull Consumer<? super T> onNext) { ObjectHelper.requireNonNull(onNext, "onNext is null"); return RxJavaPlugins.onAssembly(new ParallelPeek<T>(this, onNext, Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.EMPTY_ACTION, Functions.EMPTY_ACTION, Functions.emptyConsumer(), Functions.EMPTY_LONG_CONSUMER, Functions.EMPTY_ACTION )); } /** * Call the specified consumer with the current element passing through any 'rail' and * handles errors based on the given {@link ParallelFailureHandling} enumeration value. * * @param onNext the callback * @param errorHandler the enumeration that defines how to handle errors thrown * from the onNext consumer * @return the new ParallelFlowable instance * @since 2.0.8 - experimental */ @CheckReturnValue @Experimental @NonNull public final ParallelFlowable<T> doOnNext(@NonNull Consumer<? super T> onNext, @NonNull ParallelFailureHandling errorHandler) { ObjectHelper.requireNonNull(onNext, "onNext is null"); ObjectHelper.requireNonNull(errorHandler, "errorHandler is null"); return RxJavaPlugins.onAssembly(new ParallelDoOnNextTry<T>(this, onNext, errorHandler)); } /** * Call the specified consumer with the current element passing through any 'rail' and * handles errors based on the returned value by the handler function. * * @param onNext the callback * @param errorHandler the function called with the current repeat count and * failure Throwable and should return one of the {@link ParallelFailureHandling} * enumeration values to indicate how to proceed. * @return the new ParallelFlowable instance * @since 2.0.8 - experimental */ @CheckReturnValue @Experimental @NonNull public final ParallelFlowable<T> doOnNext(@NonNull Consumer<? super T> onNext, @NonNull BiFunction<? super Long, ? super Throwable, ParallelFailureHandling> errorHandler) { ObjectHelper.requireNonNull(onNext, "onNext is null"); ObjectHelper.requireNonNull(errorHandler, "errorHandler is null"); return RxJavaPlugins.onAssembly(new ParallelDoOnNextTry<T>(this, onNext, errorHandler)); } /** * Call the specified consumer with the current element passing through any 'rail' * after it has been delivered to downstream within the rail. * * @param onAfterNext the callback * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> doAfterNext(@NonNull Consumer<? super T> onAfterNext) { ObjectHelper.requireNonNull(onAfterNext, "onAfterNext is null"); return RxJavaPlugins.onAssembly(new ParallelPeek<T>(this, Functions.emptyConsumer(), onAfterNext, Functions.emptyConsumer(), Functions.EMPTY_ACTION, Functions.EMPTY_ACTION, Functions.emptyConsumer(), Functions.EMPTY_LONG_CONSUMER, Functions.EMPTY_ACTION )); } /** * Call the specified consumer with the exception passing through any 'rail'. * * @param onError the callback * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> doOnError(@NonNull Consumer<Throwable> onError) { ObjectHelper.requireNonNull(onError, "onError is null"); return RxJavaPlugins.onAssembly(new ParallelPeek<T>(this, Functions.emptyConsumer(), Functions.emptyConsumer(), onError, Functions.EMPTY_ACTION, Functions.EMPTY_ACTION, Functions.emptyConsumer(), Functions.EMPTY_LONG_CONSUMER, Functions.EMPTY_ACTION )); } /** * Run the specified Action when a 'rail' completes. * * @param onComplete the callback * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> doOnComplete(@NonNull Action onComplete) { ObjectHelper.requireNonNull(onComplete, "onComplete is null"); return RxJavaPlugins.onAssembly(new ParallelPeek<T>(this, Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.emptyConsumer(), onComplete, Functions.EMPTY_ACTION, Functions.emptyConsumer(), Functions.EMPTY_LONG_CONSUMER, Functions.EMPTY_ACTION )); } /** * Run the specified Action when a 'rail' completes or signals an error. * * @param onAfterTerminate the callback * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> doAfterTerminated(@NonNull Action onAfterTerminate) { ObjectHelper.requireNonNull(onAfterTerminate, "onAfterTerminate is null"); return RxJavaPlugins.onAssembly(new ParallelPeek<T>(this, Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.EMPTY_ACTION, onAfterTerminate, Functions.emptyConsumer(), Functions.EMPTY_LONG_CONSUMER, Functions.EMPTY_ACTION )); } /** * Call the specified callback when a 'rail' receives a Subscription from its upstream. * * @param onSubscribe the callback * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> doOnSubscribe(@NonNull Consumer<? super Subscription> onSubscribe) { ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null"); return RxJavaPlugins.onAssembly(new ParallelPeek<T>(this, Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.EMPTY_ACTION, Functions.EMPTY_ACTION, onSubscribe, Functions.EMPTY_LONG_CONSUMER, Functions.EMPTY_ACTION )); } /** * Call the specified consumer with the request amount if any rail receives a request. * * @param onRequest the callback * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> doOnRequest(@NonNull LongConsumer onRequest) { ObjectHelper.requireNonNull(onRequest, "onRequest is null"); return RxJavaPlugins.onAssembly(new ParallelPeek<T>(this, Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.EMPTY_ACTION, Functions.EMPTY_ACTION, Functions.emptyConsumer(), onRequest, Functions.EMPTY_ACTION )); } /** * Run the specified Action when a 'rail' receives a cancellation. * * @param onCancel the callback * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final ParallelFlowable<T> doOnCancel(@NonNull Action onCancel) { ObjectHelper.requireNonNull(onCancel, "onCancel is null"); return RxJavaPlugins.onAssembly(new ParallelPeek<T>(this, Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.emptyConsumer(), Functions.EMPTY_ACTION, Functions.EMPTY_ACTION, Functions.emptyConsumer(), Functions.EMPTY_LONG_CONSUMER, onCancel )); } /** * Collect the elements in each rail into a collection supplied via a collectionSupplier * and collected into with a collector action, emitting the collection at the end. * * @param <C> the collection type * @param collectionSupplier the supplier of the collection in each rail * @param collector the collector, taking the per-rail collection and the current item * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <C> ParallelFlowable<C> collect(@NonNull Callable<? extends C> collectionSupplier, @NonNull BiConsumer<? super C, ? super T> collector) { ObjectHelper.requireNonNull(collectionSupplier, "collectionSupplier is null"); ObjectHelper.requireNonNull(collector, "collector is null"); return RxJavaPlugins.onAssembly(new ParallelCollect<T, C>(this, collectionSupplier, collector)); } /** * Wraps multiple Publishers into a ParallelFlowable which runs them * in parallel and unordered. * * @param <T> the value type * @param publishers the array of publishers * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public static <T> ParallelFlowable<T> fromArray(@NonNull Publisher<T>... publishers) { if (publishers.length == 0) { throw new IllegalArgumentException("Zero publishers not supported"); } return RxJavaPlugins.onAssembly(new ParallelFromArray<T>(publishers)); } /** * Perform a fluent transformation to a value via a converter function which * receives this ParallelFlowable. * * @param <U> the output value type * @param converter the converter function from ParallelFlowable to some type * @return the value returned by the converter function */ @CheckReturnValue @NonNull public final <U> U to(@NonNull Function<? super ParallelFlowable<T>, U> converter) { try { return ObjectHelper.requireNonNull(converter, "converter is null").apply(this); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); throw ExceptionHelper.wrapOrThrow(ex); } } /** * Allows composing operators, in assembly time, on top of this ParallelFlowable * and returns another ParallelFlowable with composed features. * * @param <U> the output value type * @param composer the composer function from ParallelFlowable (this) to another ParallelFlowable * @return the ParallelFlowable returned by the function */ @CheckReturnValue @NonNull public final <U> ParallelFlowable<U> compose(@NonNull ParallelTransformer<T, U> composer) { return RxJavaPlugins.onAssembly(ObjectHelper.requireNonNull(composer, "composer is null").apply(this)); } /** * Generates and flattens Publishers on each 'rail'. * <p> * Errors are not delayed and uses unbounded concurrency along with default inner prefetch. * * @param <R> the result type * @param mapper the function to map each rail's value into a Publisher * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> flatMap(@NonNull Function<? super T, ? extends Publisher<? extends R>> mapper) { return flatMap(mapper, false, Integer.MAX_VALUE, Flowable.bufferSize()); } /** * Generates and flattens Publishers on each 'rail', optionally delaying errors. * <p> * It uses unbounded concurrency along with default inner prefetch. * * @param <R> the result type * @param mapper the function to map each rail's value into a Publisher * @param delayError should the errors from the main and the inner sources delayed till everybody terminates? * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> flatMap( @NonNull Function<? super T, ? extends Publisher<? extends R>> mapper, boolean delayError) { return flatMap(mapper, delayError, Integer.MAX_VALUE, Flowable.bufferSize()); } /** * Generates and flattens Publishers on each 'rail', optionally delaying errors * and having a total number of simultaneous subscriptions to the inner Publishers. * <p> * It uses a default inner prefetch. * * @param <R> the result type * @param mapper the function to map each rail's value into a Publisher * @param delayError should the errors from the main and the inner sources delayed till everybody terminates? * @param maxConcurrency the maximum number of simultaneous subscriptions to the generated inner Publishers * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> flatMap( @NonNull Function<? super T, ? extends Publisher<? extends R>> mapper, boolean delayError, int maxConcurrency) { return flatMap(mapper, delayError, maxConcurrency, Flowable.bufferSize()); } /** * Generates and flattens Publishers on each 'rail', optionally delaying errors, * having a total number of simultaneous subscriptions to the inner Publishers * and using the given prefetch amount for the inner Publishers. * * @param <R> the result type * @param mapper the function to map each rail's value into a Publisher * @param delayError should the errors from the main and the inner sources delayed till everybody terminates? * @param maxConcurrency the maximum number of simultaneous subscriptions to the generated inner Publishers * @param prefetch the number of items to prefetch from each inner Publisher * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> flatMap( @NonNull Function<? super T, ? extends Publisher<? extends R>> mapper, boolean delayError, int maxConcurrency, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency"); ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new ParallelFlatMap<T, R>(this, mapper, delayError, maxConcurrency, prefetch)); } /** * Generates and concatenates Publishers on each 'rail', signalling errors immediately * and generating 2 publishers upfront. * * @param <R> the result type * @param mapper the function to map each rail's value into a Publisher * source and the inner Publishers (immediate, boundary, end) * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> concatMap( @NonNull Function<? super T, ? extends Publisher<? extends R>> mapper) { return concatMap(mapper, 2); } /** * Generates and concatenates Publishers on each 'rail', signalling errors immediately * and using the given prefetch amount for generating Publishers upfront. * * @param <R> the result type * @param mapper the function to map each rail's value into a Publisher * @param prefetch the number of items to prefetch from each inner Publisher * source and the inner Publishers (immediate, boundary, end) * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> concatMap( @NonNull Function<? super T, ? extends Publisher<? extends R>> mapper, int prefetch) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new ParallelConcatMap<T, R>(this, mapper, prefetch, ErrorMode.IMMEDIATE)); } /** * Generates and concatenates Publishers on each 'rail', optionally delaying errors * and generating 2 publishers upfront. * * @param <R> the result type * @param mapper the function to map each rail's value into a Publisher * @param tillTheEnd if true all errors from the upstream and inner Publishers are delayed * till all of them terminate, if false, the error is emitted when an inner Publisher terminates. * source and the inner Publishers (immediate, boundary, end) * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> concatMapDelayError( @NonNull Function<? super T, ? extends Publisher<? extends R>> mapper, boolean tillTheEnd) { return concatMapDelayError(mapper, 2, tillTheEnd); } /** * Generates and concatenates Publishers on each 'rail', optionally delaying errors * and using the given prefetch amount for generating Publishers upfront. * * @param <R> the result type * @param mapper the function to map each rail's value into a Publisher * @param prefetch the number of items to prefetch from each inner Publisher * @param tillTheEnd if true all errors from the upstream and inner Publishers are delayed * till all of them terminate, if false, the error is emitted when an inner Publisher terminates. * @return the new ParallelFlowable instance */ @CheckReturnValue @NonNull public final <R> ParallelFlowable<R> concatMapDelayError( @NonNull Function<? super T, ? extends Publisher<? extends R>> mapper, int prefetch, boolean tillTheEnd) { ObjectHelper.requireNonNull(mapper, "mapper is null"); ObjectHelper.verifyPositive(prefetch, "prefetch"); return RxJavaPlugins.onAssembly(new ParallelConcatMap<T, R>( this, mapper, prefetch, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY)); } }
apache-2.0
molofi/MScheduledTask
ScheduledTask/src/main/java/net/vicp/milim/ScheduledTask/zaixianwanjia/service/IAuthorizeService.java
3140
package net.vicp.milim.ScheduledTask.zaixianwanjia.service; import java.util.List; import net.vicp.milim.ScheduledTask.zaixianwanjia.bean.domain.Authorize; import net.vicp.milim.ScheduledTask.zaixianwanjia.bean.param.AuthorizeParam; import net.vicp.milim.ScheduledTask.zaixianwanjia.common.FdServiceException; import net.vicp.milim.ScheduledTask.zaixianwanjia.common.IPage; /** * * 类说明:权限接口 * @author 聂枫 * 2016年1月12日下午4:29:06 */ public interface IAuthorizeService { /** * * 方法说明:添加权限 * @author 聂枫 * 2016年1月12日下午4:51:54 * @param req * @return * @throws FdServiceException */ public Authorize addAuthorize(Authorize authorize) throws FdServiceException; /** * * 方法说明:根据authorizeNo获取权限信息 * @author 聂枫 * 2016年4月6日下午3:49:46 * @param authorizeNo * @return * @throws FdServiceException */ public Authorize getAuthorizeByauthorizeNo(String authorizeNo) throws FdServiceException; /** * * 方法说明:获取权限列表 * @author wwq * @email * 2016年4月20日下午4:23:24 * @param authorizeNos * @return * @throws FdServiceException */ public List<Authorize> getListAuthorizeByauthorizeNos(String authorizeNos) throws FdServiceException; /** * * 方法说明:更新资源 * @author 聂枫 * 2016年4月16日上午12:25:02 * @param authorize * @throws FdServiceException */ public void updateAuthorize(Authorize authorize) throws FdServiceException; /** * * 方法说明:查找所有列表 * @author 聂枫 * 2016年4月14日下午6:34:43 * @return * @throws FdServiceException */ public List<Authorize> getAll()throws FdServiceException; public List<Authorize> getAll2()throws FdServiceException; /** * * 方法说明:通过groupNo获取权限列表 * @author 聂枫 * 2016年4月28日上午12:40:15 * @param groupNo * @return * @throws FdServiceException */ public List<Authorize> getAuthorizeByGroupNo(String groupNo)throws FdServiceException; /** * 通过编号查询权限表 * @author 聂枫 * @date 2016年08月31日 19时04分35秒 * @param String authorizeNo * @return Long * @throws 异常 */ public Authorize queryAuthorizeByAuthorizeNo(String authorizeNo) throws FdServiceException; /** * 统计查询权限表 * @author 聂枫 * @date 2016年08月31日 19时04分35秒 * @param AuthorizeParam authorizeParam * @return Long * @throws 异常 */ public Long queryAuthorizeCountByCondition(AuthorizeParam authorizeParam) throws FdServiceException; /** * 分页查询权限表 * @author 聂枫 * @date 2016年08月31日 19时04分35秒 * @param AuthorizeParam authorizeParam * @return List<Authorize> * @throws 异常 */ public IPage<Authorize> queryAuthorizeByCondition(AuthorizeParam authorizeParam) throws FdServiceException; }
apache-2.0
qkhj/PCCREDIT_QZ
src/java/com/cardpay/pccredit/customer/dao/CustomerInforDao.java
6113
package com.cardpay.pccredit.customer.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.cardpay.pccredit.customer.model.CustomerCareersInformation; import com.cardpay.pccredit.customer.model.CustomerInfor; import com.cardpay.pccredit.customer.model.CustomerInforWeb; import com.cardpay.pccredit.system.model.Dict; import com.wicresoft.util.annotation.Mapper; /** * * @author shaoming * */ @Mapper public interface CustomerInforDao { /** * 获得国籍 * @return */ public List<Dict> findNationality(); /** * 获得证件类型 * @return */ public List<Dict> findCardType(); /** * 获得婚姻状况 * @return */ public List<Dict> findMaritalStatus(); /** * 获得住宅性质 * @return */ public List<Dict> findResidentialPropertie(); /** * 获得性别 * @return */ public List<Dict> findSex(); /** * 获得单位性质 * @return */ public List<Dict> findUnitPropertis(); /** * 获得行业类型 * @return */ public List<Dict> findIndustryType(); /** * 催收,维护方式 * @return */ public List<Dict> findCollectionMethod(); /** * 职务 * @return */ public List<Dict> findPositio(); /** * 职称 * @return */ public List<Dict> findTitle(); /** * 通过证件类型代码得到证件类型名 * @param typecode * @return */ public String findTypeNameByTypeCode(String typecode); /** * 通过Name得到客户信息 * @param name * @return */ public List<CustomerInfor> findCustomerInforByName(@Param("userId") String userId,@Param("name") String name); /** * 修改客户信息的客户经理id和移交状态 * @param id * @param customerManagerId * @return */ public int updateCustomerInfor(@Param("id")String id,@Param("customerManagerId")String customerManagerId,@Param("status") String status); /** * 得到客户信息中的客户经理id * @param customerId * @return */ public String findCustomerManagerIdById(@Param("customerId")String customerId); /** * 得到页面显示的客户信息 * @param id * @return */ public CustomerInforWeb findCustomerInforWebById(@Param("id") String id); /** * 修改客户信息移交状态 * @param id * @param status */ public int updateCustomerInforDivisionalStatus(@Param("id") String id,@Param("status") String status); /** * 得到客户信息移交状态 * @param id * @return */ public String getCustomerInforDivisionalStatus(@Param("id") String id); /** * 进件申请提交时 客户维护资料做快照 * @param customerId * @param applicationId */ public void cloneBasicCustomerInfo(@Param("customerId") String customerId, @Param("applicationId") String applicationId); /** * 进件申请提交时 客户维护资料做快照 * @param customerId * @param applicationId */ public void cloneCustomerCareersInf(@Param("customerId") String customerId, @Param("applicationId") String applicationId); /** * 进件申请提交时 客户维护资料做快照 * @param customerId * @param applicationId */ public void cloneCustomerMainManager(@Param("customerId") String customerId, @Param("applicationId") String applicationId); /** * 进件申请提交时 客户维护资料做快照 * @param customerId * @param applicationId */ public void cloneCustomerQuestionInfo(@Param("customerId") String customerId, @Param("applicationId") String applicationId); /** * 进件申请提交时 客户维护资料做快照 * @param customerId * @param applicationId */ public void cloneCustomerWorkshipInfo(@Param("customerId") String customerId, @Param("applicationId") String applicationId); /** * 进件申请提交时 客户维护资料做快照 * @param customerId * @param applicationId */ public void cloneDimensionalModelCredit(@Param("customerId") String customerId, @Param("applicationId") String applicationId); /** * 进件申请提交时 客户维护资料做快照 * @param customerId * @param applicationId */ public void cloneCustomerVideoAccessories(@Param("customerId") String customerId, @Param("applicationId") String applicationId); /** * 根据进件申请Id查询客户维护资料快照 * @param applicationId */ public CustomerInfor findCloneCustomerInforByAppId(@Param("applicationId") String applicationId); /** * 根据客户Id查询客户职业资料维护资料快照 * @param customerId */ public CustomerCareersInformation findcloneCustomerCareersByCustomerId(@Param("customerId") String customerId, @Param("applicationId") String applicationId); /** * 得到该客户经理下的客户数量 * @param userId * @return */ public int findCustomerInforCountByUserId(@Param("userId") String userId); public void deleteCloneBasicCustomerInfo(@Param("customerId") String customerId, @Param("applicationId") String applicationId); public void deleteCloneCustomerCareersInf(@Param("customerId") String customerId, @Param("applicationId") String applicationId); public void deleteCloneCustomerQuestionInfo(@Param("customerId") String customerId, @Param("applicationId") String applicationId); public void deleteCloneCustomerMainManager(@Param("customerId") String customerId, @Param("applicationId") String applicationId); public void deleteCloneCustomerWorkshipInfo(@Param("customerId") String customerId, @Param("applicationId") String applicationId); public void deleteCloneDimensionalModelCredit(@Param("customerId") String customerId, @Param("applicationId") String applicationId); public void deleteCloneCustomerVideoAccessories(@Param("customerId") String customerId, @Param("applicationId") String applicationId); }
apache-2.0
eposse/osate2-agcl
org.osate.xtext.aadl2.agcl/src-gen/org/osate/xtext/aadl2/agcl/agcl/PSLEventually.java
1466
/** */ package org.osate.xtext.aadl2.agcl.agcl; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>PSL Eventually</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.osate.xtext.aadl2.agcl.agcl.PSLEventually#getSubterm <em>Subterm</em>}</li> * </ul> * </p> * * @see org.osate.xtext.aadl2.agcl.agcl.AgclPackage#getPSLEventually() * @model * @generated */ public interface PSLEventually extends PSLExpression { /** * Returns the value of the '<em><b>Subterm</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Subterm</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Subterm</em>' containment reference. * @see #setSubterm(PSLExpression) * @see org.osate.xtext.aadl2.agcl.agcl.AgclPackage#getPSLEventually_Subterm() * @model containment="true" * @generated */ PSLExpression getSubterm(); /** * Sets the value of the '{@link org.osate.xtext.aadl2.agcl.agcl.PSLEventually#getSubterm <em>Subterm</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Subterm</em>' containment reference. * @see #getSubterm() * @generated */ void setSubterm(PSLExpression value); } // PSLEventually
apache-2.0
CodaAzzurra/Powertrain
src/main/java/com/datastax/demo/vehicle/Main.java
3261
package com.datastax.demo.vehicle; import com.datastax.demo.vehicle.model.Location; import com.github.davidmoten.geo.LatLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.Random; public class Main { private static Logger logger = LoggerFactory.getLogger(Main.class); private static int TOTAL_VEHICLES = 10000; private static int BATCH = 10000; private static Map<String, Location> vehicleLocations = new HashMap<>(); private VehicleDao dao; public Main() { String contactPointsStr = System.getProperty("contactPoints", "127.0.0.1"); this.dao = new VehicleDao(new SessionService(contactPointsStr).getSession()); logger.info("Creating Locations"); createStartLocations(); // TODO move this into a background thread in the app while (true) { logger.info("Updating Locations"); updateLocations(); sleep(5); } } public static void main(String[] args) { new Main(); } private void updateLocations() { Map<String, Location> newLocations = new HashMap<String, Location>(); for (int i = 0; i < BATCH; i++) { String random = new Double(Math.random() * TOTAL_VEHICLES).intValue() + 1 + ""; Location location = vehicleLocations.get(random); Location update = update(location); vehicleLocations.put(random, update); newLocations.put(random, update); } dao.insertVehicleLocation(newLocations); } private Location update(Location location) { double lon = location.getLatLong().getLon(); double lat = location.getLatLong().getLat(); double elevation = location.getElevation(); if (Math.random() < .1) return location; if (Math.random() < .5) lon += .0001d; else lon -= .0001d; if (Math.random() < .5) lat += .0001d; else lat -= .0001d; if (Math.random() < .5) elevation += .0001d; else elevation -= .0001d; return new Location(new LatLong(lat, lon), elevation); } private void createStartLocations() { for (int i = 0; i < TOTAL_VEHICLES; i++) { double lat = getRandomLat(); double lon = getRandomLng(); double el = getRandomElevation(); this.vehicleLocations.put("" + (i + 1), new Location(new LatLong(lat, lon), el)); } dao.insertVehicleLocation(vehicleLocations); } private double getRandomElevation() { return (Math.random() < .5) ? Math.random() : -1 * Math.random(); } /** * Between 1 and -1 * * @return */ private double getRandomLng() { return (Math.random() < .5) ? Math.random() : -1 * Math.random(); } /** * Between 50 and 55 */ private double getRandomLat() { return Math.random() * 5 + 50; } private void sleep(int seconds) { try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
apache-2.0
isopov/spring-boot
spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfiguration.java
3127
/* * Copyright 2012-2018 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 org.springframework.boot.actuate.autoconfigure.metrics.export.ganglia; import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.util.HierarchicalNameMapper; import io.micrometer.ganglia.GangliaConfig; import io.micrometer.ganglia.GangliaMeterRegistry; import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * {@link EnableAutoConfiguration Auto-configuration} for exporting metrics to Ganglia. * * @author Jon Schneider * @since 2.0.0 */ @Configuration @AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @AutoConfigureAfter(MetricsAutoConfiguration.class) @ConditionalOnBean(Clock.class) @ConditionalOnClass(GangliaMeterRegistry.class) @ConditionalOnProperty(prefix = "management.metrics.export.ganglia", name = "enabled", havingValue = "true", matchIfMissing = true) @EnableConfigurationProperties(GangliaProperties.class) public class GangliaMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public GangliaConfig gangliaConfig(GangliaProperties gangliaProperties) { return new GangliaPropertiesConfigAdapter(gangliaProperties); } @Bean @ConditionalOnMissingBean public GangliaMeterRegistry gangliaMeterRegistry(GangliaConfig gangliaConfig, HierarchicalNameMapper nameMapper, Clock clock) { return new GangliaMeterRegistry(gangliaConfig, clock, nameMapper); } @Bean @ConditionalOnMissingBean public HierarchicalNameMapper hierarchicalNameMapper() { return HierarchicalNameMapper.DEFAULT; } }
apache-2.0
Netflix/msl
examples/simple/src/main/java/server/userauth/SimpleTokenFactory.java
12336
/** * Copyright (c) 2014-2017 Netflix, Inc. All rights reserved. * * 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 server.userauth; import java.sql.Date; import java.util.concurrent.ConcurrentHashMap; import javax.crypto.SecretKey; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslError; import com.netflix.msl.MslException; import com.netflix.msl.MslMasterTokenException; import com.netflix.msl.MslUserIdTokenException; import com.netflix.msl.entityauth.EntityAuthenticationData; import com.netflix.msl.io.MslEncoderException; import com.netflix.msl.io.MslEncoderUtils; import com.netflix.msl.io.MslObject; import com.netflix.msl.tokens.MasterToken; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.tokens.TokenFactory; import com.netflix.msl.tokens.UserIdToken; import com.netflix.msl.util.MslContext; import com.netflix.msl.util.MslUtils; /** * <p>A memory-backed token factory.</p> * * @author Wesley Miaw <wmiaw@netflix.com> */ public class SimpleTokenFactory implements TokenFactory { /** Renewal window start offset in milliseconds. */ private static final int RENEWAL_OFFSET = 60000; /** Expiration offset in milliseconds. */ private static final int EXPIRATION_OFFSET = 120000; /** Non-replayable ID acceptance window. */ private static final long NON_REPLAYABLE_ID_WINDOW = 65536; /** * Return true if the provided master token is the newest master token * as far as we know. * * @param masterToken the master token. * @return true if this is the newest master token. * @throws MslMasterTokenException if the master token is not decrypted. */ private boolean isNewestMasterToken(final MasterToken masterToken) throws MslMasterTokenException { if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); // Return true if we have no sequence number records or if the master // token sequence number is the most recently issued one. final Long newestSeqNo = mtSequenceNumbers.get(masterToken.getIdentity()); return (newestSeqNo == null || newestSeqNo.longValue() == masterToken.getSequenceNumber()); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRevoked(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken) */ @Override public MslError isMasterTokenRevoked(final MslContext ctx, final MasterToken masterToken) { // No support for revoked master tokens. return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#acceptNonReplayableId(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, long) */ @Override public MslError acceptNonReplayableId(final MslContext ctx, final MasterToken masterToken, final long nonReplayableId) throws MslException { if (!masterToken.isDecrypted()) throw new MslMasterTokenException(MslError.MASTERTOKEN_UNTRUSTED, masterToken); if (nonReplayableId < 0 || nonReplayableId > MslConstants.MAX_LONG_VALUE) throw new MslException(MslError.NONREPLAYABLE_ID_OUT_OF_RANGE, "nonReplayableId " + nonReplayableId); // Accept if there is no non-replayable ID. final String key = masterToken.getIdentity() + ":" + masterToken.getSerialNumber(); final Long largestNonReplayableId = nonReplayableIds.putIfAbsent(key, nonReplayableId); if (largestNonReplayableId == null) { return null; } // Reject if the non-replayable ID is equal or just a few messages // behind. The sender can recover by incrementing. final long catchupWindow = MslConstants.MAX_MESSAGES / 2; if (nonReplayableId <= largestNonReplayableId && nonReplayableId > largestNonReplayableId - catchupWindow) { return MslError.MESSAGE_REPLAYED; } // Reject if the non-replayable ID is larger by more than the // acceptance window. The sender cannot recover quickly. if (nonReplayableId - NON_REPLAYABLE_ID_WINDOW > largestNonReplayableId) return MslError.MESSAGE_REPLAYED_UNRECOVERABLE; // If the non-replayable ID is smaller reject it if it is outside the // wrap-around window. The sender cannot recover quickly. if (nonReplayableId < largestNonReplayableId) { final long cutoff = largestNonReplayableId - MslConstants.MAX_LONG_VALUE + NON_REPLAYABLE_ID_WINDOW; if (nonReplayableId >= cutoff) return MslError.MESSAGE_REPLAYED_UNRECOVERABLE; } // Accept the non-replayable ID. // // This is not perfect, since it's possible a smaller value will // overwrite a larger value, but it's good enough for the example. nonReplayableIds.put(key, nonReplayableId); return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.entityauth.EntityAuthenticationData, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject) */ @Override public MasterToken createMasterToken(final MslContext ctx, final EntityAuthenticationData entityAuthData, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException { final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET); final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET); final long sequenceNumber = 0; final long serialNumber = MslUtils.getRandomLong(ctx); final String identity = entityAuthData.getIdentity(); final MasterToken masterToken = new MasterToken(ctx, renewalWindow, expiration, sequenceNumber, serialNumber, issuerData, identity, encryptionKey, hmacKey); // Remember the sequence number. // // This is not perfect, since it's possible a smaller value will // overwrite a larger value, but it's good enough for the example. mtSequenceNumbers.put(identity, sequenceNumber); // Return the new master token. return masterToken; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isMasterTokenRenewable(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken) */ @Override public MslError isMasterTokenRenewable(final MslContext ctx, final MasterToken masterToken) throws MslMasterTokenException { if (!isNewestMasterToken(masterToken)) return MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC; return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#renewMasterToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, javax.crypto.SecretKey, javax.crypto.SecretKey, com.netflix.msl.io.MslObject) */ @Override public MasterToken renewMasterToken(final MslContext ctx, final MasterToken masterToken, final SecretKey encryptionKey, final SecretKey hmacKey, final MslObject issuerData) throws MslEncodingException, MslCryptoException, MslMasterTokenException { if (!isNewestMasterToken(masterToken)) throw new MslMasterTokenException(MslError.MASTERTOKEN_SEQUENCE_NUMBER_OUT_OF_SYNC, masterToken); // Renew master token. final MslObject mtIssuerData = masterToken.getIssuerData(); final MslObject mergedIssuerData; try { mergedIssuerData = MslEncoderUtils.merge(mtIssuerData, issuerData); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MASTERTOKEN_ISSUERDATA_ENCODE_ERROR, "mt issuerdata " + mtIssuerData + "; issuerdata " + issuerData, e); } final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET); final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET); final long oldSequenceNumber = masterToken.getSequenceNumber(); final long sequenceNumber = (oldSequenceNumber == MslConstants.MAX_LONG_VALUE) ? 0 : oldSequenceNumber + 1; final long serialNumber = masterToken.getSerialNumber(); final String identity = masterToken.getIdentity(); final MasterToken newMasterToken = new MasterToken(ctx, renewalWindow, expiration, sequenceNumber, serialNumber, mergedIssuerData, identity, encryptionKey, hmacKey); // Remember the sequence number. // // This is not perfect, since it's possible a smaller value will // overwrite a larger value, but it's good enough for the example. mtSequenceNumbers.put(identity, sequenceNumber); // Return the new master token. return newMasterToken; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#isUserIdTokenRevoked(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MasterToken, com.netflix.msl.tokens.UserIdToken) */ @Override public MslError isUserIdTokenRevoked(final MslContext ctx, final MasterToken masterToken, final UserIdToken userIdToken) { // No support for revoked user ID tokens. return null; } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.MslUser, com.netflix.msl.tokens.MasterToken) */ @Override public UserIdToken createUserIdToken(final MslContext ctx, final MslUser user, final MasterToken masterToken) throws MslEncodingException, MslCryptoException { final MslObject issuerData = null; final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET); final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET); final long serialNumber = MslUtils.getRandomLong(ctx); return new UserIdToken(ctx, renewalWindow, expiration, masterToken, serialNumber, issuerData, user); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#renewUserIdToken(com.netflix.msl.util.MslContext, com.netflix.msl.tokens.UserIdToken, com.netflix.msl.tokens.MasterToken) */ @Override public UserIdToken renewUserIdToken(final MslContext ctx, final UserIdToken userIdToken, final MasterToken masterToken) throws MslEncodingException, MslCryptoException, MslUserIdTokenException { if (!userIdToken.isDecrypted()) throw new MslUserIdTokenException(MslError.USERIDTOKEN_NOT_DECRYPTED, userIdToken).setMasterToken(masterToken); final MslObject issuerData = null; final Date renewalWindow = new Date(ctx.getTime() + RENEWAL_OFFSET); final Date expiration = new Date(ctx.getTime() + EXPIRATION_OFFSET); final long serialNumber = userIdToken.getSerialNumber(); final MslUser user = userIdToken.getUser(); return new UserIdToken(ctx, renewalWindow, expiration, masterToken, serialNumber, issuerData, user); } /* (non-Javadoc) * @see com.netflix.msl.tokens.TokenFactory#createUser(com.netflix.msl.util.MslContext, java.lang.String) */ @Override public MslUser createUser(final MslContext ctx, final String userdata) { return new SimpleUser(userdata); } /** Map of entity identities onto sequence numbers. */ private final ConcurrentHashMap<String,Long> mtSequenceNumbers = new ConcurrentHashMap<String,Long>(); /** Map of entity identities and serial numbers onto non-replayable IDs. */ private final ConcurrentHashMap<String,Long> nonReplayableIds = new ConcurrentHashMap<String,Long>(); }
apache-2.0
V1toss/JavaPA
part_3/filesearch/src/test/java/vkaretko/FileSearchTest.java
4067
package vkaretko; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Test-class for FileSearch. * * @author Karetko Victor * @version 1.00 * @since 26.11.2016 */ public class FileSearchTest { /** * First temp-file for tests. */ private File tempFileOne; /** * Second temp-file for tests. */ private File tempFileTwo; /** * Third temp-file for tests. */ private File tempFileThree; /** * Log-file. */ private File logFile; /** * Create temp-files before tests. */ @Before public void createTempFiles() { try { File tempDir = new File("c:/temp"); tempDir.mkdir(); tempDir.deleteOnExit(); this.tempFileOne = new File("c:/temp/1.txt"); this.tempFileTwo = new File("c:/temp/2.txt"); this.tempFileThree = new File("c:/temp/3.txt"); this.tempFileOne.createNewFile(); this.tempFileTwo.createNewFile(); this.tempFileThree.createNewFile(); this.tempFileOne.deleteOnExit(); this.tempFileTwo.deleteOnExit(); this.tempFileThree.deleteOnExit(); this.logFile = new File("c:/temp/log.txt"); this.logFile.deleteOnExit(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * Test-method for checking message after wrong arguments. */ @Test public void whenWrongArgumentsThenResultErrorMessage() { try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { System.setOut(new PrintStream(output)); String[] wrongArgs = {"-d", "-m", "-n"}; FileSearch.main(wrongArgs); assertThat(output.toString(), is("Wrong arguments\r\nTo show help - execute program with key /help\r\n")); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * Test-method for check search by mask. */ @Test public void whenSearchByMaskTxtThenResultThreeLinesInLogFile() { String[] argsSearchByMask = {"-d", "c:/temp/", "-n", "*.txt", "-m", "-o", "log.txt"}; FileSearch.main(argsSearchByMask); StringBuilder sb = new StringBuilder(); try (Scanner sc = new Scanner(this.logFile)) { while (sc.hasNext()) { sb.append(sc.nextLine()); } } catch (IOException ioe) { ioe.printStackTrace(); } assertThat(sb.toString(), is("c:\\temp\\1.txtc:\\temp\\2.txtc:\\temp\\3.txt")); } /** * Test-method for check search by name. */ @Test public void whenSearchByNameThenResultOneLineInLogFile() { String[] argsSearchByName = {"-d", "c:/temp/", "-n", "2.txt", "-f", "-o", "log.txt"}; FileSearch.main(argsSearchByName); StringBuilder sb = new StringBuilder(); try (Scanner sc = new Scanner(this.logFile)) { while (sc.hasNext()) { sb.append(sc.nextLine()); } } catch (IOException ioe) { ioe.printStackTrace(); } assertThat(sb.toString(), is("c:\\temp\\2.txt")); } /** * Test-method for check search by regex. */ @Test public void whenSearchByRegexThenResultTwoLinesInLogFile() { String[] argsSearchByName = {"-d", "c:/temp/", "-n", "[2-3].*", "-r", "-o", "log.txt"}; FileSearch.main(argsSearchByName); StringBuilder sb = new StringBuilder(); try (Scanner sc = new Scanner(this.logFile)) { while (sc.hasNext()) { sb.append(sc.nextLine()); } } catch (IOException ioe) { ioe.printStackTrace(); } assertThat(sb.toString(), is("c:\\temp\\2.txtc:\\temp\\3.txt")); } }
apache-2.0
kanomiya/Steward
src/com/kanomiya/steward/view/ViewUtils.java
4108
package com.kanomiya.steward.view; import java.awt.Graphics; import com.kanomiya.steward.model.event.Event; /** * @author Kanomiya * */ public class ViewUtils { public static int getCamX(Event eye) { return getCamX(eye.x, eye.area.getWidth()); } public static int getCamY(Event eye) { return getCamY(eye.y, eye.area.getHeight()); } public static int getCamX(int x, int width) { int camX = x -ViewConsts.tileCols /2; if (camX < 0) return 0; int r = width -ViewConsts.tileCols; if (r < camX) return -r; return -camX; } public static int getCamY(int y, int height) { int camY = y -ViewConsts.tileRows /2; if (camY < 0) return 0; int b = height -ViewConsts.tileRows; if (b < camY) return -b; return -camY; } public static int xCenterInWindow(Event eye) { return xCenterInWindow(getCamX(eye)); } public static int xCenterInWindow(int camX) { return camX + ViewConsts.tileCols /2; } public static int yCenterInWindow(Event eye) { return yCenterInWindow(getCamY(eye)); } public static int yCenterInWindow(int camY) { return camY + ViewConsts.tileRows /2; } public static boolean xInWindow(int x, Event eye) { return xInWindow(x, getCamX(eye)); } public static boolean xInWindow(int x, int camX) { return xInWindowEdge(x, camX, 0); } public static boolean xInWindowEdge(int x, Event eye, int distance) { return xInWindowEdge(x, getCamX(eye), distance); } public static boolean xInWindowEdge(int x, int camX, int distance) { return (leftInWindowEdge(x, camX, distance) && rightInWindowEdge(x, camX, distance)); } public static boolean leftInWindowEdge(int x, Event eye, int distance) { return leftInWindowEdge(x, getCamX(eye), distance); } public static boolean leftInWindowEdge(int x, int camX, int distance) { return (camX +distance <= x); } public static boolean rightInWindowEdge(int x, Event eye, int distance) { return rightInWindowEdge(x, getCamX(eye), distance); } public static boolean rightInWindowEdge(int x, int camX, int distance) { return (x < camX +ViewConsts.tileCols -distance); } public static boolean yInWindow(int y, Event eye) { return yInWindow(y, getCamY(eye)); } public static boolean yInWindow(int y, int camY) { return yInWindowEdge(y, camY, 0); } public static boolean yInWindowEdge(int y, Event eye, int distance) { return yInWindowEdge(y, getCamY(eye), distance); } public static boolean yInWindowEdge(int y, int camY, int distance) { return (topInWindowEdge(y, camY, distance) && bottomInWindowEdge(y, camY, distance)); } public static boolean topInWindowEdge(int y, Event eye, int distance) { return topInWindowEdge(y, getCamY(eye), distance); } public static boolean topInWindowEdge(int y, int camY, int distance) { return (camY +distance <= y); } public static boolean bottomInWindowEdge(int y, Event eye, int distance) { return bottomInWindowEdge(y, getCamY(eye), distance); } public static boolean bottomInWindowEdge(int y, int camY, int distance) { return (y < camY +ViewConsts.tileRows -distance); } /** * * 折り返すべき場所に改行(\n)を挿入します * * @param text * @param g * @param beginLeft * @param maxWidth * @return */ public static String wordWrap(String text, Graphics g, int beginLeft, int maxWidth) { int textLen = text.length(); int width = g.getFontMetrics().stringWidth(text); int right = beginLeft +width; if (maxWidth < right) // 折り返し { StringBuilder stack = new StringBuilder(textLen +20); StringBuilder builder = null; int dx = beginLeft; for (int i=0; i<textLen; i++) { if (builder == null) builder = new StringBuilder(textLen); builder.append(text.charAt(i)); int dw = g.getFontMetrics().stringWidth(builder.toString()); int dr = dx +dw; if (maxWidth < dr) { stack.append(builder); stack.append('\n'); dx = 0; builder = null; } } if (builder != null) stack.append(builder); text = stack.toString(); } return text; } }
apache-2.0
marcusportmann/mmp-java
src/mmp-application-messaging/src/test/java/guru/mmp/application/messaging/test/MessagingServletTest.java
20306
/* * Copyright 2017 Marcus Portmann * * 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 guru.mmp.application.messaging.test; //~--- non-JDK imports -------------------------------------------------------- import com.meterware.httpunit.PostMethodWebRequest; import com.meterware.httpunit.WebResponse; import com.meterware.servletunit.InvocationContext; import com.meterware.servletunit.ServletRunner; import com.meterware.servletunit.ServletUnitClient; import guru.mmp.application.messaging.*; import guru.mmp.application.messaging.messages.*; import guru.mmp.application.test.TestClassRunner; import guru.mmp.application.web.servlets.MessagingServlet; import guru.mmp.common.util.Base64; import guru.mmp.common.wbxml.Document; import guru.mmp.common.wbxml.Parser; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import javax.inject.Inject; import javax.servlet.Servlet; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.List; import java.util.UUID; import static org.junit.Assert.*; //~--- JDK imports ------------------------------------------------------------ /** * The <code>MessagingServletTest</code> class contains the implementation of the JUnit * tests for the <code>MessagingServlet</code> class. * * @author Marcus Portmann */ @SuppressWarnings("unused") @RunWith(TestClassRunner.class) @ContextConfiguration(classes = { MessagingTestConfiguration.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) public class MessagingServletTest { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(MessagingServletTest.class); /** * The HTTP content-type used when receiving and sending WBXML. */ private static final String WBXML_CONTENT_TYPE = "application/wbxml"; private static final UUID DEVICE_ID = UUID.randomUUID(); private static final String USERNAME = "Administrator"; private static final String PASSWORD = "Password1"; private ServletUnitClient servletUnitClient; /** * The Spring application context. */ @Inject private ApplicationContext applicationContext; /** * Test the "Another Test" asynchronous message functionality. */ @Test public void anotherTestMessageTest() throws Exception { byte[] userEncryptionKey = authenticateUser(USERNAME, PASSWORD, DEVICE_ID); MessageTranslator messageTranslator = new MessageTranslator(USERNAME, DEVICE_ID, userEncryptionKey); AnotherTestRequestData requestData = new AnotherTestRequestData("Test Value", "Test Data".getBytes()); Message requestMessage = messageTranslator.toMessage(requestData, UUID.randomUUID()); MessageResult messageResult = sendMessage(requestMessage); assertEquals(MessageResult.SUCCESS, messageResult.getCode()); assertEquals(null, messageResult.getMessage()); // Sleep to give the back-end a chance to process the message try { Thread.sleep(2500L); } catch (Throwable ignored) {} // Retrieve the messages queued for download MessageDownloadResponse messageDownloadResponse = sendMessageDownloadRequest(DEVICE_ID, USERNAME); assertEquals(MessageDownloadResponse.SUCCESS, messageDownloadResponse.getCode()); assertEquals(messageDownloadResponse.getNumberOfMessages(), messageDownloadResponse.getMessages().size()); List<Message> messages = messageDownloadResponse.getMessages(); assertEquals(1, messages.size()); logger.info("Downloaded " + messages.size() + " messages"); for (Message message : messages) { assertEquals(requestMessage.getCorrelationId(), message.getCorrelationId()); assertEquals(1, message.getDownloadAttempts()); logger.info("Downloaded message (" + message.getId() + ") with type (" + message.getTypeId() + ")"); MessageReceivedResponse messageReceivedResponse = sendMessageReceivedRequest(DEVICE_ID, message.getId()); assertEquals(MessageReceivedResponse.SUCCESS, messageReceivedResponse.getCode()); AnotherTestResponseData responseData = messageTranslator.fromMessage(message, new AnotherTestResponseData()); assertEquals(AnotherTestResponseData.MESSAGE_TYPE_ID, responseData.getMessageTypeId()); assertEquals(Message.Priority.HIGH, responseData.getMessageTypePriority()); assertEquals("Test Value", responseData.getTestValue()); assertArrayEquals("Test Data".getBytes(), requestData.getTestData()); } } /** * Test the "Another Test" asynchronous multi-part message functionality. */ @Test public void anotherTestMultiPartMessageTest() throws Exception { byte[] userEncryptionKey = authenticateUser(USERNAME, PASSWORD, DEVICE_ID); MessageTranslator messageTranslator = new MessageTranslator(USERNAME, DEVICE_ID, userEncryptionKey); byte[] testData = new byte[64 * 1024]; new SecureRandom().nextBytes(testData); AnotherTestRequestData requestData = new AnotherTestRequestData("Test Value", testData); Message requestMessage = messageTranslator.toMessage(requestData, UUID.randomUUID()); MessageResult messageResult = sendMessage(requestMessage); assertEquals(MessageResult.SUCCESS, messageResult.getCode()); assertEquals(null, messageResult.getMessage()); // Sleep to give the back-end a chance to process the message try { Thread.sleep(2500L); } catch (Throwable ignored) {} // Retrieve the messages queued for download MessageDownloadResponse messageDownloadResponse = sendMessageDownloadRequest(DEVICE_ID, USERNAME); assertEquals(MessageDownloadResponse.SUCCESS, messageDownloadResponse.getCode()); List<Message> messages = messageDownloadResponse.getMessages(); logger.info("Downloaded " + messages.size() + " messages"); for (Message message : messages) { logger.info("Downloaded message (" + message.getId() + ") with type (" + message.getTypeId() + ")"); MessageReceivedResponse messageReceivedResponse = sendMessageReceivedRequest(DEVICE_ID, message.getId()); assertEquals(MessageReceivedResponse.SUCCESS, messageReceivedResponse.getCode()); AnotherTestResponseData responseData = messageTranslator.fromMessage( messageResult.getMessage(), new AnotherTestResponseData()); assertEquals("Test Value", responseData.getTestValue()); assertArrayEquals(testData, requestData.getTestData()); } // Retrieve the message parts queued for download MessagePartDownloadResponse messagePartDownloadResponse = sendMessagePartDownloadRequest( DEVICE_ID, USERNAME); assertEquals(MessagePartDownloadResponse.SUCCESS, messagePartDownloadResponse.getCode()); List<MessagePart> messageParts = messagePartDownloadResponse.getMessageParts(); assertEquals(2, messageParts.size()); logger.info("Downloaded " + messageParts.size() + " message parts"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (MessagePart messagePart : messageParts) { assertEquals(1, messagePart.getDownloadAttempts()); assertEquals(requestMessage.getCorrelationId(), messagePart.getMessageCorrelationId()); logger.info("Downloaded message part (" + messagePart.getPartNo() + "/" + messagePart.getTotalParts() + ") with ID (" + messagePart.getId() + ") and type (" + messagePart.getMessageTypeId() + ")"); MessagePartReceivedResponse messagePartReceivedResponse = sendMessagePartReceivedRequest( DEVICE_ID, messagePart.getId()); assertEquals(0, messagePartReceivedResponse.getCode()); baos.write(messagePart.getData()); } MessageDigest md = MessageDigest.getInstance("SHA-256"); String messageChecksum = Base64.encodeBytes(md.digest(baos.toByteArray())); assertEquals(messageParts.get(0).getMessageChecksum(), messageChecksum); Message reconstructedMessage = new Message(messageParts.get(0).getMessageUsername(), messageParts.get(0).getMessageDeviceId(), messageParts.get(0).getMessageTypeId(), messageParts.get(0).getMessageCorrelationId(), messageParts.get(0).getMessagePriority(), baos.toByteArray(), messageParts.get(0).getMessageDataHash(), messageParts.get(0) .getMessageEncryptionIV()); AnotherTestResponseData anotherTestResponseData = messageTranslator.fromMessage( reconstructedMessage, new AnotherTestResponseData()); assertArrayEquals(testData, anotherTestResponseData.getTestData()); } /** * Test the "Test" synchronous message functionality. */ @Test public void testMessageTest() throws Exception { byte[] userEncryptionKey = authenticateUser(USERNAME, PASSWORD, DEVICE_ID); MessageTranslator messageTranslator = new MessageTranslator(USERNAME, DEVICE_ID, userEncryptionKey); TestRequestData requestData = new TestRequestData("Test Value"); Message requestMessage = messageTranslator.toMessage(requestData); MessageResult messageResult = sendMessage(requestMessage); assertEquals(MessageResult.SUCCESS, messageResult.getCode()); TestResponseData responseData = messageTranslator.fromMessage(messageResult.getMessage(), new TestResponseData()); assertEquals(TestResponseData.MESSAGE_TYPE_ID, responseData.getMessageTypeId()); assertEquals(Message.Priority.HIGH, responseData.getMessageTypePriority()); assertEquals("Test Value", responseData.getTestValue()); } private byte[] authenticateUser(String username, String password, UUID deviceId) throws Exception { AuthenticateRequestData requestData = new AuthenticateRequestData(username, password, deviceId); MessageTranslator messageTranslator = new MessageTranslator(username, deviceId); Message requestMessage = messageTranslator.toMessage(requestData, UUID.randomUUID()); MessageResult messageResult = sendMessage(requestMessage); assertEquals(MessageResult.SUCCESS, messageResult.getCode()); AuthenticateResponseData responseData = messageTranslator.fromMessage( messageResult.getMessage(), new AuthenticateResponseData()); assertEquals(AuthenticateResponseData.MESSAGE_TYPE_ID, responseData.getMessageTypeId()); assertEquals(Message.Priority.HIGH, responseData.getMessageTypePriority()); assertEquals(0, responseData.getErrorCode()); assertNotNull(responseData.getUserEncryptionKey()); return responseData.getUserEncryptionKey(); } private InvocationContext getMessagingServletInvocationContext(byte[] wbxmlRequestData) throws Exception { if (servletUnitClient == null) { ServletRunner servletRunner = new ServletRunner(); servletRunner.registerServlet("MessagingServlet", MessagingServlet.class.getName()); servletUnitClient = servletRunner.newClient(); } PostMethodWebRequest request = new PostMethodWebRequest("http://localhost/MessagingServlet", new ByteArrayInputStream(wbxmlRequestData), WBXML_CONTENT_TYPE); InvocationContext invocationContext = servletUnitClient.newInvocation(request); Servlet messagingServlet = invocationContext.getServlet(); applicationContext.getAutowireCapableBeanFactory().autowireBean(messagingServlet); return invocationContext; } private byte[] invokeMessagingServlet(byte[] requestData) throws Exception { InvocationContext invocationContext = getMessagingServletInvocationContext(requestData); invocationContext.getServlet().service(invocationContext.getRequest(), invocationContext.getResponse()); WebResponse response = invocationContext.getServletResponse(); assertEquals(200, response.getResponseCode()); assertEquals(WBXML_CONTENT_TYPE, response.getContentType()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = response.getInputStream(); int numberOfBytesRead; byte[] buffer = new byte[1024]; while ((numberOfBytesRead = in.read(buffer)) != -1) { baos.write(buffer, 0, numberOfBytesRead); } return baos.toByteArray(); } private MessageResult sendMessage(Message message) throws Exception { try { if (message.getData().length > Message.MAX_ASYNC_MESSAGE_SIZE) { // Calculate the hash for the message data to use as the message checksum MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(message.getData()); String messageChecksum = Base64.encodeBytes(messageDigest.digest()); // Split the message up into a number of message parts and persist each message part int numberOfParts = message.getData().length / MessagePart.MAX_MESSAGE_PART_SIZE; if ((message.getData().length % MessagePart.MAX_MESSAGE_PART_SIZE) > 0) { numberOfParts++; } for (int i = 0; i < numberOfParts; i++) { byte[] messagePartData; // If this is not the last message part if (i < (numberOfParts - 1)) { messagePartData = new byte[MessagePart.MAX_MESSAGE_PART_SIZE]; System.arraycopy(message.getData(), (i * MessagePart.MAX_MESSAGE_PART_SIZE), messagePartData, 0, MessagePart.MAX_MESSAGE_PART_SIZE); } // If this is the last message part else { int sizeOfPart = message.getData().length - (i * MessagePart.MAX_MESSAGE_PART_SIZE); messagePartData = new byte[sizeOfPart]; System.arraycopy(message.getData(), (i * MessagePart.MAX_MESSAGE_PART_SIZE), messagePartData, 0, sizeOfPart); } MessagePart messagePart = new MessagePart(i + 1, numberOfParts, message.getId(), message.getUsername(), message.getDeviceId(), message.getTypeId(), message.getCorrelationId(), message.getPriority(), message.getCreated(), message.getDataHash(), message.getEncryptionIV(), messageChecksum, messagePartData); messagePart.setStatus(MessagePart.Status.QUEUED_FOR_SENDING); // Send the message part byte[] data = invokeMessagingServlet(messagePart.toWBXML()); Parser parser = new Parser(); Document document = parser.parse(data); // Check if we have received a valid message result if (MessagePartResult.isValidWBXML(document)) { logger.info("Uploaded the message part (" + messagePart.getPartNo() + "/" + messagePart.getTotalParts() + ") for the message (" + messagePart.getMessageId() + ") from the user (" + messagePart.getMessageUsername() + ") and the device (" + messagePart.getMessageDeviceId() + ") with message type (" + messagePart.getMessageTypeId() + ")"); } else { throw new RuntimeException("The WBXML response data from the remote server is not a " + "valid MessageResult document"); } MessagePartResult messagePartResult = new MessagePartResult(document); assertEquals(MessagePartResult.SUCCESS, messagePartResult.getCode()); } return new MessageResult(MessageResult.SUCCESS, ""); } else { byte[] data = invokeMessagingServlet(message.toWBXML()); Parser parser = new Parser(); Document document = parser.parse(data); // Check if we have received a valid message result if (MessageResult.isValidWBXML(document)) { return new MessageResult(document); } else { throw new RuntimeException("The WBXML response data from the remote server is not a " + "valid MessageResult document"); } } } catch (Throwable e) { throw new RuntimeException("Failed to send the message (" + message.getId() + "): " + e.getMessage(), e); } } private MessageDownloadResponse sendMessageDownloadRequest(UUID deviceId, String username) throws Exception { MessageDownloadRequest messageDownloadRequest = new MessageDownloadRequest(deviceId, username); byte[] data = invokeMessagingServlet(messageDownloadRequest.toWBXML()); Parser parser = new Parser(); Document document = parser.parse(data); if (MessageDownloadResponse.isValidWBXML(document)) { return new MessageDownloadResponse(document); } else { throw new RuntimeException("Failed to send the message download request: " + "The WBXML response data from the remote server is not a valid " + "MessageDownloadResponse document"); } } private MessagePartDownloadResponse sendMessagePartDownloadRequest(UUID deviceId, String username) throws Exception { MessagePartDownloadRequest messagePartDownloadRequest = new MessagePartDownloadRequest( deviceId, username); byte[] data = invokeMessagingServlet(messagePartDownloadRequest.toWBXML()); Parser parser = new Parser(); Document document = parser.parse(data); if (MessagePartDownloadResponse.isValidWBXML(document)) { return new MessagePartDownloadResponse(document); } else { throw new RuntimeException("Failed to send the message part download request: " + "The WBXML response data from the remote server is not a valid " + "MessagePartDownloadResponse document"); } } private MessagePartReceivedResponse sendMessagePartReceivedRequest(UUID deviceId, UUID messageId) throws Exception { MessagePartReceivedRequest messagePartReceivedRequest = new MessagePartReceivedRequest( deviceId, messageId); byte[] data = invokeMessagingServlet(messagePartReceivedRequest.toWBXML()); Parser parser = new Parser(); Document document = parser.parse(data); if (MessagePartReceivedResponse.isValidWBXML(document)) { return new MessagePartReceivedResponse(document); } else { throw new RuntimeException("Failed to send the message part received request: " + "The WBXML response data from the remote server is not a valid " + "MessagePartReceivedResponse document"); } } private MessageReceivedResponse sendMessageReceivedRequest(UUID deviceId, UUID messageId) throws Exception { MessageReceivedRequest messageReceivedRequest = new MessageReceivedRequest(deviceId, messageId); byte[] data = invokeMessagingServlet(messageReceivedRequest.toWBXML()); Parser parser = new Parser(); Document document = parser.parse(data); if (MessageReceivedResponse.isValidWBXML(document)) { return new MessageReceivedResponse(document); } else { throw new RuntimeException("Failed to send the message received request: " + "The WBXML response data from the remote server is not a valid " + "MessageReceivedResponse document"); } } }
apache-2.0
ruslansennov/vertx-consul-client
src/main/java/io/vertx/ext/consul/PreparedQueryDefinition.java
13078
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.consul; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Defines a prepared query. * * @author <a href="mailto:ruslan.sennov@gmail.com">Ruslan Sennov</a> */ @DataObject public class PreparedQueryDefinition { private String id; private String name; private String session; private String service; private String token; private String dnsTtl; private int nearestN; private List<String> dcs; private List<String> tags; private boolean passing; private Map<String, String> meta; private String templateType; private String templateRegexp; /** * Default constructor */ public PreparedQueryDefinition() {} /** * Constructor from JSON * * @param json the JSON */ public PreparedQueryDefinition(JsonObject json) { id = json.getString("ID"); name = json.getString("Name"); session = json.getString("Session"); token = json.getString("Token"); service = json.getJsonObject("Service").getString("Service"); nearestN = json.getJsonObject("Service").getJsonObject("Failover").getInteger("NearestN"); JsonArray dcsJson = json.getJsonObject("Service").getJsonObject("Failover").getJsonArray("Datacenters"); if (dcsJson != null) { dcs = dcsJson.stream().map(o -> (String) o).collect(Collectors.toList()); } passing = json.getJsonObject("Service").getBoolean("OnlyPassing"); JsonArray tagsJson = json.getJsonObject("Service").getJsonArray("Tags"); if (tagsJson != null) { tags = tagsJson.stream().map(o -> (String) o).collect(Collectors.toList()); } JsonObject metaJson = json.getJsonObject("Service").getJsonObject("NodeMeta"); if (metaJson != null) { meta = metaJson.stream().collect(Collectors.toMap(Map.Entry::getKey, e -> (String) e.getValue())); } JsonObject templateJson = json.getJsonObject("Template"); if (templateJson != null) { templateType = templateJson.getString("Type"); templateRegexp = templateJson.getString("Regexp"); } dnsTtl = json.getJsonObject("DNS").getString("TTL"); } /** * Convert to JSON * * @return the JSON */ public JsonObject toJson() { return new JsonObject() .put("ID", id) .put("Name", name) .put("Session", session) .put("Token", token) .put("Template", new JsonObject() .put("Type", templateType) .put("Regexp", templateRegexp)) .put("Service", new JsonObject() .put("Service", service) .put("Failover", new JsonObject() .put("NearestN", nearestN) .put("Datacenters", dcs)) .put("OnlyPassing", passing) .put("Tags", tags) .put("NodeMeta", meta)) .put("DNS", new JsonObject() .put("TTL", dnsTtl)); } /** * Get ID of the query * * @return ID of the query */ public String getId() { return id; } /** * Set ID of the query, always generated by Consul * * @param id ID of the query * @return reference to this, for fluency */ public PreparedQueryDefinition setId(String id) { this.id = id; return this; } /** * Get an optional friendly name that can be used to execute a query instead of using its ID * * @return name of the query */ public String getName() { return name; } /** * Set an optional friendly name that can be used to execute a query instead of using its ID * * @param name name of the query * @return reference to this, for fluency */ public PreparedQueryDefinition setName(String name) { this.name = name; return this; } /** * Get the ID of an existing session. This provides a way to automatically remove a prepared query when * the given session is invalidated. If not given the prepared query must be manually removed when no longer needed. * * @return id of session */ public String getSession() { return session; } /** * Set the ID of an existing session. This provides a way to automatically remove a prepared query when * the given session is invalidated. If not given the prepared query must be manually removed when no longer needed. * * @param session id of session * @return reference to this, for fluency */ public PreparedQueryDefinition setSession(String session) { this.session = session; return this; } /** * Get the name of the service to query * * @return service name */ public String getService() { return service; } /** * Set the name of the service to query * * @param service service name * @return reference to this, for fluency */ public PreparedQueryDefinition setService(String service) { this.service = service; return this; } /** * Get the ACL token to use each time the query is executed. This allows queries to be executed by clients * with lesser or even no ACL Token, so this should be used with care. * * @return the ACL token */ public String getToken() { return token; } /** * Set the ACL token to use each time the query is executed. This allows queries to be executed by clients * with lesser or even no ACL Token, so this should be used with care. * * @param token the ACL token * @return reference to this, for fluency */ public PreparedQueryDefinition setToken(String token) { this.token = token; return this; } /** * Get the TTL duration when query results are served over DNS. If this is specified, * it will take precedence over any Consul agent-specific configuration. * * @return the TTL duration */ public String getDnsTtl() { return dnsTtl; } /** * Set the TTL duration when query results are served over DNS. If this is specified, * it will take precedence over any Consul agent-specific configuration. * * @param dnsTtl the TTL duration * @return reference to this, for fluency */ public PreparedQueryDefinition setDnsTtl(String dnsTtl) { this.dnsTtl = dnsTtl; return this; } /** * Specifies that the query will be forwarded to up to NearestN other datacenters based on their estimated network * round trip time using Network Coordinates from the WAN gossip pool. The median round trip time from the server * handling the query to the servers in the remote datacenter is used to determine the priority. * * @return number of nearest datacenters to query */ public int getNearestN() { return nearestN; } /** * Specifies that the query will be forwarded to up to NearestN other datacenters based on their estimated network * round trip time using Network Coordinates from the WAN gossip pool. The median round trip time from the server * handling the query to the servers in the remote datacenter is used to determine the priority. * * @param nearestN number of nearest datacenters to query * @return reference to this, for fluency */ public PreparedQueryDefinition setNearestN(int nearestN) { this.nearestN = nearestN; return this; } /** * Specifies a fixed list of remote datacenters to forward the query to if there are no healthy nodes * in the local datacenter. Datacenters are queried in the order given in the list. If this option is combined * with NearestN, then the NearestN queries will be performed first, followed by the list given by Datacenters. * A given datacenter will only be queried one time during a failover, even if it is selected by both NearestN * and is listed in Datacenters. * * @return the list of remote datacenters */ public List<String> getDcs() { return dcs; } /** * Specifies a fixed list of remote datacenters to forward the query to if there are no healthy nodes * in the local datacenter. Datacenters are queried in the order given in the list. If this option is combined * with NearestN, then the NearestN queries will be performed first, followed by the list given by Datacenters. * A given datacenter will only be queried one time during a failover, even if it is selected by both NearestN * and is listed in Datacenters. * * @param dcs the list of remote datacenters * @return reference to this, for fluency */ public PreparedQueryDefinition setDcs(List<String> dcs) { this.dcs = dcs; return this; } /** * Get a list of service tags to filter the query results. For a service to pass the tag filter * it must have all of the required tags, and none of the excluded tags (prefixed with `!`). * * @return list of service tags */ public List<String> getTags() { return tags; } /** * Set a list of service tags to filter the query results. For a service to pass the tag filter * it must have all of the required tags, and none of the excluded tags (prefixed with `!`). * * @param tags list of service tags * @return reference to this, for fluency */ public PreparedQueryDefinition setTags(List<String> tags) { this.tags = tags; return this; } /** * Specifies the behavior of the query's health check filtering. If this is set to false, the results will include * nodes with checks in the passing as well as the warning states. If this is set to true, * only nodes with checks in the passing state will be returned. * * @return the passing flag */ public boolean getPassing() { return passing; } /** * Specifies the behavior of the query's health check filtering. If this is set to false, the results will include * nodes with checks in the passing as well as the warning states. If this is set to true, * only nodes with checks in the passing state will be returned. * * @param passing the passing flag * @return reference to this, for fluency */ public PreparedQueryDefinition setPassing(boolean passing) { this.passing = passing; return this; } /** * Get a list of user-defined key/value pairs that will be used for filtering the query results to nodes * with the given metadata values present. * * @return list of key/value pairs */ public Map<String, String> getMeta() { return meta; } /** * Set a list of user-defined key/value pairs that will be used for filtering the query results to nodes * with the given metadata values present. * * @param meta list of key/value pairs * @return reference to this, for fluency */ public PreparedQueryDefinition setMeta(Map<String, String> meta) { this.meta = meta; return this; } /** * The template type, which must be {@code name_prefix_match}. This means that the template will apply to * any query lookup with a name whose prefix matches the Name field of the template. * * @return the query type * @see <a href="https://www.consul.io/api/query.html#prepared-query-templates">Prepared Query Templates</a> endpoint */ public String getTemplateType() { return templateType; } /** * The template type, which must be {@code name_prefix_match}. This means that the template will apply to * any query lookup with a name whose prefix matches the Name field of the template. * * @param templateType the query type * @return reference to this, for fluency * @see <a href="https://www.consul.io/api/query.html#prepared-query-templates">Prepared Query Templates</a> endpoint */ public PreparedQueryDefinition setTemplateType(String templateType) { this.templateType = templateType; return this; } /** * Get regular expression which is used to extract fields from the entire name, once this template is selected. * * @return a regular expression * @see <a href="https://www.consul.io/api/query.html#prepared-query-templates">Prepared Query Templates</a> endpoint */ public String getTemplateRegexp() { return templateRegexp; } /** * Set regular expression which is used to extract fields from the entire name, once this template is selected. * * @param templateRegexp a regular expression * @return reference to this, for fluency * @see <a href="https://www.consul.io/api/query.html#prepared-query-templates">Prepared Query Templates</a> endpoint */ public PreparedQueryDefinition setTemplateRegexp(String templateRegexp) { this.templateRegexp = templateRegexp; return this; } }
apache-2.0
spring-projects/spring-framework
spring-context-support/src/main/java/org/springframework/scheduling/quartz/LocalTaskExecutorThreadPool.java
2843
/* * Copyright 2002-2018 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 * * https://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.springframework.scheduling.quartz; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.SchedulerConfigException; import org.quartz.spi.ThreadPool; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Quartz {@link ThreadPool} adapter that delegates to a Spring-managed * {@link Executor} instance, specified on {@link SchedulerFactoryBean}. * * @author Juergen Hoeller * @since 2.0 * @see SchedulerFactoryBean#setTaskExecutor */ public class LocalTaskExecutorThreadPool implements ThreadPool { /** Logger available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); @Nullable private Executor taskExecutor; @Override public void setInstanceId(String schedInstId) { } @Override public void setInstanceName(String schedName) { } @Override public void initialize() throws SchedulerConfigException { // Absolutely needs thread-bound Executor to initialize. this.taskExecutor = SchedulerFactoryBean.getConfigTimeTaskExecutor(); if (this.taskExecutor == null) { throw new SchedulerConfigException("No local Executor found for configuration - " + "'taskExecutor' property must be set on SchedulerFactoryBean"); } } @Override public void shutdown(boolean waitForJobsToComplete) { } @Override public int getPoolSize() { return -1; } @Override public boolean runInThread(Runnable runnable) { Assert.state(this.taskExecutor != null, "No TaskExecutor available"); try { this.taskExecutor.execute(runnable); return true; } catch (RejectedExecutionException ex) { logger.error("Task has been rejected by TaskExecutor", ex); return false; } } @Override public int blockForAvailableThreads() { // The present implementation always returns 1, making Quartz // always schedule any tasks that it feels like scheduling. // This could be made smarter for specific TaskExecutors, // for example calling {@code getMaximumPoolSize() - getActiveCount()} // on a {@code java.util.concurrent.ThreadPoolExecutor}. return 1; } }
apache-2.0
signed/intellij-community
plugins/tasks/tasks-api/src/com/intellij/tasks/config/BaseRepositoryEditor.java
10332
/* * Copyright 2000-2010 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.tasks.config; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.tasks.CommitPlaceholderProvider; import com.intellij.tasks.TaskManager; import com.intellij.tasks.TaskRepository; import com.intellij.tasks.impl.BaseRepository; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.EditorTextField; import com.intellij.ui.PanelWithAnchor; import com.intellij.ui.components.JBCheckBox; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBTabbedPane; import com.intellij.util.Consumer; import com.intellij.util.net.HttpConfigurable; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; /** * @author Dmitry Avdeev */ public class BaseRepositoryEditor<T extends BaseRepository> extends TaskRepositoryEditor implements PanelWithAnchor { protected JBLabel myUrlLabel; protected JTextField myURLText; protected JTextField myUserNameText; protected JBLabel myUsernameLabel; protected JCheckBox myShareUrlCheckBox; protected JPasswordField myPasswordText; protected JBLabel myPasswordLabel; protected JButton myTestButton; private JPanel myPanel; private JBCheckBox myUseProxy; private JButton myProxySettingsButton; protected JCheckBox myUseHttpAuthenticationCheckBox; protected JPanel myCustomPanel; private JBCheckBox myAddCommitMessage; private JBLabel myComment; private JPanel myEditorPanel; protected JBCheckBox myLoginAnonymouslyJBCheckBox; protected JBTabbedPane myTabbedPane; private JTextPane myAdvertiser; private boolean myApplying; protected Project myProject; protected final T myRepository; private final Consumer<T> myChangeListener; private final Document myDocument; private final Editor myEditor; private JComponent myAnchor; public BaseRepositoryEditor(final Project project, final T repository, Consumer<T> changeListener) { myProject = project; myRepository = repository; myChangeListener = changeListener; myTestButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { afterTestConnection(TaskManager.getManager(project).testConnection(repository)); } }); myProxySettingsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { HttpConfigurable.editConfigurable(myPanel); enableButtons(); doApply(); } }); myURLText.setText(repository.getUrl()); myUserNameText.setText(repository.getUsername()); myPasswordText.setText(repository.getPassword()); myShareUrlCheckBox.setSelected(repository.isShared()); myUseProxy.setSelected(repository.isUseProxy()); myUseHttpAuthenticationCheckBox.setSelected(repository.isUseHttpAuthentication()); myUseHttpAuthenticationCheckBox.setVisible(repository.isSupported(TaskRepository.BASIC_HTTP_AUTHORIZATION)); myLoginAnonymouslyJBCheckBox.setVisible(repository.isSupported(TaskRepository.LOGIN_ANONYMOUSLY)); myLoginAnonymouslyJBCheckBox.setSelected(repository.isLoginAnonymously()); myLoginAnonymouslyJBCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { loginAnonymouslyChanged(!myLoginAnonymouslyJBCheckBox.isSelected()); } }); myAddCommitMessage.setSelected(repository.isShouldFormatCommitMessage()); myDocument = EditorFactory.getInstance().createDocument(repository.getCommitMessageFormat()); myEditor = EditorFactory.getInstance().createEditor(myDocument); myEditor.getSettings().setCaretRowShown(false); myEditorPanel.add(myEditor.getComponent(), BorderLayout.CENTER); setupPlaceholdersComment(); String advertiser = repository.getRepositoryType().getAdvertiser(); if (advertiser != null) { Messages.installHyperlinkSupport(myAdvertiser); myAdvertiser.setText(advertiser); } else { myAdvertiser.setVisible(false); } installListener(myAddCommitMessage); installListener(myDocument); installListener(myURLText); installListener(myUserNameText); installListener(myPasswordText); installListener(myShareUrlCheckBox); installListener(myUseProxy); installListener(myUseHttpAuthenticationCheckBox); installListener(myLoginAnonymouslyJBCheckBox); enableButtons(); enableEditor(); JComponent customPanel = createCustomPanel(); if (customPanel != null) { myCustomPanel.add(customPanel, BorderLayout.CENTER); } setAnchor(myUseProxy); loginAnonymouslyChanged(!myLoginAnonymouslyJBCheckBox.isSelected()); } private void setupPlaceholdersComment() { StringBuilder comment = new StringBuilder(myRepository.getComment()); CommitPlaceholderProvider[] extensions = Extensions.getExtensions(CommitPlaceholderProvider.EXTENSION_POINT_NAME); for (CommitPlaceholderProvider extension : extensions) { String[] placeholders = extension.getPlaceholders(myRepository); for (String placeholder : placeholders) { comment.append(", {").append(placeholder).append("}"); String description = extension.getPlaceholderDescription(placeholder); if (description != null) { comment.append(" (").append(description).append(")"); } } } myComment.setText("Available placeholders: " + comment); } protected final void updateCustomPanel() { myCustomPanel.removeAll(); JComponent customPanel = createCustomPanel(); if (customPanel != null) { myCustomPanel.add(customPanel, BorderLayout.CENTER); } myCustomPanel.repaint(); } private void loginAnonymouslyChanged(boolean enabled) { myUsernameLabel.setEnabled(enabled); myUserNameText.setEnabled(enabled); myPasswordLabel.setEnabled(enabled); myPasswordText.setEnabled(enabled); myUseHttpAuthenticationCheckBox.setEnabled(enabled); } @Nullable protected JComponent createCustomPanel() { return null; } protected void afterTestConnection(final boolean connectionSuccessful) { } protected void enableButtons() { myUseProxy.setEnabled(HttpConfigurable.getInstance().USE_HTTP_PROXY); if (!HttpConfigurable.getInstance().USE_HTTP_PROXY) { myUseProxy.setSelected(false); } } protected void installListener(JCheckBox checkBox) { checkBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doApply(); } }); } protected void installListener(JTextField textField) { textField.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { ApplicationManager.getApplication().invokeLater(() -> doApply()); } }); } protected void installListener(JComboBox comboBox) { comboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(final ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { doApply(); } } }); } protected void installListener(final Document document) { document.addDocumentListener(new com.intellij.openapi.editor.event.DocumentAdapter() { @Override public void documentChanged(com.intellij.openapi.editor.event.DocumentEvent e) { doApply(); } }); } protected void installListener(EditorTextField editor) { installListener(editor.getDocument()); } protected void doApply() { if (!myApplying) { try { myApplying = true; apply(); enableEditor(); } finally { myApplying = false; } } } private void enableEditor() { boolean selected = myAddCommitMessage.isSelected(); UIUtil.setEnabled(myEditorPanel, selected, true); ((EditorEx)myEditor).setRendererMode(!selected); } public JComponent createComponent() { return myPanel; } @Override public JComponent getPreferredFocusedComponent() { return myURLText; } @Override public void dispose() { EditorFactory.getInstance().releaseEditor(myEditor); } public void apply() { myRepository.setUrl(myURLText.getText().trim()); myRepository.setUsername(myUserNameText.getText().trim()); //noinspection deprecation myRepository.setPassword(myPasswordText.getText()); myRepository.setShared(myShareUrlCheckBox.isSelected()); myRepository.setUseProxy(myUseProxy.isSelected()); myRepository.setUseHttpAuthentication(myUseHttpAuthenticationCheckBox.isSelected()); myRepository.setLoginAnonymously(myLoginAnonymouslyJBCheckBox.isSelected()); myRepository.setShouldFormatCommitMessage(myAddCommitMessage.isSelected()); myRepository.setCommitMessageFormat(myDocument.getText()); myChangeListener.consume(myRepository); } @Override public JComponent getAnchor() { return myAnchor; } @Override public void setAnchor(@Nullable final JComponent anchor) { myAnchor = anchor; myUrlLabel.setAnchor(anchor); myUsernameLabel.setAnchor(anchor); myPasswordLabel.setAnchor(anchor); myUseProxy.setAnchor(anchor); } }
apache-2.0
vladmihalcea/high-performance-java-persistence
core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/time/JavaSqlDateTest.java
4905
package com.vladmihalcea.book.hpjp.hibernate.time; import com.vladmihalcea.book.hpjp.util.AbstractMySQLIntegrationTest; import org.junit.Test; import javax.persistence.*; import java.sql.Date; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import static org.junit.Assert.assertEquals; /** * @author Vlad Mihalcea */ public class JavaSqlDateTest extends AbstractMySQLIntegrationTest { @Override protected Class<?>[] entities() { return new Class<?>[]{ Post.class, UserAccount.class }; } @Test public void test() { doInJPA(entityManager -> { UserAccount user = new UserAccount() .setId(1L) .setFirstName("Vlad") .setLastName("Mihalcea") .setSubscribedOn( parseDate("2013-09-29") ); Post post = new Post() .setId(1L) .setTitle("High-Performance Java Persistence") .setCreatedBy(user) .setPublishedOn( parseTimestamp("2020-05-01 12:30:00") ); entityManager.persist(user); entityManager.persist(post); }); doInJPA(entityManager -> { Post post = entityManager.find( Post.class, 1L ); assertEquals( parseTimestamp("2020-05-01 12:30:00"), post.getPublishedOn() ); UserAccount userAccount = post.getCreatedBy(); assertEquals( parseDate("2013-09-29"), userAccount.getSubscribedOn() ); }); } private final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private java.sql.Date parseDate(String date) { try { return new Date(DATE_FORMAT.parse(date).getTime()); } catch (ParseException e) { throw new IllegalArgumentException(e); } } private java.sql.Timestamp parseTimestamp(String timestamp) { try { return new Timestamp(DATE_TIME_FORMAT.parse(timestamp).getTime()); } catch (ParseException e) { throw new IllegalArgumentException(e); } } @Entity(name = "Post") @Table(name = "post") public static class Post { @Id private Long id; @Column(length = 100) private String title; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_account_id") private UserAccount createdBy; @Column(name = "published_on") private java.sql.Timestamp publishedOn; public Long getId() { return id; } public Post setId(Long id) { this.id = id; return this; } public String getTitle() { return title; } public Post setTitle(String title) { this.title = title; return this; } public UserAccount getCreatedBy() { return createdBy; } public Post setCreatedBy(UserAccount createdBy) { this.createdBy = createdBy; return this; } public java.sql.Timestamp getPublishedOn() { return publishedOn; } public Post setPublishedOn(java.sql.Timestamp publishedOn) { this.publishedOn = publishedOn; return this; } } @Entity(name = "UserAccount") @Table(name = "user_account") public static class UserAccount { @Id private Long id; @Column(name = "first_name", length = 50) private String firstName; @Column(name = "last_name", length = 50) private String lastName; @Column(name = "subscribed_on") private java.sql.Date subscribedOn; public Long getId() { return id; } public UserAccount setId(Long id) { this.id = id; return this; } public String getFirstName() { return firstName; } public UserAccount setFirstName(String firstName) { this.firstName = firstName; return this; } public String getLastName() { return lastName; } public UserAccount setLastName(String lastName) { this.lastName = lastName; return this; } public java.sql.Date getSubscribedOn() { return subscribedOn; } public UserAccount setSubscribedOn(java.sql.Date subscribedOn) { this.subscribedOn = subscribedOn; return this; } } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-codedeploy/src/main/java/com/amazonaws/services/codedeploy/model/InvalidInstanceStatusException.java
1243
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codedeploy.model; import javax.annotation.Generated; /** * <p> * The specified instance status does not exist. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InvalidInstanceStatusException extends com.amazonaws.services.codedeploy.model.AmazonCodeDeployException { private static final long serialVersionUID = 1L; /** * Constructs a new InvalidInstanceStatusException with the specified error message. * * @param message * Describes the error encountered. */ public InvalidInstanceStatusException(String message) { super(message); } }
apache-2.0
hxf0801/jbpm
jbpm-flow/src/main/java/org/jbpm/process/instance/impl/RuleConstraintEvaluator.java
3360
/** * Copyright 2005 JBoss 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.jbpm.process.instance.impl; import java.io.Serializable; import org.drools.core.common.InternalAgenda; import org.jbpm.process.instance.ProcessInstance; import org.jbpm.workflow.core.Constraint; import org.jbpm.workflow.core.Node; import org.jbpm.workflow.instance.NodeInstance; import org.kie.api.definition.process.Connection; import org.kie.api.runtime.process.WorkflowProcessInstance; /** * Default implementation of a constraint. * * @author <a href="mailto:kris_verlaenen@hotmail.com">Kris Verlaenen</a> */ public class RuleConstraintEvaluator implements Constraint, ConstraintEvaluator, Serializable { private static final long serialVersionUID = 510l; private String name; private String constraint; private int priority; private String dialect; private String type; private boolean isDefault; public String getConstraint() { return this.constraint; } public void setConstraint(final String constraint) { this.constraint = constraint; } public String getName() { return this.name; } public void setName(final String name) { this.name = name; } public String toString() { return this.name; } public int getPriority() { return this.priority; } public void setPriority(final int priority) { this.priority = priority; } public String getDialect() { return dialect; } public void setDialect(String dialect) { this.dialect = dialect; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isDefault() { return isDefault; } public void setDefault(boolean isDefault) { this.isDefault = isDefault; } public boolean evaluate(NodeInstance instance, Connection connection, Constraint constraint) { WorkflowProcessInstance processInstance = instance.getProcessInstance(); InternalAgenda agenda = (InternalAgenda) ((ProcessInstance) processInstance).getKnowledgeRuntime().getAgenda(); String rule = "RuleFlow-Split-" + processInstance.getProcessId() + "-" + ((Node) instance.getNode()).getUniqueId() + "-" + ((Node) connection.getTo()).getUniqueId() + "-" + connection.getToType(); boolean isActive = agenda.isRuleActiveInRuleFlowGroup( "DROOLS_SYSTEM", rule, processInstance.getId() ); return isActive; } public Object getMetaData(String name) { return null; } public void setMetaData(String name, Object value) { // Do nothing } }
apache-2.0
yanguangkun/KunSoftware_Tour
src/main/java/com/kunsoftware/mapper/CommentsMapper.java
793
package com.kunsoftware.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.kunsoftware.entity.Comments; import com.kunsoftware.page.PageInfo; public interface CommentsMapper { int deleteByPrimaryKey(Integer id); int insert(Comments record); int insertSelective(Comments record); Comments selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Comments record); int updateByPrimaryKey(Comments record); List<Comments> getCommentsListPage(@Param("audit") String audit,@Param("reply") String reply,@Param("productResourceId") Integer productResourceId,@Param("page") PageInfo page); Comments selectByProduct(@Param("productResourceId") Integer productResourceId,@Param("memberId") Integer memberId); }
apache-2.0
javild/opencga
opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/adaptors/VariantQueryException.java
4299
/* * Copyright 2015-2016 OpenCB * * 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.opencb.opencga.storage.core.variant.adaptors; import org.opencb.commons.datastore.core.Query; import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor.VariantQueryParams; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Created on 29/01/16 . * * @author Jacobo Coll &lt;jacobo167@gmail.com&gt; */ public class VariantQueryException extends IllegalArgumentException { private Query query = null; public VariantQueryException(String message) { super(message); } public VariantQueryException(String message, Throwable cause) { super(message, cause); } public Query getQuery() { return query; } public VariantQueryException setQuery(Query query) { if (this.query != null) { throw new UnsupportedOperationException(); } this.query = query; return this; } public static VariantQueryException malformedParam(VariantQueryParams queryParam, String value) { return malformedParam(queryParam, value, "Expected: " + queryParam.description()); } public static VariantQueryException malformedParam(VariantQueryParams queryParam, String value, String message) { return new VariantQueryException("Malformed \"" + queryParam.key() + "\" query : \"" + value + "\". " + message); } public static VariantQueryException studyNotFound(String study) { return studyNotFound(study, Collections.emptyList()); } public static VariantQueryException studyNotFound(String study, Collection<String> availableStudies) { return new VariantQueryException("Study { name: \"" + study + "\" } not found." + (availableStudies == null || availableStudies.isEmpty() ? "" : " Available studies: " + availableStudies)); } public static VariantQueryException studyNotFound(int studyId) { return studyNotFound(studyId, Collections.emptyList()); } public static VariantQueryException studyNotFound(int studyId, Collection<String> availableStudies) { return new VariantQueryException("Study { id: " + studyId + " } not found." + (availableStudies == null || availableStudies.isEmpty() ? "" : " Available studies: " + availableStudies)); } public static VariantQueryException cohortNotFound(int cohortId, int studyId, Collection<String> availableCohorts) { return new VariantQueryException("Cohort { id: " + cohortId + " } not found in study { id: " + studyId + " }." + (availableCohorts == null || availableCohorts.isEmpty() ? "" : " Available cohorts: " + availableCohorts)); } public static VariantQueryException cohortNotFound(String cohortId, int studyId, Collection<String> availableCohorts) { return new VariantQueryException("Cohort { name: \"" + cohortId + "\" } not found in study { id: " + studyId + " }." + (availableCohorts == null || availableCohorts.isEmpty() ? "" : " Available cohorts: " + availableCohorts)); } public static VariantQueryException missingStudyForSample(String sample, List<String> availableStudies) { return new VariantQueryException("Unknown sample \"" + sample + "\". Please, specify the study belonging." + (availableStudies == null || availableStudies.isEmpty() ? "" : " Available studies: " + availableStudies)); } // public static VariantQueryException missingStudy() { // // } public static VariantQueryException sampleNotFound(Object sample, Object study) { return new VariantQueryException("Sample " + sample + " not found in study " + study); } }
apache-2.0
kokorin/MyEuler
src/java/problem/h000/d000/Problem006.java
997
package problem.h000.d000; import problem.Problem; import java.util.stream.LongStream; /** * The sum of the squares of the first ten natural numbers is, * 1<sup>2</sup> + 2<sup>2</sup> + ... + 10<sup>2</sup> = 385 * The square of the sum of the first ten natural numbers is, * (1 + 2 + ... + 10)<sup>2</sup> = 55<sup>2</sup> = 3025 * <p> * Hence the difference between the sum of the squares of the first ten natural numbers * and the square of the sum is 3025 ? 385 = 2640. * <p> * Find the difference between the sum of the squares of the first one hundred natural numbers * and the square of the sum. */ public class Problem006 implements Problem { private static final long N = 100; @Override public long solve() { long summOfSquares = LongStream.rangeClosed(1, N). map(num -> num * num). sum(); long summ = (1 + N) * N / 2; long squareOfSum = summ * summ; return squareOfSum - summOfSquares; } }
apache-2.0
wspeirs/sop4j-base
src/main/java/com/sop4j/base/google/common/collect/ForwardingImmutableMap.java
945
/* * Copyright (C) 2012 The Guava 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 com.sop4j.base.google.common.collect; import com.sop4j.base.google.common.annotations.GwtCompatible; /** * Unused stub class, unreferenced under Java and manually emulated under GWT. * * @author Chris Povirk */ @GwtCompatible(emulated = true) abstract class ForwardingImmutableMap<K, V> { private ForwardingImmutableMap() {} }
apache-2.0
Catherine22/Algorithms
src/main/java/com/catherine/sorting/MergeSort.java
1951
package com.catherine.sorting; import java.util.Arrays; /** * @param <T> * @author : Catherine */ public class MergeSort<T extends Comparable<? super T>> { public void sort(Comparable<T> a[]) { Comparable<T>[] aux = Arrays.copyOf(a, a.length); sort(a, aux, 0, a.length - 1); } private void sort(Comparable<T> a[], Comparable<T> aux[], int lo, int hi) { if (hi <= lo) { return; } int mid = (lo + hi) / 2; sort(a, aux, lo, mid); sort(a, aux, mid + 1, hi); merge(a, aux, lo, mid, hi); } /** * For example, given an array a [0, 1, 2, 3, 4, 5], the auxiliary array is the copy of a. * This method splits aux into two subarrays. The first group starts from aux[lo] to aux[mid], * another group ranged from aux[mid + 1] to aux[hi] * <p> * A precondition for this method to work is that the subarrays of the given array must be sorted. * I.e., a[lo] - a[mid] and a[mid + 1] to a[hi] * * @param a the original array, this array will be sorted * @param aux the auxiliary array, a copy of the original array a * @param lo the lowest position * @param mid the middle position * @param hi the highest position */ @SuppressWarnings("unchecked") private void merge(Comparable<T> a[], Comparable<T> aux[], int lo, int mid, int hi) { int i = lo; // a pointer in subarray 1 int j = mid + 1; // a pointer in subarray 2 // copy the array a for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } for (int k = lo; k <= hi; k++) { if (i > mid) { a[k] = aux[j++]; } else if (j > hi) { a[k] = aux[i++]; } else if (aux[i].compareTo((T) aux[j]) <= 0) { a[k] = aux[i++]; } else { a[k] = aux[j++]; } } } }
apache-2.0
OpenGamma/Strata
modules/basics/src/test/java/com/opengamma/strata/basics/BasicProjectAssertions.java
1023
/* * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.basics; import com.opengamma.strata.basics.currency.CurrencyAmount; import com.opengamma.strata.collect.CollectProjectAssertions; /** * Helper class to allow custom AssertJ assertions to be * accessible via the same static import as the standard * assertions. * <p> * Prefer to statically import {@link #assertThat(CurrencyAmount)} * from this class rather than {@link CurrencyAmountAssert#assertThat(CurrencyAmount)}. */ public class BasicProjectAssertions extends CollectProjectAssertions { /** * Create an {@code Assert} instance that enables * assertions on {@code CurrencyAmount} objects. * * @param amount the amount to create an {@code Assert} for * @return an {@code Assert} instance */ public static CurrencyAmountAssert assertThat(CurrencyAmount amount) { return CurrencyAmountAssert.assertThat(amount); } }
apache-2.0
spring-projects/spring-framework
spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateEntityManagerFactoryIntegrationTests.java
3815
/* * Copyright 2002-2019 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 * * https://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.springframework.orm.jpa.hibernate; import jakarta.persistence.EntityManager; import org.hibernate.FlushMode; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.jupiter.api.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.target.SingletonTargetSource; import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests; import org.springframework.orm.jpa.EntityManagerFactoryInfo; import org.springframework.orm.jpa.EntityManagerProxy; import static org.assertj.core.api.Assertions.assertThat; /** * Hibernate-specific JPA tests. * * @author Juergen Hoeller * @author Rod Johnson */ @SuppressWarnings("deprecation") public class HibernateEntityManagerFactoryIntegrationTests extends AbstractContainerEntityManagerFactoryIntegrationTests { @Override protected String[] getConfigLocations() { return new String[] {"/org/springframework/orm/jpa/hibernate/hibernate-manager.xml", "/org/springframework/orm/jpa/memdb.xml", "/org/springframework/orm/jpa/inject.xml"}; } @Test public void testCanCastNativeEntityManagerFactoryToHibernateEntityManagerFactoryImpl() { EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory; boolean condition1 = emfi.getNativeEntityManagerFactory() instanceof org.hibernate.jpa.HibernateEntityManagerFactory; assertThat(condition1).isTrue(); // as of Hibernate 5.2 boolean condition = emfi.getNativeEntityManagerFactory() instanceof SessionFactory; assertThat(condition).isTrue(); } @Test public void testCanCastSharedEntityManagerProxyToHibernateEntityManager() { boolean condition1 = sharedEntityManager instanceof org.hibernate.jpa.HibernateEntityManager; assertThat(condition1).isTrue(); // as of Hibernate 5.2 boolean condition = ((EntityManagerProxy) sharedEntityManager).getTargetEntityManager() instanceof Session; assertThat(condition).isTrue(); } @Test public void testCanUnwrapAopProxy() { EntityManager em = entityManagerFactory.createEntityManager(); EntityManager proxy = ProxyFactory.getProxy(EntityManager.class, new SingletonTargetSource(em)); boolean condition = em instanceof org.hibernate.jpa.HibernateEntityManager; assertThat(condition).isTrue(); boolean condition1 = proxy instanceof org.hibernate.jpa.HibernateEntityManager; assertThat(condition1).isFalse(); assertThat(proxy.unwrap(org.hibernate.jpa.HibernateEntityManager.class) != null).isTrue(); assertThat(proxy.unwrap(org.hibernate.jpa.HibernateEntityManager.class)).isSameAs(em); assertThat(proxy.getDelegate()).isSameAs(em.getDelegate()); } @Test // SPR-16956 public void testReadOnly() { assertThat(sharedEntityManager.unwrap(Session.class).getHibernateFlushMode()).isSameAs(FlushMode.AUTO); assertThat(sharedEntityManager.unwrap(Session.class).isDefaultReadOnly()).isFalse(); endTransaction(); this.transactionDefinition.setReadOnly(true); startNewTransaction(); assertThat(sharedEntityManager.unwrap(Session.class).getHibernateFlushMode()).isSameAs(FlushMode.MANUAL); assertThat(sharedEntityManager.unwrap(Session.class).isDefaultReadOnly()).isTrue(); } }
apache-2.0
cran/rkafkajars
java/javax/activation/FileDataSource.java
5279
/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * glassfish/bootstrap/legal/CDDLv1.0.txt or * https://glassfish.dev.java.net/public/CDDLv1.0.html. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ /* * @(#)FileDataSource.java 1.9 05/11/16 * * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved. */ package javax.activation; import java.io.InputStream; import java.io.OutputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import com.sun.activation.registries.MimeTypeFile; /** * The FileDataSource class implements a simple DataSource object * that encapsulates a file. It provides data typing services via * a FileTypeMap object. <p> * * <b>FileDataSource Typing Semantics</b><p> * * The FileDataSource class delegates data typing of files * to an object subclassed from the FileTypeMap class. * The <code>setFileTypeMap</code> method can be used to explicitly * set the FileTypeMap for an instance of FileDataSource. If no * FileTypeMap is set, the FileDataSource will call the FileTypeMap's * getDefaultFileTypeMap method to get the System's default FileTypeMap. * * @see javax.activation.DataSource * @see javax.activation.FileTypeMap * @see javax.activation.MimetypesFileTypeMap */ public class FileDataSource implements DataSource { // keep track of original 'ref' passed in, non-null // one indicated which was passed in: private File _file = null; private FileTypeMap typeMap = null; /** * Creates a FileDataSource from a File object. <i>Note: * The file will not actually be opened until a method is * called that requires the file to be opened.</i> * * @param file the file */ public FileDataSource(File file) { _file = file; // save the file Object... } /** * Creates a FileDataSource from * the specified path name. <i>Note: * The file will not actually be opened until a method is * called that requires the file to be opened.</i> * * @param name the system-dependent file name. */ public FileDataSource(String name) { this(new File(name)); // use the file constructor } /** * This method will return an InputStream representing the * the data and will throw an IOException if it can * not do so. This method will return a new * instance of InputStream with each invocation. * * @return an InputStream */ public InputStream getInputStream() throws IOException { return new FileInputStream(_file); } /** * This method will return an OutputStream representing the * the data and will throw an IOException if it can * not do so. This method will return a new instance of * OutputStream with each invocation. * * @return an OutputStream */ public OutputStream getOutputStream() throws IOException { return new FileOutputStream(_file); } /** * This method returns the MIME type of the data in the form of a * string. This method uses the currently installed FileTypeMap. If * there is no FileTypeMap explictly set, the FileDataSource will * call the <code>getDefaultFileTypeMap</code> method on * FileTypeMap to acquire a default FileTypeMap. <i>Note: By * default, the FileTypeMap used will be a MimetypesFileTypeMap.</i> * * @return the MIME Type * @see javax.activation.FileTypeMap#getDefaultFileTypeMap */ public String getContentType() { // check to see if the type map is null? if (typeMap == null) return FileTypeMap.getDefaultFileTypeMap().getContentType(_file); else return typeMap.getContentType(_file); } /** * Return the <i>name</i> of this object. The FileDataSource * will return the file name of the object. * * @return the name of the object. * @see javax.activation.DataSource */ public String getName() { return _file.getName(); } /** * Return the File object that corresponds to this FileDataSource. * @return the File object for the file represented by this object. */ public File getFile() { return _file; } /** * Set the FileTypeMap to use with this FileDataSource * * @param map The FileTypeMap for this object. */ public void setFileTypeMap(FileTypeMap map) { typeMap = map; } }
apache-2.0
sjsucmpe275/fluffy
src/gash/router/server/GlobalCommandChannelHandler.java
4272
/*package gash.router.server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import gash.router.client.CommInit; import gash.router.container.RoutingConf; import gash.router.server.messages.cmd_messages.handlers.ICmdMessageHandler; import global.Global.GlobalCommandMessage; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import pipe.common.Common.Header; import pipe.work.Work.Task; import pipe.work.Work.WorkMessage; import routing.Pipe.CommandMessage; public class GlobalCommandChannelHandler extends SimpleChannelInboundHandler<GlobalCommandMessage> { protected static Logger logger = LoggerFactory.getLogger("Global cmd"); private RoutingConf conf; private ICmdMessageHandler cmdMessageHandler; private Worker worker; private EventLoopGroup group; private ChannelFuture channel; public GlobalCommandChannelHandler(RoutingConf conf) throws Exception { if (conf != null) { this.conf = conf; } init(); } private void init() { group = new NioEventLoopGroup(); try { CommInit si = new CommInit(false); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(si); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_KEEPALIVE, true); // Make the connection attempt. channel = b.connect("localhost", conf.getWorkPort()).syncUninterruptibly(); logger.info(channel.channel().localAddress() + " -> open: " + channel.channel().isOpen() + ", write: " + channel.channel().isWritable() + ", reg: " + channel.channel().isRegistered()); } catch (Throwable ex) { ex.printStackTrace(); } } public void handleMessage(GlobalCommandMessage msg, Channel channel) { CommandMessage.Builder cmdMsg = CommandMessage.newBuilder(); if (msg == null) { // TODO add logging logger.info("ERROR: Unexpected content - " + msg); return; } if(msg.hasHeader()){ cmdMsg.setHeader(msg.getHeader()); logger.info("Received header"); } if(msg.hasErr()){ cmdMsg.setErr(msg.getErr()); logger.info("Received global error"); } if(msg.hasMessage()){ cmdMsg.setMessage(msg.getMessage()); logger.info("Received global message"); } if(msg.hasPing()){ cmdMsg.setPing(msg.getPing()); logger.info("Received global ping"); } if(msg.hasQuery()){ cmdMsg.setQuery(msg.getQuery()); logger.info("Received global query"); } if(msg.hasResponse()){ cmdMsg.setResponse(msg.getResponse()); logger.info("Received global Response"); } WorkMessage.Builder wrkMsg = WorkMessage.newBuilder(); Task.Builder task = Task.newBuilder(); Header.Builder header = Header.newBuilder(); header.setDestination(-1); header.setNodeId(-1); header.setTime(System.currentTimeMillis()); task.setTaskMessage(cmdMsg); task.setSeqId(cmdMsg.getQuery().getSequenceNo()); task.setSeriesId(cmdMsg.getQuery().getKey().hashCode()); wrkMsg.setTask(task); wrkMsg.setSecret(1); wrkMsg.setHeader(header); write(wrkMsg.build()); } public boolean write(WorkMessage msg) { if (msg == null) return false; else if (channel == null) throw new RuntimeException("missing channel"); // TODO a queue is needed to prevent overloading of the socket // connection. For the demonstration, we don't need it ChannelFuture cf = connect().writeAndFlush(msg); if (cf.isDone() && !cf.isSuccess()) { logger.error("failed to send message to server"); return false; } return true; } public Channel connect() { if (channel == null) { init(); } if (channel != null && channel.isSuccess() && channel.channel().isWritable()) return channel.channel(); else throw new RuntimeException("Not able to establish connection "); } @Override protected void channelRead0(ChannelHandlerContext gctx, GlobalCommandMessage gmsg) throws Exception { handleMessage(gmsg,gctx.channel()); } } */
apache-2.0
zhangchuanchuan/DesignMode
com/stream/strategy/example/Hand.java
937
public class Hand { public static final int HANDVALUE_GUU = 0;//石头 public static final int HANDVALUE_CHO = 1;//剪刀 public static final int HANDVALUE_PAA = 2;//布 public static final Hand[] hand = { new Hand(HANDVALUE_GUU), new Hand(HANDVALUE_CHO), new Hand(HANDVALUE_PAA) }; private static final String[] name = {"石头", "剪刀", "布"}; private int handValue; private Hand(int handValue) { this.handValue = handValue; } public static Hand getHand(int handValue) { return hand(handValue); } public boolean isStrongerThan(Hand h) { return fight(h) == 1; } public boolean isWeakerThan(Hand h) { return fight(h) == -1; } private int fight(Hand h) { if (this == h) { return 0; } else if ((this.handValue + 1) % 3 ==h.handValue) { return 1; } else { return -1; } } public String toString() { return name[handValue]; } }
apache-2.0
ontopia/ontopia
ontopia-realm/src/test/java/net/ontopia/topicmaps/nav2/realm/TMLoginModuleTest.java
6146
/* * #! * Ontopia Realm * #- * Copyright (C) 2001 - 2013 The Ontopia 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 net.ontopia.topicmaps.nav2.realm; import java.io.IOException; import java.security.Principal; import java.util.Collection; import java.util.Iterator; import java.util.Map; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.TextOutputCallback; import javax.security.auth.callback.UnsupportedCallbackException; import org.junit.Assert; import org.junit.Test; /** * INTERNAL: Tests the TMLoginModule class. */ public class TMLoginModuleTest { @Test public void testLoginModulePlaintextSucce() throws Exception{ String[] tokens = new String[] { "plaintext", "feil", "plaintext", "hemmelig1", "plaintext", "hemmelig3", "plaintext", "hemmelig1" }; String[] pnames = new String[] { "plaintext", "user", "Administrator" }; Map options = new java.util.HashMap(); options.put("hashmethod", "plaintext"); options.put("topicmap", "tmloginmodule.ltm"); doLoginTests(tokens, pnames, options); } @Test public void testLoginModuleBase64() throws Exception{ String[] tokens = new String[] { "base64", "feil", "base64", "hemmelig2", "base64", "hemmelig1", "base64", "hemmelig2" }; // user (small) = implicit role // User (capt) = Role topic with "User" as topicname String[] pnames = new String[] { "base64", "user", "Administrator", "Janitor", "User" }; Map options = new java.util.HashMap(); options.put("hashmethod", "base64"); options.put("topicmap", "tmloginmodule.ltm"); doLoginTests(tokens, pnames, options); } @Test public void testLoginModuleMD5() throws Exception{ String[] tokens = new String[] { "md5", "feil", "md5", "hemmelig3", "md5", "hemmelig2", "md5", "hemmelig3" }; String[] pnames = new String[] { "md5", "user" }; Map options = new java.util.HashMap(); options.put("hashmethod", "md5"); options.put("topicmap", "tmloginmodule.ltm"); doLoginTests(tokens, pnames, options); } protected void doLoginTests(String[] tokens, String[] pnames, Map options) throws Exception { TestableTMLoginModule loginModule = new TestableTMLoginModule(); Subject subject = new Subject(); CallbackHandler callbackHandler = new CallbackHandlerImpl(tokens); Map _principals = new java.util.HashMap(); loginModule.initialize( subject, callbackHandler, _principals, options); // should fail with incorrect password Assert.assertFalse("Could log in with wrong password", loginModule.login()); Assert.assertTrue("Could not log out (1)", loginModule.logout()); // should succeed Assert.assertTrue("Could not log in with correct tokens (2)", loginModule.login()); Assert.assertTrue("Could not log out (2)", loginModule.logout()); // should fail with other user's password Assert.assertFalse("Could log in with other user's password", loginModule.login()); Assert.assertTrue("Could not log out (3)", loginModule.logout()); // should succeed Assert.assertTrue("Could not log in with correct tokens", loginModule.login()); // accept last token Assert.assertTrue("Could not commit", loginModule.commit()); // verify roles Collection principals = subject.getPrincipals(); // ISSUE: all principals have just one role subject, 'user' for // the time being, totally two principals including the user // principal. //! assertTrue("Subject does not have correct number of principals", //! principals.size() == pnames.length); Assert.assertEquals("Subject does not have correct number of principals " + java.util.Arrays.asList(principals), pnames.length, principals.size()); Iterator iter = principals.iterator(); while (iter.hasNext()) { Principal principal = (Principal)iter.next(); String pname = principal.getName(); boolean ok = false; for (int i=0; i < pnames.length; i++) { if (pnames[i].equals(pname)) { ok = true; break; } } if (!ok) Assert.fail("User did not have proper principals: " + java.util.Arrays.asList(pnames)); } } static class CallbackHandlerImpl implements CallbackHandler { protected String[] tokens; protected int index; public CallbackHandlerImpl(String[] tokens) { this.tokens = tokens; } @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { // prompt the user for a username NameCallback nc = (NameCallback)callbacks[i]; String username = tokens[index++]; nc.setName(username); } else if (callbacks[i] instanceof PasswordCallback) { // prompt the user for sensitive information PasswordCallback pc = (PasswordCallback)callbacks[i]; String password = tokens[index++]; pc.setPassword(password.toCharArray()); } else if (callbacks[i] instanceof TextOutputCallback) { // ignore } else { throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); } } } } }
apache-2.0
Kestutis-Z/World-Weather
WorldWeather/app/src/main/java/com/haringeymobile/ukweather/utils/MiscMethods.java
6832
package com.haringeymobile.ukweather.utils; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import com.haringeymobile.ukweather.R; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class MiscMethods { private static final boolean LOGS_ON = false; private static final String LOGS = "Logs"; private static final String NO_CITIES_FOUND_MESSAGE_PART_PREFIX = " # "; private static final String NO_CITIES_FOUND_MESSAGE_COORDINATES = ": 13.8,109.343; 48,77.24."; /** * A convenience method to send a log message. */ public static void log(String s) { if (LOGS_ON) Log.d(LOGS, s); } /** * Formats and represents the provided {@code double} value. * * @param d a {@code double} value * @return a textual representation of the decimal number with one decimal place */ public static String formatDoubleValue(double d, int decimalPlaces) { String pattern; switch (decimalPlaces) { case 1: pattern = "##.#"; break; case 2: pattern = "##.##"; break; default: throw new IllegalArgumentException("Provide a pattern for " + decimalPlaces + " decimal places!"); } DecimalFormat df = new DecimalFormat(pattern); return df.format(d); } /** * Determines whether the user's device can connect to network at the moment. */ public static boolean isUserOnline(Context context) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } /** * Obtains a day of the week name. * * @return weekday name in abbreviated form, e.g., Mon, Fri */ public static String getAbbreviatedWeekdayName(Date date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("E"); return simpleDateFormat.format(date); } /** * Removes surrounding transparent pixels from bitmap (if there are any). * * @param originalBitmap bitmap that may contain transparent pixels we would like to remove * @return new bitmap, which looks like an original bitmap, but with the surrounding * whitespace removed */ public static Bitmap trimBitmap(Bitmap originalBitmap) { int originalHeight = originalBitmap.getHeight(); int originalWidth = originalBitmap.getWidth(); //trimming width from left int xCoordinateOfFirstPixel = 0; for (int x = 0; x < originalWidth; x++) { if (xCoordinateOfFirstPixel == 0) { for (int y = 0; y < originalHeight; y++) { if (originalBitmap.getPixel(x, y) != Color.TRANSPARENT) { xCoordinateOfFirstPixel = x; break; } } } else break; } //trimming width from right int xCoordinateOfLastPixel = 0; for (int x = originalWidth - 1; x >= 0; x--) { if (xCoordinateOfLastPixel == 0) { for (int y = 0; y < originalHeight; y++) { if (originalBitmap.getPixel(x, y) != Color.TRANSPARENT) { xCoordinateOfLastPixel = x; break; } } } else break; } //trimming height from top int yCoordinateOfFirstPixel = 0; for (int y = 0; y < originalHeight; y++) { if (yCoordinateOfFirstPixel == 0) { for (int x = 0; x < originalWidth; x++) { if (originalBitmap.getPixel(x, y) != Color.TRANSPARENT) { yCoordinateOfFirstPixel = y; break; } } } else break; } //trimming height from bottom int yCoordinateOfLastPixel = 0; for (int y = originalHeight - 1; y >= 0; y--) { if (yCoordinateOfLastPixel == 0) { for (int x = 0; x < originalWidth; x++) { if (originalBitmap.getPixel(x, y) != Color.TRANSPARENT) { yCoordinateOfLastPixel = y; break; } } } else break; } int newBitmapWidth = xCoordinateOfLastPixel - xCoordinateOfFirstPixel; int newBitmapHeight = yCoordinateOfLastPixel - yCoordinateOfFirstPixel; return Bitmap.createBitmap(originalBitmap, xCoordinateOfFirstPixel, yCoordinateOfFirstPixel, newBitmapWidth, newBitmapHeight); } /** * Generates and formats for display an explanation how to search for new cities. * * @param res app resources * @return formatted text to be displayed in a text view */ public static String getNoCitiesFoundDialogMessage(Resources res) { String dialogMessage = NO_CITIES_FOUND_MESSAGE_PART_PREFIX; dialogMessage += res.getString(R.string.message_no_cities_found_part_1); dialogMessage += "\n"; dialogMessage += NO_CITIES_FOUND_MESSAGE_PART_PREFIX; dialogMessage += res.getString(R.string.message_no_cities_found_part_2); dialogMessage += "\n"; dialogMessage += NO_CITIES_FOUND_MESSAGE_PART_PREFIX; dialogMessage += res.getString(R.string.message_no_cities_found_part_3); dialogMessage += NO_CITIES_FOUND_MESSAGE_COORDINATES; return dialogMessage; } /** * Updates locale for app process. * * @param localeCode language and (optionally) country code, defined by ISO, eg. pt-rBR for * Portuguese in Brazil * @param res app resources */ public static void updateLocale(String localeCode, Resources res) { Locale locale; if (localeCode.contains("-r") || localeCode.contains("-")) { final String[] language_region = localeCode.split("\\-(r)?"); locale = new Locale(language_region[0], language_region[1]); } else { locale = new Locale(localeCode); } Configuration config = res.getConfiguration(); config.locale = locale; res.updateConfiguration(config, res.getDisplayMetrics()); Locale.setDefault(locale); } }
apache-2.0
tectronics/hyracks
hyracks/hyracks-dataflow-std/src/test/java/org/apache/hyracks/dataflow/std/util/MathTest.java
1331
/* * Copyright 2009-2013 by The Regents of the University of California * 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 from * * 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.hyracks.dataflow.std.util; import static org.junit.Assert.assertTrue; import java.util.Random; import org.junit.Test; public class MathTest { @Test public void testLog2() { Random random = new Random(System.currentTimeMillis()); for (int i = 0; i < 31; i++) { assertTrue(MathUtil.log2Floor((int) Math.pow(2, i)) == i); for(int x = 0; x < 10; x++){ float extra = random.nextFloat(); while (extra >= 1.0){ extra = random.nextFloat(); } assertTrue(MathUtil.log2Floor((int) Math.pow(2, i + extra)) == i); } } } }
apache-2.0
vgul/spring-boot
spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
44613
/* * Copyright 2012-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 org.springframework.boot; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.security.AccessControlException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.GenericTypeResolver; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.core.env.CommandLinePropertySource; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.core.env.SimpleCommandLinePropertySource; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StopWatch; import org.springframework.util.StringUtils; import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StandardServletEnvironment; /** * Classes that can be used to bootstrap and launch a Spring application from a Java main * method. By default class will perform the following steps to bootstrap your * application: * * <ul> * <li>Create an appropriate {@link ApplicationContext} instance (depending on your * classpath)</li> * <li>Register a {@link CommandLinePropertySource} to expose command line arguments as * Spring properties</li> * <li>Refresh the application context, loading all singleton beans</li> * <li>Trigger any {@link CommandLineRunner} beans</li> * </ul> * * In most circumstances the static {@link #run(Object, String[])} method can be called * directly from your {@literal main} method to bootstrap your application: * * <pre class="code"> * &#064;Configuration * &#064;EnableAutoConfiguration * public class MyApplication { * * // ... Bean definitions * * public static void main(String[] args) throws Exception { * SpringApplication.run(MyApplication.class, args); * } * </pre> * * <p> * For more advanced configuration a {@link SpringApplication} instance can be created and * customized before being run: * * <pre class="code"> * public static void main(String[] args) throws Exception { * SpringApplication app = new SpringApplication(MyApplication.class); * // ... customize app settings here * app.run(args) * } * </pre> * * {@link SpringApplication}s can read beans from a variety of different sources. It is * generally recommended that a single {@code @Configuration} class is used to bootstrap * your application, however, any of the following sources can also be used: * * <ul> * <li>{@link Class} - A Java class to be loaded by {@link AnnotatedBeanDefinitionReader} * </li> * <li>{@link Resource} - An XML resource to be loaded by {@link XmlBeanDefinitionReader}, * or a groovy script to be loaded by {@link GroovyBeanDefinitionReader}</li> * <li>{@link Package} - A Java package to be scanned by * {@link ClassPathBeanDefinitionScanner}</li> * <li>{@link CharSequence} - A class name, resource handle or package name to loaded as * appropriate. If the {@link CharSequence} cannot be resolved to class and does not * resolve to a {@link Resource} that exists it will be considered a {@link Package}.</li> * </ul> * * @author Phillip Webb * @author Dave Syer * @author Andy Wilkinson * @author Christian Dupuis * @author Stephane Nicoll * @author Jeremy Rickard * @see #run(Object, String[]) * @see #run(Object[], String[]) * @see #SpringApplication(Object...) */ public class SpringApplication { /** * The class name of application context that will be used by default for non-web * environments. */ public static final String DEFAULT_CONTEXT_CLASS = "org.springframework.context." + "annotation.AnnotationConfigApplicationContext"; /** * The class name of application context that will be used by default for web * environments. */ public static final String DEFAULT_WEB_CONTEXT_CLASS = "org.springframework." + "boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext"; private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext" }; /** * Default banner location. */ public static final String BANNER_LOCATION_PROPERTY_VALUE = "banner.txt"; /** * Banner location property key. */ public static final String BANNER_LOCATION_PROPERTY = "banner.location"; private static final String CONFIGURABLE_WEB_ENVIRONMENT_CLASS = "org.springframework.web.context.ConfigurableWebEnvironment"; private static final String SYSTEM_PROPERTY_JAVA_AWT_HEADLESS = "java.awt.headless"; private static final Banner DEFAULT_BANNER = new SpringBootBanner(); private static final Set<String> SERVLET_ENVIRONMENT_SOURCE_NAMES; static { Set<String> names = new HashSet<String>(); names.add(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME); names.add(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME); names.add(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME); SERVLET_ENVIRONMENT_SOURCE_NAMES = Collections.unmodifiableSet(names); } private static final Log logger = LogFactory.getLog(SpringApplication.class); private final Set<Object> sources = new LinkedHashSet<Object>(); private Class<?> mainApplicationClass; private Banner.Mode bannerMode = Banner.Mode.CONSOLE; private boolean logStartupInfo = true; private boolean addCommandLineProperties = true; private Banner banner; private ResourceLoader resourceLoader; private BeanNameGenerator beanNameGenerator; private ConfigurableEnvironment environment; private Class<? extends ConfigurableApplicationContext> applicationContextClass; private boolean webEnvironment; private boolean headless = true; private boolean registerShutdownHook = true; private List<ApplicationContextInitializer<?>> initializers; private List<ApplicationListener<?>> listeners; private Map<String, Object> defaultProperties; private Set<String> additionalProfiles = new HashSet<String>(); /** * Create a new {@link SpringApplication} instance. The application context will load * beans from the specified sources (see {@link SpringApplication class-level} * documentation for details. The instance can be customized before calling * {@link #run(String...)}. * @param sources the bean sources * @see #run(Object, String[]) * @see #SpringApplication(ResourceLoader, Object...) */ public SpringApplication(Object... sources) { initialize(sources); } /** * Create a new {@link SpringApplication} instance. The application context will load * beans from the specified sources (see {@link SpringApplication class-level} * documentation for details. The instance can be customized before calling * {@link #run(String...)}. * @param resourceLoader the resource loader to use * @param sources the bean sources * @see #run(Object, String[]) * @see #SpringApplication(ResourceLoader, Object...) */ public SpringApplication(ResourceLoader resourceLoader, Object... sources) { this.resourceLoader = resourceLoader; initialize(sources); } @SuppressWarnings({ "unchecked", "rawtypes" }) private void initialize(Object[] sources) { if (sources != null && sources.length > 0) { this.sources.addAll(Arrays.asList(sources)); } this.webEnvironment = deduceWebEnvironment(); setInitializers((Collection) getSpringFactoriesInstances( ApplicationContextInitializer.class)); setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = deduceMainApplicationClass(); } private boolean deduceWebEnvironment() { for (String className : WEB_ENVIRONMENT_CLASSES) { if (!ClassUtils.isPresent(className, null)) { return false; } } return true; } private Class<?> deduceMainApplicationClass() { try { StackTraceElement[] stackTrace = new RuntimeException().getStackTrace(); for (StackTraceElement stackTraceElement : stackTrace) { if ("main".equals(stackTraceElement.getMethodName())) { return Class.forName(stackTraceElement.getClassName()); } } } catch (ClassNotFoundException ex) { // Swallow and continue } return null; } /** * Run the Spring application, creating and refreshing a new * {@link ApplicationContext}. * @param args the application arguments (usually passed from a Java main method) * @return a running {@link ApplicationContext} */ public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; configureHeadlessProperty(); SpringApplicationRunListeners listeners = getRunListeners(args); listeners.started(); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments( args); context = createAndRefreshContext(listeners, applicationArguments); afterRefresh(context, applicationArguments); listeners.finished(context, null); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass) .logStarted(getApplicationLog(), stopWatch); } return context; } catch (Throwable ex) { handleRunFailure(context, listeners, ex); throw new IllegalStateException(ex); } } private ConfigurableApplicationContext createAndRefreshContext( SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) { ConfigurableApplicationContext context; // Create and configure the environment ConfigurableEnvironment environment = getOrCreateEnvironment(); configureEnvironment(environment, applicationArguments.getSourceArgs()); listeners.environmentPrepared(environment); if (isWebEnvironment(environment) && !this.webEnvironment) { environment = convertToStandardEnvironment(environment); } if (this.bannerMode != Banner.Mode.OFF) { printBanner(environment); } // Create, load, refresh and run the ApplicationContext context = createApplicationContext(); context.setEnvironment(environment); postProcessApplicationContext(context); applyInitializers(context); listeners.contextPrepared(context); if (this.logStartupInfo) { logStartupInfo(context.getParent() == null); logStartupProfileInfo(context); } // Add boot specific singleton beans context.getBeanFactory().registerSingleton("springApplicationArguments", applicationArguments); // Load the sources Set<Object> sources = getSources(); Assert.notEmpty(sources, "Sources must not be empty"); load(context, sources.toArray(new Object[sources.size()])); listeners.contextLoaded(context); // Refresh the context refresh(context); if (this.registerShutdownHook) { try { context.registerShutdownHook(); } catch (AccessControlException ex) { // Not allowed in some environments. } } return context; } private void configureHeadlessProperty() { System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, System.getProperty( SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless))); } private SpringApplicationRunListeners getRunListeners(String[] args) { Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class }; return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances( SpringApplicationRunListener.class, types, this, args)); } private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type) { return getSpringFactoriesInstances(type, new Class<?>[] {}); } private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Use names and ensure unique to protect against duplicates Set<String> names = new LinkedHashSet<String>( SpringFactoriesLoader.loadFactoryNames(type, classLoader)); List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); AnnotationAwareOrderComparator.sort(instances); return instances; } @SuppressWarnings("unchecked") private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args, Set<String> names) { List<T> instances = new ArrayList<T>(names.size()); for (String name : names) { try { Class<?> instanceClass = ClassUtils.forName(name, classLoader); Assert.isAssignable(type, instanceClass); Constructor<?> constructor = instanceClass .getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); T instance = (T) constructor.newInstance(args); instances.add(instance); } catch (Throwable ex) { throw new IllegalArgumentException( "Cannot instantiate " + type + " : " + name, ex); } } return instances; } private ConfigurableEnvironment getOrCreateEnvironment() { if (this.environment != null) { return this.environment; } if (this.webEnvironment) { return new StandardServletEnvironment(); } return new StandardEnvironment(); } /** * Template method delegating to * {@link #configurePropertySources(ConfigurableEnvironment, String[])} and * {@link #configureProfiles(ConfigurableEnvironment, String[])} in that order. * Override this method for complete control over Environment customization, or one of * the above for fine-grained control over property sources or profiles, respectively. * @param environment this application's environment * @param args arguments passed to the {@code run} method * @see #configureProfiles(ConfigurableEnvironment, String[]) * @see #configurePropertySources(ConfigurableEnvironment, String[]) */ protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) { configurePropertySources(environment, args); configureProfiles(environment, args); } private boolean isWebEnvironment(ConfigurableEnvironment environment) { try { Class<?> webEnvironmentClass = ClassUtils .forName(CONFIGURABLE_WEB_ENVIRONMENT_CLASS, getClassLoader()); return (webEnvironmentClass.isInstance(environment)); } catch (Throwable ex) { return false; } } private ConfigurableEnvironment convertToStandardEnvironment( ConfigurableEnvironment environment) { StandardEnvironment result = new StandardEnvironment(); removeAllPropertySources(result.getPropertySources()); result.setActiveProfiles(environment.getActiveProfiles()); for (PropertySource<?> propertySource : environment.getPropertySources()) { if (!SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(propertySource.getName())) { result.getPropertySources().addLast(propertySource); } } return result; } private void removeAllPropertySources(MutablePropertySources propertySources) { Set<String> names = new HashSet<String>(); for (PropertySource<?> propertySource : propertySources) { names.add(propertySource.getName()); } for (String name : names) { propertySources.remove(name); } } /** * Add, remove or re-order any {@link PropertySource}s in this application's * environment. * @param environment this application's environment * @param args arguments passed to the {@code run} method * @see #configureEnvironment(ConfigurableEnvironment, String[]) */ protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) { sources.addLast( new MapPropertySource("defaultProperties", this.defaultProperties)); } if (this.addCommandLineProperties && args.length > 0) { String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); composite.addPropertySource(new SimpleCommandLinePropertySource( name + "-" + args.hashCode(), args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } } /** * Configure which profiles are active (or active by default) for this application * environment. Additional profiles may be activated during configuration file * processing via the {@code spring.profiles.active} property. * @param environment this application's environment * @param args arguments passed to the {@code run} method * @see #configureEnvironment(ConfigurableEnvironment, String[]) * @see org.springframework.boot.context.config.ConfigFileApplicationListener */ protected void configureProfiles(ConfigurableEnvironment environment, String[] args) { environment.getActiveProfiles(); // ensure they are initialized // But these ones should go first (last wins in a property key clash) Set<String> profiles = new LinkedHashSet<String>(this.additionalProfiles); profiles.addAll(Arrays.asList(environment.getActiveProfiles())); environment.setActiveProfiles(profiles.toArray(new String[profiles.size()])); } /** * Print a custom banner message to the console, optionally extracting its location or * content from the Environment (banner.location and banner.charset). The defaults are * banner.location=classpath:banner.txt, banner.charset=UTF-8. If the banner file does * not exist or cannot be printed, a simple default is created. * @param environment the environment * @see #setBannerMode */ protected void printBanner(Environment environment) { Banner selectedBanner = selectBanner(environment); if (this.bannerMode == Banner.Mode.LOG) { try { logger.info(createStringFromBanner(selectedBanner, environment)); } catch (UnsupportedEncodingException ex) { logger.warn("Failed to create String for banner", ex); } } else { selectedBanner.printBanner(environment, this.mainApplicationClass, System.out); } } private Banner selectBanner(Environment environment) { String location = environment.getProperty(BANNER_LOCATION_PROPERTY, BANNER_LOCATION_PROPERTY_VALUE); ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader : new DefaultResourceLoader(getClassLoader()); Resource resource = resourceLoader.getResource(location); if (resource.exists()) { return new ResourceBanner(resource); } if (this.banner != null) { return this.banner; } return DEFAULT_BANNER; } private String createStringFromBanner(Banner banner, Environment environment) throws UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); banner.printBanner(environment, this.mainApplicationClass, new PrintStream(baos)); String charset = environment.getProperty("banner.charset", "UTF-8"); return baos.toString(charset); } /** * Strategy method used to create the {@link ApplicationContext}. By default this * method will respect any explicitly set application context or application context * class before falling back to a suitable default. * @return the application context (not yet refreshed) * @see #setApplicationContextClass(Class) */ protected ConfigurableApplicationContext createApplicationContext() { Class<?> contextClass = this.applicationContextClass; if (contextClass == null) { try { contextClass = Class.forName(this.webEnvironment ? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS); } catch (ClassNotFoundException ex) { throw new IllegalStateException( "Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass", ex); } } return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass); } /** * Apply any relevant post processing the {@link ApplicationContext}. Subclasses can * apply additional processing as required. * @param context the application context */ protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.webEnvironment) { if (context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext configurableContext = (ConfigurableWebApplicationContext) context; if (this.beanNameGenerator != null) { configurableContext.getBeanFactory().registerSingleton( AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, this.beanNameGenerator); } } } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext) { ((GenericApplicationContext) context) .setResourceLoader(this.resourceLoader); } if (context instanceof DefaultResourceLoader) { ((DefaultResourceLoader) context) .setClassLoader(this.resourceLoader.getClassLoader()); } } } /** * Apply any {@link ApplicationContextInitializer}s to the context before it is * refreshed. * @param context the configured ApplicationContext (not refreshed yet) * @see ConfigurableApplicationContext#refresh() */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyInitializers(ConfigurableApplicationContext context) { for (ApplicationContextInitializer initializer : getInitializers()) { Class<?> requiredType = GenericTypeResolver.resolveTypeArgument( initializer.getClass(), ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } } /** * Called to log startup information, subclasses may override to add additional * logging. * @param isRoot true if this application is the root of a context hierarchy */ protected void logStartupInfo(boolean isRoot) { if (isRoot) { new StartupInfoLogger(this.mainApplicationClass) .logStarting(getApplicationLog()); } } /** * Called to log active profile information. * @param context the application context */ protected void logStartupProfileInfo(ConfigurableApplicationContext context) { Log log = getApplicationLog(); if (log.isInfoEnabled()) { String[] activeProfiles = context.getEnvironment().getActiveProfiles(); if (ObjectUtils.isEmpty(activeProfiles)) { String[] defaultProfiles = context.getEnvironment().getDefaultProfiles(); log.info("No active profile set, falling back to default profiles: " + StringUtils.arrayToCommaDelimitedString(defaultProfiles)); } else { log.info("The following profiles are active: " + StringUtils.arrayToCommaDelimitedString(activeProfiles)); } } } /** * Returns the {@link Log} for the application. By default will be deduced. * @return the application log */ protected Log getApplicationLog() { if (this.mainApplicationClass == null) { return logger; } return LogFactory.getLog(this.mainApplicationClass); } /** * Load beans into the application context. * @param context the context to load beans into * @param sources the sources to load */ protected void load(ApplicationContext context, Object[] sources) { if (logger.isDebugEnabled()) { logger.debug( "Loading source " + StringUtils.arrayToCommaDelimitedString(sources)); } BeanDefinitionLoader loader = createBeanDefinitionLoader( getBeanDefinitionRegistry(context), sources); if (this.beanNameGenerator != null) { loader.setBeanNameGenerator(this.beanNameGenerator); } if (this.resourceLoader != null) { loader.setResourceLoader(this.resourceLoader); } if (this.environment != null) { loader.setEnvironment(this.environment); } loader.load(); } /** * The ResourceLoader that will be used in the ApplicationContext. * @return the resourceLoader the resource loader that will be used in the * ApplicationContext (or null if the default) */ public ResourceLoader getResourceLoader() { return this.resourceLoader; } /** * Either the ClassLoader that will be used in the ApplicationContext (if * {@link #setResourceLoader(ResourceLoader) resourceLoader} is set, or the context * class loader (if not null), or the loader of the Spring {@link ClassUtils} class. * @return a ClassLoader (never null) */ public ClassLoader getClassLoader() { if (this.resourceLoader != null) { return this.resourceLoader.getClassLoader(); } return ClassUtils.getDefaultClassLoader(); } /** * Get the bean definition registry. * @param context the application context * @return the BeanDefinitionRegistry if it can be determined */ private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) { if (context instanceof BeanDefinitionRegistry) { return (BeanDefinitionRegistry) context; } if (context instanceof AbstractApplicationContext) { return (BeanDefinitionRegistry) ((AbstractApplicationContext) context) .getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } /** * Factory method used to create the {@link BeanDefinitionLoader}. * @param registry the bean definition registry * @param sources the sources to load * @return the {@link BeanDefinitionLoader} that will be used to load beans */ protected BeanDefinitionLoader createBeanDefinitionLoader( BeanDefinitionRegistry registry, Object[] sources) { return new BeanDefinitionLoader(registry, sources); } /** * Refresh the underlying {@link ApplicationContext}. * @param applicationContext the application context to refresh */ protected void refresh(ApplicationContext applicationContext) { Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext); ((AbstractApplicationContext) applicationContext).refresh(); } /** * Called after the context has been refreshed. * @param context the application context * @param args the application arguments */ protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) { callRunners(context, args); } private void callRunners(ApplicationContext context, ApplicationArguments args) { List<Object> runners = new ArrayList<Object>(); runners.addAll(context.getBeansOfType(ApplicationRunner.class).values()); runners.addAll(context.getBeansOfType(CommandLineRunner.class).values()); AnnotationAwareOrderComparator.sort(runners); for (Object runner : new LinkedHashSet<Object>(runners)) { if (runner instanceof ApplicationRunner) { callRunner((ApplicationRunner) runner, args); } if (runner instanceof CommandLineRunner) { callRunner((CommandLineRunner) runner, args); } } } private void callRunner(ApplicationRunner runner, ApplicationArguments args) { try { (runner).run(args); } catch (Exception ex) { throw new IllegalStateException("Failed to execute ApplicationRunner", ex); } } private void callRunner(CommandLineRunner runner, ApplicationArguments args) { try { (runner).run(args.getSourceArgs()); } catch (Exception ex) { throw new IllegalStateException("Failed to execute CommandLineRunner", ex); } } private void handleRunFailure(ConfigurableApplicationContext context, SpringApplicationRunListeners listeners, Throwable exception) { if (logger.isErrorEnabled()) { logger.error("Application startup failed", exception); registerLoggedException(exception); } try { try { handleExitCode(context, exception); listeners.finished(context, exception); } finally { if (context != null) { context.close(); } } } catch (Exception ex) { logger.warn("Unable to close ApplicationContext", ex); } ReflectionUtils.rethrowRuntimeException(exception); } /** * Register that the given exception has been logged. By default, if the running in * the main thread, this method will suppress additional printing of the stacktrace. * @param exception the exception that was logged */ protected void registerLoggedException(Throwable exception) { SpringBootExceptionHandler handler = getSpringBootExceptionHandler(); if (handler != null) { handler.registerLoggedException(exception); } } private void handleExitCode(ConfigurableApplicationContext context, Throwable exception) { int exitCode = getExitCodeFromException(context, exception); if (exitCode != 0) { if (context != null) { context.publishEvent(new ExitCodeEvent(context, exitCode)); } SpringBootExceptionHandler handler = getSpringBootExceptionHandler(); if (handler != null) { handler.registerExitCode(exitCode); } } } private int getExitCodeFromException(ConfigurableApplicationContext context, Throwable exception) { int exitCode = getExitCodeFromMappedException(context, exception); if (exitCode == 0) { exitCode = getExitCodeFromExitCodeGeneratorException(exception); } return exitCode; } private int getExitCodeFromMappedException(ConfigurableApplicationContext context, Throwable exception) { if (context == null) { return 0; } ExitCodeGenerators generators = new ExitCodeGenerators(); Collection<ExitCodeExceptionMapper> beans = context .getBeansOfType(ExitCodeExceptionMapper.class).values(); generators.addAll(exception, beans); return generators.getExitCode(); } private int getExitCodeFromExitCodeGeneratorException(Throwable exception) { if (exception == null) { return 0; } if (exception instanceof ExitCodeGenerator) { return ((ExitCodeGenerator) exception).getExitCode(); } return getExitCodeFromExitCodeGeneratorException(exception.getCause()); } SpringBootExceptionHandler getSpringBootExceptionHandler() { if (isMainThread(Thread.currentThread())) { return SpringBootExceptionHandler.forCurrentThread(); } return null; } private boolean isMainThread(Thread currentThread) { return ("main".equals(currentThread.getName()) || "restartedMain".equals(currentThread.getName())) && "main".equals(currentThread.getThreadGroup().getName()); } /** * Returns the main application class that has been deduced or explicitly configured. * @return the main application class or {@code null} */ public Class<?> getMainApplicationClass() { return this.mainApplicationClass; } /** * Set a specific main application class that will be used as a log source and to * obtain version information. By default the main application class will be deduced. * Can be set to {@code null} if there is no explicit application class. * @param mainApplicationClass the mainApplicationClass to set or {@code null} */ public void setMainApplicationClass(Class<?> mainApplicationClass) { this.mainApplicationClass = mainApplicationClass; } /** * Sets if this application is running within a web environment. If not specified will * attempt to deduce the environment based on the classpath. * @param webEnvironment if the application is running in a web environment */ public void setWebEnvironment(boolean webEnvironment) { this.webEnvironment = webEnvironment; } /** * Sets if the application is headless and should not instantiate AWT. Defaults to * {@code true} to prevent java icons appearing. * @param headless if the application is headless */ public void setHeadless(boolean headless) { this.headless = headless; } /** * Sets if the created {@link ApplicationContext} should have a shutdown hook * registered. Defaults to {@code true} to ensure that JVM shutdowns are handled * gracefully. * @param registerShutdownHook if the shutdown hook should be registered */ public void setRegisterShutdownHook(boolean registerShutdownHook) { this.registerShutdownHook = registerShutdownHook; } /** * Sets the {@link Banner} instance which will be used to print the banner when no * static banner file is provided. * @param banner The Banner instance to use */ public void setBanner(Banner banner) { this.banner = banner; } /** * Sets the mode used to display the banner when the application runs. Defaults to * {@code Banner.Mode.CONSOLE}. * @param bannerMode the mode used to display the banner */ public void setBannerMode(Banner.Mode bannerMode) { this.bannerMode = bannerMode; } /** * Sets if the application information should be logged when the application starts. * Defaults to {@code true}. * @param logStartupInfo if startup info should be logged. */ public void setLogStartupInfo(boolean logStartupInfo) { this.logStartupInfo = logStartupInfo; } /** * Sets if a {@link CommandLinePropertySource} should be added to the application * context in order to expose arguments. Defaults to {@code true}. * @param addCommandLineProperties if command line arguments should be exposed */ public void setAddCommandLineProperties(boolean addCommandLineProperties) { this.addCommandLineProperties = addCommandLineProperties; } /** * Set default environment properties which will be used in addition to those in the * existing {@link Environment}. * @param defaultProperties the additional properties to set */ public void setDefaultProperties(Map<String, Object> defaultProperties) { this.defaultProperties = defaultProperties; } /** * Convenient alternative to {@link #setDefaultProperties(Map)}. * @param defaultProperties some {@link Properties} */ public void setDefaultProperties(Properties defaultProperties) { this.defaultProperties = new HashMap<String, Object>(); for (Object key : Collections.list(defaultProperties.propertyNames())) { this.defaultProperties.put((String) key, defaultProperties.get(key)); } } /** * Set additional profile values to use (on top of those set in system or command line * properties). * @param profiles the additional profiles to set */ public void setAdditionalProfiles(String... profiles) { this.additionalProfiles = new LinkedHashSet<String>(Arrays.asList(profiles)); } /** * Sets the bean name generator that should be used when generating bean names. * @param beanNameGenerator the bean name generator */ public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { this.beanNameGenerator = beanNameGenerator; } /** * Sets the underlying environment that should be used with the created application * context. * @param environment the environment */ public void setEnvironment(ConfigurableEnvironment environment) { this.environment = environment; } /** * Returns a mutable set of the sources that will be added to an ApplicationContext * when {@link #run(String...)} is called. * @return the sources the application sources. * @see #SpringApplication(Object...) */ public Set<Object> getSources() { return this.sources; } /** * The sources that will be used to create an ApplicationContext. A valid source is * one of: a class, class name, package, package name, or an XML resource location. * Can also be set using constructors and static convenience methods (e.g. * {@link #run(Object[], String[])}). * <p> * NOTE: sources defined here will be used in addition to any sources specified on * construction. * @param sources the sources to set * @see #SpringApplication(Object...) */ public void setSources(Set<Object> sources) { Assert.notNull(sources, "Sources must not be null"); this.sources.addAll(sources); } /** * Sets the {@link ResourceLoader} that should be used when loading resources. * @param resourceLoader the resource loader */ public void setResourceLoader(ResourceLoader resourceLoader) { Assert.notNull(resourceLoader, "ResourceLoader must not be null"); this.resourceLoader = resourceLoader; } /** * Sets the type of Spring {@link ApplicationContext} that will be created. If not * specified defaults to {@link #DEFAULT_WEB_CONTEXT_CLASS} for web based applications * or {@link AnnotationConfigApplicationContext} for non web based applications. * @param applicationContextClass the context class to set */ public void setApplicationContextClass( Class<? extends ConfigurableApplicationContext> applicationContextClass) { this.applicationContextClass = applicationContextClass; if (!isWebApplicationContext(applicationContextClass)) { this.webEnvironment = false; } } private boolean isWebApplicationContext(Class<?> applicationContextClass) { try { return WebApplicationContext.class.isAssignableFrom(applicationContextClass); } catch (NoClassDefFoundError ex) { return false; } } /** * Sets the {@link ApplicationContextInitializer} that will be applied to the Spring * {@link ApplicationContext}. * @param initializers the initializers to set */ public void setInitializers( Collection<? extends ApplicationContextInitializer<?>> initializers) { this.initializers = new ArrayList<ApplicationContextInitializer<?>>(); this.initializers.addAll(initializers); } /** * Add {@link ApplicationContextInitializer}s to be applied to the Spring * {@link ApplicationContext}. * @param initializers the initializers to add */ public void addInitializers(ApplicationContextInitializer<?>... initializers) { this.initializers.addAll(Arrays.asList(initializers)); } /** * Returns read-only ordered Set of the {@link ApplicationContextInitializer}s that * will be applied to the Spring {@link ApplicationContext}. * @return the initializers */ public Set<ApplicationContextInitializer<?>> getInitializers() { return asUnmodifiableOrderedSet(this.initializers); } /** * Sets the {@link ApplicationListener}s that will be applied to the SpringApplication * and registered with the {@link ApplicationContext}. * @param listeners the listeners to set */ public void setListeners(Collection<? extends ApplicationListener<?>> listeners) { this.listeners = new ArrayList<ApplicationListener<?>>(); this.listeners.addAll(listeners); } /** * Add {@link ApplicationListener}s to be applied to the SpringApplication and * registered with the {@link ApplicationContext}. * @param listeners the listeners to add */ public void addListeners(ApplicationListener<?>... listeners) { this.listeners.addAll(Arrays.asList(listeners)); } /** * Returns read-only ordered Set of the {@link ApplicationListener}s that will be * applied to the SpringApplication and registered with the {@link ApplicationContext} * . * @return the listeners */ public Set<ApplicationListener<?>> getListeners() { return asUnmodifiableOrderedSet(this.listeners); } /** * Static helper that can be used to run a {@link SpringApplication} from the * specified source using default settings. * @param source the source to load * @param args the application arguments (usually passed from a Java main method) * @return the running {@link ApplicationContext} */ public static ConfigurableApplicationContext run(Object source, String... args) { return run(new Object[] { source }, args); } /** * Static helper that can be used to run a {@link SpringApplication} from the * specified sources using default settings and user supplied arguments. * @param sources the sources to load * @param args the application arguments (usually passed from a Java main method) * @return the running {@link ApplicationContext} */ public static ConfigurableApplicationContext run(Object[] sources, String[] args) { return new SpringApplication(sources).run(args); } /** * A basic main that can be used to launch an application. This method is useful when * application sources are defined via a {@literal --spring.main.sources} command line * argument. * <p> * Most developers will want to define their own main method can call the * {@link #run(Object, String...) run} method instead. * @param args command line arguments * @throws Exception if the application cannot be started * @see SpringApplication#run(Object[], String[]) * @see SpringApplication#run(Object, String...) */ public static void main(String[] args) throws Exception { SpringApplication.run(new Object[0], args); } /** * Static helper that can be used to exit a {@link SpringApplication} and obtain a * code indicating success (0) or otherwise. Does not throw exceptions but should * print stack traces of any encountered. Applies the specified * {@link ExitCodeGenerator} in addition to any Spring beans that implement * {@link ExitCodeGenerator}. In the case of multiple exit codes the highest value * will be used (or if all values are negative, the lowest value will be used) * @param context the context to close if possible * @param exitCodeGenerators exist code generators * @return the outcome (0 if successful) */ public static int exit(ApplicationContext context, ExitCodeGenerator... exitCodeGenerators) { Assert.notNull(context, "Context must not be null"); int exitCode = 0; try { try { ExitCodeGenerators generators = new ExitCodeGenerators(); Collection<ExitCodeGenerator> beans = context .getBeansOfType(ExitCodeGenerator.class).values(); generators.addAll(exitCodeGenerators); generators.addAll(beans); exitCode = generators.getExitCode(); if (exitCode != 0) { context.publishEvent(new ExitCodeEvent(context, exitCode)); } } finally { close(context); } } catch (Exception ex) { ex.printStackTrace(); exitCode = (exitCode == 0 ? 1 : exitCode); } return exitCode; } private static void close(ApplicationContext context) { if (context instanceof ConfigurableApplicationContext) { ConfigurableApplicationContext closable = (ConfigurableApplicationContext) context; closable.close(); } } private static <E> Set<E> asUnmodifiableOrderedSet(Collection<E> elements) { List<E> list = new ArrayList<E>(); list.addAll(elements); Collections.sort(list, AnnotationAwareOrderComparator.INSTANCE); return new LinkedHashSet<E>(list); } }
apache-2.0
venusdrogon/feilong-spring
feilong-spring-web/src/main/java/com/feilong/spring/web/servlet/view/MovedPermanentlyRedirectViewResolver.java
2054
/* * Copyright (C) 2008 feilong * * 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.feilong.spring.web.servlet.view; import java.util.Locale; import org.springframework.http.HttpStatus; import org.springframework.web.servlet.View; import org.springframework.web.servlet.view.RedirectView; /** * 301 永久跳转. * * @author <a href="http://feitianbenyue.iteye.com/">feilong</a> * @see org.springframework.web.servlet.view.UrlBasedViewResolver#createView(String, Locale) * @see org.springframework.http.HttpStatus#MOVED_PERMANENTLY * @see <a href="https://gist.github.com/code4craft/144cdc94464a2f5228219b5fe2864232">RedirectViewResolver</a> * @see <a href="https://blog.csdn.net/hj7jay/article/details/51372467">用Spring MVC优雅的实现301跳转</a> * * @author <a href="http://feitianbenyue.iteye.com/">feilong</a> * @since 4.0.2 */ public class MovedPermanentlyRedirectViewResolver extends AbstractPrefixViewResolver{ /** The Constant REDIRECT_PERMANENT_PREFIX. */ public static final String REDIRECT_PERMANENT_PREFIX = "redirectPermanent:"; //--------------------------------------------------------------- /* * (non-Javadoc) * * @see com.feilong.spring.web.servlet.view.AbstractPrefixViewResolver#buildView(java.lang.String) */ @Override protected View buildView(String redirectUrl){ RedirectView redirectView = new RedirectView(redirectUrl); redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY); return redirectView; } }
apache-2.0
krasserm/ipf
commons/ihe/xds/src/main/java/org/openehealth/ipf/commons/ihe/xds/core/audit/XdsSubmitAuditStrategy30.java
2800
/* * Copyright 2012 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 org.openehealth.ipf.commons.ihe.xds.core.audit; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLRegistryResponse; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLSubmitObjectsRequest; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.EbXMLRegistryResponse30; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.EbXMLSubmitObjectsRequest30; import org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.lcm.SubmitObjectsRequest; import org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.rs.RegistryResponseType; import org.openhealthtools.ihe.atna.auditor.codes.rfc3881.RFC3881EventCodes; /** * Basis for Strategy pattern implementation for ATNA Auditing * in ebXML 3.0-based submission-related XDS transactions. * * @author Dmytro Rud */ abstract public class XdsSubmitAuditStrategy30 extends XdsAuditStrategy<XdsSubmitAuditDataset> { /** * Constructs an XDS audit strategy. * * @param serverSide * whether this is a server-side or a client-side strategy. * @param allowIncompleteAudit * whether this strategy should allow incomplete audit records * (parameter initially configurable via endpoint URL). */ public XdsSubmitAuditStrategy30(boolean serverSide, boolean allowIncompleteAudit) { super(serverSide, allowIncompleteAudit); } @Override public void enrichDatasetFromRequest(Object pojo, XdsSubmitAuditDataset auditDataset) { SubmitObjectsRequest submitObjectsRequest = (SubmitObjectsRequest) pojo; EbXMLSubmitObjectsRequest ebXML = new EbXMLSubmitObjectsRequest30(submitObjectsRequest); auditDataset.enrichDatasetFromSubmitObjectsRequest(ebXML); } @Override public RFC3881EventCodes.RFC3881EventOutcomeCodes getEventOutcomeCode(Object pojo) { RegistryResponseType response = (RegistryResponseType) pojo; EbXMLRegistryResponse ebXML = new EbXMLRegistryResponse30(response); return getEventOutcomeCodeFromRegistryResponse(ebXML); } @Override public XdsSubmitAuditDataset createAuditDataset() { return new XdsSubmitAuditDataset(isServerSide()); } }
apache-2.0
contentful/contentful-management.java
src/main/java/com/contentful/java/cma/ServiceApiKeys.java
2060
/* * Copyright (C) 2019 Contentful GmbH * * 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.contentful.java.cma; import com.contentful.java.cma.model.CMAApiKey; import com.contentful.java.cma.model.CMAArray; import java.util.Map; import io.reactivex.Flowable; import retrofit2.Response; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; import retrofit2.http.QueryMap; /** * Api Token Service. */ interface ServiceApiKeys { @GET("/spaces/{spaceId}/api_keys") Flowable<CMAArray<CMAApiKey>> fetchAll(@Path("spaceId") String spaceId); @GET("/spaces/{spaceId}/api_keys") Flowable<CMAArray<CMAApiKey>> fetchAll( @Path("spaceId") String spaceId, @QueryMap Map<String, String> query ); @GET("/spaces/{spaceId}/api_keys/{keyId}") Flowable<CMAApiKey> fetchOne( @Path("spaceId") String spaceId, @Path("keyId") String keyId); @POST("/spaces/{spaceId}/api_keys") Flowable<CMAApiKey> create( @Path("spaceId") String spaceId, @Body CMAApiKey key); @PUT("/spaces/{spaceId}/api_keys/{keyId}") Flowable<CMAApiKey> update( @Header("X-Contentful-Version") Integer version, @Path("spaceId") String spaceId, @Path("keyId") String keyId, @Body CMAApiKey key); @DELETE("/spaces/{spaceId}/api_keys/{keyId}") Flowable<Response<Void>> delete( @Path("spaceId") String spaceId, @Path("keyId") String keyId); }
apache-2.0
oliveti/resolver
impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/integration/DisabledCentralRepositoryTestCase.java
3497
package org.jboss.shrinkwrap.resolver.impl.maven.integration; import java.io.File; import org.jboss.shrinkwrap.resolver.api.NoResolvedResultException; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.jboss.shrinkwrap.resolver.impl.maven.bootstrap.MavenSettingsBuilder; import org.jboss.shrinkwrap.resolver.impl.maven.util.TestFileUtil; import org.jboss.shrinkwrap.resolver.impl.maven.util.ValidationUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * Ensures that Maven Central may be disabled as a repository. This test will fail outside the presence of an internet * connection and access to repo1.maven.org * * @author <a href="mailto:alr@jboss.org">Andrew Lee Rubinger</a> */ public class DisabledCentralRepositoryTestCase { private static final String FAKE_REPO = "target/disabled-central-repo"; private static final String FAKE_SETTINGS = "target/settings/profile/settings.xml"; @BeforeClass public static void setRemoteRepository() { System.setProperty(MavenSettingsBuilder.ALT_GLOBAL_SETTINGS_XML_LOCATION, FAKE_SETTINGS); System.setProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION, FAKE_SETTINGS); System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, FAKE_REPO); } /** * Cleanup, remove the repositories from previous tests */ @Before @After // For debugging you might want to temporarily remove the @After lifecycle call just to sanity-check for yourself // the repo public void cleanup() throws Exception { TestFileUtil.removeDirectory(new File(FAKE_REPO)); } /** * Ensures that we can contact Maven Central (as a control test) */ @Test public void control() { // This should resolve from Maven Central final File file = Maven.resolver().loadPomFromFile("pom.xml").resolve("junit:junit") .withClassPathResolution(false).withoutTransitivity().asSingle(File.class); // Ensure we get JUnit new ValidationUtil("junit").validate(file); final File localRepo = new File(FAKE_REPO); // Ensure we're pulling from the alternate repo we've designated above Assert.assertTrue(file.getAbsolutePath().contains(localRepo.getAbsolutePath())); } /** * Ensures that we can contact Maven Central (as a control test) */ @Test public void controlWithNewAPI() { // This should resolve from Maven Central final File file = Maven.configureResolver().withClassPathResolution(false).loadPomFromFile("pom.xml").resolve("junit:junit") .withoutTransitivity().asSingle(File.class); // Ensure we get JUnit new ValidationUtil("junit").validate(file); final File localRepo = new File(FAKE_REPO); // Ensure we're pulling from the alternate repo we've designated above Assert.assertTrue(file.getAbsolutePath().contains(localRepo.getAbsolutePath())); } /** * Tests the disabling of the Maven central repository */ @Test(expected = NoResolvedResultException.class) public void shouldHaveCentralMavenRepositoryDisabled() { // This should NOT resolve from Maven Central Maven.resolver().loadPomFromFile("pom.xml").resolve("junit:junit").withClassPathResolution(false) .withMavenCentralRepo(false).withoutTransitivity().asSingle(File.class); } }
apache-2.0
GoogleCloudPlatform/datanucleus-appengine
tests/com/google/appengine/datanucleus/query/JDOQLDeleteTest.java
6621
/********************************************************************** Copyright (c) 2009 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.appengine.datanucleus.query; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.datanucleus.Utils; import com.google.appengine.datanucleus.jdo.JDOTestCase; import com.google.appengine.datanucleus.test.jdo.Flight; import com.google.appengine.datanucleus.test.jdo.HasKeyAncestorKeyPkJDO; import com.google.appengine.datanucleus.test.jdo.HasOneToManyListJDO; import javax.jdo.JDOFatalUserException; import javax.jdo.Query; /** * @author Max Ross <maxr@google.com> */ public class JDOQLDeleteTest extends JDOTestCase { public void testDelete_Txn_MultipleEntityGroups() { ds.put(Flight.newFlightEntity("jimmy", "bos", "mia", 23, 24, 25)); ds.put(Flight.newFlightEntity("jimmy", "bos", "mia", 23, 24, 25)); Query q = pm.newQuery(Flight.class); beginTxn(); try { q.deletePersistentAll(); fail("expected exception"); } catch (JDOFatalUserException e) { // good - can't delete books from multiple entity groups in a txn } rollbackTxn(); assertEquals(2, countForClass(Flight.class)); } public void testDelete_Txn_OneEntityGroup() { Key parentKey = KeyFactory.createKey("yar", 23); ds.put(Flight.newFlightEntity(parentKey, null, "jimmy", "bos", "mia", 23, 24, 25)); ds.put(Flight.newFlightEntity(parentKey, null, "jimmy", "bos", "mia", 23, 24, 25)); Query q = pm.newQuery(Flight.class); beginTxn(); assertEquals(2, q.deletePersistentAll()); assertEquals(2, countForClass(Flight.class)); commitTxn(); assertEquals(0, countForClass(Flight.class)); } public void testDelete_NoTxn() { switchDatasource(PersistenceManagerFactoryName.nontransactional); ds.put(Flight.newFlightEntity("jimmy", "bos", "mia", 23, 24)); ds.put(Flight.newFlightEntity("jimmy", "bos", "mia", 23, 24)); Query q = pm.newQuery(Flight.class); assertEquals(2, q.deletePersistentAll()); assertEquals(0, countForClass(Flight.class)); } public void testDeleteAncestorQuery_Txn() { Key parentKey = KeyFactory.createKey("yar", 23); Entity pojo1 = new Entity(HasKeyAncestorKeyPkJDO.class.getSimpleName(), parentKey); Entity pojo2 = new Entity(HasKeyAncestorKeyPkJDO.class.getSimpleName(), parentKey); ds.put(pojo1); ds.put(pojo2); Query q = pm.newQuery(HasKeyAncestorKeyPkJDO.class, "ancestorKey == :p1"); beginTxn(); assertEquals(2, q.deletePersistentAll(parentKey)); commitTxn(); assertEquals(0, countForClass(HasKeyAncestorKeyPkJDO.class)); } public void testDeleteAncestorQuery_TxnRollback() throws EntityNotFoundException { Key parentKey = KeyFactory.createKey("yar", 23); Entity pojo1 = new Entity(HasKeyAncestorKeyPkJDO.class.getSimpleName(), parentKey); Entity pojo2 = new Entity(HasKeyAncestorKeyPkJDO.class.getSimpleName(), parentKey); ds.put(pojo1); ds.put(pojo2); Query q = pm.newQuery(HasKeyAncestorKeyPkJDO.class, "ancestorKey == :p1"); beginTxn(); assertEquals(2, q.deletePersistentAll(parentKey)); rollbackTxn(); assertEquals(2, countForClass(HasKeyAncestorKeyPkJDO.class)); } public void testDeleteAncestorQuery_NoTxn() { switchDatasource(PersistenceManagerFactoryName.nontransactional); Key parentKey = KeyFactory.createKey("yar", 23); Entity pojo1 = new Entity(HasKeyAncestorKeyPkJDO.class.getSimpleName(), parentKey); Entity pojo2 = new Entity(HasKeyAncestorKeyPkJDO.class.getSimpleName(), parentKey); ds.put(pojo1); ds.put(pojo2); Query q = pm.newQuery(HasKeyAncestorKeyPkJDO.class, "ancestorKey == :p1"); assertEquals(2, q.deletePersistentAll(parentKey)); assertEquals(0, countForClass(HasKeyAncestorKeyPkJDO.class)); } public void testBatchDelete_NoTxn() { switchDatasource(PersistenceManagerFactoryName.nontransactional); Entity e1 = Flight.newFlightEntity("jimmy", "bos", "mia", 23, 24); ds.put(e1); Entity e2 = Flight.newFlightEntity("jimmy", "bos", "mia", 23, 24); ds.put(e2); Entity e3 = Flight.newFlightEntity("jimmy", "bos", "mia", 23, 24); ds.put(e3); Key key = KeyFactory.createKey("yar", "does not exist"); Query q = pm.newQuery(Flight.class, "id == :ids"); assertEquals(2, q.deletePersistentAll(Utils.newArrayList(key, e1.getKey(), e2.getKey()))); assertEquals(1, countForClass(Flight.class)); } public void testBatchDelete_Txn() { Key parent = KeyFactory.createKey("yar", 23); Entity e1 = Flight.newFlightEntity(parent, null, "jimmy", "bos", "mia", 23, 24, 25); ds.put(e1); Entity e2 = Flight.newFlightEntity(parent, null, "jimmy", "bos", "mia", 23, 24, 25); ds.put(e2); Entity e3 = Flight.newFlightEntity(parent, null, "jimmy", "bos", "mia", 23, 24, 25); ds.put(e3); beginTxn(); Query q = pm.newQuery(Flight.class, "id == :ids"); assertEquals(2, q.deletePersistentAll(Utils.newArrayList(parent, e1.getKey(), e2.getKey()))); assertEquals(3, countForClass(Flight.class)); commitTxn(); assertEquals(1, countForClass(Flight.class)); } public void testDeleteCascades() { HasOneToManyListJDO parent = new HasOneToManyListJDO(); Flight f = new Flight(); parent.getFlights().add(f); beginTxn(); pm.makePersistent(parent); commitTxn(); assertEquals(1, countForClass(Flight.class)); assertEquals(1, countForClass(HasOneToManyListJDO.class)); beginTxn(); Query q = pm.newQuery(HasOneToManyListJDO.class); assertEquals(1, q.deletePersistentAll()); assertEquals(1, countForClass(Flight.class)); assertEquals(1, countForClass(HasOneToManyListJDO.class)); commitTxn(); assertEquals(0, countForClass(Flight.class)); assertEquals(0, countForClass(HasOneToManyListJDO.class)); } }
apache-2.0
runningcode/AndroidApps101-JSON-Fetch
app/src/main/java/apps101/example/json/MainActivity.java
1788
/* * Copyright (c) 2014 Nelson Osacky * * Dual licensed under Apache2.0 and MIT Open Source License (included below): * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package apps101.example.json; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import edu.illinois.coursera.android.json.R; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new ItemListFragment()) .commit(); } } }
apache-2.0