repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
ClarenceAu/log4j2 | log4j-flume-ng/src/main/java/org/apache/logging/log4j/flume/appender/FlumeAvroManager.java | 10591 | /*
* 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.logging.log4j.flume.appender;
import java.util.Properties;
import org.apache.flume.Event;
import org.apache.flume.api.RpcClient;
import org.apache.flume.api.RpcClientFactory;
import org.apache.logging.log4j.core.appender.AppenderLoggingException;
import org.apache.logging.log4j.core.appender.ManagerFactory;
/**
* Manager for FlumeAvroAppenders.
*/
public class FlumeAvroManager extends AbstractFlumeManager {
private static final int MAX_RECONNECTS = 3;
private static final int MINIMUM_TIMEOUT = 1000;
private static AvroManagerFactory factory = new AvroManagerFactory();
private final Agent[] agents;
private final int batchSize;
private final int retries;
private final int connectTimeout;
private final int requestTimeout;
private final int current = 0;
private RpcClient rpcClient = null;
/**
* Constructor
* @param name The unique name of this manager.
* @param agents An array of Agents.
* @param batchSize The number of events to include in a batch.
* @param retries The number of times to retry connecting before giving up.
* @param connectTimeout The connection timeout in ms.
* @param requestTimeout The request timeout in ms.
*
*/
protected FlumeAvroManager(final String name, final String shortName, final Agent[] agents, final int batchSize,
final int retries, final int connectTimeout, final int requestTimeout) {
super(name);
this.agents = agents;
this.batchSize = batchSize;
this.retries = retries;
this.connectTimeout = connectTimeout;
this.requestTimeout = requestTimeout;
this.rpcClient = connect(agents, retries, connectTimeout, requestTimeout);
}
/**
* Returns a FlumeAvroManager.
* @param name The name of the manager.
* @param agents The agents to use.
* @param batchSize The number of events to include in a batch.
* @param retries The number of times to retry connecting before giving up.
* @param connectTimeout The connection timeout in ms.
* @param requestTimeout The request timeout in ms.
* @return A FlumeAvroManager.
*/
public static FlumeAvroManager getManager(final String name, final Agent[] agents, int batchSize,
final int retries, final int connectTimeout, final int requestTimeout) {
if (agents == null || agents.length == 0) {
throw new IllegalArgumentException("At least one agent is required");
}
if (batchSize <= 0) {
batchSize = 1;
}
final StringBuilder sb = new StringBuilder("FlumeAvro[");
boolean first = true;
for (final Agent agent : agents) {
if (!first) {
sb.append(",");
}
sb.append(agent.getHost()).append(":").append(agent.getPort());
first = false;
}
sb.append("]");
return getManager(sb.toString(), factory,
new FactoryData(name, agents, batchSize, retries, connectTimeout, requestTimeout));
}
/**
* Returns the agents.
* @return The agent array.
*/
public Agent[] getAgents() {
return agents;
}
/**
* Returns the index of the current agent.
* @return The index for the current agent.
*/
public int getCurrent() {
return current;
}
public int getRetries() {
return retries;
}
public int getConnectTimeout() {
return connectTimeout;
}
public int getRequestTimeout() {
return requestTimeout;
}
public int getBatchSize() {
return batchSize;
}
public synchronized void send(final BatchEvent events) {
if (rpcClient == null) {
rpcClient = connect(agents, retries, connectTimeout, requestTimeout);
}
if (rpcClient != null) {
try {
LOGGER.trace("Sending batch of {} events", events.getEvents().size());
rpcClient.appendBatch(events.getEvents());
} catch (final Exception ex) {
rpcClient.close();
rpcClient = null;
final String msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" +
agents[current].getPort();
LOGGER.warn(msg, ex);
throw new AppenderLoggingException("No Flume agents are available");
}
} else {
final String msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" +
agents[current].getPort();
LOGGER.warn(msg);
throw new AppenderLoggingException("No Flume agents are available");
}
}
@Override
public synchronized void send(final Event event) {
if (rpcClient == null) {
rpcClient = connect(agents, retries, connectTimeout, requestTimeout);
}
if (rpcClient != null) {
try {
rpcClient.append(event);
} catch (final Exception ex) {
rpcClient.close();
rpcClient = null;
final String msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" +
agents[current].getPort();
LOGGER.warn(msg, ex);
throw new AppenderLoggingException("No Flume agents are available");
}
} else {
final String msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" +
agents[current].getPort();
LOGGER.warn(msg);
throw new AppenderLoggingException("No Flume agents are available");
}
}
/**
* There is a very good chance that this will always return the first agent even if it isn't available.
* @param agents The list of agents to choose from
* @return The FlumeEventAvroServer.
*/
private RpcClient connect(final Agent[] agents, int retries, final int connectTimeout, final int requestTimeout) {
try {
final Properties props = new Properties();
props.put("client.type", agents.length > 1 ? "default_failover" : "default");
int count = 1;
final StringBuilder sb = new StringBuilder();
for (final Agent agent : agents) {
if (sb.length() > 0) {
sb.append(" ");
}
final String hostName = "host" + count++;
props.put("hosts." + hostName, agent.getHost() + ":" + agent.getPort());
sb.append(hostName);
}
props.put("hosts", sb.toString());
if (batchSize > 0) {
props.put("batch-size", Integer.toString(batchSize));
}
if (retries > 1) {
if (retries > MAX_RECONNECTS) {
retries = MAX_RECONNECTS;
}
props.put("max-attempts", Integer.toString(retries * agents.length));
}
if (requestTimeout >= MINIMUM_TIMEOUT) {
props.put("request-timeout", Integer.toString(requestTimeout));
}
if (connectTimeout >= MINIMUM_TIMEOUT) {
props.put("connect-timeout", Integer.toString(connectTimeout));
}
return RpcClientFactory.getInstance(props);
} catch (final Exception ex) {
LOGGER.error("Unable to create Flume RPCClient: {}", ex.getMessage());
return null;
}
}
@Override
protected void releaseSub() {
if (rpcClient != null) {
try {
rpcClient.close();
} catch (final Exception ex) {
LOGGER.error("Attempt to close RPC client failed", ex);
}
}
rpcClient = null;
}
/**
* Factory data.
*/
private static class FactoryData {
private final String name;
private final Agent[] agents;
private final int batchSize;
private final int retries;
private final int conntectTimeout;
private final int requestTimeout;
/**
* Constructor.
* @param name The name of the Appender.
* @param agents The agents.
* @param batchSize The number of events to include in a batch.
*/
public FactoryData(final String name, final Agent[] agents, final int batchSize, final int retries,
final int connectTimeout, final int requestTimeout) {
this.name = name;
this.agents = agents;
this.batchSize = batchSize;
this.retries = retries;
this.conntectTimeout = connectTimeout;
this.requestTimeout = requestTimeout;
}
}
/**
* Avro Manager Factory.
*/
private static class AvroManagerFactory implements ManagerFactory<FlumeAvroManager, FactoryData> {
/**
* Create the FlumeAvroManager.
* @param name The name of the entity to manage.
* @param data The data required to create the entity.
* @return The FlumeAvroManager.
*/
@Override
public FlumeAvroManager createManager(final String name, final FactoryData data) {
try {
return new FlumeAvroManager(name, data.name, data.agents, data.batchSize, data.retries,
data.conntectTimeout, data.requestTimeout);
} catch (final Exception ex) {
LOGGER.error("Could not create FlumeAvroManager", ex);
}
return null;
}
}
}
| apache-2.0 |
walterDurin/stickycode | net.stickycode.configuration/sticky-configuration/src/main/java/net/stickycode/configuration/value/SystemValue.java | 672 | package net.stickycode.configuration.value;
import net.stickycode.configuration.ConfigurationValue;
public class SystemValue
implements ConfigurationValue {
private String value;
public SystemValue(String value) {
this.value = value;
}
@Override
public String get() {
return value;
}
@Override
public boolean hasPrecedence(ConfigurationValue v) {
if (ApplicationValue.class.isAssignableFrom(v.getClass()))
return false;
if (SystemValue.class.isAssignableFrom(v.getClass()))
return false;
return true;
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" + value + "}";
}
}
| apache-2.0 |
bulldog2011/nano-rest | sample/EBaySearch/src/com/ebay/marketplace/search/v1/services/FindItemsForFavoriteSearchResponse.java | 2540 | // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.marketplace.search.v1.services;
import com.leansoft.nano.annotation.*;
/**
*
* Reserved for future use.
*
*/
@RootElement(name = "findItemsForFavoriteSearchResponse", namespace = "http://www.ebay.com/marketplace/search/v1/services")
public class FindItemsForFavoriteSearchResponse extends BaseFindingServiceResponse {
@Element
private CategoryHistogramContainer categoryHistogramContainer;
@Element
private AspectHistogramContainer aspectHistogramContainer;
@Element
private ConditionHistogramContainer conditionHistogramContainer;
/**
* public getter
*
*
* Reserved for future use.
*
*
* @returns com.ebay.marketplace.search.v1.services.CategoryHistogramContainer
*/
public CategoryHistogramContainer getCategoryHistogramContainer() {
return this.categoryHistogramContainer;
}
/**
* public setter
*
*
* Reserved for future use.
*
*
* @param com.ebay.marketplace.search.v1.services.CategoryHistogramContainer
*/
public void setCategoryHistogramContainer(CategoryHistogramContainer categoryHistogramContainer) {
this.categoryHistogramContainer = categoryHistogramContainer;
}
/**
* public getter
*
*
* Reserved for future use.
*
*
* @returns com.ebay.marketplace.search.v1.services.AspectHistogramContainer
*/
public AspectHistogramContainer getAspectHistogramContainer() {
return this.aspectHistogramContainer;
}
/**
* public setter
*
*
* Reserved for future use.
*
*
* @param com.ebay.marketplace.search.v1.services.AspectHistogramContainer
*/
public void setAspectHistogramContainer(AspectHistogramContainer aspectHistogramContainer) {
this.aspectHistogramContainer = aspectHistogramContainer;
}
/**
* public getter
*
*
* Reserved for future use.
*
*
* @returns com.ebay.marketplace.search.v1.services.ConditionHistogramContainer
*/
public ConditionHistogramContainer getConditionHistogramContainer() {
return this.conditionHistogramContainer;
}
/**
* public setter
*
*
* Reserved for future use.
*
*
* @param com.ebay.marketplace.search.v1.services.ConditionHistogramContainer
*/
public void setConditionHistogramContainer(ConditionHistogramContainer conditionHistogramContainer) {
this.conditionHistogramContainer = conditionHistogramContainer;
}
} | apache-2.0 |
eshen1991/optaplanner | optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/bestscore/BestScoreSubSingleStatistic.java | 2938 | /*
* Copyright 2010 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.optaplanner.benchmark.impl.statistic.bestscore;
import java.util.List;
import org.optaplanner.benchmark.config.statistic.ProblemStatisticType;
import org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult;
import org.optaplanner.benchmark.impl.statistic.ProblemBasedSubSingleStatistic;
import org.optaplanner.core.api.domain.solution.Solution;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.event.BestSolutionChangedEvent;
import org.optaplanner.core.api.solver.event.SolverEventListener;
import org.optaplanner.core.impl.score.definition.ScoreDefinition;
public class BestScoreSubSingleStatistic extends ProblemBasedSubSingleStatistic<BestScoreStatisticPoint> {
private final BestScoreSubSingleStatisticListener listener;
public BestScoreSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
super(subSingleBenchmarkResult, ProblemStatisticType.BEST_SCORE);
listener = new BestScoreSubSingleStatisticListener();
}
// ************************************************************************
// Lifecycle methods
// ************************************************************************
public void open(Solver solver) {
solver.addEventListener(listener);
}
public void close(Solver solver) {
solver.removeEventListener(listener);
}
private class BestScoreSubSingleStatisticListener implements SolverEventListener<Solution> {
public void bestSolutionChanged(BestSolutionChangedEvent<Solution> event) {
pointList.add(new BestScoreStatisticPoint(
event.getTimeMillisSpent(), event.getNewBestSolution().getScore()));
}
}
// ************************************************************************
// CSV methods
// ************************************************************************
@Override
protected String getCsvHeader() {
return BestScoreStatisticPoint.buildCsvLine("timeMillisSpent", "score");
}
@Override
protected BestScoreStatisticPoint createPointFromCsvLine(ScoreDefinition scoreDefinition,
List<String> csvLine) {
return new BestScoreStatisticPoint(Long.valueOf(csvLine.get(0)),
scoreDefinition.parseScore(csvLine.get(1)));
}
}
| apache-2.0 |
typesafehub/config | config/src/main/java/com/typesafe/config/impl/SimpleConfigObject.java | 24048 | /**
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
*/
package com.typesafe.config.impl;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.AbstractMap;
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.List;
import java.util.Map;
import java.util.Set;
import com.typesafe.config.ConfigException;
import com.typesafe.config.ConfigObject;
import com.typesafe.config.ConfigOrigin;
import com.typesafe.config.ConfigRenderOptions;
import com.typesafe.config.ConfigValue;
final class SimpleConfigObject extends AbstractConfigObject implements Serializable {
private static final long serialVersionUID = 2L;
// this map should never be modified - assume immutable
final private Map<String, AbstractConfigValue> value;
final private boolean resolved;
final private boolean ignoresFallbacks;
SimpleConfigObject(ConfigOrigin origin,
Map<String, AbstractConfigValue> value, ResolveStatus status,
boolean ignoresFallbacks) {
super(origin);
if (value == null)
throw new ConfigException.BugOrBroken(
"creating config object with null map");
this.value = value;
this.resolved = status == ResolveStatus.RESOLVED;
this.ignoresFallbacks = ignoresFallbacks;
// Kind of an expensive debug check. Comment out?
if (status != ResolveStatus.fromValues(value.values()))
throw new ConfigException.BugOrBroken("Wrong resolved status on " + this);
}
SimpleConfigObject(ConfigOrigin origin,
Map<String, AbstractConfigValue> value) {
this(origin, value, ResolveStatus.fromValues(value.values()), false /* ignoresFallbacks */);
}
@Override
public SimpleConfigObject withOnlyKey(String key) {
return withOnlyPath(Path.newKey(key));
}
@Override
public SimpleConfigObject withoutKey(String key) {
return withoutPath(Path.newKey(key));
}
// gets the object with only the path if the path
// exists, otherwise null if it doesn't. this ensures
// that if we have { a : { b : 42 } } and do
// withOnlyPath("a.b.c") that we don't keep an empty
// "a" object.
@Override
protected SimpleConfigObject withOnlyPathOrNull(Path path) {
String key = path.first();
Path next = path.remainder();
AbstractConfigValue v = value.get(key);
if (next != null) {
if (v != null && (v instanceof AbstractConfigObject)) {
v = ((AbstractConfigObject) v).withOnlyPathOrNull(next);
} else {
// if the path has more elements but we don't have an object,
// then the rest of the path does not exist.
v = null;
}
}
if (v == null) {
return null;
} else {
return new SimpleConfigObject(origin(), Collections.singletonMap(key, v),
v.resolveStatus(), ignoresFallbacks);
}
}
@Override
SimpleConfigObject withOnlyPath(Path path) {
SimpleConfigObject o = withOnlyPathOrNull(path);
if (o == null) {
return new SimpleConfigObject(origin(),
Collections.<String, AbstractConfigValue> emptyMap(), ResolveStatus.RESOLVED,
ignoresFallbacks);
} else {
return o;
}
}
@Override
SimpleConfigObject withoutPath(Path path) {
String key = path.first();
Path next = path.remainder();
AbstractConfigValue v = value.get(key);
if (v != null && next != null && v instanceof AbstractConfigObject) {
v = ((AbstractConfigObject) v).withoutPath(next);
Map<String, AbstractConfigValue> updated = new HashMap<String, AbstractConfigValue>(
value);
updated.put(key, v);
return new SimpleConfigObject(origin(), updated, ResolveStatus.fromValues(updated
.values()), ignoresFallbacks);
} else if (next != null || v == null) {
// can't descend, nothing to remove
return this;
} else {
Map<String, AbstractConfigValue> smaller = new HashMap<String, AbstractConfigValue>(
value.size() - 1);
for (Map.Entry<String, AbstractConfigValue> old : value.entrySet()) {
if (!old.getKey().equals(key))
smaller.put(old.getKey(), old.getValue());
}
return new SimpleConfigObject(origin(), smaller, ResolveStatus.fromValues(smaller
.values()), ignoresFallbacks);
}
}
@Override
public SimpleConfigObject withValue(String key, ConfigValue v) {
if (v == null)
throw new ConfigException.BugOrBroken(
"Trying to store null ConfigValue in a ConfigObject");
Map<String, AbstractConfigValue> newMap;
if (value.isEmpty()) {
newMap = Collections.singletonMap(key, (AbstractConfigValue) v);
} else {
newMap = new HashMap<String, AbstractConfigValue>(value);
newMap.put(key, (AbstractConfigValue) v);
}
return new SimpleConfigObject(origin(), newMap, ResolveStatus.fromValues(newMap.values()),
ignoresFallbacks);
}
@Override
SimpleConfigObject withValue(Path path, ConfigValue v) {
String key = path.first();
Path next = path.remainder();
if (next == null) {
return withValue(key, v);
} else {
AbstractConfigValue child = value.get(key);
if (child != null && child instanceof AbstractConfigObject) {
// if we have an object, add to it
return withValue(key, ((AbstractConfigObject) child).withValue(next, v));
} else {
// as soon as we have a non-object, replace it entirely
SimpleConfig subtree = ((AbstractConfigValue) v).atPath(
SimpleConfigOrigin.newSimple("withValue(" + next.render() + ")"), next);
return withValue(key, subtree.root());
}
}
}
@Override
protected AbstractConfigValue attemptPeekWithPartialResolve(String key) {
return value.get(key);
}
private SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin,
boolean newIgnoresFallbacks) {
return new SimpleConfigObject(newOrigin, value, newStatus, newIgnoresFallbacks);
}
@Override
protected SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin) {
return newCopy(newStatus, newOrigin, ignoresFallbacks);
}
@Override
protected SimpleConfigObject withFallbacksIgnored() {
if (ignoresFallbacks)
return this;
else
return newCopy(resolveStatus(), origin(), true /* ignoresFallbacks */);
}
@Override
ResolveStatus resolveStatus() {
return ResolveStatus.fromBoolean(resolved);
}
@Override
public SimpleConfigObject replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) {
HashMap<String, AbstractConfigValue> newChildren = new HashMap<String, AbstractConfigValue>(value);
for (Map.Entry<String, AbstractConfigValue> old : newChildren.entrySet()) {
if (old.getValue() == child) {
if (replacement != null)
old.setValue(replacement);
else
newChildren.remove(old.getKey());
return new SimpleConfigObject(origin(), newChildren, ResolveStatus.fromValues(newChildren.values()),
ignoresFallbacks);
}
}
throw new ConfigException.BugOrBroken("SimpleConfigObject.replaceChild did not find " + child + " in " + this);
}
@Override
public boolean hasDescendant(AbstractConfigValue descendant) {
for (AbstractConfigValue child : value.values()) {
if (child == descendant)
return true;
}
// now do the expensive search
for (AbstractConfigValue child : value.values()) {
if (child instanceof Container && ((Container) child).hasDescendant(descendant))
return true;
}
return false;
}
@Override
protected boolean ignoresFallbacks() {
return ignoresFallbacks;
}
@Override
public Map<String, Object> unwrapped() {
Map<String, Object> m = new HashMap<String, Object>();
for (Map.Entry<String, AbstractConfigValue> e : value.entrySet()) {
m.put(e.getKey(), e.getValue().unwrapped());
}
return m;
}
@Override
protected SimpleConfigObject mergedWithObject(AbstractConfigObject abstractFallback) {
requireNotIgnoringFallbacks();
if (!(abstractFallback instanceof SimpleConfigObject)) {
throw new ConfigException.BugOrBroken(
"should not be reached (merging non-SimpleConfigObject)");
}
SimpleConfigObject fallback = (SimpleConfigObject) abstractFallback;
boolean changed = false;
boolean allResolved = true;
Map<String, AbstractConfigValue> merged = new HashMap<String, AbstractConfigValue>();
Set<String> allKeys = new HashSet<String>();
allKeys.addAll(this.keySet());
allKeys.addAll(fallback.keySet());
for (String key : allKeys) {
AbstractConfigValue first = this.value.get(key);
AbstractConfigValue second = fallback.value.get(key);
AbstractConfigValue kept;
if (first == null)
kept = second;
else if (second == null)
kept = first;
else
kept = first.withFallback(second);
merged.put(key, kept);
if (first != kept)
changed = true;
if (kept.resolveStatus() == ResolveStatus.UNRESOLVED)
allResolved = false;
}
ResolveStatus newResolveStatus = ResolveStatus.fromBoolean(allResolved);
boolean newIgnoresFallbacks = fallback.ignoresFallbacks();
if (changed)
return new SimpleConfigObject(mergeOrigins(this, fallback), merged, newResolveStatus,
newIgnoresFallbacks);
else if (newResolveStatus != resolveStatus() || newIgnoresFallbacks != ignoresFallbacks())
return newCopy(newResolveStatus, origin(), newIgnoresFallbacks);
else
return this;
}
private SimpleConfigObject modify(NoExceptionsModifier modifier) {
try {
return modifyMayThrow(modifier);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new ConfigException.BugOrBroken("unexpected checked exception", e);
}
}
private SimpleConfigObject modifyMayThrow(Modifier modifier) throws Exception {
Map<String, AbstractConfigValue> changes = null;
for (String k : keySet()) {
AbstractConfigValue v = value.get(k);
// "modified" may be null, which means remove the child;
// to do that we put null in the "changes" map.
AbstractConfigValue modified = modifier.modifyChildMayThrow(k, v);
if (modified != v) {
if (changes == null)
changes = new HashMap<String, AbstractConfigValue>();
changes.put(k, modified);
}
}
if (changes == null) {
return this;
} else {
Map<String, AbstractConfigValue> modified = new HashMap<String, AbstractConfigValue>();
boolean sawUnresolved = false;
for (String k : keySet()) {
if (changes.containsKey(k)) {
AbstractConfigValue newValue = changes.get(k);
if (newValue != null) {
modified.put(k, newValue);
if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED)
sawUnresolved = true;
} else {
// remove this child; don't put it in the new map.
}
} else {
AbstractConfigValue newValue = value.get(k);
modified.put(k, newValue);
if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED)
sawUnresolved = true;
}
}
return new SimpleConfigObject(origin(), modified,
sawUnresolved ? ResolveStatus.UNRESOLVED : ResolveStatus.RESOLVED,
ignoresFallbacks());
}
}
private static final class ResolveModifier implements Modifier {
final Path originalRestrict;
ResolveContext context;
final ResolveSource source;
ResolveModifier(ResolveContext context, ResolveSource source) {
this.context = context;
this.source = source;
originalRestrict = context.restrictToChild();
}
@Override
public AbstractConfigValue modifyChildMayThrow(String key, AbstractConfigValue v) throws NotPossibleToResolve {
if (context.isRestrictedToChild()) {
if (key.equals(context.restrictToChild().first())) {
Path remainder = context.restrictToChild().remainder();
if (remainder != null) {
ResolveResult<? extends AbstractConfigValue> result = context.restrict(remainder).resolve(v,
source);
context = result.context.unrestricted().restrict(originalRestrict);
return result.value;
} else {
// we don't want to resolve the leaf child.
return v;
}
} else {
// not in the restrictToChild path
return v;
}
} else {
// no restrictToChild, resolve everything
ResolveResult<? extends AbstractConfigValue> result = context.unrestricted().resolve(v, source);
context = result.context.unrestricted().restrict(originalRestrict);
return result.value;
}
}
}
@Override
ResolveResult<? extends AbstractConfigObject> resolveSubstitutions(ResolveContext context, ResolveSource source)
throws NotPossibleToResolve {
if (resolveStatus() == ResolveStatus.RESOLVED)
return ResolveResult.make(context, this);
final ResolveSource sourceWithParent = source.pushParent(this);
try {
ResolveModifier modifier = new ResolveModifier(context, sourceWithParent);
AbstractConfigValue value = modifyMayThrow(modifier);
return ResolveResult.make(modifier.context, value).asObjectResult();
} catch (NotPossibleToResolve e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new ConfigException.BugOrBroken("unexpected checked exception", e);
}
}
@Override
SimpleConfigObject relativized(final Path prefix) {
return modify(new NoExceptionsModifier() {
@Override
public AbstractConfigValue modifyChild(String key, AbstractConfigValue v) {
return v.relativized(prefix);
}
});
}
// this is only Serializable to chill out a findbugs warning
static final private class RenderComparator implements java.util.Comparator<String>, Serializable {
private static final long serialVersionUID = 1L;
private static boolean isAllDigits(String s) {
int length = s.length();
// empty string doesn't count as a number
// string longer than "max number of digits in a long" cannot be parsed as a long
if (length == 0)
return false;
for (int i = 0; i < length; ++i) {
char c = s.charAt(i);
if (!Character.isDigit(c))
return false;
}
return true;
}
// This is supposed to sort numbers before strings,
// and sort the numbers numerically. The point is
// to make objects which are really list-like
// (numeric indices) appear in order.
@Override
public int compare(String a, String b) {
boolean aDigits = isAllDigits(a);
boolean bDigits = isAllDigits(b);
if (aDigits && bDigits) {
return new BigInteger(a).compareTo(new BigInteger(b));
} else if (aDigits) {
return -1;
} else if (bDigits) {
return 1;
} else {
return a.compareTo(b);
}
}
}
@Override
protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) {
if (isEmpty()) {
sb.append("{}");
} else {
boolean outerBraces = options.getJson() || !atRoot;
int innerIndent;
if (outerBraces) {
innerIndent = indent + 1;
sb.append("{");
if (options.getFormatted())
sb.append('\n');
} else {
innerIndent = indent;
}
int separatorCount = 0;
String[] keys = keySet().toArray(new String[size()]);
Arrays.sort(keys, new RenderComparator());
for (String k : keys) {
AbstractConfigValue v;
v = value.get(k);
if (options.getOriginComments()) {
String[] lines = v.origin().description().split("\n");
for (String l : lines) {
indent(sb, indent + 1, options);
sb.append('#');
if (!l.isEmpty())
sb.append(' ');
sb.append(l);
sb.append("\n");
}
}
if (options.getComments()) {
for (String comment : v.origin().comments()) {
indent(sb, innerIndent, options);
sb.append("#");
if (!comment.startsWith(" "))
sb.append(' ');
sb.append(comment);
sb.append("\n");
}
}
indent(sb, innerIndent, options);
v.render(sb, innerIndent, false /* atRoot */, k, options);
if (options.getFormatted()) {
if (options.getJson()) {
sb.append(",");
separatorCount = 2;
} else {
separatorCount = 1;
}
sb.append('\n');
} else {
sb.append(",");
separatorCount = 1;
}
}
// chop last commas/newlines
sb.setLength(sb.length() - separatorCount);
if (outerBraces) {
if (options.getFormatted()) {
sb.append('\n'); // put a newline back
if (outerBraces)
indent(sb, indent, options);
}
sb.append("}");
}
}
if (atRoot && options.getFormatted())
sb.append('\n');
}
@Override
public AbstractConfigValue get(Object key) {
return value.get(key);
}
private static boolean mapEquals(Map<String, ConfigValue> a, Map<String, ConfigValue> b) {
if (a == b)
return true;
Set<String> aKeys = a.keySet();
Set<String> bKeys = b.keySet();
if (!aKeys.equals(bKeys))
return false;
for (String key : aKeys) {
if (!a.get(key).equals(b.get(key)))
return false;
}
return true;
}
private static int mapHash(Map<String, ConfigValue> m) {
// the keys have to be sorted, otherwise we could be equal
// to another map but have a different hashcode.
List<String> keys = new ArrayList<String>();
keys.addAll(m.keySet());
Collections.sort(keys);
int valuesHash = 0;
for (String k : keys) {
valuesHash += m.get(k).hashCode();
}
return 41 * (41 + keys.hashCode()) + valuesHash;
}
@Override
protected boolean canEqual(Object other) {
return other instanceof ConfigObject;
}
@Override
public boolean equals(Object other) {
// note that "origin" is deliberately NOT part of equality.
// neither are other "extras" like ignoresFallbacks or resolve status.
if (other instanceof ConfigObject) {
// optimization to avoid unwrapped() for two ConfigObject,
// which is what AbstractConfigValue does.
return canEqual(other) && mapEquals(this, ((ConfigObject) other));
} else {
return false;
}
}
@Override
public int hashCode() {
// note that "origin" is deliberately NOT part of equality
// neither are other "extras" like ignoresFallbacks or resolve status.
return mapHash(this);
}
@Override
public boolean containsKey(Object key) {
return value.containsKey(key);
}
@Override
public Set<String> keySet() {
return value.keySet();
}
@Override
public boolean containsValue(Object v) {
return value.containsValue(v);
}
@Override
public Set<Map.Entry<String, ConfigValue>> entrySet() {
// total bloat just to work around lack of type variance
HashSet<java.util.Map.Entry<String, ConfigValue>> entries = new HashSet<Map.Entry<String, ConfigValue>>();
for (Map.Entry<String, AbstractConfigValue> e : value.entrySet()) {
entries.add(new AbstractMap.SimpleImmutableEntry<String, ConfigValue>(
e.getKey(), e
.getValue()));
}
return entries;
}
@Override
public boolean isEmpty() {
return value.isEmpty();
}
@Override
public int size() {
return value.size();
}
@Override
public Collection<ConfigValue> values() {
return new HashSet<ConfigValue>(value.values());
}
final private static String EMPTY_NAME = "empty config";
final private static SimpleConfigObject emptyInstance = empty(SimpleConfigOrigin
.newSimple(EMPTY_NAME));
final static SimpleConfigObject empty() {
return emptyInstance;
}
final static SimpleConfigObject empty(ConfigOrigin origin) {
if (origin == null)
return empty();
else
return new SimpleConfigObject(origin,
Collections.<String, AbstractConfigValue> emptyMap());
}
final static SimpleConfigObject emptyMissing(ConfigOrigin baseOrigin) {
return new SimpleConfigObject(SimpleConfigOrigin.newSimple(
baseOrigin.description() + " (not found)"),
Collections.<String, AbstractConfigValue> emptyMap());
}
// serialization all goes through SerializedConfigValue
private Object writeReplace() throws ObjectStreamException {
return new SerializedConfigValue(this);
}
}
| apache-2.0 |
udayinfy/ECommerce-Java | ECommerce-Web/src/main/java/com/appdynamicspilot/rest/ShoppingCart.java | 1458 | /*
* Copyright 2015 AppDynamics, 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.appdynamicspilot.rest;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
public class ShoppingCart implements java.io.Serializable {
Logger log = Logger.getLogger(ShoppingCart.class);
private List<ShoppingCartItem> items;
public ShoppingCart() {
items = new ArrayList<ShoppingCartItem>();
}
public void addItem(ShoppingCartItem item) {
items.add(item);
}
public void removeItem(ShoppingCartItem item) {
items.remove(item);
}
public List<ShoppingCartItem> getAllItems() {
return items;
}
public double getCartTotal() {
double total = 0.0;
for (ShoppingCartItem item : items) {
total += item.getPrice();
}
return total;
}
public void clear() {
items.clear();
}
}
| apache-2.0 |
sbespalov/strongbox | strongbox-web-core/src/main/java/org/carlspring/strongbox/validation/UniqueRoleNameValidator.java | 922 | package org.carlspring.strongbox.validation;
import javax.inject.Inject;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.carlspring.strongbox.authorization.service.AuthorizationConfigService;
import org.springframework.util.StringUtils;
/**
* @author Pablo Tirado
*/
public class UniqueRoleNameValidator
implements ConstraintValidator<UniqueRoleName, String>
{
@Inject
private AuthorizationConfigService authorizationConfigService;
@Override
public void initialize(UniqueRoleName constraint)
{
// empty by design
}
@Override
public boolean isValid(String roleName,
ConstraintValidatorContext context)
{
return StringUtils.isEmpty(roleName)
|| !authorizationConfigService.get().getRoles().stream().anyMatch(r -> r.getName().equals(roleName));
}
}
| apache-2.0 |
Netbrasoft/gnuob-api | src/main/java/br/com/netbrasoft/gnuob/api/category/CategoryWebServiceRepository.java | 5406 | /*
* Copyright 2016 Netbrasoft
*
* 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 br.com.netbrasoft.gnuob.api.category;
import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToCountCategory;
import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToFindCategory;
import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToFindCategoryById;
import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToMergeCategory;
import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToPersistCategory;
import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToRefreshCategory;
import static br.com.netbrasoft.gnuob.api.category.CategoryWebServiceWrapperHelper.wrapToRemoveCategory;
import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.CAN_NOT_INITIALIZE_THE_DEFAULT_WSDL_FROM_0;
import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.CATEGORY_WEB_SERVICE_REPOSITORY_NAME;
import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.GNUOB_SOAP_CATEGORY_WEBSERVICE_WSDL;
import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.HTTP_LOCALHOST_8080_GNUOB_SOAP_CATEGORY_WEB_SERVICE_IMPL_WSDL;
import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.UNCHECKED_VALUE;
import static java.lang.System.getProperty;
import static org.slf4j.LoggerFactory.getLogger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.javasimon.aop.Monitored;
import org.slf4j.Logger;
import org.springframework.stereotype.Repository;
import br.com.netbrasoft.gnuob.api.Category;
import br.com.netbrasoft.gnuob.api.CategoryWebServiceImpl;
import br.com.netbrasoft.gnuob.api.CategoryWebServiceImplService;
import br.com.netbrasoft.gnuob.api.MetaData;
import br.com.netbrasoft.gnuob.api.OrderBy;
import br.com.netbrasoft.gnuob.api.Paging;
import br.com.netbrasoft.gnuob.api.generic.IGenericTypeWebServiceRepository;
@Monitored
@Repository(CATEGORY_WEB_SERVICE_REPOSITORY_NAME)
public class CategoryWebServiceRepository<C extends Category> implements IGenericTypeWebServiceRepository<C> {
private static final Logger LOGGER = getLogger(CategoryWebServiceRepository.class);
private static final URL WSDL_LOCATION;
static {
URL url = null;
try {
url = new URL(getProperty(GNUOB_SOAP_CATEGORY_WEBSERVICE_WSDL,
HTTP_LOCALHOST_8080_GNUOB_SOAP_CATEGORY_WEB_SERVICE_IMPL_WSDL));
} catch (final MalformedURLException e) {
LOGGER.info(CAN_NOT_INITIALIZE_THE_DEFAULT_WSDL_FROM_0, getProperty(GNUOB_SOAP_CATEGORY_WEBSERVICE_WSDL,
HTTP_LOCALHOST_8080_GNUOB_SOAP_CATEGORY_WEB_SERVICE_IMPL_WSDL));
}
WSDL_LOCATION = url;
}
private transient CategoryWebServiceImpl categoryWebServiceImpl = null;
private CategoryWebServiceImpl getCategoryWebServiceImpl() {
if (categoryWebServiceImpl == null) {
categoryWebServiceImpl = new CategoryWebServiceImplService(WSDL_LOCATION).getCategoryWebServiceImplPort();
}
return categoryWebServiceImpl;
}
@Override
public long count(final MetaData credentials, final C categoryExample) {
return getCategoryWebServiceImpl().countCategory(wrapToCountCategory(categoryExample), credentials).getReturn();
}
@Override
@SuppressWarnings(UNCHECKED_VALUE)
public List<C> find(final MetaData credentials, final C categoryExample, final Paging paging,
final OrderBy orderingProperty) {
return (List<C>) getCategoryWebServiceImpl()
.findCategory(wrapToFindCategory(categoryExample, paging, orderingProperty), credentials).getReturn();
}
@Override
@SuppressWarnings(UNCHECKED_VALUE)
public C find(final MetaData credentials, final C categoryExample) {
return (C) getCategoryWebServiceImpl().findCategoryById(wrapToFindCategoryById(categoryExample), credentials)
.getReturn();
}
@Override
@SuppressWarnings(UNCHECKED_VALUE)
public C persist(final MetaData credentials, final C category) {
return (C) getCategoryWebServiceImpl().persistCategory(wrapToPersistCategory(category), credentials).getReturn();
}
@Override
@SuppressWarnings(UNCHECKED_VALUE)
public C merge(final MetaData credentials, final C category) {
return (C) getCategoryWebServiceImpl().mergeCategory(wrapToMergeCategory(category), credentials).getReturn();
}
@Override
@SuppressWarnings(UNCHECKED_VALUE)
public C refresh(final MetaData credentials, final C category) {
return (C) getCategoryWebServiceImpl().refreshCategory(wrapToRefreshCategory(category), credentials).getReturn();
}
@Override
public void remove(final MetaData credentials, final C category) {
getCategoryWebServiceImpl().removeCategory(wrapToRemoveCategory(category), credentials);
}
}
| apache-2.0 |
nuwand/carbon-apimgt | components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/AlertTypesListDTO.java | 2369 | package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.ArrayList;
import java.util.List;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AlertTypeDTO;
import javax.validation.constraints.*;
import io.swagger.annotations.*;
import java.util.Objects;
import javax.xml.bind.annotation.*;
import org.wso2.carbon.apimgt.rest.api.util.annotations.Scope;
public class AlertTypesListDTO {
private Integer count = null;
private List<AlertTypeDTO> alerts = new ArrayList<>();
/**
* The number of alerts
**/
public AlertTypesListDTO count(Integer count) {
this.count = count;
return this;
}
@ApiModelProperty(example = "3", value = "The number of alerts")
@JsonProperty("count")
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
/**
**/
public AlertTypesListDTO alerts(List<AlertTypeDTO> alerts) {
this.alerts = alerts;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("alerts")
public List<AlertTypeDTO> getAlerts() {
return alerts;
}
public void setAlerts(List<AlertTypeDTO> alerts) {
this.alerts = alerts;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AlertTypesListDTO alertTypesList = (AlertTypesListDTO) o;
return Objects.equals(count, alertTypesList.count) &&
Objects.equals(alerts, alertTypesList.alerts);
}
@Override
public int hashCode() {
return Objects.hash(count, alerts);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AlertTypesListDTO {\n");
sb.append(" count: ").append(toIndentedString(count)).append("\n");
sb.append(" alerts: ").append(toIndentedString(alerts)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| apache-2.0 |
pavolloffay/hawkular-agent | hawkular-wildfly-monitor/src/test/java/org/hawkular/agent/monitor/inventory/ResourceManagerTest.java | 6531 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.agent.monitor.inventory;
import org.hawkular.agent.monitor.inventory.dmr.DMRResource;
import org.hawkular.agent.monitor.inventory.dmr.DMRResourceType;
import org.hawkular.dmrclient.Address;
import org.jboss.dmr.ModelNode;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.traverse.BreadthFirstIterator;
import org.jgrapht.traverse.DepthFirstIterator;
import org.junit.Assert;
import org.junit.Test;
public class ResourceManagerTest {
@Test
public void testEmptyResourceManager() {
ResourceManager<DMRResource> rm = new ResourceManager<>();
Assert.assertNull(rm.getResource(new ID("foo")));
Assert.assertTrue(rm.getAllResources().isEmpty());
Assert.assertTrue(rm.getRootResources().isEmpty());
Assert.assertFalse(rm.getBreadthFirstIterator().hasNext());
Assert.assertFalse(rm.getDepthFirstIterator().hasNext());
}
@Test
public void testResourceManager() {
DMRResourceType type = new DMRResourceType(new ID("resType"), new Name("resTypeName"));
ResourceManager<DMRResource> rm = new ResourceManager<>();
DMRResource root1 = new DMRResource(new ID("root1"), new Name("root1Name"), null, type, null, new Address(),
new ModelNode());
DMRResource root2 = new DMRResource(new ID("root2"), new Name("root2Name"), null, type, null, new Address(),
new ModelNode());
DMRResource child1 = new DMRResource(new ID("child1"), new Name("child1Name"), null, type, root1,
new Address(), new ModelNode());
DMRResource child2 = new DMRResource(new ID("child2"), new Name("child2Name"), null, type, root1,
new Address(), new ModelNode());
DMRResource grandChild1 = new DMRResource(new ID("grand1"), new Name("grand1Name"), null, type, child1,
new Address(), new ModelNode());
// add root1
rm.addResource(root1);
Assert.assertEquals(1, rm.getAllResources().size());
Assert.assertTrue(rm.getAllResources().contains(root1));
Assert.assertEquals(root1, rm.getResource(root1.getID()));
DepthFirstIterator<DMRResource, DefaultEdge> dIter = rm.getDepthFirstIterator();
Assert.assertEquals(root1, dIter.next());
Assert.assertFalse(dIter.hasNext());
BreadthFirstIterator<DMRResource, DefaultEdge> bIter = rm.getBreadthFirstIterator();
Assert.assertEquals(root1, bIter.next());
Assert.assertFalse(bIter.hasNext());
Assert.assertEquals(1, rm.getRootResources().size());
Assert.assertTrue(rm.getRootResources().contains(root1));
// add child1
rm.addResource(child1);
Assert.assertEquals(2, rm.getAllResources().size());
Assert.assertTrue(rm.getAllResources().contains(child1));
Assert.assertEquals(child1, rm.getResource(child1.getID()));
// add grandChild1
rm.addResource(grandChild1);
Assert.assertEquals(3, rm.getAllResources().size());
Assert.assertTrue(rm.getAllResources().contains(grandChild1));
Assert.assertEquals(grandChild1, rm.getResource(grandChild1.getID()));
// add root2
rm.addResource(root2);
Assert.assertEquals(4, rm.getAllResources().size());
Assert.assertTrue(rm.getAllResources().contains(root2));
Assert.assertEquals(root2, rm.getResource(root2.getID()));
Assert.assertEquals(2, rm.getRootResources().size());
Assert.assertTrue(rm.getRootResources().contains(root2));
// add child2
rm.addResource(child2);
Assert.assertEquals(5, rm.getAllResources().size());
Assert.assertTrue(rm.getAllResources().contains(child2));
Assert.assertEquals(child2, rm.getResource(child2.getID()));
//
// the tree now looks like:
//
// root1 root2
// / \
// child1 child2
// |
// grandchild1
//
Assert.assertEquals(2, rm.getChildren(root1).size());
Assert.assertTrue(rm.getChildren(root1).contains(child1));
Assert.assertTrue(rm.getChildren(root1).contains(child2));
Assert.assertEquals(1, rm.getChildren(child1).size());
Assert.assertTrue(rm.getChildren(child1).contains(grandChild1));
Assert.assertEquals(0, rm.getChildren(grandChild1).size());
Assert.assertEquals(0, rm.getChildren(root2).size());
Assert.assertEquals(null, rm.getParent(root1));
Assert.assertEquals(null, rm.getParent(root2));
Assert.assertEquals(root1, rm.getParent(child1));
Assert.assertEquals(root1, rm.getParent(child2));
Assert.assertEquals(child1, rm.getParent(grandChild1));
/*
* WHY DOESN'T THIS ITERATE LIKE IT SHOULD?
*
// iterate depth first which should be:
// root1 -> child1 -> grandchild1 -> child2 -> root2
dIter = rm.getDepthFirstIterator();
Assert.assertEquals(root1, dIter.next());
Assert.assertEquals(child1, dIter.next());
Assert.assertEquals(grandChild1, dIter.next());
Assert.assertEquals(child2, dIter.next());
Assert.assertEquals(root2, dIter.next());
Assert.assertFalse(dIter.hasNext());
// iterate breadth first which should be (assuming roots are done in order)
// root1 -> child1 -> child2 -> grandchild1 -> root2
bIter = rm.getBreadthFirstIterator();
Assert.assertEquals(root1, bIter.next());
Assert.assertEquals(child1, bIter.next());
Assert.assertEquals(child2, bIter.next());
Assert.assertEquals(grandChild1, bIter.next());
Assert.assertEquals(root2, bIter.next());
Assert.assertFalse(bIter.hasNext());
*
* THE ABOVE DOESN'T WORK AS EXPECTED
*/
}
}
| apache-2.0 |
koscejev/camel | components/camel-docker/src/test/java/org/apache/camel/component/docker/headers/ListContainersCmdHeaderTest.java | 2786 | /**
* 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.component.docker.headers;
import java.util.Map;
import com.github.dockerjava.api.command.ListContainersCmd;
import org.apache.camel.component.docker.DockerConstants;
import org.apache.camel.component.docker.DockerOperation;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
/**
* Validates List Containers Request headers are applied properly
*/
public class ListContainersCmdHeaderTest extends BaseDockerHeaderTest<ListContainersCmd> {
@Mock
private ListContainersCmd mockObject;
@Test
public void listContainerHeaderTest() {
boolean showSize = true;
boolean showAll = false;
int limit = 2;
String since = "id1";
String before = "id2";
Map<String, Object> headers = getDefaultParameters();
headers.put(DockerConstants.DOCKER_LIMIT, limit);
headers.put(DockerConstants.DOCKER_SHOW_ALL, showAll);
headers.put(DockerConstants.DOCKER_SHOW_SIZE, showSize);
headers.put(DockerConstants.DOCKER_SINCE, since);
headers.put(DockerConstants.DOCKER_BEFORE, before);
template.sendBodyAndHeaders("direct:in", "", headers);
Mockito.verify(dockerClient, Mockito.times(1)).listContainersCmd();
Mockito.verify(mockObject, Mockito.times(1)).withShowAll(Matchers.eq(showAll));
Mockito.verify(mockObject, Mockito.times(1)).withShowSize(Matchers.eq(showSize));
Mockito.verify(mockObject, Mockito.times(1)).withLimit(Matchers.eq(limit));
Mockito.verify(mockObject, Mockito.times(1)).withSince(Matchers.eq(since));
Mockito.verify(mockObject, Mockito.times(1)).withBefore(Matchers.eq(before));
}
@Override
protected void setupMocks() {
Mockito.when(dockerClient.listContainersCmd()).thenReturn(mockObject);
}
@Override
protected DockerOperation getOperation() {
return DockerOperation.LIST_CONTAINERS;
}
}
| apache-2.0 |
elasticjob/elastic-job | elasticjob-lite/elasticjob-lite-spring/elasticjob-lite-spring-boot-starter/src/test/java/org/apache/shardingsphere/elasticjob/lite/spring/boot/reg/snapshot/ElasticJobSnapshotServiceConfigurationTest.java | 1874 | /*
* 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.shardingsphere.elasticjob.lite.spring.boot.reg.snapshot;
import static org.junit.Assert.assertNotNull;
import org.apache.shardingsphere.elasticjob.lite.internal.snapshot.SnapshotService;
import org.apache.shardingsphere.elasticjob.lite.spring.boot.job.fixture.EmbedTestingServer;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
@SpringBootTest
@SpringBootApplication
@ActiveProfiles("snapshot")
public class ElasticJobSnapshotServiceConfigurationTest extends AbstractJUnit4SpringContextTests {
@BeforeClass
public static void init() {
EmbedTestingServer.start();
}
@Test
public void assertSnapshotServiceConfiguration() {
assertNotNull(applicationContext);
assertNotNull(applicationContext.getBean(SnapshotService.class));
}
}
| apache-2.0 |
joewalnes/idea-community | java/java-impl/src/com/intellij/codeInsight/template/macro/IterableComponentTypeMacro.java | 3485 | /*
* Copyright 2000-2009 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.codeInsight.template.macro;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.template.*;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.TypeConversionUtil;
import org.jetbrains.annotations.NotNull;
/**
* @author ven
*/
public class IterableComponentTypeMacro implements Macro {
public String getName() {
return "iterableComponentType";
}
public String getDescription() {
return CodeInsightBundle.message("macro.iterable.component.type");
}
public String getDefaultValue() {
return "a";
}
public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) {
if (params.length != 1) return null;
final Result result = params[0].calculateResult(context);
if (result == null) return null;
Project project = context.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiExpression expr = MacroUtil.resultToPsiExpression(result, context);
if (expr == null) return null;
PsiType type = expr.getType();
if (type instanceof PsiArrayType) {
return new PsiTypeResult(((PsiArrayType)type).getComponentType(), project);
}
if (type instanceof PsiClassType) {
PsiClassType.ClassResolveResult resolveResult = ((PsiClassType)type).resolveGenerics();
PsiClass aClass = resolveResult.getElement();
if (aClass != null) {
PsiClass iterableClass = JavaPsiFacade.getInstance(project).findClass("java.lang.Iterable", aClass.getResolveScope());
if (iterableClass != null) {
PsiSubstitutor substitutor = TypeConversionUtil.getClassSubstitutor(iterableClass, aClass, resolveResult.getSubstitutor());
if (substitutor != null) {
PsiType parameterType = substitutor.substitute(iterableClass.getTypeParameters()[0]);
if (parameterType instanceof PsiCapturedWildcardType) {
parameterType = ((PsiCapturedWildcardType)parameterType).getWildcard();
}
if (parameterType != null) {
if (parameterType instanceof PsiWildcardType) {
if (((PsiWildcardType)parameterType).isExtends()) {
return new PsiTypeResult(((PsiWildcardType)parameterType).getBound(), project);
}
else return null;
}
return new PsiTypeResult(parameterType, project);
}
}
}
}
}
return null;
}
public Result calculateQuickResult(@NotNull Expression[] params, ExpressionContext context) {
return calculateResult(params, context);
}
public LookupElement[] calculateLookupItems(@NotNull Expression[] params, ExpressionContext context) {
return LookupElement.EMPTY_ARRAY;
}
}
| apache-2.0 |
semonte/intellij-community | platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java | 29248 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.fileEditor.impl;
import com.intellij.AppTopics;
import com.intellij.CommonBundle;
import com.intellij.codeStyle.CodeStyleFacade;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.application.TransactionGuardImpl;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.PrioritizedDocumentListener;
import com.intellij.openapi.editor.impl.EditorFactoryImpl;
import com.intellij.openapi.editor.impl.TrailingSpacesStripper;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.*;
import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl;
import com.intellij.openapi.fileTypes.BinaryFileTypeDecompilers;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.UnknownFileType;
import com.intellij.openapi.project.*;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem;
import com.intellij.pom.core.impl.PomModelImpl;
import com.intellij.psi.ExternalChangeAction;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.SingleRootFileViewProvider;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.ui.UIBundle;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.nio.charset.Charset;
import java.util.*;
import java.util.List;
public class FileDocumentManagerImpl extends FileDocumentManager implements VirtualFileListener, VetoableProjectManagerListener, SafeWriteRequestor {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl");
public static final Key<Document> HARD_REF_TO_DOCUMENT_KEY = Key.create("HARD_REF_TO_DOCUMENT_KEY");
private static final Key<String> LINE_SEPARATOR_KEY = Key.create("LINE_SEPARATOR_KEY");
private static final Key<VirtualFile> FILE_KEY = Key.create("FILE_KEY");
private static final Key<Boolean> MUST_RECOMPUTE_FILE_TYPE = Key.create("Must recompute file type");
private final Set<Document> myUnsavedDocuments = ContainerUtil.newConcurrentSet();
private final MessageBus myBus;
private static final Object lock = new Object();
private final FileDocumentManagerListener myMultiCaster;
private final TrailingSpacesStripper myTrailingSpacesStripper = new TrailingSpacesStripper();
private boolean myOnClose;
private volatile MemoryDiskConflictResolver myConflictResolver = new MemoryDiskConflictResolver();
private final PrioritizedDocumentListener myPhysicalDocumentChangeTracker = new PrioritizedDocumentListener() {
@Override
public int getPriority() {
return Integer.MIN_VALUE;
}
@Override
public void documentChanged(DocumentEvent e) {
final Document document = e.getDocument();
if (!ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.ExternalDocumentChange.class)) {
myUnsavedDocuments.add(document);
}
final Runnable currentCommand = CommandProcessor.getInstance().getCurrentCommand();
Project project = currentCommand == null ? null : CommandProcessor.getInstance().getCurrentCommandProject();
if (project == null)
project = ProjectUtil.guessProjectForFile(getFile(document));
String lineSeparator = CodeStyleFacade.getInstance(project).getLineSeparator();
document.putUserData(LINE_SEPARATOR_KEY, lineSeparator);
// avoid documents piling up during batch processing
if (areTooManyDocumentsInTheQueue(myUnsavedDocuments)) {
saveAllDocumentsLater();
}
}
};
public FileDocumentManagerImpl(@NotNull VirtualFileManager virtualFileManager, @NotNull ProjectManager projectManager) {
virtualFileManager.addVirtualFileListener(this);
projectManager.addProjectManagerListener(this);
myBus = ApplicationManager.getApplication().getMessageBus();
myBus.connect().subscribe(ProjectManager.TOPIC, this);
InvocationHandler handler = (proxy, method, args) -> {
multiCast(method, args);
return null;
};
final ClassLoader loader = FileDocumentManagerListener.class.getClassLoader();
myMultiCaster = (FileDocumentManagerListener)Proxy.newProxyInstance(loader, new Class[]{FileDocumentManagerListener.class}, handler);
}
private static void unwrapAndRethrow(Exception e) {
Throwable unwrapped = e;
if (e instanceof InvocationTargetException) {
unwrapped = e.getCause() == null ? e : e.getCause();
}
if (unwrapped instanceof Error) throw (Error)unwrapped;
if (unwrapped instanceof RuntimeException) throw (RuntimeException)unwrapped;
LOG.error(unwrapped);
}
@SuppressWarnings("OverlyBroadCatchBlock")
private void multiCast(@NotNull Method method, Object[] args) {
try {
method.invoke(myBus.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), args);
}
catch (ClassCastException e) {
LOG.error("Arguments: "+ Arrays.toString(args), e);
}
catch (Exception e) {
unwrapAndRethrow(e);
}
// Allows pre-save document modification
for (FileDocumentManagerListener listener : getListeners()) {
try {
method.invoke(listener, args);
}
catch (Exception e) {
unwrapAndRethrow(e);
}
}
// stripping trailing spaces
try {
method.invoke(myTrailingSpacesStripper, args);
}
catch (Exception e) {
unwrapAndRethrow(e);
}
}
@Override
@Nullable
public Document getDocument(@NotNull final VirtualFile file) {
ApplicationManager.getApplication().assertReadAccessAllowed();
DocumentEx document = (DocumentEx)getCachedDocument(file);
if (document == null) {
if (!file.isValid() || file.isDirectory() || isBinaryWithoutDecompiler(file)) return null;
boolean tooLarge = FileUtilRt.isTooLarge(file.getLength());
if (file.getFileType().isBinary() && tooLarge) return null;
final CharSequence text = tooLarge ? LoadTextUtil.loadText(file, getPreviewCharCount(file)) : LoadTextUtil.loadText(file);
synchronized (lock) {
document = (DocumentEx)getCachedDocument(file);
if (document != null) return document; // Double checking
document = (DocumentEx)createDocument(text, file);
document.setModificationStamp(file.getModificationStamp());
final FileType fileType = file.getFileType();
document.setReadOnly(tooLarge || !file.isWritable() || fileType.isBinary());
if (!(file instanceof LightVirtualFile || file.getFileSystem() instanceof NonPhysicalFileSystem)) {
document.addDocumentListener(myPhysicalDocumentChangeTracker);
}
if (file instanceof LightVirtualFile) {
registerDocument(document, file);
}
else {
document.putUserData(FILE_KEY, file);
cacheDocument(file, document);
}
}
myMultiCaster.fileContentLoaded(file, document);
}
return document;
}
public static boolean areTooManyDocumentsInTheQueue(Collection<Document> documents) {
if (documents.size() > 100) return true;
int totalSize = 0;
for (Document document : documents) {
totalSize += document.getTextLength();
if (totalSize > FileUtilRt.LARGE_FOR_CONTENT_LOADING) return true;
}
return false;
}
private static Document createDocument(final CharSequence text, VirtualFile file) {
boolean acceptSlashR = file instanceof LightVirtualFile && StringUtil.indexOf(text, '\r') >= 0;
boolean freeThreaded = Boolean.TRUE.equals(file.getUserData(SingleRootFileViewProvider.FREE_THREADED));
return ((EditorFactoryImpl)EditorFactory.getInstance()).createDocument(text, acceptSlashR, freeThreaded);
}
@Override
@Nullable
public Document getCachedDocument(@NotNull VirtualFile file) {
Document hard = file.getUserData(HARD_REF_TO_DOCUMENT_KEY);
return hard != null ? hard : getDocumentFromCache(file);
}
public static void registerDocument(@NotNull final Document document, @NotNull VirtualFile virtualFile) {
synchronized (lock) {
document.putUserData(FILE_KEY, virtualFile);
virtualFile.putUserData(HARD_REF_TO_DOCUMENT_KEY, document);
}
}
@Override
@Nullable
public VirtualFile getFile(@NotNull Document document) {
return document.getUserData(FILE_KEY);
}
@TestOnly
public void dropAllUnsavedDocuments() {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
throw new RuntimeException("This method is only for test mode!");
}
ApplicationManager.getApplication().assertWriteAccessAllowed();
if (!myUnsavedDocuments.isEmpty()) {
myUnsavedDocuments.clear();
fireUnsavedDocumentsDropped();
}
}
private void saveAllDocumentsLater() {
// later because some document might have been blocked by PSI right now
ApplicationManager.getApplication().invokeLater(() -> {
if (ApplicationManager.getApplication().isDisposed()) {
return;
}
final Document[] unsavedDocuments = getUnsavedDocuments();
for (Document document : unsavedDocuments) {
VirtualFile file = getFile(document);
if (file == null) continue;
Project project = ProjectUtil.guessProjectForFile(file);
if (project == null) continue;
if (PsiDocumentManager.getInstance(project).isDocumentBlockedByPsi(document)) continue;
saveDocument(document);
}
});
}
@Override
public void saveAllDocuments() {
saveAllDocuments(true);
}
/**
* @param isExplicit caused by user directly (Save action) or indirectly (e.g. Compile)
*/
public void saveAllDocuments(boolean isExplicit) {
ApplicationManager.getApplication().assertIsDispatchThread();
((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed();
myMultiCaster.beforeAllDocumentsSaving();
if (myUnsavedDocuments.isEmpty()) return;
final Map<Document, IOException> failedToSave = new HashMap<>();
final Set<Document> vetoed = new HashSet<>();
while (true) {
int count = 0;
for (Document document : myUnsavedDocuments) {
if (failedToSave.containsKey(document)) continue;
if (vetoed.contains(document)) continue;
try {
doSaveDocument(document, isExplicit);
}
catch (IOException e) {
//noinspection ThrowableResultOfMethodCallIgnored
failedToSave.put(document, e);
}
catch (SaveVetoException e) {
vetoed.add(document);
}
count++;
}
if (count == 0) break;
}
if (!failedToSave.isEmpty()) {
handleErrorsOnSave(failedToSave);
}
}
@Override
public void saveDocument(@NotNull final Document document) {
saveDocument(document, true);
}
public void saveDocument(@NotNull final Document document, final boolean explicit) {
ApplicationManager.getApplication().assertIsDispatchThread();
((TransactionGuardImpl)TransactionGuard.getInstance()).assertWriteActionAllowed();
if (!myUnsavedDocuments.contains(document)) return;
try {
doSaveDocument(document, explicit);
}
catch (IOException e) {
handleErrorsOnSave(Collections.singletonMap(document, e));
}
catch (SaveVetoException ignored) {
}
}
@Override
public void saveDocumentAsIs(@NotNull Document document) {
VirtualFile file = getFile(document);
boolean spaceStrippingEnabled = true;
if (file != null) {
spaceStrippingEnabled = TrailingSpacesStripper.isEnabled(file);
TrailingSpacesStripper.setEnabled(file, false);
}
try {
saveDocument(document);
}
finally {
if (file != null) {
TrailingSpacesStripper.setEnabled(file, spaceStrippingEnabled);
}
}
}
private static class SaveVetoException extends Exception {}
private void doSaveDocument(@NotNull final Document document, boolean isExplicit) throws IOException, SaveVetoException {
VirtualFile file = getFile(document);
if (file == null || file instanceof LightVirtualFile || file.isValid() && !isFileModified(file)) {
removeFromUnsaved(document);
return;
}
if (file.isValid() && needsRefresh(file)) {
file.refresh(false, false);
if (!myUnsavedDocuments.contains(document)) return;
}
if (!maySaveDocument(file, document, isExplicit)) {
throw new SaveVetoException();
}
WriteAction.run(() -> doSaveDocumentInWriteAction(document, file));
}
private boolean maySaveDocument(VirtualFile file, Document document, boolean isExplicit) {
return !myConflictResolver.hasConflict(file) &&
Arrays.stream(Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)).allMatch(vetoer -> vetoer.maySaveDocument(document, isExplicit));
}
private void doSaveDocumentInWriteAction(@NotNull final Document document, @NotNull final VirtualFile file) throws IOException {
if (!file.isValid()) {
removeFromUnsaved(document);
return;
}
if (!file.equals(getFile(document))) {
registerDocument(document, file);
}
if (!isSaveNeeded(document, file)) {
if (document instanceof DocumentEx) {
((DocumentEx)document).setModificationStamp(file.getModificationStamp());
}
removeFromUnsaved(document);
updateModifiedProperty(file);
return;
}
PomModelImpl.guardPsiModificationsIn(() -> {
myMultiCaster.beforeDocumentSaving(document);
LOG.assertTrue(file.isValid());
String text = document.getText();
String lineSeparator = getLineSeparator(document, file);
if (!lineSeparator.equals("\n")) {
text = StringUtil.convertLineSeparators(text, lineSeparator);
}
Project project = ProjectLocator.getInstance().guessProjectForFile(file);
LoadTextUtil.write(project, file, this, text, document.getModificationStamp());
myUnsavedDocuments.remove(document);
LOG.assertTrue(!myUnsavedDocuments.contains(document));
myTrailingSpacesStripper.clearLineModificationFlags(document);
});
}
private static void updateModifiedProperty(@NotNull VirtualFile file) {
for (Project project : ProjectManager.getInstance().getOpenProjects()) {
FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
for (FileEditor editor : fileEditorManager.getAllEditors(file)) {
if (editor instanceof TextEditorImpl) {
((TextEditorImpl)editor).updateModifiedProperty();
}
}
}
}
private void removeFromUnsaved(@NotNull Document document) {
myUnsavedDocuments.remove(document);
fireUnsavedDocumentsDropped();
LOG.assertTrue(!myUnsavedDocuments.contains(document));
}
private static boolean isSaveNeeded(@NotNull Document document, @NotNull VirtualFile file) throws IOException {
if (file.getFileType().isBinary() || document.getTextLength() > 1000 * 1000) { // don't compare if the file is too big
return true;
}
byte[] bytes = file.contentsToByteArray();
CharSequence loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false);
return !Comparing.equal(document.getCharsSequence(), loaded);
}
private static boolean needsRefresh(final VirtualFile file) {
final VirtualFileSystem fs = file.getFileSystem();
return fs instanceof NewVirtualFileSystem && file.getTimeStamp() != ((NewVirtualFileSystem)fs).getTimeStamp(file);
}
@NotNull
public static String getLineSeparator(@NotNull Document document, @NotNull VirtualFile file) {
String lineSeparator = LoadTextUtil.getDetectedLineSeparator(file);
if (lineSeparator == null) {
lineSeparator = document.getUserData(LINE_SEPARATOR_KEY);
assert lineSeparator != null : document;
}
return lineSeparator;
}
@Override
@NotNull
public String getLineSeparator(@Nullable VirtualFile file, @Nullable Project project) {
String lineSeparator = file == null ? null : LoadTextUtil.getDetectedLineSeparator(file);
if (lineSeparator == null) {
CodeStyleFacade settingsManager = project == null
? CodeStyleFacade.getInstance()
: CodeStyleFacade.getInstance(project);
lineSeparator = settingsManager.getLineSeparator();
}
return lineSeparator;
}
@Override
public boolean requestWriting(@NotNull Document document, Project project) {
final VirtualFile file = getInstance().getFile(document);
if (project != null && file != null && file.isValid()) {
return !file.getFileType().isBinary() && ReadonlyStatusHandler.ensureFilesWritable(project, file);
}
if (document.isWritable()) {
return true;
}
document.fireReadOnlyModificationAttempt();
return false;
}
@Override
public void reloadFiles(@NotNull final VirtualFile... files) {
for (VirtualFile file : files) {
if (file.exists()) {
final Document doc = getCachedDocument(file);
if (doc != null) {
reloadFromDisk(doc);
}
}
}
}
@Override
@NotNull
public Document[] getUnsavedDocuments() {
if (myUnsavedDocuments.isEmpty()) {
return Document.EMPTY_ARRAY;
}
List<Document> list = new ArrayList<>(myUnsavedDocuments);
return list.toArray(new Document[list.size()]);
}
@Override
public boolean isDocumentUnsaved(@NotNull Document document) {
return myUnsavedDocuments.contains(document);
}
@Override
public boolean isFileModified(@NotNull VirtualFile file) {
final Document doc = getCachedDocument(file);
return doc != null && isDocumentUnsaved(doc) && doc.getModificationStamp() != file.getModificationStamp();
}
@Override
public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
final VirtualFile file = event.getFile();
if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName())) {
final Document document = getCachedDocument(file);
if (document != null) {
ApplicationManager.getApplication().runWriteAction((ExternalChangeAction)() -> document.setReadOnly(!file.isWritable()));
}
}
else if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) {
Document document = getCachedDocument(file);
if (document != null) {
// a file is linked to a document - chances are it is an "unknown text file" now
if (isBinaryWithoutDecompiler(file)) {
unbindFileFromDocument(file, document);
}
}
}
}
private void unbindFileFromDocument(@NotNull VirtualFile file, @NotNull Document document) {
removeDocumentFromCache(file);
file.putUserData(HARD_REF_TO_DOCUMENT_KEY, null);
document.putUserData(FILE_KEY, null);
}
private static boolean isBinaryWithDecompiler(@NotNull VirtualFile file) {
final FileType ft = file.getFileType();
return ft.isBinary() && BinaryFileTypeDecompilers.INSTANCE.forFileType(ft) != null;
}
private static boolean isBinaryWithoutDecompiler(@NotNull VirtualFile file) {
final FileType fileType = file.getFileType();
return fileType.isBinary() && BinaryFileTypeDecompilers.INSTANCE.forFileType(fileType) == null;
}
@Override
public void contentsChanged(@NotNull VirtualFileEvent event) {
if (event.isFromSave()) return;
final VirtualFile file = event.getFile();
final Document document = getCachedDocument(file);
if (document == null) {
myMultiCaster.fileWithNoDocumentChanged(file);
return;
}
if (isBinaryWithDecompiler(file)) {
myMultiCaster.fileWithNoDocumentChanged(file); // This will generate PSI event at FileManagerImpl
}
if (document.getModificationStamp() == event.getOldModificationStamp() || !isDocumentUnsaved(document)) {
reloadFromDisk(document);
}
}
@Override
public void reloadFromDisk(@NotNull final Document document) {
ApplicationManager.getApplication().assertIsDispatchThread();
final VirtualFile file = getFile(document);
assert file != null;
if (!fireBeforeFileContentReload(file, document)) {
return;
}
final Project project = ProjectLocator.getInstance().guessProjectForFile(file);
boolean[] isReloadable = {isReloadable(file, document, project)};
if (isReloadable[0]) {
CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(
new ExternalChangeAction.ExternalDocumentChange(document, project) {
@Override
public void run() {
if (!isBinaryWithoutDecompiler(file)) {
LoadTextUtil.setCharsetWasDetectedFromBytes(file, null);
file.setBOM(null); // reset BOM in case we had one and the external change stripped it away
file.setCharset(null, null, false);
boolean wasWritable = document.isWritable();
document.setReadOnly(false);
boolean tooLarge = FileUtilRt.isTooLarge(file.getLength());
CharSequence reloaded = tooLarge ? LoadTextUtil.loadText(file, getPreviewCharCount(file)) : LoadTextUtil.loadText(file);
isReloadable[0] = isReloadable(file, document, project);
if (isReloadable[0]) {
DocumentEx documentEx = (DocumentEx)document;
documentEx.replaceText(reloaded, file.getModificationStamp());
}
document.setReadOnly(!wasWritable);
}
}
}
), UIBundle.message("file.cache.conflict.action"), null, UndoConfirmationPolicy.REQUEST_CONFIRMATION);
}
if (isReloadable[0]) {
myMultiCaster.fileContentReloaded(file, document);
}
else {
unbindFileFromDocument(file, document);
myMultiCaster.fileWithNoDocumentChanged(file);
}
myUnsavedDocuments.remove(document);
}
private static boolean isReloadable(@NotNull VirtualFile file, @NotNull Document document, @Nullable Project project) {
PsiFile cachedPsiFile = project == null ? null : PsiDocumentManager.getInstance(project).getCachedPsiFile(document);
return !(FileUtilRt.isTooLarge(file.getLength()) && file.getFileType().isBinary()) &&
(cachedPsiFile == null || cachedPsiFile instanceof PsiFileImpl || isBinaryWithDecompiler(file));
}
@TestOnly
void setAskReloadFromDisk(@NotNull Disposable disposable, @NotNull MemoryDiskConflictResolver newProcessor) {
final MemoryDiskConflictResolver old = myConflictResolver;
myConflictResolver = newProcessor;
Disposer.register(disposable, () -> myConflictResolver = old);
}
@Override
public void fileDeleted(@NotNull VirtualFileEvent event) {
Document doc = getCachedDocument(event.getFile());
if (doc != null) {
myTrailingSpacesStripper.documentDeleted(doc);
}
}
@Override
public void beforeContentsChange(@NotNull VirtualFileEvent event) {
VirtualFile virtualFile = event.getFile();
// check file type in second order to avoid content detection running
if (virtualFile.getLength() == 0 && virtualFile.getFileType() == UnknownFileType.INSTANCE) {
virtualFile.putUserData(MUST_RECOMPUTE_FILE_TYPE, Boolean.TRUE);
}
myConflictResolver.beforeContentChange(event);
}
public static boolean recomputeFileTypeIfNecessary(@NotNull VirtualFile virtualFile) {
if (virtualFile.getUserData(MUST_RECOMPUTE_FILE_TYPE) != null) {
virtualFile.getFileType();
virtualFile.putUserData(MUST_RECOMPUTE_FILE_TYPE, null);
return true;
}
return false;
}
@Override
public boolean canClose(@NotNull Project project) {
if (!myUnsavedDocuments.isEmpty()) {
myOnClose = true;
try {
saveAllDocuments();
}
finally {
myOnClose = false;
}
}
return myUnsavedDocuments.isEmpty();
}
private void fireUnsavedDocumentsDropped() {
myMultiCaster.unsavedDocumentsDropped();
}
private boolean fireBeforeFileContentReload(final VirtualFile file, @NotNull Document document) {
for (FileDocumentSynchronizationVetoer vetoer : Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) {
try {
if (!vetoer.mayReloadFileContent(file, document)) {
return false;
}
}
catch (Exception e) {
LOG.error(e);
}
}
myMultiCaster.beforeFileContentReload(file, document);
return true;
}
@NotNull
private static FileDocumentManagerListener[] getListeners() {
return FileDocumentManagerListener.EP_NAME.getExtensions();
}
private static int getPreviewCharCount(@NotNull VirtualFile file) {
Charset charset = EncodingManager.getInstance().getEncoding(file, false);
float bytesPerChar = charset == null ? 2 : charset.newEncoder().averageBytesPerChar();
return (int)(FileUtilRt.LARGE_FILE_PREVIEW_SIZE / bytesPerChar);
}
private void handleErrorsOnSave(@NotNull Map<Document, IOException> failures) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
IOException ioException = ContainerUtil.getFirstItem(failures.values());
if (ioException != null) {
throw new RuntimeException(ioException);
}
return;
}
for (IOException exception : failures.values()) {
LOG.warn(exception);
}
final String text = StringUtil.join(failures.values(), Throwable::getMessage, "\n");
final DialogWrapper dialog = new DialogWrapper(null) {
{
init();
setTitle(UIBundle.message("cannot.save.files.dialog.title"));
}
@Override
protected void createDefaultActions() {
super.createDefaultActions();
myOKAction.putValue(Action.NAME, UIBundle
.message(myOnClose ? "cannot.save.files.dialog.ignore.changes" : "cannot.save.files.dialog.revert.changes"));
myOKAction.putValue(DEFAULT_ACTION, null);
if (!myOnClose) {
myCancelAction.putValue(Action.NAME, CommonBundle.getCloseButtonText());
}
}
@Override
protected JComponent createCenterPanel() {
final JPanel panel = new JPanel(new BorderLayout(0, 5));
panel.add(new JLabel(UIBundle.message("cannot.save.files.dialog.message")), BorderLayout.NORTH);
final JTextPane area = new JTextPane();
area.setText(text);
area.setEditable(false);
area.setMinimumSize(new Dimension(area.getMinimumSize().width, 50));
panel.add(new JBScrollPane(area, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER),
BorderLayout.CENTER);
return panel;
}
};
if (dialog.showAndGet()) {
for (Document document : failures.keySet()) {
reloadFromDisk(document);
}
}
}
private final Map<VirtualFile, Document> myDocumentCache = ContainerUtil.createConcurrentWeakValueMap();
// used in Upsource
protected void cacheDocument(@NotNull VirtualFile file, @NotNull Document document) {
myDocumentCache.put(file, document);
}
// used in Upsource
protected void removeDocumentFromCache(@NotNull VirtualFile file) {
myDocumentCache.remove(file);
}
// used in Upsource
protected Document getDocumentFromCache(@NotNull VirtualFile file) {
return myDocumentCache.get(file);
}
}
| apache-2.0 |
tombujok/hazelcast | hazelcast/src/main/java/com/hazelcast/cluster/impl/TcpIpJoiner.java | 22055 | /*
* 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.cluster.impl;
import com.hazelcast.config.Config;
import com.hazelcast.config.InterfacesConfig;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.config.TcpIpConfig;
import com.hazelcast.instance.Node;
import com.hazelcast.internal.cluster.impl.AbstractJoiner;
import com.hazelcast.internal.cluster.impl.ClusterServiceImpl;
import com.hazelcast.internal.cluster.impl.SplitBrainJoinMessage;
import com.hazelcast.internal.cluster.impl.operations.JoinMastershipClaimOp;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.Connection;
import com.hazelcast.spi.properties.GroupProperty;
import com.hazelcast.util.AddressUtil;
import com.hazelcast.util.AddressUtil.AddressMatcher;
import com.hazelcast.util.AddressUtil.InvalidAddressException;
import com.hazelcast.util.Clock;
import com.hazelcast.util.EmptyStatement;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.util.AddressUtil.AddressHolder;
public class TcpIpJoiner extends AbstractJoiner {
private static final long JOIN_RETRY_WAIT_TIME = 1000L;
private static final int LOOK_FOR_MASTER_MAX_TRY_COUNT = 20;
private final int maxPortTryCount;
private volatile boolean claimingMaster;
public TcpIpJoiner(Node node) {
super(node);
int tryCount = node.getProperties().getInteger(GroupProperty.TCP_JOIN_PORT_TRY_COUNT);
if (tryCount <= 0) {
throw new IllegalArgumentException(String.format("%s should be greater than zero! Current value: %d",
GroupProperty.TCP_JOIN_PORT_TRY_COUNT, tryCount));
}
maxPortTryCount = tryCount;
}
public boolean isClaimingMaster() {
return claimingMaster;
}
protected int getConnTimeoutSeconds() {
return config.getNetworkConfig().getJoin().getTcpIpConfig().getConnectionTimeoutSeconds();
}
@Override
public void doJoin() {
final Address targetAddress = getTargetAddress();
if (targetAddress != null) {
long maxJoinMergeTargetMillis = node.getProperties().getMillis(GroupProperty.MAX_JOIN_MERGE_TARGET_SECONDS);
joinViaTargetMember(targetAddress, maxJoinMergeTargetMillis);
if (!clusterService.isJoined()) {
joinViaPossibleMembers();
}
} else if (config.getNetworkConfig().getJoin().getTcpIpConfig().getRequiredMember() != null) {
Address requiredMember = getRequiredMemberAddress();
long maxJoinMillis = getMaxJoinMillis();
joinViaTargetMember(requiredMember, maxJoinMillis);
} else {
joinViaPossibleMembers();
}
}
private void joinViaTargetMember(Address targetAddress, long maxJoinMillis) {
try {
if (targetAddress == null) {
throw new IllegalArgumentException("Invalid target address -> NULL");
}
if (logger.isFineEnabled()) {
logger.fine("Joining over target member " + targetAddress);
}
if (targetAddress.equals(node.getThisAddress()) || isLocalAddress(targetAddress)) {
clusterJoinManager.setThisMemberAsMaster();
return;
}
long joinStartTime = Clock.currentTimeMillis();
Connection connection;
while (shouldRetry() && (Clock.currentTimeMillis() - joinStartTime < maxJoinMillis)) {
connection = node.connectionManager.getOrConnect(targetAddress);
if (connection == null) {
//noinspection BusyWait
Thread.sleep(JOIN_RETRY_WAIT_TIME);
continue;
}
if (logger.isFineEnabled()) {
logger.fine("Sending joinRequest " + targetAddress);
}
clusterJoinManager.sendJoinRequest(targetAddress, true);
//noinspection BusyWait
Thread.sleep(JOIN_RETRY_WAIT_TIME);
}
} catch (final Exception e) {
logger.warning(e);
}
}
private void joinViaPossibleMembers() {
try {
blacklistedAddresses.clear();
Collection<Address> possibleAddresses = getPossibleAddresses();
boolean foundConnection = tryInitialConnection(possibleAddresses);
if (!foundConnection) {
logger.fine("This node will assume master role since no possible member where connected to.");
clusterJoinManager.setThisMemberAsMaster();
return;
}
long maxJoinMillis = getMaxJoinMillis();
long startTime = Clock.currentTimeMillis();
while (shouldRetry() && (Clock.currentTimeMillis() - startTime < maxJoinMillis)) {
tryToJoinPossibleAddresses(possibleAddresses);
if (clusterService.isJoined()) {
return;
}
if (isAllBlacklisted(possibleAddresses)) {
logger.fine(
"This node will assume master role since none of the possible members accepted join request.");
clusterJoinManager.setThisMemberAsMaster();
return;
}
boolean masterCandidate = isThisNodeMasterCandidate(possibleAddresses);
if (masterCandidate) {
boolean consensus = claimMastership(possibleAddresses);
if (consensus) {
if (logger.isFineEnabled()) {
Set<Address> votingEndpoints = new HashSet<Address>(possibleAddresses);
votingEndpoints.removeAll(blacklistedAddresses.keySet());
logger.fine("Setting myself as master after consensus!"
+ " Voting endpoints: " + votingEndpoints);
}
clusterJoinManager.setThisMemberAsMaster();
claimingMaster = false;
return;
}
} else {
if (logger.isFineEnabled()) {
logger.fine("Cannot claim myself as master! Will try to connect a possible master...");
}
}
claimingMaster = false;
lookForMaster(possibleAddresses);
}
} catch (Throwable t) {
logger.severe(t);
}
}
@SuppressWarnings("checkstyle:npathcomplexity")
private boolean claimMastership(Collection<Address> possibleAddresses) {
if (logger.isFineEnabled()) {
Set<Address> votingEndpoints = new HashSet<Address>(possibleAddresses);
votingEndpoints.removeAll(blacklistedAddresses.keySet());
logger.fine("Claiming myself as master node! Asking to endpoints: " + votingEndpoints);
}
claimingMaster = true;
Collection<Future<Boolean>> responses = new LinkedList<Future<Boolean>>();
for (Address address : possibleAddresses) {
if (isBlacklisted(address)) {
continue;
}
if (node.getConnectionManager().getConnection(address) != null) {
Future<Boolean> future = node.nodeEngine.getOperationService()
.createInvocationBuilder(ClusterServiceImpl.SERVICE_NAME,
new JoinMastershipClaimOp(), address).setTryCount(1).invoke();
responses.add(future);
}
}
final long maxWait = TimeUnit.SECONDS.toMillis(10);
long waitTime = 0L;
boolean consensus = true;
for (Future<Boolean> response : responses) {
long t = Clock.currentTimeMillis();
try {
consensus = response.get(1, TimeUnit.SECONDS);
} catch (Exception e) {
logger.finest(e);
consensus = false;
} finally {
waitTime += (Clock.currentTimeMillis() - t);
}
if (!consensus) {
break;
}
if (waitTime > maxWait) {
consensus = false;
break;
}
}
return consensus;
}
private boolean isThisNodeMasterCandidate(Collection<Address> possibleAddresses) {
int thisHashCode = node.getThisAddress().hashCode();
for (Address address : possibleAddresses) {
if (isBlacklisted(address)) {
continue;
}
if (node.connectionManager.getConnection(address) != null) {
if (thisHashCode > address.hashCode()) {
return false;
}
}
}
return true;
}
private void tryToJoinPossibleAddresses(Collection<Address> possibleAddresses) throws InterruptedException {
long connectionTimeoutMillis = TimeUnit.SECONDS.toMillis(getConnTimeoutSeconds());
long start = Clock.currentTimeMillis();
while (!clusterService.isJoined() && Clock.currentTimeMillis() - start < connectionTimeoutMillis) {
Address masterAddress = clusterService.getMasterAddress();
if (isAllBlacklisted(possibleAddresses) && masterAddress == null) {
return;
}
if (masterAddress != null) {
if (logger.isFineEnabled()) {
logger.fine("Sending join request to " + masterAddress);
}
clusterJoinManager.sendJoinRequest(masterAddress, true);
} else {
sendMasterQuestion(possibleAddresses);
}
if (!clusterService.isJoined()) {
Thread.sleep(JOIN_RETRY_WAIT_TIME);
}
}
}
private boolean tryInitialConnection(Collection<Address> possibleAddresses) throws InterruptedException {
long connectionTimeoutMillis = TimeUnit.SECONDS.toMillis(getConnTimeoutSeconds());
long start = Clock.currentTimeMillis();
while (Clock.currentTimeMillis() - start < connectionTimeoutMillis) {
if (isAllBlacklisted(possibleAddresses)) {
return false;
}
if (logger.isFineEnabled()) {
logger.fine("Will send master question to each address in: " + possibleAddresses);
}
if (sendMasterQuestion(possibleAddresses)) {
return true;
}
Thread.sleep(JOIN_RETRY_WAIT_TIME);
}
return false;
}
private boolean isAllBlacklisted(Collection<Address> possibleAddresses) {
return blacklistedAddresses.keySet().containsAll(possibleAddresses);
}
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity"})
private void lookForMaster(Collection<Address> possibleAddresses) throws InterruptedException {
int tryCount = 0;
while (clusterService.getMasterAddress() == null && tryCount++ < LOOK_FOR_MASTER_MAX_TRY_COUNT) {
sendMasterQuestion(possibleAddresses);
//noinspection BusyWait
Thread.sleep(JOIN_RETRY_WAIT_TIME);
if (isAllBlacklisted(possibleAddresses)) {
break;
}
}
if (clusterService.isJoined()) {
return;
}
if (isAllBlacklisted(possibleAddresses) && clusterService.getMasterAddress() == null) {
if (logger.isFineEnabled()) {
logger.fine("Setting myself as master! No possible addresses remaining to connect...");
}
clusterJoinManager.setThisMemberAsMaster();
return;
}
long maxMasterJoinTime = getMaxJoinTimeToMasterNode();
long start = Clock.currentTimeMillis();
while (shouldRetry() && Clock.currentTimeMillis() - start < maxMasterJoinTime) {
Address master = clusterService.getMasterAddress();
if (master != null) {
if (logger.isFineEnabled()) {
logger.fine("Joining to master " + master);
}
clusterJoinManager.sendJoinRequest(master, true);
} else {
break;
}
//noinspection BusyWait
Thread.sleep(JOIN_RETRY_WAIT_TIME);
}
if (!clusterService.isJoined()) {
Address master = clusterService.getMasterAddress();
if (master != null) {
logger.warning("Couldn't join to the master: " + master);
} else {
if (logger.isFineEnabled()) {
logger.fine("Couldn't find a master! But there was connections available: " + possibleAddresses);
}
}
}
}
private boolean sendMasterQuestion(Collection<Address> possibleAddresses) {
if (logger.isFineEnabled()) {
logger.fine("NOT sending master question to blacklisted endpoints: " + blacklistedAddresses);
}
boolean sent = false;
for (Address address : possibleAddresses) {
if (isBlacklisted(address)) {
continue;
}
if (logger.isFineEnabled()) {
logger.fine("Sending master question to " + address);
}
if (clusterJoinManager.sendMasterQuestion(address)) {
sent = true;
}
}
return sent;
}
private Address getRequiredMemberAddress() {
TcpIpConfig tcpIpConfig = config.getNetworkConfig().getJoin().getTcpIpConfig();
String host = tcpIpConfig.getRequiredMember();
try {
AddressHolder addressHolder = AddressUtil.getAddressHolder(host, config.getNetworkConfig().getPort());
if (AddressUtil.isIpAddress(addressHolder.getAddress())) {
return new Address(addressHolder.getAddress(), addressHolder.getPort());
}
InterfacesConfig interfaces = config.getNetworkConfig().getInterfaces();
if (interfaces.isEnabled()) {
InetAddress[] inetAddresses = InetAddress.getAllByName(addressHolder.getAddress());
if (inetAddresses.length > 1) {
for (InetAddress inetAddress : inetAddresses) {
if (AddressUtil.matchAnyInterface(inetAddress.getHostAddress(), interfaces.getInterfaces())) {
return new Address(inetAddress, addressHolder.getPort());
}
}
} else if (AddressUtil.matchAnyInterface(inetAddresses[0].getHostAddress(), interfaces.getInterfaces())) {
return new Address(addressHolder.getAddress(), addressHolder.getPort());
}
} else {
return new Address(addressHolder.getAddress(), addressHolder.getPort());
}
} catch (final Exception e) {
logger.warning(e);
}
return null;
}
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity"})
protected Collection<Address> getPossibleAddresses() {
final Collection<String> possibleMembers = getMembers();
final Set<Address> possibleAddresses = new HashSet<Address>();
final NetworkConfig networkConfig = config.getNetworkConfig();
for (String possibleMember : possibleMembers) {
AddressHolder addressHolder = AddressUtil.getAddressHolder(possibleMember);
try {
boolean portIsDefined = addressHolder.getPort() != -1 || !networkConfig.isPortAutoIncrement();
int count = portIsDefined ? 1 : maxPortTryCount;
int port = addressHolder.getPort() != -1 ? addressHolder.getPort() : networkConfig.getPort();
AddressMatcher addressMatcher = null;
try {
addressMatcher = AddressUtil.getAddressMatcher(addressHolder.getAddress());
} catch (InvalidAddressException ignore) {
EmptyStatement.ignore(ignore);
}
if (addressMatcher != null) {
final Collection<String> matchedAddresses;
if (addressMatcher.isIPv4()) {
matchedAddresses = AddressUtil.getMatchingIpv4Addresses(addressMatcher);
} else {
// for IPv6 we are not doing wildcard matching
matchedAddresses = Collections.singleton(addressHolder.getAddress());
}
for (String matchedAddress : matchedAddresses) {
addPossibleAddresses(possibleAddresses, null, InetAddress.getByName(matchedAddress), port, count);
}
} else {
final String host = addressHolder.getAddress();
final InterfacesConfig interfaces = networkConfig.getInterfaces();
if (interfaces.isEnabled()) {
final InetAddress[] inetAddresses = InetAddress.getAllByName(host);
for (InetAddress inetAddress : inetAddresses) {
if (AddressUtil.matchAnyInterface(inetAddress.getHostAddress(),
interfaces.getInterfaces())) {
addPossibleAddresses(possibleAddresses, host, inetAddress, port, count);
}
}
} else {
addPossibleAddresses(possibleAddresses, host, null, port, count);
}
}
} catch (UnknownHostException e) {
logger.warning("Cannot resolve hostname '" + addressHolder.getAddress()
+ "'. Please make sure host is valid and reachable.");
if (logger.isFineEnabled()) {
logger.fine("Error during resolving possible target!", e);
}
}
}
possibleAddresses.remove(node.getThisAddress());
return possibleAddresses;
}
private void addPossibleAddresses(final Set<Address> possibleAddresses,
final String host, final InetAddress inetAddress,
final int port, final int count) throws UnknownHostException {
for (int i = 0; i < count; i++) {
int currentPort = port + i;
Address address;
if (host != null && inetAddress != null) {
address = new Address(host, inetAddress, currentPort);
} else if (host != null) {
address = new Address(host, currentPort);
} else {
address = new Address(inetAddress, currentPort);
}
if (!isLocalAddress(address)) {
possibleAddresses.add(address);
}
}
}
private boolean isLocalAddress(final Address address) throws UnknownHostException {
final Address thisAddress = node.getThisAddress();
final boolean local = thisAddress.getInetSocketAddress().equals(address.getInetSocketAddress());
if (logger.isFineEnabled()) {
logger.fine(address + " is local? " + local);
}
return local;
}
protected Collection<String> getMembers() {
return getConfigurationMembers(config);
}
public static Collection<String> getConfigurationMembers(Config config) {
final TcpIpConfig tcpIpConfig = config.getNetworkConfig().getJoin().getTcpIpConfig();
final Collection<String> configMembers = tcpIpConfig.getMembers();
final Set<String> possibleMembers = new HashSet<String>();
for (String member : configMembers) {
// split members defined in tcp-ip configuration by comma(,) semi-colon(;) space( ).
String[] members = member.split("[,; ]");
Collections.addAll(possibleMembers, members);
}
return possibleMembers;
}
@Override
public void searchForOtherClusters() {
final Collection<Address> possibleAddresses;
try {
possibleAddresses = getPossibleAddresses();
} catch (Throwable e) {
logger.severe(e);
return;
}
possibleAddresses.remove(node.getThisAddress());
possibleAddresses.removeAll(node.getClusterService().getMemberAddresses());
if (possibleAddresses.isEmpty()) {
return;
}
for (Address address : possibleAddresses) {
SplitBrainJoinMessage response = sendSplitBrainJoinMessage(address);
if (shouldMerge(response)) {
logger.warning(node.getThisAddress() + " is merging [tcp/ip] to " + address);
setTargetAddress(address);
startClusterMerge(address);
return;
}
}
}
@Override
public String getType() {
return "tcp-ip";
}
}
| apache-2.0 |
marques-work/gocd | server/src/test-shared/java/com/thoughtworks/go/server/perf/commands/RegisterAgentCommand.java | 1951 | /*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.server.perf.commands;
import com.thoughtworks.go.config.Agent;
import com.thoughtworks.go.server.service.AgentRuntimeInfo;
import com.thoughtworks.go.server.service.AgentService;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Optional;
import java.util.UUID;
public class RegisterAgentCommand extends AgentPerformanceCommand {
public RegisterAgentCommand(AgentService agentService) {
this.agentService = agentService;
}
@Override
Optional<String> execute() {
return registerAgent();
}
private Optional<String> registerAgent() {
InetAddress localHost = getInetAddress();
Agent agent = new Agent("Perf-Test-Agent-" + UUID.randomUUID(), localHost.getHostName(), localHost.getHostAddress(), UUID.randomUUID().toString());
AgentRuntimeInfo agentRuntimeInfo = AgentRuntimeInfo.fromServer(agent, false, "location", 233232L, "osx");
agentService.requestRegistration(agentRuntimeInfo);
return Optional.ofNullable(agent.getUuid());
}
private InetAddress getInetAddress() {
InetAddress localHost;
try {
localHost = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
return localHost;
}
}
| apache-2.0 |
OnurKirkizoglu/master_thesis | at.jku.sea.cloud/src/main/java/at/jku/sea/cloud/exceptions/ArtifactIsNotACollectionException.java | 2111 | /*
* (C) Johannes Kepler University Linz, Austria, 2005-2013
* Institute for Systems Engineering and Automation (SEA)
*
* The software may only be used for academic purposes (teaching, scientific
* research). Any redistribution or commercialization of the software program
* and documentation (or any part thereof) requires prior written permission of
* the JKU. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* This software program and documentation are copyrighted by Johannes Kepler
* University Linz, Austria (the JKU). The software program and documentation
* are supplied AS IS, without any accompanying services from the JKU. The JKU
* does not warrant that the operation of the program will be uninterrupted or
* error-free. The end-user understands that the program was developed for
* research purposes and is advised not to rely exclusively on the program for
* any reason.
*
* IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
* SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE
* AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHOR
* SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
* THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE AUTHOR HAS
* NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
* OR MODIFICATIONS.
*/
/*
* ArtifactIsNotACollectionException.java created on 13.03.2013
*
* (c) alexander noehrer
*/
package at.jku.sea.cloud.exceptions;
/**
* @author alexander noehrer
*/
public class ArtifactIsNotACollectionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ArtifactIsNotACollectionException(final long version, final long id) {
super("artifact (id=" + id + ", version=" + version + ") is not a collection");
}
}
| apache-2.0 |
ning/collector | src/test/java/com/ning/metrics/collector/filtering/TestPatternSetFilter.java | 3816 | /*
* Copyright 2010-2012 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.metrics.collector.filtering;
import com.ning.metrics.collector.endpoint.ParsedRequest;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
public class TestPatternSetFilter
{
@Test(groups = "fast")
public void testNullValue() throws Exception
{
final Filter<ParsedRequest> filter = new PatternSetFilter(createFieldExtractor(null), createPatternSet("pattern1", "pattern2"));
Assert.assertEquals(filter.passesFilter(null, null), false);
}
@Test(groups = "fast")
public void testEmptySetPatternEventRESTRequestFilter() throws Exception
{
final Filter<ParsedRequest> filter = new PatternSetFilter(createFieldExtractor("test-host"), Collections.<Pattern>emptySet());
Assert.assertEquals(filter.passesFilter(null, null), false);
}
@Test(groups = "fast")
public void testSinglePatternEventRESTRequestFilter() throws Exception
{
final Filter<ParsedRequest> filterShouldMatch = new PatternSetFilter(createFieldExtractor("test-host"), createPatternSet("test-host"));
Assert.assertEquals(filterShouldMatch.passesFilter(null, null), true);
final Filter<ParsedRequest> filterDoesNotMatch = new PatternSetFilter(createFieldExtractor("test-host"), createPatternSet("mugen"));
Assert.assertEquals(filterDoesNotMatch.passesFilter(null, null), false);
}
@Test(groups = "fast")
public void testMultiplePatternEventRESTRequestFilter() throws Exception
{
final Filter<ParsedRequest> trueFilter = new PatternSetFilter(createFieldExtractor("test-host"), createPatternSet("test-host", "nothing"));
Assert.assertTrue(trueFilter.passesFilter(null, null));
final Filter<ParsedRequest> falseFilter = new PatternSetFilter(createFieldExtractor("test-host"), createPatternSet("mugen", "nothing"));
Assert.assertFalse(falseFilter.passesFilter(null, null));
}
@Test(groups = "fast")
public void testSinglePatternEventInclusionFilter() throws Exception
{
final Filter<ParsedRequest> filterShouldMatch = new EventInclusionFilter(createFieldExtractor("test-host"), createPatternSet("test-host"));
Assert.assertEquals(filterShouldMatch.passesFilter(null, null), false);
final Filter<ParsedRequest> filterDoesNotMatch = new EventInclusionFilter(createFieldExtractor("test-host"), createPatternSet("mugen"));
Assert.assertEquals(filterDoesNotMatch.passesFilter(null, null), true);
}
private Set<Pattern> createPatternSet(final String... patterns)
{
final Set<Pattern> patternSet = new HashSet<Pattern>();
for (final String str : patterns) {
patternSet.add(Pattern.compile(str));
}
return patternSet;
}
private FieldExtractor createFieldExtractor(final String value)
{
return new FieldExtractor()
{
@Override
public String getField(final String eventName, final ParsedRequest annotation)
{
return value;
}
};
}
} | apache-2.0 |
pivotal-amurmann/geode | geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/ExportLogsStatsOverHttpDUnitTest.java | 2773 | /*
* 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.geode.management.internal.cli.commands;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.geode.test.junit.rules.GfshShellConnectionRule;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@Category(DistributedTest.class)
public class ExportLogsStatsOverHttpDUnitTest extends ExportLogsStatsDUnitTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Override
public void connectIfNeeded() throws Exception {
if (!connector.isConnected())
connector.connect(httpPort, GfshShellConnectionRule.PortType.http);
}
@Test
public void testExportWithDir() throws Exception {
connectIfNeeded();
File dir = temporaryFolder.newFolder();
// export the logs
connector.executeCommand("export logs --dir=" + dir.getAbsolutePath());
// verify that the message contains a path to the user.dir
String message = connector.getGfshOutput();
assertThat(message).contains("Logs exported to: ");
assertThat(message).contains(dir.getAbsolutePath());
String zipPath = getZipPathFromCommandResult(message);
Set<String> actualZipEntries =
new ZipFile(zipPath).stream().map(ZipEntry::getName).collect(Collectors.toSet());
assertThat(actualZipEntries).isEqualTo(expectedZipEntries);
// also verify that the zip file on locator is deleted
assertThat(Arrays.stream(locator.getWorkingDir().listFiles())
.filter(file -> file.getName().endsWith(".zip")).collect(Collectors.toSet())).isEmpty();
}
protected String getZipPathFromCommandResult(String message) {
return message.replaceAll("Logs exported to: ", "").trim();
}
}
| apache-2.0 |
clicktravel-martindimitrov/Cheddar | cheddar/cheddar-integration-aws/src/test/java/com/clicktravel/infrastructure/persistence/aws/dynamodb/DynamoDocumentStoreTemplateTest.java | 16505 | /*
* Copyright 2014 Click Travel 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.clicktravel.infrastructure.persistence.aws.dynamodb;
import static com.clicktravel.common.random.Randoms.randomId;
import static com.clicktravel.common.random.Randoms.randomString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.clicktravel.cheddar.infrastructure.persistence.database.ItemId;
import com.clicktravel.cheddar.infrastructure.persistence.database.configuration.DatabaseSchemaHolder;
import com.clicktravel.cheddar.infrastructure.persistence.database.configuration.ItemConfiguration;
import com.clicktravel.cheddar.infrastructure.persistence.database.exception.NonExistentItemException;
import com.clicktravel.cheddar.infrastructure.persistence.database.exception.OptimisticLockException;
import com.clicktravel.common.random.Randoms;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ DynamoDocumentStoreTemplate.class })
public class DynamoDocumentStoreTemplateTest {
private DatabaseSchemaHolder mockDatabaseSchemaHolder;
private String schemaName;
private String tableName;
private AmazonDynamoDB mockAmazonDynamoDbClient;
private DynamoDB mockDynamoDBClient;
@Before
public void setup() throws Exception {
schemaName = randomString(10);
tableName = randomString(10);
mockDatabaseSchemaHolder = mock(DatabaseSchemaHolder.class);
when(mockDatabaseSchemaHolder.schemaName()).thenReturn(schemaName);
mockAmazonDynamoDbClient = mock(AmazonDynamoDB.class);
mockDynamoDBClient = mock(DynamoDB.class);
whenNew(DynamoDB.class).withParameterTypes(AmazonDynamoDB.class).withArguments(eq(mockAmazonDynamoDbClient))
.thenReturn(mockDynamoDBClient);
}
@SuppressWarnings("deprecation")
@Test
public void shouldCreate_withItem() {
// Given
final ItemId itemId = new ItemId(randomId());
final StubItem stubItem = generateRandomStubItem(itemId);
final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
final Table mockTable = mock(Table.class);
when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable);
final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate(
mockDatabaseSchemaHolder);
dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient);
final Item mockTableItem = mock(Item.class);
when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem));
// When
final StubItem returnedItem = dynamoDocumentStoreTemplate.create(stubItem);
// Then
final ArgumentCaptor<PutItemSpec> getItemRequestCaptor = ArgumentCaptor.forClass(PutItemSpec.class);
verify(mockTable).putItem(getItemRequestCaptor.capture());
final PutItemSpec spec = getItemRequestCaptor.getValue();
assertEquals(itemId.value(), spec.getItem().get("id"));
assertEquals(itemId.value(), returnedItem.getId());
assertEquals(stubItem.getStringProperty(), returnedItem.getStringProperty());
assertEquals(stubItem.getStringProperty2(), returnedItem.getStringProperty2());
assertEquals(stubItem.getStringSetProperty(), returnedItem.getStringSetProperty());
}
@SuppressWarnings("deprecation")
@Test
public void shouldNotCreate_withItem() {
// Given
final ItemId itemId = new ItemId(randomId());
final StubItem stubItem = generateRandomStubItem(itemId);
final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
final Table mockTable = mock(Table.class);
when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable);
final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate(
mockDatabaseSchemaHolder);
dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient);
final Item mockTableItem = mock(Item.class);
when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem));
doThrow(RuntimeException.class).when(mockTable).putItem(any(PutItemSpec.class));
RuntimeException thrownException = null;
// When
try {
dynamoDocumentStoreTemplate.create(stubItem);
} catch (final RuntimeException runtimeException) {
thrownException = runtimeException;
}
// Then
assertNotNull(thrownException);
}
@SuppressWarnings("deprecation")
@Test
public void shouldRead_withItemIdAndItemClass() throws Exception {
// Given
final ItemId itemId = new ItemId(randomId());
final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate(
mockDatabaseSchemaHolder);
dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient);
final Table mockTable = mock(Table.class);
when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable);
final Item mockTableItem = mock(Item.class);
when(mockTable.getItem(any(GetItemSpec.class))).thenReturn(mockTableItem);
final StubItem stubItem = generateRandomStubItem(itemId);
when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem));
// When
final StubItem returnedItem = dynamoDocumentStoreTemplate.read(itemId, StubItem.class);
// Then
final ArgumentCaptor<GetItemSpec> getItemRequestCaptor = ArgumentCaptor.forClass(GetItemSpec.class);
verify(mockTable).getItem(getItemRequestCaptor.capture());
final GetItemSpec spec = getItemRequestCaptor.getValue();
assertEquals(1, spec.getKeyComponents().size());
assertEquals(itemId.value(), spec.getKeyComponents().iterator().next().getValue());
assertEquals(itemId.value(), returnedItem.getId());
assertEquals(stubItem.getStringProperty(), returnedItem.getStringProperty());
assertEquals(stubItem.getStringProperty2(), returnedItem.getStringProperty2());
assertEquals(stubItem.getStringSetProperty(), returnedItem.getStringSetProperty());
}
@SuppressWarnings("deprecation")
@Test
public void shouldNotRead_withNonExistentItemExceptionNoItem() throws Exception {
// Given
final ItemId itemId = new ItemId(randomId());
final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate(
mockDatabaseSchemaHolder);
dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient);
final Table mockTable = mock(Table.class);
when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable);
when(mockTable.getItem(any(GetItemSpec.class))).thenReturn(null);
NonExistentItemException thrownException = null;
// When
try {
dynamoDocumentStoreTemplate.read(itemId, StubItem.class);
} catch (final NonExistentItemException nonExistentItemException) {
thrownException = nonExistentItemException;
}
// Then
assertNotNull(thrownException);
}
@SuppressWarnings("deprecation")
@Test
public void shouldNotRead_withNonExistentItemExceptionNoContent() throws Exception {
// Given
final ItemId itemId = new ItemId(randomId());
final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate(
mockDatabaseSchemaHolder);
dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient);
final Table mockTable = mock(Table.class);
when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable);
final Item mockTableItem = mock(Item.class);
when(mockTable.getItem(any(GetItemSpec.class))).thenReturn(mockTableItem);
when(mockTableItem.toJSON()).thenReturn("");
NonExistentItemException thrownException = null;
// When
try {
dynamoDocumentStoreTemplate.read(itemId, StubItem.class);
} catch (final NonExistentItemException nonExistentItemException) {
thrownException = nonExistentItemException;
}
// Then
assertNotNull(thrownException);
}
@SuppressWarnings("deprecation")
@Test
public void shouldUpdate_withItem() {
// Given
final ItemId itemId = new ItemId(randomId());
final StubItem stubItem = generateRandomStubItem(itemId);
final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
final Table mockTable = mock(Table.class);
when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable);
final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate(
mockDatabaseSchemaHolder);
dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient);
final Item mockTableItem = mock(Item.class);
when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem));
// When
final StubItem returnedItem = dynamoDocumentStoreTemplate.update(stubItem);
// Then
final ArgumentCaptor<PutItemSpec> getItemRequestCaptor = ArgumentCaptor.forClass(PutItemSpec.class);
verify(mockTable).putItem(getItemRequestCaptor.capture());
final PutItemSpec spec = getItemRequestCaptor.getValue();
assertEquals(itemId.value(), spec.getItem().get("id"));
assertEquals(itemId.value(), returnedItem.getId());
assertEquals(stubItem.getStringProperty(), returnedItem.getStringProperty());
assertEquals(stubItem.getStringProperty2(), returnedItem.getStringProperty2());
assertEquals(stubItem.getStringSetProperty(), returnedItem.getStringSetProperty());
}
@SuppressWarnings("deprecation")
@Test
public void shouldNotUpdate_withItem() {
// Given
final ItemId itemId = new ItemId(randomId());
final StubItem stubItem = generateRandomStubItem(itemId);
final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
final Table mockTable = mock(Table.class);
when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable);
final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate(
mockDatabaseSchemaHolder);
dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient);
final Item mockTableItem = mock(Item.class);
when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem));
doThrow(ConditionalCheckFailedException.class).when(mockTable).putItem(any(PutItemSpec.class));
OptimisticLockException thrownException = null;
// When
try {
dynamoDocumentStoreTemplate.update(stubItem);
} catch (final OptimisticLockException optimisticLockException) {
thrownException = optimisticLockException;
}
// Then
assertNotNull(thrownException);
}
@SuppressWarnings("deprecation")
@Test
public void shouldDelete_withItem() {
// Given
final ItemId itemId = new ItemId(randomId());
final StubItem stubItem = generateRandomStubItem(itemId);
final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
final Table mockTable = mock(Table.class);
when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable);
final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate(
mockDatabaseSchemaHolder);
dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient);
// When
dynamoDocumentStoreTemplate.delete(stubItem);
// Then
final ArgumentCaptor<DeleteItemSpec> getItemRequestCaptor = ArgumentCaptor.forClass(DeleteItemSpec.class);
verify(mockTable).deleteItem(getItemRequestCaptor.capture());
}
private StubItem generateRandomStubItem(final ItemId itemId) {
final StubItem item = new StubItem();
item.setBooleanProperty(Randoms.randomBoolean());
item.setId(itemId.value());
item.setStringProperty(Randoms.randomString());
item.setStringProperty2(Randoms.randomString());
item.setVersion(Randoms.randomLong());
final Set<String> stringSet = new HashSet<String>();
for (int i = 0; i < Randoms.randomInt(20); i++) {
stringSet.add(Randoms.randomString());
}
item.setStringSetProperty(stringSet);
return item;
}
}
| apache-2.0 |
azkaoru/migration-tool | src/tubame.knowhow/src/tubame/knowhow/plugin/ui/view/remove/RemoveRelationKnowhow.java | 5041 | /*
* RemoveRelationKnowhow.java
* Created on 2013/06/28
*
* Copyright (C) 2011-2013 Nippon Telegraph and Telephone Corporation
*
* 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 tubame.knowhow.plugin.ui.view.remove;
import tubame.common.util.CmnStringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tubame.knowhow.plugin.logic.KnowhowManagement;
import tubame.knowhow.plugin.model.view.CategoryViewType;
import tubame.knowhow.plugin.model.view.KnowhowDetailType;
import tubame.knowhow.plugin.model.view.KnowhowViewType;
import tubame.knowhow.plugin.model.view.PortabilityKnowhowListViewOperation;
import tubame.knowhow.plugin.ui.editor.multi.MaintenanceKnowhowMultiPageEditor;
import tubame.knowhow.plugin.ui.editor.multi.docbook.KnowhowDetailEditor;
import tubame.knowhow.util.PluginUtil;
/**
* Make a related item deletion process know-how information.<br/>
* Delete stick know-how related to the item to be deleted,<br/>
* the item that you want to match the key of its own from the reference list of
* key know-how detailed information,<br/>
* the parent category.<br/>
*/
public class RemoveRelationKnowhow implements RemoveRelationItemStrategy {
/** Logger */
private static final Logger LOGGER = LoggerFactory
.getLogger(RemoveRelationKnowhow.class);
/** Know-how entry view item */
private KnowhowViewType knowhowViewType;
/** Deleted items */
private PortabilityKnowhowListViewOperation portabilityKnowhowListViewOperation;
/**
* Constructor.<br/>
*
* @param portabilityKnowhowListViewOperation
* Deleted items
*/
public RemoveRelationKnowhow(
PortabilityKnowhowListViewOperation portabilityKnowhowListViewOperation) {
this.portabilityKnowhowListViewOperation = portabilityKnowhowListViewOperation;
this.knowhowViewType = (KnowhowViewType) portabilityKnowhowListViewOperation
.getKnowhowViewType();
}
/**
* {@inheritDoc}
*/
@Override
public void removeRelationItem() {
RemoveRelationKnowhow.LOGGER.debug(CmnStringUtil.EMPTY);
removeKnowhowDetail();
removeEntryViewItem();
}
/**
* Delete key reference to itself from the parent category that is
* registered in the entry view.<br/>
*
*/
private void removeEntryViewItem() {
CategoryViewType categoryViewType = (CategoryViewType) portabilityKnowhowListViewOperation
.getParent().getKnowhowViewType();
String removeTargetKey = null;
for (String knowhowRefKey : categoryViewType.getKnowhowRefKeies()) {
if (knowhowViewType.getRegisterKey().equals(knowhowRefKey)) {
removeTargetKey = knowhowRefKey;
}
}
if (removeTargetKey != null) {
categoryViewType.getKnowhowRefKeies().remove(removeTargetKey);
}
}
/**
* Delete the data that matches the key from its own know-how detail data
* list.<br/>
* Remove know-how detail data that matches the reference key know-how from
* its own know-how detail data list.<br/>
*
*/
private void removeKnowhowDetail() {
KnowhowDetailType removeTargetItem = null;
for (KnowhowDetailType knowhowDetailType : KnowhowManagement
.getKnowhowDetailTypes()) {
if (knowhowDetailType.getKnowhowDetailId().equals(
knowhowViewType.getKnowhowDetailRefKey())) {
removeTargetItem = knowhowDetailType;
}
}
if (removeTargetItem != null) {
KnowhowManagement.getKnowhowDetailTypes().remove(removeTargetItem);
clearKnowhoweDetaileditor(removeTargetItem);
}
}
/**
* Initialization of know-how detail page editor.<br/>
*
* @param removeTargetItem
* Deleted items
*/
private void clearKnowhoweDetaileditor(KnowhowDetailType removeTargetItem) {
MaintenanceKnowhowMultiPageEditor knowhowMultiPageEditor = PluginUtil
.getKnowhowEditor();
KnowhowDetailEditor detailEditor = knowhowMultiPageEditor
.getKnowhowDetailEditor();
if (detailEditor.getKnowhowDetailType() != null) {
if (removeTargetItem.getKnowhowDetailId().equals(
detailEditor.getKnowhowDetailType().getKnowhowDetailId())) {
knowhowMultiPageEditor.clearKnowhowDetail();
}
}
}
}
| apache-2.0 |
eccyan/SpinningTabStrip | spinning/src/main/java/com/eccyan/widget/SpinningViewPager.java | 6099 | /*
* Copyright (C) 2013 Leszek Mzyk
* Modifications Copyright (C) 2015 eccyan <g00.eccyan@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 com.eccyan.widget;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
/**
* A ViewPager subclass enabling infinte scrolling of the viewPager elements
*
* When used for paginating views (in opposite to fragments), no code changes
* should be needed only change xml's from <android.support.v4.view.ViewPager>
* to <com.imbryk.viewPager.LoopViewPager>
*
* If "blinking" can be seen when paginating to first or last view, simply call
* seBoundaryCaching( true ), or change DEFAULT_BOUNDARY_CASHING to true
*
* When using a FragmentPagerAdapter or FragmentStatePagerAdapter,
* additional changes in the adapter must be done.
* The adapter must be prepared to create 2 extra items e.g.:
*
* The original adapter creates 4 items: [0,1,2,3]
* The modified adapter will have to create 6 items [0,1,2,3,4,5]
* with mapping realPosition=(position-1)%count
* [0->3, 1->0, 2->1, 3->2, 4->3, 5->0]
*/
public class SpinningViewPager extends ViewPager {
private static final boolean DEFAULT_BOUNDARY_CASHING = false;
OnPageChangeListener mOuterPageChangeListener;
private LoopPagerAdapterWrapper mAdapter;
private boolean mBoundaryCaching = DEFAULT_BOUNDARY_CASHING;
/**
* helper function which may be used when implementing FragmentPagerAdapter
*
* @param position
* @param count
* @return (position-1)%count
*/
public static int toRealPosition( int position, int count ){
position = position-1;
if( position < 0 ){
position += count;
}else{
position = position%count;
}
return position;
}
/**
* If set to true, the boundary views (i.e. first and last) will never be destroyed
* This may help to prevent "blinking" of some views
*
* @param flag
*/
public void setBoundaryCaching(boolean flag) {
mBoundaryCaching = flag;
if (mAdapter != null) {
mAdapter.setBoundaryCaching(flag);
}
}
@Override
public void setAdapter(PagerAdapter adapter) {
mAdapter = new LoopPagerAdapterWrapper(adapter);
mAdapter.setBoundaryCaching(mBoundaryCaching);
super.setAdapter(mAdapter);
}
@Override
public PagerAdapter getAdapter() {
return mAdapter != null ? mAdapter.getRealAdapter() : mAdapter;
}
@Override
public int getCurrentItem() {
return mAdapter != null ? mAdapter.toRealPosition(super.getCurrentItem()) : 0;
}
public void setCurrentItem(int item, boolean smoothScroll) {
int realItem = mAdapter.toInnerPosition(item);
super.setCurrentItem(realItem, smoothScroll);
}
@Override
public void setCurrentItem(int item) {
if (getCurrentItem() != item) {
setCurrentItem(item, true);
}
}
@Override
public void setOnPageChangeListener(OnPageChangeListener listener) {
mOuterPageChangeListener = listener;
};
public SpinningViewPager(Context context) {
super(context);
init();
}
public SpinningViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
super.setOnPageChangeListener(onPageChangeListener);
}
private OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {
private float mPreviousOffset = -1;
private float mPreviousPosition = -1;
@Override
public void onPageSelected(int position) {
int realPosition = mAdapter.toRealPosition(position);
if (mPreviousPosition != realPosition) {
mPreviousPosition = realPosition;
if (mOuterPageChangeListener != null) {
mOuterPageChangeListener.onPageSelected(realPosition);
}
}
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
int realPosition = position;
if (mAdapter != null) {
realPosition = mAdapter.toRealPosition(position);
if (positionOffset == 0
&& mPreviousOffset == 0
&& (position == 0 || position == mAdapter.getCount() - 1)) {
setCurrentItem(realPosition, false);
}
}
mPreviousOffset = positionOffset;
if (mOuterPageChangeListener != null) {
mOuterPageChangeListener.onPageScrolled(realPosition,
positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageScrollStateChanged(int state) {
if (mAdapter != null) {
int position = SpinningViewPager.super.getCurrentItem();
int realPosition = mAdapter.toRealPosition(position);
if (state == ViewPager.SCROLL_STATE_IDLE
&& (position == 0 || position == mAdapter.getCount() - 1)) {
setCurrentItem(realPosition, false);
}
}
if (mOuterPageChangeListener != null) {
mOuterPageChangeListener.onPageScrollStateChanged(state);
}
}
};
}
| apache-2.0 |
OBIGOGIT/etch | util/src/test/java/org/apache/etch/util/core/io/TestUdpConnection.java | 3671 | /* $Id$
*
* 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.etch.util.core.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.apache.etch.util.FlexBuffer;
import org.apache.etch.util.core.Who;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/** Test UdpConnection. */
public class TestUdpConnection
{
/** @throws Exception */
@Before @Ignore
public void init() throws Exception
{
aph = new MyPacketHandler();
ac = new UdpConnection( "udp://localhost:4011" );
ac.setSession( aph );
ac.start();
ac.waitUp( 4000 );
System.out.println( "ac up" );
bph = new MyPacketHandler();
bc = new UdpConnection( "udp://localhost:4010" );
bc.setSession( bph );
bc.start();
bc.waitUp( 4000 );
System.out.println( "bc up" );
}
/** @throws Exception */
@After @Ignore
public void fini() throws Exception
{
ac.close( false );
bc.close( false );
}
private MyPacketHandler aph;
private UdpConnection ac;
private MyPacketHandler bph;
private UdpConnection bc;
/** @throws Exception */
@Test @Ignore
public void blah() throws Exception
{
assertEquals( What.UP, aph.what );
assertEquals( What.UP, bph.what );
FlexBuffer buf = new FlexBuffer();
buf.put( 1 );
buf.put( 2 );
buf.put( 3 );
buf.put( 4 );
buf.put( 5 );
buf.setIndex( 0 );
ac.transportPacket( null, buf );
Thread.sleep( 500 );
assertEquals( What.PACKET, bph.what );
assertNotNull( bph.xsender );
assertNotSame( buf, bph.xbuf );
assertEquals( 0, bph.xbuf.index() );
assertEquals( 5, bph.xbuf.length() );
assertEquals( 1, bph.xbuf.get() );
assertEquals( 2, bph.xbuf.get() );
assertEquals( 3, bph.xbuf.get() );
assertEquals( 4, bph.xbuf.get() );
assertEquals( 5, bph.xbuf.get() );
}
/** */
public enum What
{
/** */ UP,
/** */ PACKET,
/** */ DOWN
}
/**
* receive packets from the udp connection
*/
public static class MyPacketHandler implements SessionPacket
{
/** */
public What what;
/** */
public Who xsender;
/** */
public FlexBuffer xbuf;
public void sessionPacket( Who sender, FlexBuffer buf ) throws Exception
{
assertEquals( What.UP, what );
what = What.PACKET;
xsender = sender;
xbuf = buf;
}
public void sessionControl( Object control, Object value )
{
// ignore.
}
public void sessionNotify( Object event )
{
if (event.equals( Session.UP ))
{
assertNull( what );
what = What.UP;
return;
}
if (event.equals( Session.DOWN ))
{
assertTrue( what == What.UP || what == What.PACKET );
what = What.DOWN;
return;
}
}
public Object sessionQuery( Object query )
{
// ignore.
return null;
}
}
}
| apache-2.0 |
apache/zest-qi4j | libraries/sql-generator/src/main/java/org/apache/polygene/library/sql/generator/implementation/grammar/builders/query/OrderByBuilderImpl.java | 2500 | /*
* 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.polygene.library.sql.generator.implementation.grammar.builders.query;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.apache.polygene.library.sql.generator.grammar.builders.query.OrderByBuilder;
import org.apache.polygene.library.sql.generator.grammar.query.OrderByClause;
import org.apache.polygene.library.sql.generator.grammar.query.SortSpecification;
import org.apache.polygene.library.sql.generator.implementation.grammar.common.SQLBuilderBase;
import org.apache.polygene.library.sql.generator.implementation.grammar.query.OrderByClauseImpl;
import org.apache.polygene.library.sql.generator.implementation.transformation.spi.SQLProcessorAggregator;
/**
* @author Stanislav Muhametsin
*/
public class OrderByBuilderImpl extends SQLBuilderBase
implements OrderByBuilder
{
private final List<SortSpecification> _sortSpecs;
public OrderByBuilderImpl( SQLProcessorAggregator processor )
{
super( processor );
this._sortSpecs = new ArrayList<SortSpecification>();
}
public OrderByBuilder addSortSpecs( SortSpecification... specs )
{
for( SortSpecification spec : specs )
{
Objects.requireNonNull( spec, "specification" );
}
this._sortSpecs.addAll( Arrays.asList( specs ) );
return this;
}
public List<SortSpecification> getSortSpecs()
{
return Collections.unmodifiableList( this._sortSpecs );
}
public OrderByClause createExpression()
{
return new OrderByClauseImpl( this.getProcessor(), this._sortSpecs );
}
}
| apache-2.0 |
pivotal-amurmann/geode | geode-core/src/main/java/org/apache/geode/management/internal/cli/GfshParseResult.java | 4495 | /*
* 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.geode.management.internal.cli;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.shell.event.ParseResult;
import org.apache.geode.management.cli.CliMetaData;
import org.apache.geode.management.internal.cli.shell.GfshExecutionStrategy;
import org.apache.geode.management.internal.cli.shell.OperationInvoker;
/**
* Immutable representation of the outcome of parsing a given shell line. * Extends
* {@link ParseResult} to add a field to specify the command string that was input by the user.
*
* <p>
* Some commands are required to be executed on a remote GemFire managing member. These should be
* marked with the annotation {@link CliMetaData#shellOnly()} set to <code>false</code>.
* {@link GfshExecutionStrategy} will detect whether the command is a remote command and send it to
* ManagementMBean via {@link OperationInvoker}.
*
*
* @since GemFire 7.0
*/
public class GfshParseResult extends ParseResult {
private String userInput;
private String commandName;
private Map<String, String> paramValueStringMap = new HashMap<>();
/**
* Creates a GfshParseResult instance to represent parsing outcome.
*
* @param method Method associated with the command
* @param instance Instance on which this method has to be executed
* @param arguments arguments of the method
* @param userInput user specified commands string
*/
protected GfshParseResult(final Method method, final Object instance, final Object[] arguments,
final String userInput) {
super(method, instance, arguments);
this.userInput = userInput.trim();
CliCommand cliCommand = method.getAnnotation(CliCommand.class);
commandName = cliCommand.value()[0];
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
if (arguments == null) {
return;
}
for (int i = 0; i < arguments.length; i++) {
Object argument = arguments[i];
if (argument == null) {
continue;
}
CliOption cliOption = getCliOption(parameterAnnotations, i);
String argumentAsString;
if (argument instanceof Object[]) {
argumentAsString = StringUtils.join((Object[]) argument, ",");
} else {
argumentAsString = argument.toString();
}
// this maps are used for easy access of option values in String form.
// It's used in tests and validation of option values in pre-execution
paramValueStringMap.put(cliOption.key()[0], argumentAsString);
}
}
/**
* @return the userInput
*/
public String getUserInput() {
return userInput;
}
/**
* Used only in tests and command pre-execution for validating arguments
*/
public String getParamValue(String param) {
return paramValueStringMap.get(param);
}
/**
* Used only in tests and command pre-execution for validating arguments
*
* @return the unmodifiable paramValueStringMap
*/
public Map<String, String> getParamValueStrings() {
return Collections.unmodifiableMap(paramValueStringMap);
}
public String getCommandName() {
return commandName;
}
private CliOption getCliOption(Annotation[][] parameterAnnotations, int index) {
Annotation[] annotations = parameterAnnotations[index];
for (Annotation annotation : annotations) {
if (annotation instanceof CliOption) {
return (CliOption) annotation;
}
}
return null;
}
}
| apache-2.0 |
mhmdfy/autopsy | Core/src/org/sleuthkit/autopsy/corecomponents/Installer.java | 6087 | /*
* Autopsy Forensic Browser
*
* Copyright 2011-2015 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.corecomponents;
import java.awt.Insets;
import java.io.File;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import org.netbeans.spi.sendopts.OptionProcessor;
import org.netbeans.swing.tabcontrol.plaf.DefaultTabbedContainerUI;
import org.openide.modules.ModuleInstall;
import org.openide.util.Lookup;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.CaseActionException;
import org.sleuthkit.autopsy.casemodule.OpenFromArguments;
import org.sleuthkit.autopsy.coreutils.Logger;
/**
* Manages this module's life cycle. Opens the startup dialog during startup.
*/
public class Installer extends ModuleInstall {
private static Installer instance;
private static final Logger logger = Logger.getLogger(Installer.class.getName());
public synchronized static Installer getDefault() {
if (instance == null) {
instance = new Installer();
}
return instance;
}
private Installer() {
super();
}
@Override
public void restored() {
super.restored();
setupLAF();
UIManager.put("ViewTabDisplayerUI", "org.sleuthkit.autopsy.corecomponents.NoTabsTabDisplayerUI");
UIManager.put(DefaultTabbedContainerUI.KEY_VIEW_CONTENT_BORDER, BorderFactory.createEmptyBorder());
UIManager.put("TabbedPane.contentBorderInsets", new Insets(0, 0, 0, 0));
/*
* Open the passed in case, if an aut file was double clicked.
*/
WindowManager.getDefault().invokeWhenUIReady(() -> {
Collection<? extends OptionProcessor> processors = Lookup.getDefault().lookupAll(OptionProcessor.class);
for (OptionProcessor processor : processors) {
if (processor instanceof OpenFromArguments) {
OpenFromArguments argsProcessor = (OpenFromArguments) processor;
final String caseFile = argsProcessor.getDefaultArg();
if (caseFile != null && !caseFile.equals("") && caseFile.endsWith(".aut") && new File(caseFile).exists()) { //NON-NLS
new Thread(() -> {
// Create case.
try {
Case.open(caseFile);
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error opening case: ", ex); //NON-NLS
}
}).start();
return;
}
}
}
Case.invokeStartupDialog(); // bring up the startup dialog
});
}
@Override
public void uninstalled() {
super.uninstalled();
}
@Override
public void close() {
new Thread(() -> {
try {
if (Case.isCaseOpen()) {
Case.getCurrentCase().closeCase();
}
} catch (CaseActionException | IllegalStateException unused) {
// Exception already logged. Shutting down, no need to do popup.
}
}).start();
}
private void setupLAF() {
//TODO apply custom skinning
//UIManager.put("nimbusBase", new Color());
//UIManager.put("nimbusBlueGrey", new Color());
//UIManager.put("control", new Color());
if (System.getProperty("os.name").toLowerCase().contains("mac")) { //NON-NLS
setupMacOsXLAF();
}
}
/**
* Set the look and feel to be the Cross Platform 'Metal', but keep Aqua
* dependent elements that set the Menu Bar to be in the correct place on
* Mac OS X.
*/
private void setupMacOsXLAF() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
logger.log(Level.WARNING, "Unable to set theme. ", ex); //NON-NLS
}
final String[] UI_MENU_ITEM_KEYS = new String[]{"MenuBarUI", //NON-NLS
};
Map<Object, Object> uiEntries = new TreeMap<>();
// Store the keys that deal with menu items
for (String key : UI_MENU_ITEM_KEYS) {
uiEntries.put(key, UIManager.get(key));
}
//use Metal if available
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) { //NON-NLS
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | UnsupportedLookAndFeelException ex) {
logger.log(Level.WARNING, "Unable to set theme. ", ex); //NON-NLS
}
break;
}
}
// Overwrite the Metal menu item keys to use the Aqua versions
uiEntries.entrySet().stream().forEach((entry) -> {
UIManager.put(entry.getKey(), entry.getValue());
});
}
}
| apache-2.0 |
ludo1026/tuto | generator-uml-to-config-xml/save/_3/src/org/ludo/codegenerator/core/gen/bean/IStereotype.java | 562 | /*
* Package : org.ludo.codegenerator.core.gen.bean
* Source : IStereotype.java
*/
package org.ludo.codegenerator.core.gen.bean;
import java.io.Serializable;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import org.ludo.codegenerator.core.gen.bean.impl.AttributBean;
import org.ludo.codegenerator.core.gen.bean.impl.ClasseBean;
import org.ludo.codegenerator.core.gen.bean.abst.IStereotypeAbstract;
/**
* <b>Description :</b>
* IStereotype
*
*/
public interface IStereotype extends IStereotypeAbstract, Serializable {
}
| artistic-2.0 |
AeroGlass/g3m | JavaDesktop/G3MJavaDesktopSDK/src/org/glob3/mobile/specific/JSONParser_JavaDesktop.java | 3373 |
package org.glob3.mobile.specific;
import java.util.Map;
import org.glob3.mobile.generated.IByteBuffer;
import org.glob3.mobile.generated.IJSONParser;
import org.glob3.mobile.generated.JSONArray;
import org.glob3.mobile.generated.JSONBaseObject;
import org.glob3.mobile.generated.JSONBoolean;
import org.glob3.mobile.generated.JSONDouble;
import org.glob3.mobile.generated.JSONFloat;
import org.glob3.mobile.generated.JSONInteger;
import org.glob3.mobile.generated.JSONLong;
import org.glob3.mobile.generated.JSONNull;
import org.glob3.mobile.generated.JSONObject;
import org.glob3.mobile.generated.JSONString;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
public class JSONParser_JavaDesktop
extends
IJSONParser {
@Override
public JSONBaseObject parse(final IByteBuffer buffer,
final boolean nullAsObject) {
return parse(buffer.getAsString(), nullAsObject);
}
@Override
public JSONBaseObject parse(final String string,
final boolean nullAsObject) {
final JsonParser parser = new JsonParser();
final JsonElement element = parser.parse(string);
return convert(element, nullAsObject);
}
private JSONBaseObject convert(final JsonElement element,
final boolean nullAsObject) {
if (element.isJsonNull()) {
return nullAsObject ? new JSONNull() : null;
}
else if (element.isJsonObject()) {
final JsonObject jsonObject = (JsonObject) element;
final JSONObject result = new JSONObject();
for (final Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
result.put(entry.getKey(), convert(entry.getValue(), nullAsObject));
}
return result;
}
else if (element.isJsonPrimitive()) {
final JsonPrimitive jsonPrimitive = (JsonPrimitive) element;
if (jsonPrimitive.isBoolean()) {
return new JSONBoolean(jsonPrimitive.getAsBoolean());
}
else if (jsonPrimitive.isNumber()) {
final double doubleValue = jsonPrimitive.getAsDouble();
final long longValue = (long) doubleValue;
if (doubleValue == longValue) {
final int intValue = (int) longValue;
return (intValue == longValue) ? new JSONInteger(intValue) : new JSONLong(longValue);
}
final float floatValue = (float) doubleValue;
return (floatValue == doubleValue) ? new JSONFloat(floatValue) : new JSONDouble(doubleValue);
}
else if (jsonPrimitive.isString()) {
return new JSONString(jsonPrimitive.getAsString());
}
else {
throw new RuntimeException("JSON unsopoerted" + element.getClass());
}
}
else if (element.isJsonArray()) {
final JsonArray jsonArray = (JsonArray) element;
final JSONArray result = new JSONArray();
for (final JsonElement child : jsonArray) {
result.add(convert(child, nullAsObject));
}
return result;
}
else {
throw new RuntimeException("JSON unsopoerted" + element.getClass());
}
}
}
| bsd-2-clause |
ColaMachine/MyBlock | src/main/java/de/matthiasmann/twl/WheelWidget.java | 16353 | /*
* Copyright (c) 2008-2011, Matthias Mann
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Matthias Mann nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.matthiasmann.twl;
import de.matthiasmann.twl.model.IntegerModel;
import de.matthiasmann.twl.model.ListModel;
import de.matthiasmann.twl.renderer.Image;
import de.matthiasmann.twl.utils.TypeMapping;
/**
* A wheel widget.
*
* @param <T> The data type for the wheel items
*
* @author Matthias Mann
*/
public class WheelWidget<T> extends Widget {
public interface ItemRenderer {
public Widget getRenderWidget(Object data);
}
private final TypeMapping<ItemRenderer> itemRenderer;
private final L listener;
private final R renderer;
private final Runnable timerCB;
protected int itemHeight;
protected int numVisibleItems;
protected Image selectedOverlay;
private static final int TIMER_INTERVAL = 30;
private static final int MIN_SPEED = 3;
private static final int MAX_SPEED = 100;
protected Timer timer;
protected int dragStartY;
protected long lastDragTime;
protected long lastDragDelta;
protected int lastDragDist;
protected boolean hasDragStart;
protected boolean dragActive;
protected int scrollOffset;
protected int scrollAmount;
protected ListModel<T> model;
protected IntegerModel selectedModel;
protected int selected;
protected boolean cyclic;
public WheelWidget() {
this.itemRenderer = new TypeMapping<ItemRenderer>();
this.listener = new L();
this.renderer = new R();
this.timerCB = new Runnable() {
public void run() {
onTimer();
}
};
itemRenderer.put(String.class, new StringItemRenderer());
super.insertChild(renderer, 0);
setCanAcceptKeyboardFocus(true);
}
public WheelWidget(ListModel<T> model) {
this();
this.model = model;
}
public ListModel<T> getModel() {
return model;
}
public void setModel(ListModel<T> model) {
removeListener();
this.model = model;
addListener();
invalidateLayout();
}
public IntegerModel getSelectedModel() {
return selectedModel;
}
public void setSelectedModel(IntegerModel selectedModel) {
removeSelectedListener();
this.selectedModel = selectedModel;
addSelectedListener();
}
public int getSelected() {
return selected;
}
public void setSelected(int selected) {
int oldSelected = this.selected;
if(oldSelected != selected) {
this.selected = selected;
if(selectedModel != null) {
selectedModel.setValue(selected);
}
firePropertyChange("selected", oldSelected, selected);
}
}
public boolean isCyclic() {
return cyclic;
}
public void setCyclic(boolean cyclic) {
this.cyclic = cyclic;
}
public int getItemHeight() {
return itemHeight;
}
public int getNumVisibleItems() {
return numVisibleItems;
}
public boolean removeItemRenderer(Class<? extends T> clazz) {
if(itemRenderer.remove(clazz)) {
super.removeAllChildren();
invalidateLayout();
return true;
}
return false;
}
public void registerItemRenderer(Class<? extends T> clazz, ItemRenderer value) {
itemRenderer.put(clazz, value);
invalidateLayout();
}
public void scroll(int amount) {
scrollInt(amount);
scrollAmount = 0;
}
protected void scrollInt(int amount) {
int pos = selected;
int half = itemHeight / 2;
scrollOffset += amount;
while(scrollOffset >= half) {
scrollOffset -= itemHeight;
pos++;
}
while(scrollOffset <= -half) {
scrollOffset += itemHeight;
pos--;
}
if(!cyclic) {
int n = getNumEntries();
if(n > 0) {
while(pos >= n) {
pos--;
scrollOffset += itemHeight;
}
}
while(pos < 0) {
pos++;
scrollOffset -= itemHeight;
}
scrollOffset = Math.max(-itemHeight, Math.min(itemHeight, scrollOffset));
}
setSelected(pos);
if(scrollOffset == 0 && scrollAmount == 0) {
stopTimer();
} else {
startTimer();
}
}
public void autoScroll(int dir) {
if(dir != 0) {
if(scrollAmount != 0 && Integer.signum(scrollAmount) != Integer.signum(dir)) {
scrollAmount = dir;
} else {
scrollAmount += dir;
}
startTimer();
}
}
@Override
public int getPreferredInnerHeight() {
return numVisibleItems * itemHeight;
}
@Override
public int getPreferredInnerWidth() {
int width = 0;
for(int i=0,n=getNumEntries() ; i<n ; i++) {
Widget w = getItemRenderer(i);
if(w != null) {
width = Math.max(width, w.getPreferredWidth());
}
}
return width;
}
@Override
protected void paintOverlay(GUI gui) {
super.paintOverlay(gui);
if(selectedOverlay != null) {
int y = getInnerY() + itemHeight * (numVisibleItems/2);
if((numVisibleItems & 1) == 0) {
y -= itemHeight/2;
}
selectedOverlay.draw(getAnimationState(), getX(), y, getWidth(), itemHeight);
}
}
@Override
protected boolean handleEvent(Event evt) {
if(evt.isMouseDragEnd() && dragActive) {
int absDist = Math.abs(lastDragDist);
if(absDist > 3 && lastDragDelta > 0) {
int amount = (int)Math.min(1000, absDist * 100 / lastDragDelta);
autoScroll(amount * Integer.signum(lastDragDist));
}
hasDragStart = false;
dragActive = false;
return true;
}
if(evt.isMouseDragEvent()) {
if(hasDragStart) {
long time = getTime();
dragActive = true;
lastDragDist = dragStartY - evt.getMouseY();
lastDragDelta = Math.max(1, time - lastDragTime);
scroll(lastDragDist);
dragStartY = evt.getMouseY();
lastDragTime = time;
}
return true;
}
if(super.handleEvent(evt)) {
return true;
}
switch(evt.getType()) {
case MOUSE_WHEEL:
autoScroll(itemHeight * evt.getMouseWheelDelta());
return true;
case MOUSE_BTNDOWN:
if(evt.getMouseButton() == Event.MOUSE_LBUTTON) {
dragStartY = evt.getMouseY();
lastDragTime = getTime();
hasDragStart = true;
}
return true;
case KEY_PRESSED:
switch(evt.getKeyCode()) {
case Event.KEY_UP:
autoScroll(-itemHeight);
return true;
case Event.KEY_DOWN:
autoScroll(+itemHeight);
return true;
}
return false;
}
return evt.isMouseEvent();
}
protected long getTime() {
GUI gui = getGUI();
return (gui != null) ? gui.getCurrentTime() : 0;
}
protected int getNumEntries() {
return (model == null) ? 0 : model.getNumEntries();
}
protected Widget getItemRenderer(int i) {
T item = model.getEntry(i);
if(item != null) {
ItemRenderer ir = itemRenderer.get(item.getClass());
if(ir != null) {
Widget w = ir.getRenderWidget(item);
if(w != null) {
if(w.getParent() != renderer) {
w.setVisible(false);
renderer.add(w);
}
return w;
}
}
}
return null;
}
protected void startTimer() {
if(timer != null && !timer.isRunning()) {
timer.start();
}
}
protected void stopTimer() {
if(timer != null) {
timer.stop();
}
}
protected void onTimer() {
int amount = scrollAmount;
int newAmount = amount;
if(amount == 0 && !dragActive) {
amount = -scrollOffset;
}
if(amount != 0) {
int absAmount = Math.abs(amount);
int speed = absAmount * TIMER_INTERVAL / 200;
int dir = Integer.signum(amount) * Math.min(absAmount,
Math.max(MIN_SPEED, Math.min(MAX_SPEED, speed)));
if(newAmount != 0) {
newAmount -= dir;
}
scrollAmount = newAmount;
scrollInt(dir);
}
}
@Override
protected void layout() {
layoutChildFullInnerArea(renderer);
}
@Override
protected void applyTheme(ThemeInfo themeInfo) {
super.applyTheme(themeInfo);
applyThemeWheel(themeInfo);
}
protected void applyThemeWheel(ThemeInfo themeInfo) {
itemHeight = themeInfo.getParameter("itemHeight", 10);
numVisibleItems = themeInfo.getParameter("visibleItems", 5);
selectedOverlay = themeInfo.getImage("selectedOverlay");
invalidateLayout();
}
@Override
protected void afterAddToGUI(GUI gui) {
super.afterAddToGUI(gui);
addListener();
addSelectedListener();
timer = gui.createTimer();
timer.setCallback(timerCB);
timer.setDelay(TIMER_INTERVAL);
timer.setContinuous(true);
}
@Override
protected void beforeRemoveFromGUI(GUI gui) {
timer.stop();
timer = null;
removeListener();
removeSelectedListener();
super.beforeRemoveFromGUI(gui);
}
@Override
public void insertChild(Widget child, int index) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void removeAllChildren() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public Widget removeChild(int index) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
private void addListener() {
if(model != null) {
model.addChangeListener(listener);
}
}
private void removeListener() {
if(model != null) {
model.removeChangeListener(listener);
}
}
private void addSelectedListener() {
if(selectedModel != null) {
selectedModel.addCallback(listener);
syncSelected();
}
}
private void removeSelectedListener() {
if(selectedModel != null) {
selectedModel.removeCallback(listener);
}
}
void syncSelected() {
setSelected(selectedModel.getValue());
}
void entriesDeleted(int first, int last) {
if(selected > first) {
if(selected > last) {
setSelected(selected - (last-first+1));
} else {
setSelected(first);
}
}
invalidateLayout();
}
void entriesInserted(int first, int last) {
if(selected >= first) {
setSelected(selected + (last-first+1));
}
invalidateLayout();
}
class L implements ListModel.ChangeListener, Runnable {
public void allChanged() {
invalidateLayout();
}
public void entriesChanged(int first, int last) {
invalidateLayout();
}
public void entriesDeleted(int first, int last) {
WheelWidget.this.entriesDeleted(first, last);
}
public void entriesInserted(int first, int last) {
WheelWidget.this.entriesInserted(first, last);
}
public void run() {
syncSelected();
}
}
class R extends Widget {
public R() {
setTheme("");
setClip(true);
}
@Override
protected void paintWidget(GUI gui) {
if(model == null) {
return;
}
int width = getInnerWidth();
int x = getInnerX();
int y = getInnerY();
int numItems = model.getNumEntries();
int numDraw = numVisibleItems;
int startIdx = selected - numVisibleItems/2;
if((numDraw & 1) == 0) {
y -= itemHeight / 2;
numDraw++;
}
if(scrollOffset > 0) {
y -= scrollOffset;
numDraw++;
}
if(scrollOffset < 0) {
y -= itemHeight + scrollOffset;
numDraw++;
startIdx--;
}
main: for(int i=0 ; i<numDraw ; i++) {
int idx = startIdx + i;
while(idx < 0) {
if(!cyclic) {
continue main;
}
idx += numItems;
}
while(idx >= numItems) {
if(!cyclic) {
continue main;
}
idx -= numItems;
}
Widget w = getItemRenderer(idx);
if(w != null) {
w.setSize(width, itemHeight);
w.setPosition(x, y + i*itemHeight);
w.validateLayout();
paintChild(gui, w);
}
}
}
@Override
public void invalidateLayout() {
}
@Override
protected void sizeChanged() {
}
}
public static class StringItemRenderer extends Label implements WheelWidget.ItemRenderer {
public StringItemRenderer() {
setCache(false);
}
public Widget getRenderWidget(Object data) {
setText(String.valueOf(data));
return this;
}
@Override
protected void sizeChanged() {
}
}
}
| bsd-2-clause |
edina/lockss-daemon | test/src/org/lockss/mail/TestMimeMessage.java | 8543 | /*
* $Id$
*/
/*
Copyright (c) 2000-2004 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.mail;
import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.oro.text.regex.*;
import javax.mail.*;
import javax.mail.internet.*;
// import javax.activation.*;
import org.lockss.test.*;
import org.lockss.mail.*;
import org.lockss.util.*;
import org.lockss.daemon.*;
import org.lockss.plugin.*;
public class TestMimeMessage extends LockssTestCase {
// The generated message is checked against these patterns, in a way that
// is too brittle (order dependent, etc.). If the format of the message
// changes innocuously the patterns and/or tests may have to be changed
static final String PAT_MESSAGE_ID = "^Message-ID: ";
static final String PAT_MIME_VERSION = "^MIME-Version: 1.0";
static final String PAT_CONTENT_TYPE = "^Content-Type: ";
static final String PAT_FROM = "^From: ";
static final String PAT_TO = "^To: ";
static final String PAT_BOUNDARY = "^------=_Part";
static final String PAT_CONTENT_TRANSFER_ENCODING =
"^Content-Transfer-Encoding: ";
static final String PAT_CONTENT_DISPOSITION = "^Content-Disposition: ";
String toString(MailMessage msg) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream out = new BufferedOutputStream(baos);
msg.writeData(out);
out.flush();
return baos.toString();
} catch (IOException e) {
throw new RuntimeException("Error converting MimeMessage to string", e);
}
}
/** Return the header part (lines preceding first blank line) */
String getHeader(String body) {
List lst = StringUtil.breakAt(body, "\r\n\r\n");
if (lst.size() < 1) return null;
return (String)lst.get(0);
}
/** Return the header part (lines preceding first blank line) */
String getHeader(MimeMessage msg) {
return getHeader(toString(msg));
}
/** Return the body part (lines following first blank line) */
String getBody(String body) {
int pos = body.indexOf("\r\n\r\n");
if (pos < 0) return null;
return body.substring(pos+4);
}
/** Return the body part (lines following first blank line) */
String getBody(MimeMessage msg) {
return getBody(toString(msg));
}
/** Break a string at <crlf>s into an array of lines */
String[] getLines(String body) {
List lst = StringUtil.breakAt(body, "\r\n");
return (String[])lst.toArray(new String[0]);
}
String[] getHeaderLines(MimeMessage msg) {
return getLines(getHeader(msg));
}
String[] getBodyLines(MimeMessage msg) {
return getLines(getBody(msg));
}
/** assert that the pattern exists in the string, interpreting the string
* as having multiple lines */
void assertHeaderLine(String expPat, String hdr) {
Pattern pat = RegexpUtil.uncheckedCompile(expPat,
Perl5Compiler.MULTILINE_MASK);
assertMatchesRE(pat, hdr);
}
/** assert that the message starts with the expected header */
void assertHeader(MimeMessage msg) {
assertHeader(null, null, msg);
}
/** assert that the message starts with the expected header */
void assertHeader(String expFrom, String expTo, MimeMessage msg) {
String hdr = getHeader(msg);
assertHeaderLine(PAT_MESSAGE_ID, hdr);
assertHeaderLine(PAT_MIME_VERSION, hdr);
assertHeaderLine(PAT_CONTENT_TYPE, hdr);
if (expFrom != null) {
assertHeaderLine(PAT_FROM + expFrom, hdr);
}
if (expTo != null) {
assertHeaderLine(PAT_TO + expTo, hdr);
}
}
/** assert that the array of lines is a MIME text-part with the expected
* text */
void assertTextPart(String expText, String[]lines, int idx) {
assertMatchesRE(PAT_BOUNDARY, lines[idx + 0]);
assertMatchesRE(PAT_CONTENT_TYPE + "text/plain; charset=us-ascii",
lines[idx + 1]);
assertMatchesRE(PAT_CONTENT_TRANSFER_ENCODING + "7bit",
lines[idx + 2]);
assertEquals("", lines[idx + 3]);
assertEquals(expText, lines[idx + 4]);
assertMatchesRE(PAT_BOUNDARY, lines[idx + 5]);
}
public void testNull() throws IOException {
MimeMessage msg = new MimeMessage();
assertHeader(msg);
assertEquals(2, getBodyLines(msg).length);
assertMatchesRE(PAT_BOUNDARY, getBody(msg));
assertEquals("", getBodyLines(msg)[1]);
}
public void testGetHeader() throws IOException {
MimeMessage msg = new MimeMessage();
msg.addHeader("From", "me");
msg.addHeader("To", "you");
msg.addHeader("To", "and you");
assertEquals("me", msg.getHeader("From"));
assertEquals("you, and you", msg.getHeader("To"));
assertEquals(null, msg.getHeader("xxxx"));
}
public void testText() throws IOException {
MimeMessage msg = new MimeMessage();
msg.addHeader("From", "me");
msg.addHeader("To", "you");
msg.addHeader("Subject", "topic");
msg.addTextPart("Message\ntext");
assertHeader("me", "you", msg);
String[] blines = getBodyLines(msg);
log.debug2("msg: " + StringUtil.separatedString(blines, ", "));
assertTextPart("Message\ntext", blines, 0);
}
public void testDot() throws IOException {
MimeMessage msg = new MimeMessage();
msg.addHeader("From", "me");
msg.addHeader("To", "you");
msg.addTextPart("one\n.\ntwo\n");
assertHeader("me", "you", msg);
String[] blines = getBodyLines(msg);
log.debug2("msg: " + StringUtil.separatedString(blines, ", "));
assertTextPart("one\n.\ntwo\n", blines, 0);
}
public void testTextAndFile() throws IOException {
File file = FileTestUtil.writeTempFile("XXX",
"\000\001\254\255this is a test");
MimeMessage msg = new MimeMessage();
msg.addHeader("From", "us");
msg.addHeader("To", "them");
msg.addHeader("Subject", "object");
msg.addTextPart("Explanatory text");
msg.addFile(file, "file.foo");
assertHeader("us", "them", msg);
String[] blines = getBodyLines(msg);
log.debug2("msg: " + StringUtil.separatedString(blines, ", "));
assertTextPart("Explanatory text", blines, 0);
assertMatchesRE(PAT_CONTENT_TYPE +
"application/octet-stream; name=file.foo", blines[6]);
assertMatchesRE(PAT_CONTENT_TRANSFER_ENCODING + "base64", blines[7]);
assertMatchesRE(PAT_CONTENT_DISPOSITION, blines[8]);
assertEquals("", blines[9]);
assertEquals("AAGsrXRoaXMgaXMgYSB0ZXN0", blines[10]);
assertMatchesRE(PAT_BOUNDARY, blines[11]);
assertTrue(file.exists());
msg.delete(true);
assertTrue(file.exists());
}
public void testGetParts() throws Exception {
File file = FileTestUtil.writeTempFile("XXX",
"\000\001\254\255this is a test");
MimeMessage msg = new MimeMessage();
msg.addTextPart("foo text");
msg.addFile(file, "file.foo");
MimeBodyPart[] parts = msg.getParts();
assertEquals(2, parts.length);
assertEquals("foo text", parts[0].getContent());
assertEquals("file.foo", parts[1].getFileName());
}
public void testTmpFile() throws IOException {
File file = FileTestUtil.writeTempFile("XXX",
"\000\001\254\255this is a test");
MimeMessage msg = new MimeMessage();
msg.addTmpFile(file, "file.foo");
assertTrue(file.exists());
msg.delete(true);
assertFalse(file.exists());
}
}
| bsd-3-clause |
hzhao/galago-git | core/src/main/java/org/lemurproject/galago/core/util/IterUtils.java | 1424 | package org.lemurproject.galago.core.util;
import org.lemurproject.galago.core.retrieval.iterator.BaseIterator;
import org.lemurproject.galago.core.retrieval.traversal.Traversal;
import org.lemurproject.galago.utility.Parameters;
import java.util.ArrayList;
import java.util.List;
/**
* @author jfoley.
*/
public class IterUtils {
/**
* Adds an operator into a Retrieval's parameters for usage.
* @param p the parameters object
* @param name the name of the operator, e.g. "combine" for #combine
* @param iterClass the operator to register
*/
public static void addToParameters(Parameters p, String name, Class<? extends BaseIterator> iterClass) {
if(!p.containsKey("operators")) {
p.put("operators", Parameters.create());
}
p.getMap("operators").put(name, iterClass.getName());
}
/**
* Adds a traversal into a Retrieval's parameters for usage.
* @param argp the parameters object
* @param traversalClass the traversal to register
*/
public static void addToParameters(Parameters argp, Class<? extends Traversal> traversalClass) {
if(!argp.isList("traversals")) {
argp.put("traversals", new ArrayList<>());
}
List<Parameters> traversals = argp.getList("traversals", Parameters.class);
traversals.add(Parameters.parseArray(
"name", traversalClass.getName(),
"order", "before"
));
argp.put("traversals", traversals);
}
}
| bsd-3-clause |
NCIP/webgenome | tags/WEBGENOME_R3.2_6MAR2009_BUILD1/java/webui/src/org/rti/webgenome/webui/struts/upload/ReporterColumnNameForm.java | 1844 | /*L
* Copyright RTI International
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/webgenome/LICENSE.txt for details.
*/
/*
$Revision: 1.1 $
$Date: 2007-08-22 20:03:57 $
*/
package org.rti.webgenome.webui.struts.upload;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.rti.webgenome.util.SystemUtils;
import org.rti.webgenome.webui.struts.BaseForm;
/**
* Form for inputting the name of a rectangular file
* column that contains reporter names.
* @author dhall
*
*/
public class ReporterColumnNameForm extends BaseForm {
/** Serialized version ID. */
private static final long serialVersionUID =
SystemUtils.getLongApplicationProperty("serial.version.uid");
/** Name of column containing reporter names. */
private String reporterColumnName = null;
/**
* Get name of column containing reporter names.
* @return Column heading.
*/
public String getReporterColumnName() {
return reporterColumnName;
}
/**
* Set name of column containing reporter names.
* @param reporterColumnName Column heading.
*/
public void setReporterColumnName(final String reporterColumnName) {
this.reporterColumnName = reporterColumnName;
}
/**
* {@inheritDoc}
*/
@Override
public ActionErrors validate(final ActionMapping mapping,
final HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (this.reporterColumnName == null
|| this.reporterColumnName.length() < 1) {
errors.add("reporterColumnName", new ActionError("invalid.field"));
}
if (errors.size() > 0) {
errors.add("global", new ActionError("invalid.fields"));
}
return errors;
}
}
| bsd-3-clause |
msf-oca-his/dhis-core | dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/sms/listener/TrackedEntityRegistrationSMSListener.java | 7054 | package org.hisp.dhis.sms.listener;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramInstanceService;
import org.hisp.dhis.sms.command.SMSCommand;
import org.hisp.dhis.sms.command.SMSCommandService;
import org.hisp.dhis.sms.command.code.SMSCode;
import org.hisp.dhis.sms.incoming.IncomingSms;
import org.hisp.dhis.sms.incoming.SmsMessageStatus;
import org.hisp.dhis.sms.parse.ParserType;
import org.hisp.dhis.sms.parse.SMSParserException;
import org.hisp.dhis.system.util.SmsUtils;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.trackedentity.TrackedEntityInstanceService;
import org.hisp.dhis.trackedentity.TrackedEntityTypeService;
import org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class TrackedEntityRegistrationSMSListener
extends BaseSMSListener
{
private static final String SUCCESS_MESSAGE = "Tracked Entity Registered Successfully with uid. ";
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
@Autowired
private SMSCommandService smsCommandService;
@Autowired
private TrackedEntityTypeService trackedEntityTypeService;
@Autowired
private TrackedEntityInstanceService trackedEntityInstanceService;
@Autowired
private ProgramInstanceService programInstanceService;
// -------------------------------------------------------------------------
// IncomingSmsListener implementation
// -------------------------------------------------------------------------
@Override
protected void postProcess( IncomingSms sms, SMSCommand smsCommand, Map<String, String> parsedMessage )
{
String message = sms.getText();
Date date = SmsUtils.lookForDate( message );
String senderPhoneNumber = StringUtils.replace( sms.getOriginator(), "+", "" );
Collection<OrganisationUnit> orgUnits = getOrganisationUnits( sms );
Program program = smsCommand.getProgram();
OrganisationUnit orgUnit = SmsUtils.selectOrganisationUnit( orgUnits, parsedMessage, smsCommand );
if ( !program.hasOrganisationUnit( orgUnit ) )
{
sendFeedback( SMSCommand.NO_OU_FOR_PROGRAM, senderPhoneNumber, WARNING );
throw new SMSParserException( SMSCommand.NO_OU_FOR_PROGRAM );
}
TrackedEntityInstance trackedEntityInstance = new TrackedEntityInstance();
trackedEntityInstance.setOrganisationUnit( orgUnit );
trackedEntityInstance.setTrackedEntityType( trackedEntityTypeService.getTrackedEntityByName( smsCommand.getProgram().getTrackedEntityType().getName() ) );
Set<TrackedEntityAttributeValue> patientAttributeValues = new HashSet<>();
smsCommand.getCodes().stream()
.filter( code -> parsedMessage.containsKey( code.getCode() ) )
.forEach( code ->
{
TrackedEntityAttributeValue trackedEntityAttributeValue = this.createTrackedEntityAttributeValue( parsedMessage, code, trackedEntityInstance) ;
patientAttributeValues.add( trackedEntityAttributeValue );
});
int trackedEntityInstanceId = 0;
if ( patientAttributeValues.size() > 0 )
{
trackedEntityInstanceId = trackedEntityInstanceService.createTrackedEntityInstance( trackedEntityInstance,
null, null, patientAttributeValues );
}
else
{
sendFeedback( "No TrackedEntityAttribute found", senderPhoneNumber, WARNING );
}
TrackedEntityInstance tei = trackedEntityInstanceService.getTrackedEntityInstance( trackedEntityInstanceId );
programInstanceService.enrollTrackedEntityInstance( tei, smsCommand.getProgram(), new Date(), date, orgUnit );
sendFeedback( StringUtils.defaultIfBlank( smsCommand.getSuccessMessage(), SUCCESS_MESSAGE + tei.getUid() ), senderPhoneNumber, INFO );
update( sms, SmsMessageStatus.PROCESSED, true );
}
@Override
protected SMSCommand getSMSCommand( IncomingSms sms )
{
return smsCommandService.getSMSCommand( SmsUtils.getCommandString( sms ),
ParserType.TRACKED_ENTITY_REGISTRATION_PARSER );
}
private TrackedEntityAttributeValue createTrackedEntityAttributeValue( Map<String, String> parsedMessage,
SMSCode code, TrackedEntityInstance trackedEntityInstance )
{
String value = parsedMessage.get( code.getCode() );
TrackedEntityAttribute trackedEntityAttribute = code.getTrackedEntityAttribute();
TrackedEntityAttributeValue trackedEntityAttributeValue = new TrackedEntityAttributeValue();
trackedEntityAttributeValue.setAttribute( trackedEntityAttribute );
trackedEntityAttributeValue.setEntityInstance( trackedEntityInstance );
trackedEntityAttributeValue.setValue( value );
return trackedEntityAttributeValue;
}
}
| bsd-3-clause |
vietnguyen/dhis2-core | dhis-2/dhis-api/src/main/java/org/hisp/dhis/email/EmailResponse.java | 2144 | package org.hisp.dhis.email;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author Zubair <rajazubair.asghar@gmail.com>
*/
public enum EmailResponse
{
SENT( "success" ),
FAILED( "failed" ),
ABORTED( "aborted" ),
NOT_CONFIGURED( "no configuration found" );
private String responseMessage;
EmailResponse( String responseMessage )
{
this.responseMessage = responseMessage;
}
public String getResponseMessage()
{
return responseMessage;
}
public void setResponseMessage( String responseMessage )
{
this.responseMessage = responseMessage;
}
}
| bsd-3-clause |
jeking3/scheduling-server | Reports/src/au/edu/uts/eng/remotelabs/schedserver/reports/intf/types/QuerySessionReportType.java | 20256 | /**
* SAHARA Scheduling Server
*
* Schedules and assigns local laboratory rigs.
*
* @license See LICENSE in the top level directory for complete license terms.
*
* Copyright (c) 2009, University of Technology, Sydney
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Technology, Sydney nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Tania Machet (tmachet)
* @date 13 December 2010
*/
package au.edu.uts.eng.remotelabs.schedserver.reports.intf.types;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.apache.axiom.om.OMConstants;
import org.apache.axiom.om.OMDataSource;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.llom.OMSourcedElementImpl;
import org.apache.axis2.databinding.ADBBean;
import org.apache.axis2.databinding.ADBDataSource;
import org.apache.axis2.databinding.ADBException;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.databinding.utils.ConverterUtil;
import org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl;
import org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter;
/**
* QuerySessionReportType bean class.
*/
public class QuerySessionReportType implements ADBBean
{
/*
* This type was generated from the piece of schema that had
* name = QuerySessionReportType
* Namespace URI = http://remotelabs.eng.uts.edu.au/schedserver/reports
* Namespace Prefix = ns1
*/
private static final long serialVersionUID = -5121246029757741056L;
private static String generatePrefix(final String namespace)
{
if (namespace.equals("http://remotelabs.eng.uts.edu.au/schedserver/reports"))
{
return "ns1";
}
return BeanUtil.getUniquePrefix();
}
protected RequestorType requestor;
public RequestorType getRequestor()
{
return this.requestor;
}
public void setRequestor(final RequestorType param)
{
this.requestor = param;
}
protected QueryFilterType querySelect;
public QueryFilterType getQuerySelect()
{
return this.querySelect;
}
public void setQuerySelect(final QueryFilterType param)
{
this.querySelect = param;
}
protected QueryFilterType queryConstraints;
protected boolean queryConstraintsTracker = false;
public QueryFilterType getQueryConstraints()
{
return this.queryConstraints;
}
public void setQueryConstraints(final QueryFilterType param)
{
this.queryConstraints = param;
this.queryConstraintsTracker = param != null;
}
protected Calendar startTime;
protected boolean startTimeTracker = false;
public Calendar getStartTime()
{
return this.startTime;
}
public void setStartTime(final Calendar param)
{
this.startTime = param;
this.startTimeTracker = param != null;
}
protected Calendar endTime;
protected boolean endTimeTracker = false;
public Calendar getEndTime()
{
return this.endTime;
}
public void setEndTime(final Calendar param)
{
this.endTime = param;
this.endTimeTracker = param != null;
}
protected PaginationType pagination;
protected boolean paginationTracker = false;
public PaginationType getPagination()
{
return this.pagination;
}
public void setPagination(final PaginationType param)
{
this.pagination = param;
this.paginationTracker = param != null;
}
public static boolean isReaderMTOMAware(final XMLStreamReader reader)
{
boolean isReaderMTOMAware = false;
try
{
isReaderMTOMAware = Boolean.TRUE.equals(reader.getProperty(OMConstants.IS_DATA_HANDLERS_AWARE));
}
catch (final IllegalArgumentException e)
{
isReaderMTOMAware = false;
}
return isReaderMTOMAware;
}
public OMElement getOMElement(final QName parentQName, final OMFactory factory) throws ADBException
{
final OMDataSource dataSource = new ADBDataSource(this, parentQName)
{
@Override
public void serialize(final MTOMAwareXMLStreamWriter xmlWriter) throws XMLStreamException
{
QuerySessionReportType.this.serialize(this.parentQName, factory, xmlWriter);
}
};
return new OMSourcedElementImpl(parentQName, factory, dataSource);
}
@Override
public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter)
throws XMLStreamException, ADBException
{
this.serialize(parentQName, factory, xmlWriter, false);
}
@Override
public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter,
final boolean serializeType) throws XMLStreamException, ADBException
{
String prefix = parentQName.getPrefix();
String namespace = parentQName.getNamespaceURI();
if ((namespace != null) && (namespace.trim().length() > 0))
{
final String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null)
{
xmlWriter.writeStartElement(namespace, parentQName.getLocalPart());
}
else
{
if (prefix == null)
{
prefix = QuerySessionReportType.generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
else
{
xmlWriter.writeStartElement(parentQName.getLocalPart());
}
if (serializeType)
{
final String namespacePrefix = this.registerPrefix(xmlWriter,
"http://remotelabs.eng.uts.edu.au/schedserver/reports");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0))
{
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix
+ ":QuerySessionReportType", xmlWriter);
}
else
{
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type",
"QuerySessionReportType", xmlWriter);
}
}
if (this.requestor == null)
{
throw new ADBException("requestor cannot be null!!");
}
this.requestor.serialize(new QName("", "requestor"), factory, xmlWriter);
if (this.querySelect == null)
{
throw new ADBException("querySelect cannot be null!!");
}
this.querySelect.serialize(new QName("", "querySelect"), factory, xmlWriter);
if (this.queryConstraintsTracker)
{
if (this.queryConstraints == null)
{
throw new ADBException("queryConstraints cannot be null!!");
}
this.queryConstraints.serialize(new QName("", "queryConstraints"), factory, xmlWriter);
}
if (this.startTimeTracker)
{
namespace = "";
if (!namespace.equals(""))
{
prefix = xmlWriter.getPrefix(namespace);
if (prefix == null)
{
prefix = QuerySessionReportType.generatePrefix(namespace);
xmlWriter.writeStartElement(prefix, "startTime", namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
else
{
xmlWriter.writeStartElement(namespace, "startTime");
}
}
else
{
xmlWriter.writeStartElement("startTime");
}
if (this.startTime == null)
{
throw new ADBException("startTime cannot be null!!");
}
else
{
xmlWriter.writeCharacters(ConverterUtil.convertToString(this.startTime));
}
xmlWriter.writeEndElement();
}
if (this.endTimeTracker)
{
namespace = "";
if (!namespace.equals(""))
{
prefix = xmlWriter.getPrefix(namespace);
if (prefix == null)
{
prefix = QuerySessionReportType.generatePrefix(namespace);
xmlWriter.writeStartElement(prefix, "endTime", namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
else
{
xmlWriter.writeStartElement(namespace, "endTime");
}
}
else
{
xmlWriter.writeStartElement("endTime");
}
if (this.endTime == null)
{
throw new ADBException("endTime cannot be null!!");
}
else
{
xmlWriter.writeCharacters(ConverterUtil.convertToString(this.endTime));
}
xmlWriter.writeEndElement();
}
if (this.paginationTracker)
{
if (this.pagination == null)
{
throw new ADBException("pagination cannot be null!!");
}
this.pagination.serialize(new QName("", "pagination"), factory, xmlWriter);
}
xmlWriter.writeEndElement();
}
private void writeAttribute(final String prefix, final String namespace, final String attName,
final String attValue, final XMLStreamWriter xmlWriter) throws XMLStreamException
{
if (xmlWriter.getPrefix(namespace) == null)
{
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace, attName, attValue);
}
private String registerPrefix(final XMLStreamWriter xmlWriter, final String namespace) throws XMLStreamException
{
String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null)
{
prefix = QuerySessionReportType.generatePrefix(namespace);
while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null)
{
prefix = BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
@Override
public XMLStreamReader getPullParser(final QName qName) throws ADBException
{
final ArrayList<Serializable> elementList = new ArrayList<Serializable>();
elementList.add(new QName("", "requestor"));
if (this.requestor == null)
{
throw new ADBException("requestor cannot be null!!");
}
elementList.add(this.requestor);
elementList.add(new QName("", "querySelect"));
if (this.querySelect == null)
{
throw new ADBException("querySelect cannot be null!!");
}
elementList.add(this.querySelect);
if (this.queryConstraintsTracker)
{
elementList.add(new QName("", "queryConstraints"));
if (this.queryConstraints == null)
{
throw new ADBException("queryConstraints cannot be null!!");
}
elementList.add(this.queryConstraints);
}
if (this.startTimeTracker)
{
elementList.add(new QName("", "startTime"));
if (this.startTime != null)
{
elementList.add(ConverterUtil.convertToString(this.startTime));
}
else
{
throw new ADBException("startTime cannot be null!!");
}
}
if (this.endTimeTracker)
{
elementList.add(new QName("", "endTime"));
if (this.endTime != null)
{
elementList.add(ConverterUtil.convertToString(this.endTime));
}
else
{
throw new ADBException("endTime cannot be null!!");
}
}
if (this.paginationTracker)
{
elementList.add(new QName("", "pagination"));
if (this.pagination == null)
{
throw new ADBException("pagination cannot be null!!");
}
elementList.add(this.pagination);
}
return new ADBXMLStreamReaderImpl(qName, elementList.toArray(), new Object[0]);
}
public static class Factory
{
public static QuerySessionReportType parse(final XMLStreamReader reader) throws Exception
{
final QuerySessionReportType object = new QuerySessionReportType();
try
{
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null)
{
final String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName != null)
{
String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1)
{
nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix == null ? "" : nsPrefix;
final String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"QuerySessionReportType".equals(type))
{
final String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (QuerySessionReportType) ExtensionMapper.getTypeObject(nsUri, type, reader);
}
}
}
reader.next();
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "requestor").equals(reader.getName()))
{
object.setRequestor(RequestorType.Factory.parse(reader));
reader.next();
}
else
{
throw new ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "querySelect").equals(reader.getName()))
{
object.setQuerySelect(QueryFilterType.Factory.parse(reader));
reader.next();
}
else
{
throw new ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "queryConstraints").equals(reader.getName()))
{
object.setQueryConstraints(QueryFilterType.Factory.parse(reader));
reader.next();
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "startTime").equals(reader.getName()))
{
final String content = reader.getElementText();
object.setStartTime(ConverterUtil.convertToDateTime(content));
reader.next();
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "endTime").equals(reader.getName()))
{
final String content = reader.getElementText();
object.setEndTime(ConverterUtil.convertToDateTime(content));
reader.next();
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement() && new QName("", "pagination").equals(reader.getName()))
{
object.setPagination(PaginationType.Factory.parse(reader));
reader.next();
}
while (!reader.isStartElement() && !reader.isEndElement())
{
reader.next();
}
if (reader.isStartElement())
{
throw new ADBException("Unexpected subelement " + reader.getLocalName());
}
}
catch (final XMLStreamException e)
{
throw new Exception(e);
}
return object;
}
}
}
| bsd-3-clause |
snail1966/droid | droid-report/src/main/java/uk/gov/nationalarchives/droid/report/planets/domain/YearItemType.java | 5288 | /**
* Copyright (c) 2016, The National Archives <pronom@nationalarchives.gsi.gov.uk>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the The National Archives nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.03.22 at 11:40:59 AM GMT
//
package uk.gov.nationalarchives.droid.report.planets.domain;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for YearItemType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="YearItemType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="year" type="{http://www.w3.org/2001/XMLSchema}gYear"/>
* <element name="numFiles" type="{http://www.w3.org/2001/XMLSchema}integer"/>
* <element name="totalFileSize" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
* @deprecated PLANETS XML is now generated using XSLT over normal report xml files.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "YearItemType", propOrder = {
"year",
"numFiles",
"totalFileSize"
})
@Deprecated
public class YearItemType {
@XmlElement(required = true)
@XmlSchemaType(name = "gYear")
protected XMLGregorianCalendar year;
@XmlElement(required = true)
protected BigInteger numFiles;
@XmlElement(required = true)
protected BigDecimal totalFileSize;
/**
* Gets the value of the year property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getYear() {
return year;
}
/**
* Sets the value of the year property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setYear(XMLGregorianCalendar value) {
this.year = value;
}
/**
* Gets the value of the numFiles property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNumFiles() {
return numFiles;
}
/**
* Sets the value of the numFiles property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNumFiles(BigInteger value) {
this.numFiles = value;
}
/**
* Gets the value of the totalFileSize property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getTotalFileSize() {
return totalFileSize;
}
/**
* Sets the value of the totalFileSize property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setTotalFileSize(BigDecimal value) {
this.totalFileSize = value;
}
}
| bsd-3-clause |
snail1966/droid | droid-command-line/src/main/java/uk/gov/nationalarchives/droid/command/action/DisplayDefaultSignatureFileVersionCommand.java | 3404 | /**
* Copyright (c) 2016, The National Archives <pronom@nationalarchives.gsi.gov.uk>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the The National Archives nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.gov.nationalarchives.droid.command.action;
import java.io.PrintWriter;
import java.util.Map;
import uk.gov.nationalarchives.droid.command.i18n.I18N;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileException;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileInfo;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureManager;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureType;
/**
* @author rflitcroft
*
*/
public class DisplayDefaultSignatureFileVersionCommand implements DroidCommand {
private PrintWriter printWriter;
private SignatureManager signatureManager;
/**
* {@inheritDoc}
*/
@Override
public void execute() throws CommandExecutionException {
try {
Map<SignatureType, SignatureFileInfo> sigFileInfos = signatureManager.getDefaultSignatures();
for (SignatureFileInfo info : sigFileInfos.values()) {
printWriter.println(I18N.getResource(I18N.DEFAULT_SIGNATURE_VERSION,
info.getType(), info.getVersion(), info.getFile().getName()));
}
} catch (SignatureFileException e) {
throw new CommandExecutionException(e);
}
}
/**
* @param printWriter the printWriter to set
*/
public void setPrintWriter(PrintWriter printWriter) {
this.printWriter = printWriter;
}
/**
* @param signatureManager the signatureManager to set
*/
public void setSignatureManager(SignatureManager signatureManager) {
this.signatureManager = signatureManager;
}
}
| bsd-3-clause |
gooddata/GoodData-CL | connector/src/main/java/com/restfb/DefaultJsonMapper.java | 26108 | /*
* Copyright (c) 2010-2011 Mark Allen.
*
* 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 com.restfb;
import static com.restfb.json.JsonObject.NULL;
import static com.restfb.util.ReflectionUtils.findFieldsWithAnnotation;
import static com.restfb.util.ReflectionUtils.getFirstParameterizedTypeArgument;
import static com.restfb.util.ReflectionUtils.isPrimitive;
import static com.restfb.util.StringUtils.isBlank;
import static com.restfb.util.StringUtils.trimToEmpty;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableSet;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.FINER;
import static java.util.logging.Level.FINEST;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import com.restfb.exception.FacebookJsonMappingException;
import com.restfb.json.JsonArray;
import com.restfb.json.JsonException;
import com.restfb.json.JsonObject;
import com.restfb.types.Post.Comments;
import com.restfb.util.ReflectionUtils.FieldWithAnnotation;
/**
* Default implementation of a JSON-to-Java mapper.
*
* @author <a href="http://restfb.com">Mark Allen</a>
*/
public class DefaultJsonMapper implements JsonMapper {
/**
* Logger.
*/
private static final Logger logger = Logger.getLogger(DefaultJsonMapper.class.getName());
/**
* @see com.restfb.JsonMapper#toJavaList(String, Class)
*/
@Override
public <T> List<T> toJavaList(String json, Class<T> type) {
json = trimToEmpty(json);
if (isBlank(json))
throw new FacebookJsonMappingException("JSON is an empty string - can't map it.");
if (type == null)
throw new FacebookJsonMappingException("You must specify the Java type to map to.");
if (json.startsWith("{")) {
// Sometimes Facebook returns the empty object {} when it really should be
// returning an empty list [] (example: do an FQL query for a user's
// affiliations - it's a list except when there are none, then it turns
// into an object). Check for that special case here.
if (isEmptyObject(json)) {
if (logger.isLoggable(FINER))
logger.finer("Encountered {} when we should've seen []. "
+ "Mapping the {} as an empty list and moving on...");
return new ArrayList<T>();
}
// Special case: if the only element of this object is an array called
// "data", then treat it as a list. The Graph API uses this convention for
// connections and in a few other places, e.g. comments on the Post
// object.
// Doing this simplifies mapping, so we don't have to worry about having a
// little placeholder object that only has a "data" value.
try {
JsonObject jsonObject = new JsonObject(json);
String[] fieldNames = JsonObject.getNames(jsonObject);
if (fieldNames != null) {
boolean hasSingleDataProperty = fieldNames.length == 1 && "data".equals(fieldNames[0]);
Object jsonDataObject = jsonObject.get("data");
if (!hasSingleDataProperty && !(jsonDataObject instanceof JsonArray))
throw new FacebookJsonMappingException("JSON is an object but is being mapped as a list "
+ "instead. Offending JSON is '" + json + "'.");
json = jsonDataObject.toString();
}
} catch (JsonException e) {
// Should never get here, but just in case...
throw new FacebookJsonMappingException("Unable to convert Facebook response " + "JSON to a list of "
+ type.getName() + " instances. Offending JSON is " + json, e);
}
}
try {
List<T> list = new ArrayList<T>();
JsonArray jsonArray = new JsonArray(json);
for (int i = 0; i < jsonArray.length(); i++)
list.add(toJavaObject(jsonArray.get(i).toString(), type));
return unmodifiableList(list);
} catch (FacebookJsonMappingException e) {
throw e;
} catch (Exception e) {
throw new FacebookJsonMappingException("Unable to convert Facebook response " + "JSON to a list of "
+ type.getName() + " instances", e);
}
}
/**
* @see com.restfb.JsonMapper#toJavaObject(String, Class)
*/
@Override
@SuppressWarnings("unchecked")
public <T> T toJavaObject(String json, Class<T> type) {
verifyThatJsonIsOfObjectType(json);
try {
// Are we asked to map to JsonObject? If so, short-circuit right away.
if (type.equals(JsonObject.class))
return (T) new JsonObject(json);
List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation = findFieldsWithAnnotation(type, Facebook.class);
Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation);
// If there are no annotated fields, assume we're mapping to a built-in
// type. If this is actually the empty object, just return a new instance
// of the corresponding Java type.
if (fieldsWithAnnotation.size() == 0)
if (isEmptyObject(json))
return createInstance(type);
else
return toPrimitiveJavaType(json, type);
// Facebook will sometimes return the string "null".
// Check for that and bail early if we find it.
if ("null".equals(json))
return null;
// Facebook will sometimes return the string "false" to mean null.
// Check for that and bail early if we find it.
if ("false".equals(json)) {
if (logger.isLoggable(FINE))
logger.fine("Encountered 'false' from Facebook when trying to map to " + type.getSimpleName()
+ " - mapping null instead.");
return null;
}
JsonObject jsonObject = new JsonObject(json);
T instance = createInstance(type);
if (instance instanceof JsonObject)
return (T) jsonObject;
// For each Facebook-annotated field on the current Java object, pull data
// out of the JSON object and put it in the Java object
for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
String facebookFieldName = getFacebookFieldName(fieldWithAnnotation);
if (!jsonObject.has(facebookFieldName)) {
if (logger.isLoggable(FINER))
logger.finer("No JSON value present for '" + facebookFieldName + "', skipping. JSON is '" + json + "'.");
continue;
}
fieldWithAnnotation.getField().setAccessible(true);
// Set the Java field's value.
//
// If we notice that this Facebook field name is mapped more than once,
// go into a special mode where we swallow any exceptions that occur
// when mapping to the Java field. This is because Facebook will
// sometimes return data in different formats for the same field name.
// See issues 56 and 90 for examples of this behavior and discussion.
if (facebookFieldNamesWithMultipleMappings.contains(facebookFieldName)) {
try {
fieldWithAnnotation.getField()
.set(instance, toJavaType(fieldWithAnnotation, jsonObject, facebookFieldName));
} catch (FacebookJsonMappingException e) {
logMultipleMappingFailedForField(facebookFieldName, fieldWithAnnotation, json);
} catch (JsonException e) {
logMultipleMappingFailedForField(facebookFieldName, fieldWithAnnotation, json);
}
} else {
fieldWithAnnotation.getField().set(instance, toJavaType(fieldWithAnnotation, jsonObject, facebookFieldName));
}
}
return instance;
} catch (FacebookJsonMappingException e) {
throw e;
} catch (Exception e) {
throw new FacebookJsonMappingException("Unable to map JSON to Java. Offending JSON is '" + json + "'.", e);
}
}
/**
* Dumps out a log message when one of a multiple-mapped Facebook field name
* JSON-to-Java mapping operation fails.
*
* @param facebookFieldName
* The Facebook field name.
* @param fieldWithAnnotation
* The Java field to map to and its annotation.
* @param json
* The JSON that failed to map to the Java field.
*/
protected void logMultipleMappingFailedForField(String facebookFieldName,
FieldWithAnnotation<Facebook> fieldWithAnnotation, String json) {
if (!logger.isLoggable(FINER))
return;
Field field = fieldWithAnnotation.getField();
if (logger.isLoggable(FINER))
logger.finer("Could not map '" + facebookFieldName + "' to " + field.getDeclaringClass().getSimpleName() + "."
+ field.getName() + ", but continuing on because '" + facebookFieldName
+ "' is mapped to multiple fields in " + field.getDeclaringClass().getSimpleName() + ". JSON is " + json);
}
/**
* For a Java field annotated with the {@code Facebook} annotation, figure out
* what the corresponding Facebook JSON field name to map to it is.
*
* @param fieldWithAnnotation
* A Java field annotated with the {@code Facebook} annotation.
* @return The Facebook JSON field name that should be mapped to this Java
* field.
*/
protected String getFacebookFieldName(FieldWithAnnotation<Facebook> fieldWithAnnotation) {
String facebookFieldName = fieldWithAnnotation.getAnnotation().value();
Field field = fieldWithAnnotation.getField();
// If no Facebook field name was specified in the annotation, assume
// it's the same name as the Java field
if (isBlank(facebookFieldName)) {
if (logger.isLoggable(FINEST))
logger.finest("No explicit Facebook field name found for " + field
+ ", so defaulting to the field name itself (" + field.getName() + ")");
facebookFieldName = field.getName();
}
return facebookFieldName;
}
/**
* Finds any Facebook JSON fields that are mapped to more than 1 Java field.
*
* @param fieldsWithAnnotation
* Java fields annotated with the {@code Facebook} annotation.
* @return Any Facebook JSON fields that are mapped to more than 1 Java field.
*/
protected Set<String> facebookFieldNamesWithMultipleMappings(List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation) {
Map<String, Integer> facebookFieldsNamesWithOccurrenceCount = new HashMap<String, Integer>();
Set<String> facebookFieldNamesWithMultipleMappings = new HashSet<String>();
// Get a count of Facebook field name occurrences for each
// @Facebook-annotated field
for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
String fieldName = getFacebookFieldName(fieldWithAnnotation);
int occurrenceCount =
facebookFieldsNamesWithOccurrenceCount.containsKey(fieldName) ? facebookFieldsNamesWithOccurrenceCount
.get(fieldName) : 0;
facebookFieldsNamesWithOccurrenceCount.put(fieldName, occurrenceCount + 1);
}
// Pull out only those field names with multiple mappings
for (Entry<String, Integer> entry : facebookFieldsNamesWithOccurrenceCount.entrySet())
if (entry.getValue() > 1)
facebookFieldNamesWithMultipleMappings.add(entry.getKey());
return unmodifiableSet(facebookFieldNamesWithMultipleMappings);
}
/**
* @see com.restfb.JsonMapper#toJson(Object)
*/
@Override
public String toJson(Object object) {
// Delegate to recursive method
return toJsonInternal(object).toString();
}
/**
* Is the given {@code json} a valid JSON object?
*
* @param json
* The JSON to check.
* @throws FacebookJsonMappingException
* If {@code json} is not a valid JSON object.
*/
protected void verifyThatJsonIsOfObjectType(String json) {
if (isBlank(json))
throw new FacebookJsonMappingException("JSON is an empty string - can't map it.");
if (json.startsWith("["))
throw new FacebookJsonMappingException("JSON is an array but is being mapped as an object "
+ "- you should map it as a List instead. Offending JSON is '" + json + "'.");
}
/**
* Recursively marshal the given {@code object} to JSON.
* <p>
* Used by {@link #toJson(Object)}.
*
* @param object
* The object to marshal.
* @return JSON representation of the given {@code object}.
* @throws FacebookJsonMappingException
* If an error occurs while marshaling to JSON.
*/
protected Object toJsonInternal(Object object) {
if (object == null)
return NULL;
if (object instanceof List<?>) {
JsonArray jsonArray = new JsonArray();
for (Object o : (List<?>) object)
jsonArray.put(toJsonInternal(o));
return jsonArray;
}
if (object instanceof Map<?, ?>) {
JsonObject jsonObject = new JsonObject();
for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
if (!(entry.getKey() instanceof String))
throw new FacebookJsonMappingException("Your Map keys must be of type " + String.class
+ " in order to be converted to JSON. Offending map is " + object);
try {
jsonObject.put((String) entry.getKey(), toJsonInternal(entry.getValue()));
} catch (JsonException e) {
throw new FacebookJsonMappingException("Unable to process value '" + entry.getValue() + "' for key '"
+ entry.getKey() + "' in Map " + object, e);
}
}
return jsonObject;
}
if (isPrimitive(object))
return object;
if (object instanceof BigInteger)
return ((BigInteger) object).longValue();
if (object instanceof BigDecimal)
return ((BigDecimal) object).doubleValue();
// We've passed the special-case bits, so let's try to marshal this as a
// plain old Javabean...
List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation =
findFieldsWithAnnotation(object.getClass(), Facebook.class);
JsonObject jsonObject = new JsonObject();
Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation);
if (facebookFieldNamesWithMultipleMappings.size() > 0)
throw new FacebookJsonMappingException("Unable to convert to JSON because multiple @"
+ Facebook.class.getSimpleName() + " annotations for the same name are present: "
+ facebookFieldNamesWithMultipleMappings);
for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
String facebookFieldName = getFacebookFieldName(fieldWithAnnotation);
fieldWithAnnotation.getField().setAccessible(true);
try {
jsonObject.put(facebookFieldName, toJsonInternal(fieldWithAnnotation.getField().get(object)));
} catch (Exception e) {
throw new FacebookJsonMappingException("Unable to process field '" + facebookFieldName + "' for "
+ object.getClass(), e);
}
}
return jsonObject;
}
/**
* Given a {@code json} value of something like {@code MyValue} or {@code 123}
* , return a representation of that value of type {@code type}.
* <p>
* This is to support non-legal JSON served up by Facebook for API calls like
* {@code Friends.get} (example result: {@code [222333,1240079]}).
*
* @param <T>
* The Java type to map to.
* @param json
* The non-legal JSON to map to the Java type.
* @param type
* Type token.
* @return Java representation of {@code json}.
* @throws FacebookJsonMappingException
* If an error occurs while mapping JSON to Java.
*/
@SuppressWarnings("unchecked")
protected <T> T toPrimitiveJavaType(String json, Class<T> type) {
if (String.class.equals(type)) {
// If the string starts and ends with quotes, remove them, since Facebook
// can serve up strings surrounded by quotes.
if (json.length() > 1 && json.startsWith("\"") && json.endsWith("\"")) {
json = json.replaceFirst("\"", "");
json = json.substring(0, json.length() - 1);
}
return (T) json;
}
if (Integer.class.equals(type) || Integer.TYPE.equals(type))
return (T) new Integer(json);
if (Boolean.class.equals(type) || Boolean.TYPE.equals(type))
return (T) new Boolean(json);
if (Long.class.equals(type) || Long.TYPE.equals(type))
return (T) new Long(json);
if (Double.class.equals(type) || Double.TYPE.equals(type))
return (T) new Double(json);
if (Float.class.equals(type) || Float.TYPE.equals(type))
return (T) new Float(json);
if (BigInteger.class.equals(type))
return (T) new BigInteger(json);
if (BigDecimal.class.equals(type))
return (T) new BigDecimal(json);
throw new FacebookJsonMappingException("Don't know how to map JSON to " + type
+ ". Are you sure you're mapping to the right class? " + "Offending JSON is '" + json + "'.");
}
/**
* Extracts JSON data for a field according to its {@code Facebook} annotation
* and returns it converted to the proper Java type.
*
* @param fieldWithAnnotation
* The field/annotation pair which specifies what Java type to
* convert to.
* @param jsonObject
* "Raw" JSON object to pull data from.
* @param facebookFieldName
* Specifies what JSON field to pull "raw" data from.
* @return A
* @throws JsonException
* If an error occurs while mapping JSON to Java.
* @throws FacebookJsonMappingException
* If an error occurs while mapping JSON to Java.
*/
protected Object toJavaType(FieldWithAnnotation<Facebook> fieldWithAnnotation, JsonObject jsonObject,
String facebookFieldName) throws JsonException, FacebookJsonMappingException {
Class<?> type = fieldWithAnnotation.getField().getType();
Object rawValue = jsonObject.get(facebookFieldName);
// Short-circuit right off the bat if we've got a null value.
if (NULL.equals(rawValue))
return null;
if (String.class.equals(type)) {
// Special handling here for better error checking.
// Since JsonObject.getString() will return literal JSON text even if it's
// _not_ a JSON string, we check the marshaled type and bail if needed.
// For example, calling JsonObject.getString("results") on the below
// JSON...
// {"results":[{"name":"Mark Allen"}]}
// ... would return the string "[{"name":"Mark Allen"}]" instead of
// throwing an error. So we throw the error ourselves.
// Per Antonello Naccarato, sometimes FB will return an empty JSON array
// instead of an empty string. Look for that here.
if (rawValue instanceof JsonArray)
if (((JsonArray) rawValue).length() == 0) {
if (logger.isLoggable(FINER))
logger.finer("Coercing an empty JSON array " + "to an empty string for " + fieldWithAnnotation);
return "";
}
// If the user wants a string, _always_ give her a string.
// This is useful if, for example, you've got a @Facebook-annotated string
// field that you'd like to have a numeric type shoved into.
// User beware: this will turn *anything* into a string, which might lead
// to results you don't expect.
return rawValue.toString();
}
if (Integer.class.equals(type) || Integer.TYPE.equals(type))
return new Integer(jsonObject.getInt(facebookFieldName));
if (Boolean.class.equals(type) || Boolean.TYPE.equals(type))
return new Boolean(jsonObject.getBoolean(facebookFieldName));
if (Long.class.equals(type) || Long.TYPE.equals(type))
return new Long(jsonObject.getLong(facebookFieldName));
if (Double.class.equals(type) || Double.TYPE.equals(type))
return new Double(jsonObject.getDouble(facebookFieldName));
if (Float.class.equals(type) || Float.TYPE.equals(type))
return new BigDecimal(jsonObject.getString(facebookFieldName)).floatValue();
if (BigInteger.class.equals(type))
return new BigInteger(jsonObject.getString(facebookFieldName));
if (BigDecimal.class.equals(type))
return new BigDecimal(jsonObject.getString(facebookFieldName));
if (List.class.equals(type))
return toJavaList(rawValue.toString(), getFirstParameterizedTypeArgument(fieldWithAnnotation.getField()));
String rawValueAsString = rawValue.toString();
// Hack for issue 76 where FB will sometimes return a Post's Comments as
// "[]" instead of an object type (wtf)
if (Comments.class.isAssignableFrom(type) && rawValue instanceof JsonArray) {
if (logger.isLoggable(FINE))
logger.fine("Encountered comment array '" + rawValueAsString + "' but expected a "
+ Comments.class.getSimpleName() + " object instead. Working around that " + "by coercing into an empty "
+ Comments.class.getSimpleName() + " instance...");
JsonObject workaroundJsonObject = new JsonObject();
workaroundJsonObject.put("count", 0);
workaroundJsonObject.put("data", new JsonArray());
rawValueAsString = workaroundJsonObject.toString();
}
// Some other type - recurse into it
return toJavaObject(rawValueAsString, type);
}
/**
* Creates a new instance of the given {@code type}.
*
* @param <T>
* Java type to map to.
* @param type
* Type token.
* @return A new instance of {@code type}.
* @throws FacebookJsonMappingException
* If an error occurs when creating a new instance ({@code type} is
* inaccessible, doesn't have a public no-arg constructor, etc.)
*/
protected <T> T createInstance(Class<T> type) {
String errorMessage =
"Unable to create an instance of " + type + ". Please make sure that it's marked 'public' "
+ "and, if it's a nested class, is marked 'static'. " + "It should have a public, no-argument constructor.";
try {
return type.newInstance();
} catch (IllegalAccessException e) {
throw new FacebookJsonMappingException(errorMessage, e);
} catch (InstantiationException e) {
throw new FacebookJsonMappingException(errorMessage, e);
}
}
/**
* Is the given JSON equivalent to the empty object (<code>{}</code>)?
*
* @param json
* The JSON to check.
* @return {@code true} if the JSON is equivalent to the empty object,
* {@code false} otherwise.
*/
protected boolean isEmptyObject(String json) {
return "{}".equals(json);
}
} | bsd-3-clause |
groupon/mongo-deep-mapreduce | src/main/java/com/groupon/mapreduce/mongo/in/MongoRecordReader.java | 3408 | /*
Copyright (c) 2013, Groupon, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of GROUPON nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.groupon.mapreduce.mongo.in;
import com.groupon.mapreduce.mongo.WritableBSONObject;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import java.io.IOException;
import java.util.Iterator;
/**
* This reads Mongo Records from an Extent and returns Hadoop Records as WritableBSONObjects. The key
* returned to the Mapper is the _id field from the Mongo Record as Text.
*/
public class MongoRecordReader extends RecordReader<Text, WritableBSONObject> {
private Record current = null;
private Iterator<Record> iterator = null;
private FileSystem fs;
@Override
public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext)
throws IOException, InterruptedException {
MongoInputSplit mongoInputSplit = (MongoInputSplit) inputSplit;
fs = ((MongoInputSplit) inputSplit).getExtent().getPath().getFileSystem(taskAttemptContext.getConfiguration());
iterator = mongoInputSplit.getExtent().iterator(fs);
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (!iterator.hasNext())
return false;
current = iterator.next();
return true;
}
@Override
public Text getCurrentKey() throws IOException, InterruptedException {
return new Text(current.getId(fs));
}
@Override
public WritableBSONObject getCurrentValue() throws IOException, InterruptedException {
return new WritableBSONObject(current.getContent(fs));
}
@Override
public float getProgress() throws IOException, InterruptedException {
if (!iterator.hasNext())
return 1.0f;
return 0.0f;
}
@Override
public void close() throws IOException {
}
}
| bsd-3-clause |
beiyuxinke/CONNECT | Product/Production/Services/DocumentQueryCore/src/test/java/gov/hhs/fha/nhinc/docquery/nhin/proxy/NhinDocQueryWebServiceProxyTest.java | 6930 | /*
* Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.docquery.nhin.proxy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.any;
import gov.hhs.fha.nhinc.aspect.NwhinInvocationEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.connectmgr.ConnectionManager;
import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerCache;
import gov.hhs.fha.nhinc.docquery.aspect.AdhocQueryRequestDescriptionBuilder;
import gov.hhs.fha.nhinc.docquery.aspect.AdhocQueryResponseDescriptionBuilder;
import gov.hhs.fha.nhinc.messaging.client.CONNECTClient;
import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants.UDDI_SPEC_VERSION;
import ihe.iti.xds_b._2007.RespondingGatewayQueryPortType;
import java.lang.reflect.Method;
import javax.xml.ws.Service;
import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author Neil Webb
*/
@RunWith(JMock.class)
public class NhinDocQueryWebServiceProxyTest {
Mockery context = new JUnit4Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
final Service mockService = context.mock(Service.class);
final RespondingGatewayQueryPortType mockPort = context.mock(RespondingGatewayQueryPortType.class);
@SuppressWarnings("unchecked")
private CONNECTClient<RespondingGatewayQueryPortType> client = mock(CONNECTClient.class);
private ConnectionManagerCache cache = mock(ConnectionManagerCache.class);
private AdhocQueryRequest request;
private AssertionType assertion;
@Test
public void hasBeginOutboundProcessingEvent() throws Exception {
Class<NhinDocQueryProxyWebServiceSecuredImpl> clazz = NhinDocQueryProxyWebServiceSecuredImpl.class;
Method method = clazz.getMethod("respondingGatewayCrossGatewayQuery", AdhocQueryRequest.class,
AssertionType.class, NhinTargetSystemType.class);
NwhinInvocationEvent annotation = method.getAnnotation(NwhinInvocationEvent.class);
assertNotNull(annotation);
assertEquals(AdhocQueryRequestDescriptionBuilder.class, annotation.beforeBuilder());
assertEquals(AdhocQueryResponseDescriptionBuilder.class, annotation.afterReturningBuilder());
assertEquals("Document Query", annotation.serviceType());
assertEquals("", annotation.version());
}
@Test
public void testNoMtom() throws Exception {
NhinDocQueryProxyWebServiceSecuredImpl impl = getImpl();
NhinTargetSystemType target = getTarget("1.1");
impl.respondingGatewayCrossGatewayQuery(request, assertion, target);
verify(client, never()).enableMtom();
}
@Test
public void testUsingGuidance() throws Exception {
NhinDocQueryProxyWebServiceSecuredImpl impl = getImpl();
NhinTargetSystemType target = getTarget("1.1");
impl.respondingGatewayCrossGatewayQuery(request, assertion, target);
verify(cache).getEndpointURLByServiceNameSpecVersion(any(String.class), any(String.class), any(UDDI_SPEC_VERSION.class));
}
/**
* @param hcidValue
* @return
*/
private NhinTargetSystemType getTarget(String hcidValue) {
NhinTargetSystemType target = new NhinTargetSystemType();
HomeCommunityType hcid = new HomeCommunityType();
hcid.setHomeCommunityId(hcidValue);
target.setHomeCommunity(hcid);
target.setUseSpecVersion("2.0");
return target;
}
/**
* @return
*/
private NhinDocQueryProxyWebServiceSecuredImpl getImpl() {
return new NhinDocQueryProxyWebServiceSecuredImpl() {
/*
* (non-Javadoc)
*
* @see
* gov.hhs.fha.nhinc.docquery.nhin.proxy.NhinDocQueryProxyWebServiceSecuredImpl#getCONNECTClientSecured(
* gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor,
* gov.hhs.fha.nhinc.common.nhinccommon.AssertionType, java.lang.String,
* gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType)
*/
@Override
public CONNECTClient<RespondingGatewayQueryPortType> getCONNECTClientSecured(
ServicePortDescriptor<RespondingGatewayQueryPortType> portDescriptor, AssertionType assertion,
String url, NhinTargetSystemType target) {
return client;
}
/* (non-Javadoc)
* @see gov.hhs.fha.nhinc.docquery.nhin.proxy.NhinDocQueryProxyWebServiceSecuredImpl#getCMInstance()
*/
@Override
protected ConnectionManager getCMInstance() {
return cache;
}
};
}
} | bsd-3-clause |
wizjany/Plume | src/main/java/com/skcraft/plume/event/block/BlockEvent.java | 1892 | package com.skcraft.plume.event.block;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.skcraft.plume.event.BulkEvent;
import com.skcraft.plume.event.Cause;
import com.skcraft.plume.event.DelegateEvent;
import com.skcraft.plume.event.Result;
import com.skcraft.plume.util.Location3i;
import net.minecraft.world.World;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
abstract class BlockEvent extends DelegateEvent implements BulkEvent {
private final World world;
protected BlockEvent(Cause cause, World world) {
super(cause);
checkNotNull(world, "world");
this.world = world;
}
/**
* Get the world.
*
* @return The world
*/
public World getWorld() {
return world;
}
/**
* Get a list of affected locations.
*
* @return A list of affected locations
*/
public abstract List<Location3i> getLocations();
/**
* Filter the list of affected blocks with the given predicate. If the
* predicate returns {@code false}, then the block is removed.
*
* @param predicate the predicate
* @param cancelEventOnFalse true to cancel the event and clear the block
* list once the predicate returns {@code false}
* @return Whether one or more blocks were filtered out
*/
public boolean filterLocations(Predicate<Location3i> predicate, boolean cancelEventOnFalse) {
return filter(getLocations(), Functions.<Location3i>identity(), predicate, cancelEventOnFalse);
}
@Override
public Result getResult() {
if (getLocations().isEmpty()) {
return Result.DENY;
}
return super.getResult();
}
@Override
public Result getExplicitResult() {
return super.getResult();
}
}
| bsd-3-clause |
hispindia/dhis2-Core | dhis-2/dhis-api/src/main/java/org/hisp/dhis/expression/ExpressionService.java | 11199 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.expression;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hisp.dhis.analytics.DataType;
import org.hisp.dhis.common.DimensionalItemId;
import org.hisp.dhis.common.DimensionalItemObject;
import org.hisp.dhis.constant.Constant;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.indicator.IndicatorValue;
import org.hisp.dhis.organisationunit.OrganisationUnitGroup;
import org.hisp.dhis.period.Period;
/**
* Expressions are mathematical formulas and can contain references to various
* elements.
*
* @author Margrethe Store
* @author Lars Helge Overland
* @author Jim Grace
*/
public interface ExpressionService
{
String ID = ExpressionService.class.getName();
String DAYS_DESCRIPTION = "[Number of days]";
String SYMBOL_DAYS = "[days]";
String SYMBOL_WILDCARD = "*";
String UID_EXPRESSION = "[a-zA-Z]\\w{10}";
String INT_EXPRESSION = "^(0|-?[1-9]\\d*)$";
// -------------------------------------------------------------------------
// Expression CRUD operations
// -------------------------------------------------------------------------
/**
* Adds a new Expression to the database.
*
* @param expression The Expression to add.
* @return The generated identifier for this Expression.
*/
long addExpression( Expression expression );
/**
* Updates an Expression.
*
* @param expression The Expression to update.
*/
void updateExpression( Expression expression );
/**
* Deletes an Expression from the database.
*
* @param expression the expression.
*/
void deleteExpression( Expression expression );
/**
* Get the Expression with the given identifier.
*
* @param id The identifier.
* @return an Expression with the given identifier.
*/
Expression getExpression( long id );
/**
* Gets all Expressions.
*
* @return A list with all Expressions.
*/
List<Expression> getAllExpressions();
// -------------------------------------------------------------------------
// Indicator expression logic
// -------------------------------------------------------------------------
/**
* Returns all dimensional item objects which are present in numerator and
* denominator of the given indicators, as a map from id to object.
*
* @param indicators the collection of indicators.
* @return a map from dimensional item id to object.
*/
Map<DimensionalItemId, DimensionalItemObject> getIndicatorDimensionalItemMap( Collection<Indicator> indicators );
/**
* Returns all OrganisationUnitGroups in the numerator and denominator
* expressions in the given Indicators. Returns an empty set if the given
* indicators are null or empty.
*
* @param indicators the set of indicators.
* @return a Set of OrganisationUnitGroups.
*/
List<OrganisationUnitGroup> getOrgUnitGroupCountGroups( Collection<Indicator> indicators );
/**
* Generates the calculated value for the given parameters based on the
* values in the given maps.
*
* @param indicator the indicator for which to calculate the value.
* @param periods a List of periods for which to calculate the value.
* @param itemMap map of dimensional item id to object in expression.
* @param valueMap the map of data values.
* @param orgUnitCountMap the map of organisation unit group member counts.
* @return the calculated value as a double.
*/
IndicatorValue getIndicatorValueObject( Indicator indicator, List<Period> periods,
Map<DimensionalItemId, DimensionalItemObject> itemMap, Map<DimensionalItemObject, Object> valueMap,
Map<String, Integer> orgUnitCountMap );
/**
* Substitutes any constants and org unit group member counts in the
* numerator and denominator on all indicators in the given collection.
*
* @param indicators the set of indicators.
*/
void substituteIndicatorExpressions( Collection<Indicator> indicators );
// -------------------------------------------------------------------------
// Get information about the expression
// -------------------------------------------------------------------------
/**
* Tests whether the expression is valid.
*
* @param expression the expression string.
* @param parseType the type of expression to parse.
* @return the ExpressionValidationOutcome of the validation.
*/
ExpressionValidationOutcome expressionIsValid( String expression, ParseType parseType );
/**
* Creates an expression description containing the names of the
* DimensionalItemObjects from a numeric valued expression.
*
* @param expression the expression string.
* @param parseType the type of expression to parse.
* @return An description containing DimensionalItemObjects names.
*/
String getExpressionDescription( String expression, ParseType parseType );
/**
* Creates an expression description containing the names of the
* DimensionalItemObjects from an expression string, for an expression that
* will return the specified data type.
*
* @param expression the expression string.
* @param parseType the type of expression to parse.
* @param dataType the data type for the expression to return.
* @return An description containing DimensionalItemObjects names.
*/
String getExpressionDescription( String expression, ParseType parseType, DataType dataType );
/**
* Gets information we need from an expression string.
*
* @param params the expression parameters.
* @return the expression information.
*/
ExpressionInfo getExpressionInfo( ExpressionParams params );
/**
* From expression info, create a "base" expression parameters object with
* certain metadata fields supplied that are needed for later evaluation.
* <p>
* Before evaluation, the caller will need to add to this "base" object
* fields such as expression, parseType, dataType, valueMap, etc.
*
* @param info the expression information.
* @return the expression parameters with metadata pre-filled.
*/
ExpressionParams getBaseExpressionParams( ExpressionInfo info );
/**
* Returns UIDs of Data Elements and associated Option Combos (if any) found
* in the Data Element Operands an expression.
* <p/>
* If the Data Element Operand consists of just a Data Element, or if the
* Option Combo is a wildcard "*", returns just dataElementUID.
* <p/>
* If an Option Combo is present, returns dataElementUID.optionComboUID.
*
* @param expression the expression string.
* @param parseType the type of expression to parse.
* @return a Set of data element identifiers.
*/
Set<String> getExpressionElementAndOptionComboIds( String expression, ParseType parseType );
/**
* Returns all data elements found in the given expression string, including
* those found in data element operands. Returns an empty set if the given
* expression is null.
*
* @param expression the expression string.
* @param parseType the type of expression to parse.
* @return a Set of data elements included in the expression string.
*/
Set<DataElement> getExpressionDataElements( String expression, ParseType parseType );
/**
* Returns all CategoryOptionCombo uids in the given expression string that
* are used as a data element operand categoryOptionCombo or
* attributeOptionCombo. Returns an empty set if the expression is null.
*
* @param expression the expression string.
* @param parseType the type of expression to parse.
* @return a Set of CategoryOptionCombo uids in the expression string.
*/
Set<String> getExpressionOptionComboIds( String expression, ParseType parseType );
/**
* Returns all dimensional item object ids in the given expression.
*
* @param expression the expression string.
* @param parseType the type of expression to parse.
* @return a Set of dimensional item object ids.
*/
Set<DimensionalItemId> getExpressionDimensionalItemIds( String expression, ParseType parseType );
/**
* Returns set of all OrganisationUnitGroup UIDs in the given expression.
*
* @param expression the expression string.
* @param parseType the type of expression to parse.
* @return Map of UIDs to OrganisationUnitGroups in the expression string.
*/
Set<String> getExpressionOrgUnitGroupIds( String expression, ParseType parseType );
// -------------------------------------------------------------------------
// Compute the value of the expression
// -------------------------------------------------------------------------
/**
* Generates the calculated value for an expression.
*
* @param params the expression parameters.
* @return the calculated value.
*/
Object getExpressionValue( ExpressionParams params );
// -------------------------------------------------------------------------
// Gets a (possibly cached) constant map
// -------------------------------------------------------------------------
/**
* Gets the (possibly cached) constant map.
*
* @return the constant map.
*/
Map<String, Constant> getConstantMap();
}
| bsd-3-clause |
chinmaygarde/flutter_engine | shell/platform/android/test/io/flutter/embedding/engine/mutatorsstack/FlutterMutatorViewTest.java | 3135 | package io.flutter.embedding.engine.mutatorsstack;
import static junit.framework.TestCase.*;
import static org.mockito.Mockito.*;
import android.graphics.Matrix;
import android.view.MotionEvent;
import io.flutter.embedding.android.AndroidTouchProcessor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class FlutterMutatorViewTest {
@Test
public void canDragViews() {
final AndroidTouchProcessor touchProcessor = mock(AndroidTouchProcessor.class);
final FlutterMutatorView view =
new FlutterMutatorView(RuntimeEnvironment.systemContext, 1.0f, touchProcessor);
final FlutterMutatorsStack mutatorStack = mock(FlutterMutatorsStack.class);
assertTrue(view.onInterceptTouchEvent(mock(MotionEvent.class)));
{
view.readyToDisplay(mutatorStack, /*left=*/ 1, /*top=*/ 2, /*width=*/ 0, /*height=*/ 0);
view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0));
final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class);
verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture());
final Matrix screenMatrix = new Matrix();
screenMatrix.postTranslate(1, 2);
assertTrue(matrixCaptor.getValue().equals(screenMatrix));
}
reset(touchProcessor);
{
view.readyToDisplay(mutatorStack, /*left=*/ 3, /*top=*/ 4, /*width=*/ 0, /*height=*/ 0);
view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0));
final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class);
verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture());
final Matrix screenMatrix = new Matrix();
screenMatrix.postTranslate(1, 2);
assertTrue(matrixCaptor.getValue().equals(screenMatrix));
}
reset(touchProcessor);
{
view.readyToDisplay(mutatorStack, /*left=*/ 5, /*top=*/ 6, /*width=*/ 0, /*height=*/ 0);
view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0));
final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class);
verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture());
final Matrix screenMatrix = new Matrix();
screenMatrix.postTranslate(3, 4);
assertTrue(matrixCaptor.getValue().equals(screenMatrix));
}
reset(touchProcessor);
{
view.readyToDisplay(mutatorStack, /*left=*/ 7, /*top=*/ 8, /*width=*/ 0, /*height=*/ 0);
view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0));
final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class);
verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture());
final Matrix screenMatrix = new Matrix();
screenMatrix.postTranslate(7, 8);
assertTrue(matrixCaptor.getValue().equals(screenMatrix));
}
}
}
| bsd-3-clause |
uonafya/jphes-core | dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/AdxDataSetMetadata.java | 4017 | package org.hisp.dhis.dxf2.adx;
/*
* Copyright (c) 2015, UiO
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.xerces.util.XMLChar;
import org.hisp.dhis.dataelement.DataElementCategory;
import org.hisp.dhis.dataelement.DataElementCategoryCombo;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dataset.DataSetElement;
/**
* @author bobj
*/
public class AdxDataSetMetadata
{
// Lookup category options per cat option combo
private final Map<Integer, Map<String, String>> categoryOptionMap;
AdxDataSetMetadata( DataSet dataSet )
throws AdxException
{
categoryOptionMap = new HashMap<>();
Set<DataElementCategoryCombo> catCombos = new HashSet<>();
catCombos.add( dataSet.getCategoryCombo() );
for ( DataSetElement element : dataSet.getDataSetElements() )
{
catCombos.add( element.getResolvedCategoryCombo() );
}
for ( DataElementCategoryCombo categoryCombo : catCombos )
{
for ( DataElementCategoryOptionCombo catOptCombo : categoryCombo.getOptionCombos() )
{
addExplodedCategoryAttributes( catOptCombo );
}
}
}
private void addExplodedCategoryAttributes( DataElementCategoryOptionCombo coc )
throws AdxException
{
Map<String, String> categoryAttributes = new HashMap<>();
if ( !coc.isDefault() )
{
for ( DataElementCategory category : coc.getCategoryCombo().getCategories() )
{
String categoryCode = category.getCode();
if ( categoryCode == null || !XMLChar.isValidName( categoryCode ) )
{
throw new AdxException(
"Category code for " + category.getName() + " is missing or invalid: " + categoryCode );
}
String catOptCode = category.getCategoryOption( coc ).getCode();
if ( catOptCode == null || catOptCode.isEmpty() )
{
throw new AdxException(
"CategoryOption code for " + category.getCategoryOption( coc ).getName() + " is missing" );
}
categoryAttributes.put( categoryCode, catOptCode );
}
}
categoryOptionMap.put( coc.getId(), categoryAttributes );
}
public Map<String, String> getExplodedCategoryAttributes( int cocId )
{
return this.categoryOptionMap.get( cocId );
}
}
| bsd-3-clause |
mbosecke/pebble | pebble/src/main/java/com/mitchellbosecke/pebble/extension/AbstractExtension.java | 1366 | /*
* This file is part of Pebble.
*
* Copyright (c) 2014 by Mitchell Bösecke
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.mitchellbosecke.pebble.extension;
import com.mitchellbosecke.pebble.attributes.AttributeResolver;
import com.mitchellbosecke.pebble.operator.BinaryOperator;
import com.mitchellbosecke.pebble.operator.UnaryOperator;
import com.mitchellbosecke.pebble.tokenParser.TokenParser;
import java.util.List;
import java.util.Map;
public abstract class AbstractExtension implements Extension {
@Override
public List<TokenParser> getTokenParsers() {
return null;
}
@Override
public List<BinaryOperator> getBinaryOperators() {
return null;
}
@Override
public List<UnaryOperator> getUnaryOperators() {
return null;
}
@Override
public Map<String, Filter> getFilters() {
return null;
}
@Override
public Map<String, Test> getTests() {
return null;
}
@Override
public Map<String, Function> getFunctions() {
return null;
}
@Override
public Map<String, Object> getGlobalVariables() {
return null;
}
@Override
public List<NodeVisitorFactory> getNodeVisitors() {
return null;
}
@Override
public List<AttributeResolver> getAttributeResolver() {
return null;
}
}
| bsd-3-clause |
strahanjen/strahanjen.github.io | elasticsearch-master/core/src/test/java/org/elasticsearch/cluster/routing/allocation/CatAllocationTestCase.java | 8869 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.cluster.routing.allocation;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.cluster.routing.TestShardRouting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.cluster.ESAllocationTestCase;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING;
/**
* A base testcase that allows to run tests based on the output of the CAT API
* The input is a line based cat/shards output like:
* kibana-int 0 p STARTED 2 24.8kb 10.202.245.2 r5-9-35
*
* the test builds up a clusterstate from the cat input and optionally runs a full balance on it.
* This can be used to debug cluster allocation decisions.
*/
public abstract class CatAllocationTestCase extends ESAllocationTestCase {
protected abstract Path getCatPath() throws IOException;
public void testRun() throws IOException {
Set<String> nodes = new HashSet<>();
Map<String, Idx> indices = new HashMap<>();
try (BufferedReader reader = Files.newBufferedReader(getCatPath(), StandardCharsets.UTF_8)) {
String line = null;
// regexp FTW
Pattern pattern = Pattern.compile("^(.+)\\s+(\\d)\\s+([rp])\\s+(STARTED|RELOCATING|INITIALIZING|UNASSIGNED)" +
"\\s+\\d+\\s+[0-9.a-z]+\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+).*$");
while((line = reader.readLine()) != null) {
final Matcher matcher;
if ((matcher = pattern.matcher(line)).matches()) {
final String index = matcher.group(1);
Idx idx = indices.get(index);
if (idx == null) {
idx = new Idx(index);
indices.put(index, idx);
}
final int shard = Integer.parseInt(matcher.group(2));
final boolean primary = matcher.group(3).equals("p");
ShardRoutingState state = ShardRoutingState.valueOf(matcher.group(4));
String ip = matcher.group(5);
nodes.add(ip);
ShardRouting routing = TestShardRouting.newShardRouting(index, shard, ip, null, primary, state);
idx.add(routing);
logger.debug("Add routing {}", routing);
} else {
fail("can't read line: " + line);
}
}
}
logger.info("Building initial routing table");
MetaData.Builder builder = MetaData.builder();
RoutingTable.Builder routingTableBuilder = RoutingTable.builder();
for(Idx idx : indices.values()) {
IndexMetaData.Builder idxMetaBuilder = IndexMetaData.builder(idx.name).settings(settings(Version.CURRENT))
.numberOfShards(idx.numShards()).numberOfReplicas(idx.numReplicas());
for (ShardRouting shardRouting : idx.routing) {
if (shardRouting.active()) {
Set<String> allocationIds = idxMetaBuilder.getInSyncAllocationIds(shardRouting.id());
if (allocationIds == null) {
allocationIds = new HashSet<>();
} else {
allocationIds = new HashSet<>(allocationIds);
}
allocationIds.add(shardRouting.allocationId().getId());
idxMetaBuilder.putInSyncAllocationIds(shardRouting.id(), allocationIds);
}
}
IndexMetaData idxMeta = idxMetaBuilder.build();
builder.put(idxMeta, false);
IndexRoutingTable.Builder tableBuilder = new IndexRoutingTable.Builder(idxMeta.getIndex()).initializeAsRecovery(idxMeta);
Map<Integer, IndexShardRoutingTable> shardIdToRouting = new HashMap<>();
for (ShardRouting r : idx.routing) {
IndexShardRoutingTable refData = new IndexShardRoutingTable.Builder(r.shardId()).addShard(r).build();
if (shardIdToRouting.containsKey(r.getId())) {
refData = new IndexShardRoutingTable.Builder(shardIdToRouting.get(r.getId())).addShard(r).build();
}
shardIdToRouting.put(r.getId(), refData);
}
for (IndexShardRoutingTable t: shardIdToRouting.values()) {
tableBuilder.addIndexShard(t);
}
IndexRoutingTable table = tableBuilder.build();
routingTableBuilder.add(table);
}
MetaData metaData = builder.build();
RoutingTable routingTable = routingTableBuilder.build();
DiscoveryNodes.Builder builderDiscoNodes = DiscoveryNodes.builder();
for (String node : nodes) {
builderDiscoNodes.add(newNode(node));
}
ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.CLUSTER_NAME_SETTING
.getDefault(Settings.EMPTY)).metaData(metaData).routingTable(routingTable).nodes(builderDiscoNodes.build()).build();
if (balanceFirst()) {
clusterState = rebalance(clusterState);
}
clusterState = allocateNew(clusterState);
}
protected abstract ClusterState allocateNew(ClusterState clusterState);
protected boolean balanceFirst() {
return true;
}
private ClusterState rebalance(ClusterState clusterState) {
RoutingTable routingTable;AllocationService strategy = createAllocationService(Settings.builder()
.build());
RoutingAllocation.Result routingResult = strategy.reroute(clusterState, "reroute");
clusterState = ClusterState.builder(clusterState).routingResult(routingResult).build();
int numRelocations = 0;
while (true) {
List<ShardRouting> initializing = clusterState.routingTable().shardsWithState(INITIALIZING);
if (initializing.isEmpty()) {
break;
}
logger.debug("Initializing shards: {}", initializing);
numRelocations += initializing.size();
routingResult = strategy.applyStartedShards(clusterState, initializing);
clusterState = ClusterState.builder(clusterState).routingResult(routingResult).build();
}
logger.debug("--> num relocations to get balance: {}", numRelocations);
return clusterState;
}
public class Idx {
final String name;
final List<ShardRouting> routing = new ArrayList<>();
public Idx(String name) {
this.name = name;
}
public void add(ShardRouting r) {
routing.add(r);
}
public int numReplicas() {
int count = 0;
for (ShardRouting msr : routing) {
if (msr.primary() == false && msr.id()==0) {
count++;
}
}
return count;
}
public int numShards() {
int max = 0;
for (ShardRouting msr : routing) {
if (msr.primary()) {
max = Math.max(msr.getId()+1, max);
}
}
return max;
}
}
}
| bsd-3-clause |
pscadiz/pmd-4.2.6-gds | src/net/sourceforge/pmd/rules/design/NullAssignmentRule.java | 2343 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.rules.design;
import net.sourceforge.pmd.AbstractRule;
import net.sourceforge.pmd.ast.ASTAssignmentOperator;
import net.sourceforge.pmd.ast.ASTConditionalExpression;
import net.sourceforge.pmd.ast.ASTEqualityExpression;
import net.sourceforge.pmd.ast.ASTExpression;
import net.sourceforge.pmd.ast.ASTName;
import net.sourceforge.pmd.ast.ASTNullLiteral;
import net.sourceforge.pmd.ast.ASTStatementExpression;
import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
// TODO - should check that this is not the first assignment. e.g., this is OK:
// Object x;
// x = null;
public class NullAssignmentRule extends AbstractRule {
public Object visit(ASTNullLiteral node, Object data) {
if (node.getNthParent(5) instanceof ASTStatementExpression) {
ASTStatementExpression n = (ASTStatementExpression) node.getNthParent(5);
if (isAssignmentToFinalField(n)) {
return data;
}
if (n.jjtGetNumChildren() > 2 && n.jjtGetChild(1) instanceof ASTAssignmentOperator) {
addViolation(data, node);
}
} else if (node.getNthParent(4) instanceof ASTConditionalExpression) {
// "false" expression of ternary
if (isBadTernary((ASTConditionalExpression)node.getNthParent(4))) {
addViolation(data, node);
}
} else if (node.getNthParent(5) instanceof ASTConditionalExpression && node.getNthParent(4) instanceof ASTExpression) {
// "true" expression of ternary
if (isBadTernary((ASTConditionalExpression)node.getNthParent(5))) {
addViolation(data, node);
}
}
return data;
}
private boolean isAssignmentToFinalField(ASTStatementExpression n) {
ASTName name = n.getFirstChildOfType(ASTName.class);
return name != null
&& name.getNameDeclaration() instanceof VariableNameDeclaration
&& ((VariableNameDeclaration) name.getNameDeclaration()).getAccessNodeParent().isFinal();
}
private boolean isBadTernary(ASTConditionalExpression n) {
return n.isTernary() && !(n.jjtGetChild(0) instanceof ASTEqualityExpression);
}
}
| bsd-3-clause |
luminousfennell/jgs | DynamicAnalyzer/src/main/java/testclasses/PrintMediumSuccess.java | 430 | package testclasses;
import de.unifreiburg.cs.proglang.jgs.support.DynamicLabel;
import util.printer.SecurePrinter;
public class PrintMediumSuccess {
public static void main(String[] args) {
String med = "This is medium information";
med = DynamicLabel.makeMedium(med);
SecurePrinter.printMedium(med);
String low = "This is low information";
low = DynamicLabel.makeLow(low);
SecurePrinter.printMedium(low);
}
}
| bsd-3-clause |
eheydemann/PaperOrPlastic | PaperOrPlasticApp/app/src/test/java/edu/pacificu/cs493f15_1/paperorplasticapp/ExampleUnitTest.java | 326 | package edu.pacificu.cs493f15_1.paperorplasticapp;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest
{
@Test
public void addition_isCorrect() throws Exception
{
assertEquals(4, 2 + 2);
}
} | mit |
slaymaker1907/HearthSim | src/test/java/com/hearthsim/test/minion/TestAbomination.java | 11770 | package com.hearthsim.test.minion;
import com.hearthsim.card.Card;
import com.hearthsim.card.CharacterIndex;
import com.hearthsim.card.basic.minion.BoulderfistOgre;
import com.hearthsim.card.basic.minion.RaidLeader;
import com.hearthsim.card.classic.minion.common.ScarletCrusader;
import com.hearthsim.card.classic.minion.rare.Abomination;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.exception.HSException;
import com.hearthsim.model.BoardModel;
import com.hearthsim.model.PlayerModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.tree.HearthTreeNode;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestAbomination {
private HearthTreeNode board;
private PlayerModel currentPlayer;
private PlayerModel waitingPlayer;
@Before
public void setup() throws HSException {
board = new HearthTreeNode(new BoardModel());
currentPlayer = board.data_.getCurrentPlayer();
waitingPlayer = board.data_.getWaitingPlayer();
board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new RaidLeader());
board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new BoulderfistOgre());
board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new ScarletCrusader());
board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new RaidLeader());
board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new BoulderfistOgre());
Card fb = new Abomination();
currentPlayer.placeCardHand(fb);
currentPlayer.setMana((byte) 8);
waitingPlayer.setMana((byte) 8);
}
@Test
public void test0() throws HSException {
Card theCard = currentPlayer.getHand().get(0);
HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, CharacterIndex.HERO, board);
assertNull(ret);
assertEquals(currentPlayer.getHand().size(), 1);
assertEquals(currentPlayer.getNumMinions(), 2);
assertEquals(waitingPlayer.getNumMinions(), 3);
assertEquals(currentPlayer.getMana(), 8);
assertEquals(waitingPlayer.getMana(), 8);
assertEquals(currentPlayer.getHero().getHealth(), 30);
assertEquals(waitingPlayer.getHero().getHealth(), 30);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7);
assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield());
}
@Test
public void test1() throws HSException {
Card theCard = currentPlayer.getHand().get(0);
HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, CharacterIndex.HERO, board);
assertFalse(ret == null);
assertEquals(currentPlayer.getHand().size(), 0);
assertEquals(currentPlayer.getNumMinions(), 3);
assertEquals(waitingPlayer.getNumMinions(), 3);
assertEquals(currentPlayer.getMana(), 3);
assertEquals(waitingPlayer.getMana(), 8);
assertEquals(currentPlayer.getHero().getHealth(), 30);
assertEquals(waitingPlayer.getHero().getHealth(), 30);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 4);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 5);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7);
assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield());
}
@Test
public void test2() throws HSException {
Card theCard = currentPlayer.getHand().get(0);
HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, CharacterIndex.HERO, board);
assertFalse(ret == null);
assertEquals(currentPlayer.getHand().size(), 0);
assertEquals(currentPlayer.getNumMinions(), 3);
assertEquals(waitingPlayer.getNumMinions(), 3);
assertEquals(currentPlayer.getMana(), 3);
assertEquals(waitingPlayer.getMana(), 8);
assertEquals(currentPlayer.getHero().getHealth(), 30);
assertEquals(waitingPlayer.getHero().getHealth(), 30);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalHealth(), 4);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalHealth(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalHealth(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalHealth(), 1);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalHealth(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalHealth(), 7);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 5);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7);
assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield());
//attack the Ogre... should kill everything except the Scarlet Crusader
Minion attacker = currentPlayer.getCharacter(CharacterIndex.MINION_1);
attacker.hasAttacked(false);
ret = attacker.attack(PlayerSide.WAITING_PLAYER, CharacterIndex.MINION_3, ret);
assertFalse(ret == null);
assertEquals(currentPlayer.getHand().size(), 0);
assertEquals(currentPlayer.getNumMinions(), 1);
assertEquals(waitingPlayer.getNumMinions(), 1);
assertEquals(currentPlayer.getMana(), 3);
assertEquals(waitingPlayer.getMana(), 8);
assertEquals(currentPlayer.getHero().getHealth(), 28);
assertEquals(waitingPlayer.getHero().getHealth(), 28);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 5);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 6);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 3);
assertFalse(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield());
}
@Test
public void test3() throws HSException {
Card theCard = currentPlayer.getHand().get(0);
HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, CharacterIndex.HERO, board);
assertFalse(ret == null);
assertEquals(currentPlayer.getHand().size(), 0);
assertEquals(currentPlayer.getNumMinions(), 3);
assertEquals(waitingPlayer.getNumMinions(), 3);
assertEquals(currentPlayer.getMana(), 3);
assertEquals(waitingPlayer.getMana(), 8);
assertEquals(currentPlayer.getHero().getHealth(), 30);
assertEquals(waitingPlayer.getHero().getHealth(), 30);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 4);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 5);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7);
assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield());
//Silence the Abomination first, then attack with it
Minion attacker = currentPlayer.getCharacter(CharacterIndex.MINION_1);
attacker.silenced(PlayerSide.CURRENT_PLAYER, board);
attacker.hasAttacked(false);
attacker.attack(PlayerSide.WAITING_PLAYER, CharacterIndex.MINION_3, ret);
assertEquals(currentPlayer.getHand().size(), 0);
assertEquals(currentPlayer.getNumMinions(), 2);
assertEquals(waitingPlayer.getNumMinions(), 3);
assertEquals(currentPlayer.getMana(), 3);
assertEquals(waitingPlayer.getMana(), 8);
assertEquals(currentPlayer.getHero().getHealth(), 30);
assertEquals(waitingPlayer.getHero().getHealth(), 30);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 2);
assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 7);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2);
assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7);
assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield());
}
}
| mit |
chenDoInG/jenkins | core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java | 2868 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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 hudson.node_monitors;
import hudson.Extension;
import hudson.FilePath;
import hudson.Functions;
import hudson.model.Computer;
import hudson.remoting.Callable;
import jenkins.model.Jenkins;
import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.IOException;
import java.text.ParseException;
/**
* Checks available disk space of the remote FS root.
* Requires Mustang.
*
* @author Kohsuke Kawaguchi
* @since 1.123
*/
public class DiskSpaceMonitor extends AbstractDiskSpaceMonitor {
@DataBoundConstructor
public DiskSpaceMonitor(String freeSpaceThreshold) throws ParseException {
super(freeSpaceThreshold);
}
public DiskSpaceMonitor() {}
public DiskSpace getFreeSpace(Computer c) {
return DESCRIPTOR.get(c);
}
@Override
public String getColumnCaption() {
// Hide this column from non-admins
return Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER) ? super.getColumnCaption() : null;
}
public static final DiskSpaceMonitorDescriptor DESCRIPTOR = new DiskSpaceMonitorDescriptor() {
public String getDisplayName() {
return Messages.DiskSpaceMonitor_DisplayName();
}
@Override
protected Callable<DiskSpace, IOException> createCallable(Computer c) {
FilePath p = c.getNode().getRootPath();
if(p==null) return null;
return p.asCallableWith(new GetUsableSpace());
}
};
@Extension
public static DiskSpaceMonitorDescriptor install() {
if(Functions.isMustangOrAbove()) return DESCRIPTOR;
return null;
}
}
| mit |
openshopio/openshop.io-android | app/src/main/java/bf/io/openshop/entities/Page.java | 1413 | package bf.io.openshop.entities;
public class Page {
private long id;
private String title;
private String text;
public Page() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Page page = (Page) o;
if (id != page.id) return false;
if (title != null ? !title.equals(page.title) : page.title != null) return false;
return !(text != null ? !text.equals(page.text) : page.text != null);
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (text != null ? text.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Page{" +
"id=" + id +
", title='" + title + '\'' +
", text='" + text + '\'' +
'}';
}
}
| mit |
oleg-nenashev/jenkins | core/src/test/java/hudson/model/LoadStatisticsTest.java | 4339 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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 hudson.model;
import hudson.model.MultiStageTimeSeries.TimeScale;
import hudson.model.queue.SubTask;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import org.jfree.chart.JFreeChart;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Kohsuke Kawaguchi
*/
public class LoadStatisticsTest {
@Test
public void graph() throws IOException {
LoadStatistics ls = new LoadStatistics(0, 0) {
public int computeIdleExecutors() {
throw new UnsupportedOperationException();
}
public int computeTotalExecutors() {
throw new UnsupportedOperationException();
}
public int computeQueueLength() {
throw new UnsupportedOperationException();
}
@Override
protected Iterable<Node> getNodes() {
throw new UnsupportedOperationException();
}
@Override
protected boolean matches(Queue.Item item, SubTask subTask) {
throw new UnsupportedOperationException();
}
};
for (int i = 0; i < 50; i++) {
ls.onlineExecutors.update(4);
ls.busyExecutors.update(3);
ls.availableExecutors.update(1);
ls.queueLength.update(3);
}
for (int i = 0; i < 50; i++) {
ls.onlineExecutors.update(0);
ls.busyExecutors.update(0);
ls.availableExecutors.update(0);
ls.queueLength.update(1);
}
JFreeChart chart = ls.createTrendChart(TimeScale.SEC10).createChart();
BufferedImage image = chart.createBufferedImage(400, 200);
File tempFile = File.createTempFile("chart-", "png");
try (OutputStream os = Files.newOutputStream(tempFile.toPath(), StandardOpenOption.DELETE_ON_CLOSE)) {
ImageIO.write(image, "PNG", os);
} finally {
tempFile.delete();
}
}
@Test
public void isModernWorks() throws Exception {
assertThat(LoadStatistics.isModern(Modern.class), is(true));
assertThat(LoadStatistics.isModern(LoadStatistics.class), is(false));
}
private static class Modern extends LoadStatistics {
protected Modern(int initialOnlineExecutors, int initialBusyExecutors) {
super(initialOnlineExecutors, initialBusyExecutors);
}
@Override
public int computeIdleExecutors() {
return 0;
}
@Override
public int computeTotalExecutors() {
return 0;
}
@Override
public int computeQueueLength() {
return 0;
}
@Override
protected Iterable<Node> getNodes() {
return null;
}
@Override
protected boolean matches(Queue.Item item, SubTask subTask) {
return false;
}
}
}
| mit |
Yashi100/rhodes3.3.2 | platform/bb/RubyVM/src/com/xruby/runtime/lang/RubyConstant.java | 802 | package com.xruby.runtime.lang;
public abstract class RubyConstant extends RubyBasic {
public static RubyConstant QFALSE = new RubyConstant(RubyRuntime.FalseClassClass) {
public boolean isTrue() {
return false;
}
};
public static RubyConstant QTRUE = new RubyConstant(RubyRuntime.TrueClassClass) {
public boolean isTrue() {
return true;
}
};
public static RubyConstant QNIL = new RubyConstant(RubyRuntime.NilClassClass) {
public boolean isTrue() {
return false;
}
public String toStr() {
throw new RubyException(RubyRuntime.TypeErrorClass, "Cannot convert nil into String");
}
};
private RubyConstant(RubyClass c) {
super(c);
}
}
| mit |
diegocedrim/organic | test/br/pucrio/opus/smells/tests/visitor/FieldDeclarationCollectorTest.java | 1022 | package br.pucrio.opus.smells.tests.visitor;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import br.pucrio.opus.smells.ast.visitors.FieldDeclarationCollector;
import br.pucrio.opus.smells.tests.util.CompilationUnitLoader;
public class FieldDeclarationCollectorTest {
private CompilationUnit compilationUnit;
@Before
public void setUp() throws IOException{
File file = new File("test/br/pucrio/opus/smells/tests/dummy/FieldDeclaration.java");
this.compilationUnit = CompilationUnitLoader.getCompilationUnit(file);
}
@Test
public void allFieldsCollectionCountTest() {
FieldDeclarationCollector visitor = new FieldDeclarationCollector();
this.compilationUnit.accept(visitor);
List<FieldDeclaration> collectedFields = visitor.getNodesCollected();
Assert.assertEquals(6, collectedFields.size());
}
}
| mit |
sarhanm/jsondoc | jsondoc-core/src/test/java/org/jsondoc/core/issues/issue151/FooController.java | 612 | package org.jsondoc.core.issues.issue151;
import org.jsondoc.core.annotation.Api;
import org.jsondoc.core.annotation.ApiMethod;
import org.jsondoc.core.annotation.ApiResponseObject;
@Api(name = "Foo Services", description = "bla, bla, bla ...", group = "foogroup")
public class FooController {
@ApiMethod(path = { "/api/foo" }, description = "Main foo service")
@ApiResponseObject
public FooWrapper<BarPojo> getBar() {
return null;
}
@ApiMethod(path = { "/api/foo-wildcard" }, description = "Main foo service with wildcard")
@ApiResponseObject
public FooWrapper<?> wildcard() {
return null;
}
} | mit |
sanmubird/yuanjihua_blog | src/main/java/com/tale/model/Comments.java | 2962 | package com.tale.model;
import com.blade.jdbc.annotation.Table;
import java.io.Serializable;
//
@Table(name = "t_comments", pk = "coid")
public class Comments implements Serializable {
private static final long serialVersionUID = 1L;
// comment表主键
private Integer coid;
// post表主键,关联字段
private Integer cid;
// 评论生成时的GMT unix时间戳
private Integer created;
// 评论作者
private String author;
// 评论所属用户id
private Integer author_id;
// 评论所属内容作者id
private Integer owner_id;
// 评论者邮件
private String mail;
// 评论者网址
private String url;
// 评论者ip地址
private String ip;
// 评论者客户端
private String agent;
// 评论内容
private String content;
// 评论类型
private String type;
// 评论状态
private String status;
// 父级评论
private Integer parent;
public Comments() {
}
public Integer getCoid() {
return coid;
}
public void setCoid(Integer coid) {
this.coid = coid;
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public Integer getCreated() {
return created;
}
public void setCreated(Integer created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getAgent() {
return agent;
}
public void setAgent(String agent) {
this.agent = agent;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getParent() {
return parent;
}
public void setParent(Integer parent) {
this.parent = parent;
}
public Integer getAuthor_id() {
return author_id;
}
public void setAuthor_id(Integer author_id) {
this.author_id = author_id;
}
public Integer getOwner_id() {
return owner_id;
}
public void setOwner_id(Integer owner_id) {
this.owner_id = owner_id;
}
} | mit |
goose2460/game_author_cs308 | src/engine/actions/FixedCollisionTypeAction.java | 989 | package engine.actions;
import engine.gameObject.GameObject;
import authoring.model.collections.GameObjectsCollection;
public class FixedCollisionTypeAction extends PhysicsTypeAction {
public FixedCollisionTypeAction (String type, String secondType, Double value) {
super(type, secondType, value);
// TODO Auto-generated constructor stub
}
@Override
public void applyPhysics (GameObjectsCollection myObjects) {
GameObject firstCollisionObject = null;
GameObject secondCollisionObject = null;
for (GameObject g : myObjects){
if (g.getIdentifier().getType().equals(myType) && g.isCollisionEnabled()){
firstCollisionObject = g;
}
if (g.getIdentifier().getType().equals(mySecondType) && g.isCollisionEnabled()){
secondCollisionObject = g;
}
}
myCollision.fixedCollision(firstCollisionObject, secondCollisionObject);
}
}
| mit |
jvm-bloggers/jvm-bloggers | src/main/java/com/jvm_bloggers/core/data_fetching/blog_posts/BlogPostsFetcher.java | 2766 | package com.jvm_bloggers.core.data_fetching.blog_posts;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.routing.RoundRobinPool;
import com.jvm_bloggers.core.data_fetching.blogs.PreventConcurrentExecutionSafeguard;
import com.jvm_bloggers.core.rss.SyndFeedProducer;
import com.jvm_bloggers.entities.blog.Blog;
import com.jvm_bloggers.entities.blog.BlogRepository;
import com.jvm_bloggers.entities.metadata.Metadata;
import com.jvm_bloggers.entities.metadata.MetadataKeys;
import com.jvm_bloggers.entities.metadata.MetadataRepository;
import com.jvm_bloggers.utils.NowProvider;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
@NoArgsConstructor
public class BlogPostsFetcher {
private BlogRepository blogRepository;
private ActorRef rssCheckingActor;
private MetadataRepository metadataRepository;
private NowProvider nowProvider;
private PreventConcurrentExecutionSafeguard concurrentExecutionSafeguard
= new PreventConcurrentExecutionSafeguard();
@Autowired
public BlogPostsFetcher(ActorSystem actorSystem, BlogRepository blogRepository,
BlogPostService blogPostService,
SyndFeedProducer syndFeedFactory,
MetadataRepository metadataRepository,
NowProvider nowProvider) {
this.blogRepository = blogRepository;
final ActorRef blogPostStoringActor = actorSystem
.actorOf(NewBlogPostStoringActor.props(blogPostService));
rssCheckingActor = actorSystem.actorOf(new RoundRobinPool(10)
.props(RssCheckingActor.props(blogPostStoringActor, syndFeedFactory)), "rss-checkers");
this.metadataRepository = metadataRepository;
this.nowProvider = nowProvider;
}
void refreshPosts() {
concurrentExecutionSafeguard.preventConcurrentExecution(this::startFetchingProcess);
}
@Async("singleThreadExecutor")
public void refreshPostsAsynchronously() {
refreshPosts();
}
private Void startFetchingProcess() {
blogRepository.findAllActiveBlogs()
.filter(Blog::isActive)
.forEach(person -> rssCheckingActor.tell(new RssLink(person), ActorRef.noSender()));
final Metadata dateOfLastFetch = metadataRepository
.findByName(MetadataKeys.DATE_OF_LAST_FETCHING_BLOG_POSTS);
dateOfLastFetch.setValue(nowProvider.now().toString());
metadataRepository.save(dateOfLastFetch);
return null;
}
public boolean isFetchingProcessInProgress() {
return concurrentExecutionSafeguard.isExecuting();
}
}
| mit |
china-zhuangxuxin/LKFramework | lichkin-springboot-demos/lichkin-springboot-demo-web/src/main/java/com/lichkin/framework/springboot/controllers/impl/LKDemoController.java | 1209 | package com.lichkin.framework.springboot.controllers.impl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.lichkin.framework.bases.LKDatas;
import com.lichkin.framework.bases.annotations.WithOutLogin;
import com.lichkin.framework.springboot.controllers.LKController;
/**
* 页面跳转逻辑
* @author SuZhou LichKin Information Technology Co., Ltd.
*/
@Controller
@RequestMapping(value = "/demo")
public class LKDemoController extends LKController {
/**
* 页面跳转
* @param requestDatas 请求参数,由框架自动解析请求的参数并注入。
* @param subUrl 子路径
* @return 页面路径,附带了请求参数及请求路径的相关信息。
*/
@WithOutLogin
@RequestMapping(value = "/{subUrl}.html", method = RequestMethod.GET)
public ModelAndView toGo(final LKDatas requestDatas, @PathVariable(value = "subUrl") final String subUrl) {
return getModelAndView(requestDatas);
}
}
| mit |
jife94/wwmmo | planet-render/src/au/com/codeka/planetrender/RayWarper.java | 2860 | package au.com.codeka.planetrender;
import java.util.Random;
import au.com.codeka.common.PerlinNoise;
import au.com.codeka.common.Vector2;
import au.com.codeka.common.Vector3;
/**
* This class takes a ray that's going in a certain direction and warps it based on a noise pattern. This is used
* to generate misshapen asteroid images, for example.
*/
public class RayWarper {
private NoiseGenerator mNoiseGenerator;
private double mWarpFactor;
public RayWarper(Template.WarpTemplate tmpl, Random rand) {
if (tmpl.getNoiseGenerator() == Template.WarpTemplate.NoiseGenerator.Perlin) {
mNoiseGenerator = new PerlinGenerator(tmpl, rand);
} else if (tmpl.getNoiseGenerator() == Template.WarpTemplate.NoiseGenerator.Spiral) {
mNoiseGenerator = new SpiralGenerator(tmpl, rand);
}
mWarpFactor = tmpl.getWarpFactor();
}
public void warp(Vector3 vec, double u, double v) {
mNoiseGenerator.warp(vec, u, v, mWarpFactor);
}
static abstract class NoiseGenerator {
protected double getNoise(double u, double v) {
return 0.0;
}
protected Vector3 getValue(double u, double v) {
double x = getNoise(u * 0.25, v * 0.25);
double y = getNoise(0.25 + u * 0.25, v * 0.25);
double z = getNoise(u * 0.25, 0.25 + v * 0.25);
return Vector3.pool.borrow().reset(x, y, z);
}
protected void warp(Vector3 vec, double u, double v, double factor) {
Vector3 warpVector = getValue(u, v);
warpVector.reset(warpVector.x * factor + (1.0 - factor),
warpVector.y * factor + (1.0 - factor),
warpVector.z * factor + (1.0 - factor));
vec.reset(vec.x * warpVector.x,
vec.y * warpVector.y,
vec.z * warpVector.z);
Vector3.pool.release(warpVector);
}
}
static class PerlinGenerator extends NoiseGenerator {
private PerlinNoise mNoise;
public PerlinGenerator(Template.WarpTemplate tmpl, Random rand) {
mNoise = new TemplatedPerlinNoise(tmpl.getParameter(Template.PerlinNoiseTemplate.class), rand);
}
@Override
public double getNoise(double u, double v) {
return mNoise.getNoise(u, v);
}
}
static class SpiralGenerator extends NoiseGenerator {
public SpiralGenerator(Template.WarpTemplate tmpl, Random rand) {
}
@Override
protected void warp(Vector3 vec, double u, double v, double factor) {
Vector2 uv = Vector2.pool.borrow().reset(u, v);
uv.rotate(factor * uv.length() * 2.0 * Math.PI * 2.0 / 360.0);
vec.reset(uv.x, -uv.y, 1.0);
Vector2.pool.release(uv);
}
}
}
| mit |
lounien/OApp | Alipay/src/test/java/cn/mutils/app/alipay/ExampleUnitTest.java | 313 | package cn.mutils.app.alipay;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
ex3ndr/telegram | app/src/main/java/org/telegram/android/views/dialog/ConversationListView.java | 13050 | package org.telegram.android.views.dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.AbsListView;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import org.telegram.android.R;
import org.telegram.android.TelegramApplication;
import org.telegram.android.log.Logger;
import org.telegram.android.ui.FontController;
import org.telegram.android.ui.TextUtil;
/**
* Created by ex3ndr on 15.11.13.
*/
public class ConversationListView extends ListView {
private static final String TAG = "ConversationListView";
private static final int DELTA = 26;
private static final long ANIMATION_DURATION = 200;
private static final int ACTIVATE_DELTA = 50;
private static final long UI_TIMEOUT = 900;
private TelegramApplication application;
private String visibleDate = null;
private int formattedVisibleDate = -1;
private int timeDivMeasure;
private String visibleDateNext = null;
private int formattedVisibleDateNext = -1;
private int timeDivMeasureNext;
private TextPaint timeDivPaint;
private Drawable serviceDrawable;
private Rect servicePadding;
private int offset;
private int oldHeight;
private long animationTime = 0;
private boolean isTimeVisible = false;
private Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
Logger.d(TAG, "notify");
if (msg.what == 0) {
if (isTimeVisible) {
isTimeVisible = false;
scrollDistance = 0;
animationTime = SystemClock.uptimeMillis();
}
invalidate();
} else if (msg.what == 1) {
isTimeVisible = true;
invalidate();
}
}
};
private int scrollDistance;
public ConversationListView(Context context) {
super(context);
init();
}
public ConversationListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ConversationListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public VisibleViewItem[] dump() {
int childCount = getChildCount();
int idCount = 0;
int headerCount = 0;
for (int i = 0; i < childCount; i++) {
int index = getFirstVisiblePosition() + i;
long id = getItemIdAtPosition(index);
if (id > 0) {
idCount++;
} else {
headerCount++;
}
}
VisibleViewItem[] res = new VisibleViewItem[idCount];
int resIndex = 0;
for (int i = 0; i < childCount; i++) {
View v = getChildAt(i);
int index = getFirstVisiblePosition() + i;
long id = getItemIdAtPosition(index);
if (id > 0) {
int top = ((v == null) ? 0 : v.getTop()) - getPaddingTop();
res[resIndex++] = new VisibleViewItem(index + headerCount, top, id);
}
}
return res;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
VisibleViewItem[] items = null;
if (changed) {
items = dump();
}
super.onLayout(changed, l, t, r, b);
if (changed) {
final int changeDelta = (b - t) - oldHeight;
if (changeDelta < 0 && items.length > 0) {
final VisibleViewItem item = items[items.length - 1];
setSelectionFromTop(item.getIndex(), item.getTop() + changeDelta);
post(new Runnable() {
@Override
public void run() {
setSelectionFromTop(item.getIndex(), item.getTop() + changeDelta);
}
});
}
}
oldHeight = b - t;
}
private void init() {
application = (TelegramApplication) getContext().getApplicationContext();
setOnScrollListener(new ScrollListener());
serviceDrawable = getResources().getDrawable(R.drawable.st_bubble_service);
servicePadding = new Rect();
serviceDrawable.getPadding(servicePadding);
timeDivPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
timeDivPaint.setTextSize(getSp(15));
timeDivPaint.setColor(0xffFFFFFF);
timeDivPaint.setTypeface(FontController.loadTypeface(getContext(), "regular"));
}
private void drawTime(Canvas canvas, int drawOffset, float alpha, boolean first) {
int w = first ? timeDivMeasure : timeDivMeasureNext;
serviceDrawable.setAlpha((int) (alpha * 255));
timeDivPaint.setAlpha((int) (alpha * 255));
serviceDrawable.setBounds(
getWidth() / 2 - w / 2 - servicePadding.left,
getPx(44 - 8) - serviceDrawable.getIntrinsicHeight() + drawOffset,
getWidth() / 2 + w / 2 + servicePadding.right,
getPx(44 - 8) + drawOffset);
serviceDrawable.draw(canvas);
canvas.drawText(first ? visibleDate : visibleDateNext, getWidth() / 2 - w / 2, getPx(44 - 17) + drawOffset, timeDivPaint);
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
boolean isAnimated = false;
boolean isShown;
if (isTimeVisible) {
isShown = isTimeVisible;
} else {
isShown = SystemClock.uptimeMillis() - animationTime < ANIMATION_DURATION;
}
if (isShown) {
float animationRatio = 1.0f;
if (SystemClock.uptimeMillis() - animationTime < ANIMATION_DURATION) {
isAnimated = true;
animationRatio = (SystemClock.uptimeMillis() - animationTime) / ((float) ANIMATION_DURATION);
if (animationRatio > 1.0f) {
animationRatio = 1.0f;
}
if (!isTimeVisible) {
animationRatio = 1.0f - animationRatio;
}
}
int drawOffset = offset;
if (offset == 0) {
if (visibleDate != null) {
drawTime(canvas, drawOffset, 1.0f * animationRatio, true);
}
} else {
float ratio = Math.min(1.0f, Math.abs(offset / (float) getPx(DELTA)));
if (visibleDateNext != null) {
drawTime(canvas, drawOffset + getPx(DELTA), ratio * animationRatio, false);
}
if (visibleDate != null) {
drawTime(canvas, drawOffset, (1.0f - ratio) * animationRatio, true);
}
}
}
if (isAnimated) {
invalidate();
}
}
protected int getPx(float dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
protected int getSp(float sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
}
private class ScrollListener implements OnScrollListener {
private int state = SCROLL_STATE_IDLE;
private int lastVisibleItem = -1;
private int lastTop = 0;
private int lastScrollY = -1;
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == SCROLL_STATE_FLING || i == SCROLL_STATE_TOUCH_SCROLL) {
handler.removeMessages(0);
}
if (i == SCROLL_STATE_IDLE) {
handler.removeMessages(0);
handler.sendEmptyMessageDelayed(0, UI_TIMEOUT);
}
state = i;
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// if (lastScrollY == -1) {
// lastScrollY = getScrollY();
// } else if (lastScrollY != getScrollY()) {
// lastScrollY = getScrollY();
// application.getImageController().doPause();
// }
if (lastVisibleItem == -1 || lastVisibleItem != firstVisibleItem || state == SCROLL_STATE_IDLE) {
lastVisibleItem = firstVisibleItem;
lastTop = 0;
View view = getChildAt(0 + getHeaderViewsCount());
if (view != null) {
lastTop = view.getTop();
}
} else {
View view = getChildAt(0 + getHeaderViewsCount());
if (view != null) {
int topDelta = Math.abs(view.getTop() - lastTop);
lastTop = view.getTop();
scrollDistance += topDelta;
if (scrollDistance > getPx(ACTIVATE_DELTA) && !isTimeVisible) {
isTimeVisible = true;
animationTime = SystemClock.uptimeMillis();
handler.removeMessages(0);
}
}
}
// handler.removeMessages(0);
ListAdapter adapter = getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
adapter = ((HeaderViewListAdapter) adapter).getWrappedAdapter();
}
if (adapter instanceof ConversationAdapter) {
if (firstVisibleItem == 0) {
visibleDate = null;
visibleDateNext = null;
formattedVisibleDate = -1;
formattedVisibleDateNext = -1;
View view = getChildAt(1);
if (view != null) {
offset = Math.min(view.getTop() - getPx(DELTA), 0);
if (adapter.getCount() > 0) {
int date = ((ConversationAdapter) adapter).getItemDate(0);
visibleDateNext = TextUtil.formatDateLong(date);
timeDivMeasureNext = (int) timeDivPaint.measureText(visibleDateNext);
}
}
return;
}
int realFirstVisibleItem = firstVisibleItem - getHeaderViewsCount();
if (realFirstVisibleItem >= 0 && realFirstVisibleItem < adapter.getCount()) {
int date = ((ConversationAdapter) adapter).getItemDate(realFirstVisibleItem);
int prevDate = date;
boolean isSameDays = true;
if (realFirstVisibleItem > 0 && realFirstVisibleItem + 2 < adapter.getCount()) {
prevDate = ((ConversationAdapter) adapter).getItemDate(realFirstVisibleItem + 1);
isSameDays = TextUtil.areSameDays(prevDate, date);
}
if (isSameDays) {
offset = 0;
} else {
View view = getChildAt(firstVisibleItem - realFirstVisibleItem);
if (view != null) {
offset = Math.min(view.getTop() - getPx(DELTA), 0);
}
if (!TextUtil.areSameDays(prevDate, System.currentTimeMillis() / 1000)) {
if (!TextUtil.areSameDays(prevDate, formattedVisibleDateNext)) {
formattedVisibleDateNext = prevDate;
visibleDateNext = TextUtil.formatDateLong(prevDate);
timeDivMeasureNext = (int) timeDivPaint.measureText(visibleDateNext);
}
} else {
visibleDateNext = null;
formattedVisibleDateNext = -1;
}
}
if (!TextUtil.areSameDays(date, System.currentTimeMillis() / 1000)) {
if (!TextUtil.areSameDays(date, formattedVisibleDate)) {
formattedVisibleDate = date;
visibleDate = TextUtil.formatDateLong(date);
timeDivMeasure = (int) timeDivPaint.measureText(visibleDate);
}
} else {
visibleDate = null;
formattedVisibleDate = -1;
}
}
}
}
}
}
| mit |
ctron/kura | kura/org.eclipse.kura.api/src/main/java/org/eclipse/kura/net/NetInterfaceRemovedEvent.java | 1545 | /*******************************************************************************
* Copyright (c) 2011, 2020 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech
******************************************************************************/
package org.eclipse.kura.net;
import java.util.Map;
import org.osgi.annotation.versioning.ProviderType;
import org.osgi.service.event.Event;
/**
* An event raised when a network interface has been removed from the system.
*
* @noextend This class is not intended to be subclassed by clients.
*/
@ProviderType
public class NetInterfaceRemovedEvent extends Event {
/** Topic of the NetworkInterfaceRemovedEvent */
public static final String NETWORK_EVENT_INTERFACE_REMOVED_TOPIC = "org/eclipse/kura/net/NetworkEvent/interface/REMOVED";
/** Name of the property to access the network interface name */
public static final String NETWORK_EVENT_INTERFACE_PROPERTY = "network.interface";
public NetInterfaceRemovedEvent(Map<String, ?> properties) {
super(NETWORK_EVENT_INTERFACE_REMOVED_TOPIC, properties);
}
/**
* Returns the name of the removed interface.
*
* @return
*/
public String getInterfaceName() {
return (String) getProperty(NETWORK_EVENT_INTERFACE_PROPERTY);
}
}
| epl-1.0 |
maxeler/eclipse | eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/invalid/TestInvalidFieldInitializer3.java | 151 | package invalid;
public class TestInvalidFieldInitializer3 {
private Object field= /*]*/foo()/*[*/;
public Object foo() {
return field;
}
}
| epl-1.0 |
rssowl/RSSOwl | org.rssowl.core/src/org/rssowl/core/internal/persist/service/EventsMap.java | 6658 | /* ********************************************************************** **
** Copyright notice **
** **
** (c) 2005-2009 RSSOwl Development Team **
** http://www.rssowl.org/ **
** **
** All rights reserved **
** **
** This program and the accompanying materials are made available under **
** the terms of the Eclipse Public License v1.0 which accompanies this **
** distribution, and is available at: **
** http://www.rssowl.org/legal/epl-v10.html **
** **
** A copy is found in the file epl-v10.html and important notices to the **
** license from the team is found in the textfile LICENSE.txt distributed **
** in this package. **
** **
** This copyright notice MUST APPEAR in all copies of the file! **
** **
** Contributors: **
** RSSOwl Development Team - initial API and implementation **
** **
** ********************************************************************** */
package org.rssowl.core.internal.persist.service;
import org.rssowl.core.persist.IEntity;
import org.rssowl.core.persist.event.ModelEvent;
import org.rssowl.core.persist.event.runnable.EventRunnable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
/**
* A {@link Map} of {@link ModelEvent} pointing to {@link EventRunnable}.
*/
public class EventsMap {
private static final EventsMap INSTANCE = new EventsMap();
private static class InternalMap extends HashMap<Class<? extends ModelEvent>, EventRunnable<? extends ModelEvent>> {
InternalMap() {
super();
}
}
private final ThreadLocal<InternalMap> fEvents = new ThreadLocal<InternalMap>();
private final ThreadLocal<Map<IEntity, ModelEvent>> fEventTemplatesMap = new ThreadLocal<Map<IEntity, ModelEvent>>();
private EventsMap() {
// Enforce singleton pattern
}
public final static EventsMap getInstance() {
return INSTANCE;
}
public final void putPersistEvent(ModelEvent event) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event);
eventRunnable.addCheckedPersistEvent(event);
}
public final void putUpdateEvent(ModelEvent event) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event);
eventRunnable.addCheckedUpdateEvent(event);
}
public final void putRemoveEvent(ModelEvent event) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event);
eventRunnable.addCheckedRemoveEvent(event);
}
public final boolean containsPersistEvent(Class<? extends ModelEvent> eventClass, IEntity entity) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass);
return eventRunnable.getPersistEvents().contains(entity);
}
public final boolean containsUpdateEvent(Class<? extends ModelEvent> eventClass, IEntity entity) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass);
return eventRunnable.getUpdateEvents().contains(entity);
}
public final boolean containsRemoveEvent(Class<? extends ModelEvent> eventClass, IEntity entity) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass);
return eventRunnable.getRemoveEvents().contains(entity);
}
private EventRunnable<? extends ModelEvent> getEventRunnable(Class<? extends ModelEvent> eventClass) {
InternalMap map = fEvents.get();
if (map == null) {
map = new InternalMap();
fEvents.set(map);
}
EventRunnable<? extends ModelEvent> eventRunnable = map.get(eventClass);
return eventRunnable;
}
private EventRunnable<? extends ModelEvent> getEventRunnable(ModelEvent event) {
Class<? extends ModelEvent> eventClass = event.getClass();
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass);
if (eventRunnable == null) {
eventRunnable = event.createEventRunnable();
fEvents.get().put(eventClass, eventRunnable);
}
return eventRunnable;
}
public EventRunnable<? extends ModelEvent> removeEventRunnable(Class<? extends ModelEvent> klass) {
InternalMap map = fEvents.get();
if (map == null)
return null;
EventRunnable<? extends ModelEvent> runnable = map.remove(klass);
return runnable;
}
public List<EventRunnable<?>> getEventRunnables() {
InternalMap map = fEvents.get();
if (map == null)
return new ArrayList<EventRunnable<?>>(0);
List<EventRunnable<?>> eventRunnables = new ArrayList<EventRunnable<?>>(map.size());
for (Map.Entry<Class<? extends ModelEvent>, EventRunnable<? extends ModelEvent>> entry : map.entrySet()) {
eventRunnables.add(entry.getValue());
}
return eventRunnables;
}
public List<EventRunnable<?>> removeEventRunnables() {
InternalMap map = fEvents.get();
if (map == null)
return new ArrayList<EventRunnable<?>>(0);
List<EventRunnable<?>> eventRunnables = getEventRunnables();
map.clear();
return eventRunnables;
}
public void putEventTemplate(ModelEvent event) {
Map<IEntity, ModelEvent> map = fEventTemplatesMap.get();
if (map == null) {
map = new IdentityHashMap<IEntity, ModelEvent>();
fEventTemplatesMap.set(map);
}
map.put(event.getEntity(), event);
}
public final Map<IEntity, ModelEvent> getEventTemplatesMap() {
Map<IEntity, ModelEvent> map = fEventTemplatesMap.get();
if (map == null)
return Collections.emptyMap();
return Collections.unmodifiableMap(fEventTemplatesMap.get());
}
public Map<IEntity, ModelEvent> removeEventTemplatesMap() {
Map<IEntity, ModelEvent> map = fEventTemplatesMap.get();
fEventTemplatesMap.remove();
return map;
}
} | epl-1.0 |
ctron/kura | kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/shared/model/GwtDeviceConfig.java | 7591 | /*******************************************************************************
* Copyright (c) 2011, 2020 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech
*******************************************************************************/
package org.eclipse.kura.web.shared.model;
import java.io.Serializable;
import java.util.Date;
import org.eclipse.kura.web.shared.DateUtils;
public class GwtDeviceConfig extends GwtBaseModel implements Serializable {
private static final long serialVersionUID = 1708831984640005284L;
public GwtDeviceConfig() {
}
@Override
@SuppressWarnings({ "unchecked" })
public <X> X get(String property) {
if ("lastEventOnFormatted".equals(property)) {
return (X) DateUtils.formatDateTime((Date) get("lastEventOn"));
} else if ("uptimeFormatted".equals(property)) {
if (getUptime() == -1) {
return (X) "Unknown";
} else {
return (X) String.valueOf(getUptime());
}
} else {
return super.get(property);
}
}
public String getAccountName() {
return get("accountName");
}
public void setAccountName(String accountName) {
set("accountName", accountName);
}
public String getClientId() {
return (String) get("clientId");
}
public void setClientId(String clientId) {
set("clientId", clientId);
}
public Long getUptime() {
return (Long) get("uptime");
}
public String getUptimeFormatted() {
return (String) get("uptimeFormatted");
}
public void setUptime(Long uptime) {
set("uptime", uptime);
}
public String getGwtDeviceStatus() {
return (String) get("gwtDeviceStatus");
}
public void setGwtDeviceStatus(String gwtDeviceStatus) {
set("gwtDeviceStatus", gwtDeviceStatus);
}
public String getDisplayName() {
return (String) get("displayName");
}
public void setDisplayName(String displayName) {
set("displayName", displayName);
}
public String getModelName() {
return (String) get("modelName");
}
public void setModelName(String modelName) {
set("modelName", modelName);
}
public String getModelId() {
return (String) get("modelId");
}
public void setModelId(String modelId) {
set("modelId", modelId);
}
public String getPartNumber() {
return (String) get("partNumber");
}
public void setPartNumber(String partNumber) {
set("partNumber", partNumber);
}
public String getSerialNumber() {
return (String) get("serialNumber");
}
public void setSerialNumber(String serialNumber) {
set("serialNumber", serialNumber);
}
public String getAvailableProcessors() {
return (String) get("availableProcessors");
}
public void setAvailableProcessors(String availableProcessors) {
set("availableProcessors", availableProcessors);
}
public String getTotalMemory() {
return (String) get("totalMemory");
}
public void setTotalMemory(String totalMemory) {
set("totalMemory", totalMemory);
}
public String getFirmwareVersion() {
return (String) get("firmwareVersion");
}
public void setFirmwareVersion(String firmwareVersion) {
set("firmwareVersion", firmwareVersion);
}
public String getBiosVersion() {
return (String) get("biosVersion");
}
public void setBiosVersion(String biosVersion) {
set("biosVersion", biosVersion);
}
public String getOs() {
return (String) get("os");
}
public void setOs(String os) {
set("os", os);
}
public String getOsVersion() {
return (String) get("osVersion");
}
public void setOsVersion(String osVersion) {
set("osVersion", osVersion);
}
public String getOsArch() {
return (String) get("osArch");
}
public void setOsArch(String osArch) {
set("osArch", osArch);
}
public String getJvmName() {
return (String) get("jvmName");
}
public void setJvmName(String jvmName) {
set("jvmName", jvmName);
}
public String getJvmVersion() {
return (String) get("jvmVersion");
}
public void setJvmVersion(String jvmVersion) {
set("jvmVersion", jvmVersion);
}
public String getJvmProfile() {
return (String) get("jvmProfile");
}
public void setJvmProfile(String jvmProfile) {
set("jvmProfile", jvmProfile);
}
public String getOsgiFramework() {
return (String) get("osgiFramework");
}
public void setOsgiFramework(String osgiFramework) {
set("osgiFramework", osgiFramework);
}
public String getOsgiFrameworkVersion() {
return (String) get("osgiFrameworkVersion");
}
public void setOsgiFrameworkVersion(String osgiFrameworkVersion) {
set("osgiFrameworkVersion", osgiFrameworkVersion);
}
public String getConnectionInterface() {
return (String) get("connectionInterface");
}
public void setConnectionInterface(String connectionInterface) {
set("connectionInterface", connectionInterface);
}
public String getConnectionIp() {
return (String) get("connectionIp");
}
public void setConnectionIp(String connectionIp) {
set("connectionIp", connectionIp);
}
public String getAcceptEncoding() {
return (String) get("acceptEncoding");
}
public void setAcceptEncoding(String acceptEncoding) {
set("acceptEncoding", acceptEncoding);
}
public String getApplicationIdentifiers() {
return (String) get("applicationIdentifiers");
}
public void setApplicationIdentifiers(String applicationIdentifiers) {
set("applicationIdentifiers", applicationIdentifiers);
}
public Double getGpsLatitude() {
return (Double) get("gpsLatitude");
}
public void setGpsLatitude(Double gpsLatitude) {
set("gpsLatitude", gpsLatitude);
}
public Double getGpsLongitude() {
return (Double) get("gpsLongitude");
}
public void setGpsLongitude(Double gpsLongitude) {
set("gpsLongitude", gpsLongitude);
}
public Double getGpsAltitude() {
return (Double) get("gpsAltitude");
}
public void setGpsAltitude(Double gpsAltitude) {
set("gpsAltitude", gpsAltitude);
}
public String getGpsAddress() {
return (String) get("gpsAddress");
}
public void setGpsAddress(String gpsAddress) {
set("gpsAddress", gpsAddress);
}
public Date getLastEventOn() {
return (Date) get("lastEventOn");
}
public String getLastEventOnFormatted() {
return (String) get("lastEventOnFormatted");
}
public void setLastEventOn(Date lastEventDate) {
set("lastEventOn", lastEventDate);
}
public String getLastEventType() {
return (String) get("lastEventType");
}
public void setLastEventType(String lastEventType) {
set("lastEventType", lastEventType);
}
public boolean isOnline() {
return getGwtDeviceStatus().compareTo("CONNECTED") == 0;
}
}
| epl-1.0 |
yuyf10/opendaylight-controller | opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImplTest.java | 6052 | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.sal.connector.remoterpc;
import com.google.common.base.Optional;
import junit.framework.Assert;
import org.junit.*;
import org.opendaylight.controller.sal.connector.api.RpcRouter;
import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil;
import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.zeromq.ZMQ;
import zmq.Ctx;
import zmq.SocketBase;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ServerImplTest {
private static ZMQ.Context context;
private ServerImpl server;
private Broker.ProviderSession brokerSession;
private RoutingTableProvider routingTableProvider;
private RpcRegistrationListener listener;
ExecutorService pool;
//Server configuration
private final int HANDLER_COUNT = 2;
private final int HWM = 200;
private final int port = 5554;
//server address
private final String SERVER_ADDRESS = "tcp://localhost:5554";
//@BeforeClass
public static void init() {
context = ZMQ.context(1);
}
//@AfterClass
public static void destroy() {
MessagingUtil.closeZmqContext(context);
}
@Before
public void setup() throws InterruptedException {
context = ZMQ.context(1);
brokerSession = mock(Broker.ProviderSession.class);
routingTableProvider = mock(RoutingTableProvider.class);
listener = mock(RpcRegistrationListener.class);
server = new ServerImpl(port);
server.setBrokerSession(brokerSession);
RoutingTable<RpcRouter.RouteIdentifier, String> mockRoutingTable = new MockRoutingTable<String, String>();
Optional<RoutingTable<RpcRouter.RouteIdentifier, String>> optionalRoutingTable = Optional.fromNullable(mockRoutingTable);
when(routingTableProvider.getRoutingTable()).thenReturn(optionalRoutingTable);
when(brokerSession.addRpcRegistrationListener(listener)).thenReturn(null);
when(brokerSession.getSupportedRpcs()).thenReturn(Collections.EMPTY_SET);
when(brokerSession.rpc(null, mock(CompositeNode.class))).thenReturn(null);
server.start();
Thread.sleep(5000);//wait for server to start
}
@After
public void tearDown() throws InterruptedException {
if (pool != null)
pool.shutdown();
if (server != null)
server.stop();
MessagingUtil.closeZmqContext(context);
Thread.sleep(5000);//wait for server to stop
Assert.assertEquals(ServerImpl.State.STOPPED, server.getStatus());
}
@Test
public void getBrokerSession_Call_ShouldReturnBrokerSession() throws Exception {
Optional<Broker.ProviderSession> mayBeBroker = server.getBrokerSession();
if (mayBeBroker.isPresent())
Assert.assertEquals(brokerSession, mayBeBroker.get());
else
Assert.fail("Broker does not exist in Remote RPC Server");
}
@Test
public void start_Call_ShouldSetServerStatusToStarted() throws Exception {
Assert.assertEquals(ServerImpl.State.STARTED, server.getStatus());
}
@Test
public void start_Call_ShouldCreateNZmqSockets() throws Exception {
final int EXPECTED_COUNT = 2 + HANDLER_COUNT; //1 ROUTER + 1 DEALER + HANDLER_COUNT
Optional<ZMQ.Context> mayBeContext = server.getZmqContext();
if (mayBeContext.isPresent())
Assert.assertEquals(EXPECTED_COUNT, findSocketCount(mayBeContext.get()));
else
Assert.fail("ZMQ Context does not exist in Remote RPC Server");
}
@Test
public void start_Call_ShouldCreate1ServerThread() {
final String SERVER_THREAD_NAME = "remote-rpc-server";
final int EXPECTED_COUNT = 1;
List<Thread> serverThreads = findThreadsWithName(SERVER_THREAD_NAME);
Assert.assertEquals(EXPECTED_COUNT, serverThreads.size());
}
@Test
public void start_Call_ShouldCreateNHandlerThreads() {
//final String WORKER_THREAD_NAME = "remote-rpc-worker";
final int EXPECTED_COUNT = HANDLER_COUNT;
Optional<ServerRequestHandler> serverRequestHandlerOptional = server.getHandler();
if (serverRequestHandlerOptional.isPresent()){
ServerRequestHandler handler = serverRequestHandlerOptional.get();
ThreadPoolExecutor workerPool = handler.getWorkerPool();
Assert.assertEquals(EXPECTED_COUNT, workerPool.getPoolSize());
} else {
Assert.fail("Server is in illegal state. ServerHandler does not exist");
}
}
@Test
public void testStop() throws Exception {
}
@Test
public void testOnRouteUpdated() throws Exception {
}
@Test
public void testOnRouteDeleted() throws Exception {
}
private int findSocketCount(ZMQ.Context context)
throws NoSuchFieldException, IllegalAccessException {
Field ctxField = context.getClass().getDeclaredField("ctx");
ctxField.setAccessible(true);
Ctx ctx = Ctx.class.cast(ctxField.get(context));
Field socketListField = ctx.getClass().getDeclaredField("sockets");
socketListField.setAccessible(true);
List<SocketBase> sockets = List.class.cast(socketListField.get(ctx));
return sockets.size();
}
private List<Thread> findThreadsWithName(String name) {
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
List<Thread> foundThreads = new ArrayList();
for (Thread t : threads) {
if (t.getName().startsWith(name))
foundThreads.add(t);
}
return foundThreads;
}
}
| epl-1.0 |
scela/EclipseCon2014 | com.vogella.e4.appmodel.app/src/com/vogella/e4/appmodel/app/handlers/QuitHandler.java | 1040 | /*******************************************************************************
* Copyright (c) 2010 - 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Lars Vogel <lars.Vogel@gmail.com> - Bug 419770
*******************************************************************************/
package com.vogella.e4.appmodel.app.handlers;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
public class QuitHandler {
@Execute
public void execute(IWorkbench workbench, Shell shell){
if (MessageDialog.openConfirm(shell, "Confirmation",
"Do you want to exit?")) {
workbench.close();
}
}
}
| epl-1.0 |
akervern/che | plugins/plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/compare/MutableAlteredFiles.java | 2645 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.ext.git.client.compare;
import org.eclipse.che.ide.api.resources.Project;
import org.eclipse.che.ide.ext.git.client.compare.FileStatus.Status;
/**
* Describes changed in any way project files. Supports adding and removing items dynamically.
*
* @author Mykola Morhun
*/
public class MutableAlteredFiles extends AlteredFiles {
/**
* Parses raw git diff string and creates advanced representation.
*
* @param project the project under diff operation
* @param diff plain result of git diff operation
*/
public MutableAlteredFiles(Project project, String diff) {
super(project, diff);
}
/**
* Creates mutable altered files list based on changes from another project.
*
* @param project the project under diff operation
* @param alteredFiles changes from another project
*/
public MutableAlteredFiles(Project project, AlteredFiles alteredFiles) {
super(project, "");
this.alteredFilesStatuses.putAll(alteredFiles.alteredFilesStatuses);
this.alteredFilesList.addAll(alteredFiles.alteredFilesList);
}
/**
* Creates an empty list of altered files.
*
* @param project the project under diff operation
*/
public MutableAlteredFiles(Project project) {
super(project, "");
}
/**
* Adds or updates a file in altered file list. If given file is already exists does nothing.
*
* @param file full path to file and its name relatively to project root
* @param status git status of the file
* @return true if file was added or updated and false if the file is already exists in this list
*/
public boolean addFile(String file, Status status) {
if (status.equals(alteredFilesStatuses.get(file))) {
return false;
}
if (alteredFilesStatuses.put(file, status) == null) {
// it's not a status change, new file was added
alteredFilesList.add(file);
}
return true;
}
/**
* Removes given file from the altered files list. If given file isn't present does nothing.
*
* @param file full path to file and its name relatively to project root
* @return true if the file was deleted and false otherwise
*/
public boolean removeFile(String file) {
alteredFilesStatuses.remove(file);
return alteredFilesList.remove(file);
}
}
| epl-1.0 |
Mark-Booth/daq-eclipse | uk.ac.diamond.org.apache.activemq/org/apache/activemq/transport/multicast/MulticastDatagramHeaderMarshaller.java | 1880 | /**
* 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.activemq.transport.multicast;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import org.apache.activemq.command.Command;
import org.apache.activemq.command.Endpoint;
import org.apache.activemq.transport.udp.DatagramEndpoint;
import org.apache.activemq.transport.udp.DatagramHeaderMarshaller;
/**
*
*
*/
public class MulticastDatagramHeaderMarshaller extends DatagramHeaderMarshaller {
private final byte[] localUriAsBytes;
public MulticastDatagramHeaderMarshaller(String localUri) {
this.localUriAsBytes = localUri.getBytes();
}
public Endpoint createEndpoint(ByteBuffer readBuffer, SocketAddress address) {
int size = readBuffer.getInt();
byte[] data = new byte[size];
readBuffer.get(data);
return new DatagramEndpoint(new String(data), address);
}
public void writeHeader(Command command, ByteBuffer writeBuffer) {
writeBuffer.putInt(localUriAsBytes.length);
writeBuffer.put(localUriAsBytes);
super.writeHeader(command, writeBuffer);
}
}
| epl-1.0 |
ControlSystemStudio/cs-studio | applications/databrowser/databrowser-plugins/org.csstudio.trends.databrowser2/src/org/csstudio/trends/databrowser2/propsheet/UseDefaultArchivesAction.java | 1688 | /*******************************************************************************
* Copyright (c) 2010 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.trends.databrowser2.propsheet;
import org.csstudio.swt.rtplot.undo.UndoableActionManager;
import org.csstudio.trends.databrowser2.Activator;
import org.csstudio.trends.databrowser2.Messages;
import org.csstudio.trends.databrowser2.model.PVItem;
import org.csstudio.trends.databrowser2.preferences.Preferences;
import org.eclipse.jface.action.Action;
/** Action that configures PVs to use default archive data sources.
* @author Kay Kasemir
*/
public class UseDefaultArchivesAction extends Action
{
final private UndoableActionManager operations_manager;
final private PVItem pvs[];
/** Initialize
* @param shell Parent shell for dialog
* @param pvs PVs that should use default archives
*/
public UseDefaultArchivesAction(final UndoableActionManager operations_manager,
final PVItem pvs[])
{
super(Messages.UseDefaultArchives,
Activator.getDefault().getImageDescriptor("icons/archive.gif")); //$NON-NLS-1$
this.operations_manager = operations_manager;
this.pvs = pvs;
}
@Override
public void run()
{
new AddArchiveCommand(operations_manager, pvs, Preferences.getArchives(), true);
}
}
| epl-1.0 |
alastrina123/debrief | org.mwc.cmap.legacy/src/MWC/GUI/Properties/Swing/SwingDatePropertyEditor.java | 7774 | /*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package MWC.GUI.Properties.Swing;
// Copyright MWC 1999, Debrief 3 Project
// $RCSfile: SwingDatePropertyEditor.java,v $
// @author $Author: Ian.Mayo $
// @version $Revision: 1.3 $
// $Log: SwingDatePropertyEditor.java,v $
// Revision 1.3 2004/11/26 11:32:48 Ian.Mayo
// Moving closer, supporting checking for time resolution
//
// Revision 1.2 2004/05/25 15:29:37 Ian.Mayo
// Commit updates from home
//
// Revision 1.1.1.1 2004/03/04 20:31:20 ian
// no message
//
// Revision 1.1.1.1 2003/07/17 10:07:26 Ian.Mayo
// Initial import
//
// Revision 1.2 2002-05-28 09:25:47+01 ian_mayo
// after switch to new system
//
// Revision 1.1 2002-05-28 09:14:33+01 ian_mayo
// Initial revision
//
// Revision 1.1 2002-04-11 14:01:26+01 ian_mayo
// Initial revision
//
// Revision 1.1 2001-08-31 10:36:55+01 administrator
// Tidied up layout, so all data is displayed when editor panel is first opened
//
// Revision 1.0 2001-07-17 08:43:31+01 administrator
// Initial revision
//
// Revision 1.4 2001-07-12 12:06:59+01 novatech
// use tooltips to show the date format
//
// Revision 1.3 2001-01-21 21:38:23+00 novatech
// handle focusGained = select all text
//
// Revision 1.2 2001-01-17 09:41:37+00 novatech
// factor generic processing to parent class, and provide support for NULL values
//
// Revision 1.1 2001-01-03 13:42:39+00 novatech
// Initial revision
//
// Revision 1.1.1.1 2000/12/12 21:45:37 ianmayo
// initial version
//
// Revision 1.5 2000-10-09 13:35:47+01 ian_mayo
// Switched stack traces to go to log file
//
// Revision 1.4 2000-04-03 10:48:57+01 ian_mayo
// squeeze up the controls
//
// Revision 1.3 2000-02-02 14:25:07+00 ian_mayo
// correct package naming
//
// Revision 1.2 1999-11-23 11:05:03+00 ian_mayo
// further introduction of SWING components
//
// Revision 1.1 1999-11-16 16:07:19+00 ian_mayo
// Initial revision
//
// Revision 1.1 1999-11-16 16:02:29+00 ian_mayo
// Initial revision
//
// Revision 1.2 1999-11-11 18:16:09+00 ian_mayo
// new class, now working
//
// Revision 1.1 1999-10-12 15:36:48+01 ian_mayo
// Initial revision
//
// Revision 1.1 1999-08-26 10:05:48+01 administrator
// Initial revision
//
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import MWC.GUI.Dialogs.DialogFactory;
import MWC.GenericData.HiResDate;
import MWC.Utilities.TextFormatting.DebriefFormatDateTime;
public class SwingDatePropertyEditor extends
MWC.GUI.Properties.DatePropertyEditor implements java.awt.event.FocusListener
{
/////////////////////////////////////////////////////////////
// member variables
////////////////////////////////////////////////////////////
/**
* field to edit the date
*/
JTextField _theDate;
/**
* field to edit the time
*/
JTextField _theTime;
/**
* label to show the microsecodns
*/
JLabel _theMicrosTxt;
/**
* panel to hold everything
*/
JPanel _theHolder;
/////////////////////////////////////////////////////////////
// constructor
////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
// member functions
////////////////////////////////////////////////////////////
/**
* build the editor
*/
public java.awt.Component getCustomEditor()
{
_theHolder = new JPanel();
final java.awt.BorderLayout bl1 = new java.awt.BorderLayout();
bl1.setVgap(0);
bl1.setHgap(0);
final java.awt.BorderLayout bl2 = new java.awt.BorderLayout();
bl2.setVgap(0);
bl2.setHgap(0);
final JPanel lPanel = new JPanel();
lPanel.setLayout(bl1);
final JPanel rPanel = new JPanel();
rPanel.setLayout(bl2);
_theHolder.setLayout(new java.awt.GridLayout(0, 2));
_theDate = new JTextField();
_theDate.setToolTipText("Format: " + NULL_DATE);
_theTime = new JTextField();
_theTime.setToolTipText("Format: " + NULL_TIME);
lPanel.add("Center", new JLabel("Date:", JLabel.RIGHT));
lPanel.add("East", _theDate);
rPanel.add("Center", new JLabel("Time:", JLabel.RIGHT));
rPanel.add("East", _theTime);
_theHolder.add(lPanel);
_theHolder.add(rPanel);
// get the fields to select the full text when they're selected
_theDate.addFocusListener(this);
_theTime.addFocusListener(this);
// right, just see if we are in hi-res DTG editing mode
if (HiResDate.inHiResProcessingMode())
{
// ok, add a button to allow the user to enter DTG data
final JButton editMicros = new JButton("Micros");
editMicros.addActionListener(new ActionListener()
{
public void actionPerformed(final ActionEvent e)
{
editMicrosPressed();
}
});
// ok, we'
_theMicrosTxt = new JLabel("..");
_theHolder.add(_theMicrosTxt);
_theHolder.add(editMicros);
}
resetData();
return _theHolder;
}
/**
* user wants to edit the microseconds. give him a popup
*/
void editMicrosPressed()
{
//To change body of created methods use File | Settings | File Templates.
final Integer res = DialogFactory.getInteger("Edit microseconds", "Enter microseconds",(int) _theMicros);
// did user enter anything?
if(res != null)
{
// store the data
_theMicros = res.intValue();
// and update the screen
resetData();
}
}
/**
* get the date text as a string
*/
protected String getDateText()
{
return _theDate.getText();
}
/**
* get the date text as a string
*/
protected String getTimeText()
{
return _theTime.getText();
}
/**
* set the date text in string form
*/
protected void setDateText(final String val)
{
if (_theHolder != null)
{
_theDate.setText(val);
}
}
/**
* set the time text in string form
*/
protected void setTimeText(final String val)
{
if (_theHolder != null)
{
_theTime.setText(val);
}
}
/**
* show the user how many microseconds there are
*
* @param val
*/
protected void setMicroText(final long val)
{
// output the number of microseconds
_theMicrosTxt.setText(DebriefFormatDateTime.formatMicros(new HiResDate(0, val)) + " micros");
}
/////////////////////////////
// focus listener support classes
/////////////////////////////
/**
* Invoked when a component gains the keyboard focus.
*/
public void focusGained(final FocusEvent e)
{
final java.awt.Component c = e.getComponent();
if (c instanceof JTextField)
{
final JTextField jt = (JTextField) c;
jt.setSelectionStart(0);
jt.setSelectionEnd(jt.getText().length());
}
}
/**
* Invoked when a component loses the keyboard focus.
*/
public void focusLost(final FocusEvent e)
{
}
}
| epl-1.0 |
inspur-iop/Mycat-Server | src/main/java/io/mycat/backend/postgresql/PostgreSQLBackendConnection.java | 14050 | package io.mycat.backend.postgresql;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.NetworkChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import io.mycat.backend.jdbc.ShowVariables;
import io.mycat.backend.mysql.CharsetUtil;
import io.mycat.backend.mysql.nio.MySQLConnectionHandler;
import io.mycat.backend.mysql.nio.handler.ResponseHandler;
import io.mycat.backend.postgresql.packet.Query;
import io.mycat.backend.postgresql.packet.Terminate;
import io.mycat.backend.postgresql.utils.PIOUtils;
import io.mycat.backend.postgresql.utils.PacketUtils;
import io.mycat.backend.postgresql.utils.PgSqlApaterUtils;
import io.mycat.config.Isolations;
import io.mycat.net.BackendAIOConnection;
import io.mycat.route.RouteResultsetNode;
import io.mycat.server.ServerConnection;
import io.mycat.server.parser.ServerParse;
import io.mycat.util.exception.UnknownTxIsolationException;
/*************************************************************
* PostgreSQL Native Connection impl
*
* @author Coollf
*
*/
public class PostgreSQLBackendConnection extends BackendAIOConnection {
public static enum BackendConnectionState {
closed, connected, connecting
}
private static class StatusSync {
private final Boolean autocommit;
private final Integer charsetIndex;
private final String schema;
private final AtomicInteger synCmdCount;
private final Integer txtIsolation;
private final boolean xaStarted;
public StatusSync(boolean xaStarted, String schema, Integer charsetIndex, Integer txtIsolation,
Boolean autocommit, int synCount) {
super();
this.xaStarted = xaStarted;
this.schema = schema;
this.charsetIndex = charsetIndex;
this.txtIsolation = txtIsolation;
this.autocommit = autocommit;
this.synCmdCount = new AtomicInteger(synCount);
}
public boolean synAndExecuted(PostgreSQLBackendConnection conn) {
int remains = synCmdCount.decrementAndGet();
if (remains == 0) {// syn command finished
this.updateConnectionInfo(conn);
conn.metaDataSyned = true;
return false;
} else if (remains < 0) {
return true;
}
return false;
}
private void updateConnectionInfo(PostgreSQLBackendConnection conn)
{
conn.xaStatus = (xaStarted) ? 1 : 0;
if (schema != null) {
conn.schema = schema;
conn.oldSchema = conn.schema;
}
if (charsetIndex != null) {
conn.setCharset(CharsetUtil.getCharset(charsetIndex));
}
if (txtIsolation != null) {
conn.txIsolation = txtIsolation;
}
if (autocommit != null) {
conn.autocommit = autocommit;
}
}
}
private static final Query _COMMIT = new Query("commit");
private static final Query _ROLLBACK = new Query("rollback");
private static void getCharsetCommand(StringBuilder sb, int clientCharIndex) {
sb.append("SET names '").append(CharsetUtil.getCharset(clientCharIndex).toUpperCase()).append("';");
}
/**
* 获取 更改事物级别sql
*
* @param
* @param txIsolation
*/
private static void getTxIsolationCommand(StringBuilder sb, int txIsolation) {
switch (txIsolation) {
case Isolations.READ_UNCOMMITTED:
sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
return;
case Isolations.READ_COMMITTED:
sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;");
return;
case Isolations.REPEATED_READ:
sb.append("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
return;
case Isolations.SERIALIZABLE:
sb.append("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;");
return;
default:
throw new UnknownTxIsolationException("txIsolation:" + txIsolation);
}
}
private Object attachment;
private volatile boolean autocommit=true;
private volatile boolean borrowed;
protected volatile String charset = "utf8";
/***
* 当前事物ID
*/
private volatile String currentXaTxId;
/**
* 来自子接口
*/
private volatile boolean fromSlaveDB;
/****
* PG是否在事物中
*/
private volatile boolean inTransaction = false;
private AtomicBoolean isQuit = new AtomicBoolean(false);
private volatile long lastTime;
/**
* 元数据同步
*/
private volatile boolean metaDataSyned = true;
private volatile boolean modifiedSQLExecuted = false;
private volatile String oldSchema;
/**
* 密码
*/
private volatile String password;
/**
* 数据源配置
*/
private PostgreSQLDataSource pool;
/***
* 响应handler
*/
private volatile ResponseHandler responseHandler;
/***
* 对应数据库空间
*/
private volatile String schema;
// PostgreSQL服务端密码
private volatile int serverSecretKey;
private volatile BackendConnectionState state = BackendConnectionState.connecting;
private volatile StatusSync statusSync;
private volatile int txIsolation;
/***
* 用户名
*/
private volatile String user;
private volatile int xaStatus;
public PostgreSQLBackendConnection(NetworkChannel channel, boolean fromSlaveDB) {
super(channel);
this.fromSlaveDB = fromSlaveDB;
}
@Override
public void commit() {
ByteBuffer buf = this.allocate();
_COMMIT.write(buf);
this.write(buf);
}
@Override
public void execute(RouteResultsetNode rrn, ServerConnection sc, boolean autocommit) throws IOException {
int sqlType = rrn.getSqlType();
String orgin = rrn.getStatement();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{}查询任务。。。。{}", id, rrn.getStatement());
LOGGER.debug(orgin);
}
//FIX BUG https://github.com/MyCATApache/Mycat-Server/issues/1185
if (sqlType == ServerParse.SELECT || sqlType == ServerParse.SHOW) {
if (sqlType == ServerParse.SHOW) {
//此处进行部分SHOW 语法适配
String _newSql = PgSqlApaterUtils.apater(orgin);
if(_newSql.trim().substring(0,4).equalsIgnoreCase("show")){//未能适配成功
ShowVariables.execute(sc, orgin, this);
return;
}
} else if ("SELECT CONNECTION_ID()".equalsIgnoreCase(orgin)) {
ShowVariables.justReturnValue(sc, String.valueOf(sc.getId()), this);
return;
}
}
if (!modifiedSQLExecuted && rrn.isModifySQL()) {
modifiedSQLExecuted = true;
}
String xaTXID = sc.getSession2().getXaTXID();
synAndDoExecute(xaTXID, rrn, sc.getCharsetIndex(), sc.getTxIsolation(), autocommit);
}
@Override
public Object getAttachment() {
return attachment;
}
private void getAutocommitCommand(StringBuilder sb, boolean autoCommit) {
if (autoCommit) {
sb.append(/*"SET autocommit=1;"*/"");//Fix bug 由于 PG9.0 开始不支持此选项,默认是为自动提交逻辑。
} else {
sb.append("begin transaction;");
}
}
@Override
public long getLastTime() {
return lastTime;
}
public String getPassword() {
return password;
}
public PostgreSQLDataSource getPool() {
return pool;
}
public ResponseHandler getResponseHandler() {
return responseHandler;
}
@Override
public String getSchema() {
return this.schema;
}
public int getServerSecretKey() {
return serverSecretKey;
}
public BackendConnectionState getState() {
return state;
}
@Override
public int getTxIsolation() {
return txIsolation;
}
public String getUser() {
return user;
}
@Override
public boolean isAutocommit() {
return autocommit;
}
@Override
public boolean isBorrowed() {
return borrowed;
}
@Override
public boolean isClosedOrQuit() {
return isClosed() || isQuit.get();
}
@Override
public boolean isFromSlaveDB() {
return fromSlaveDB;
}
public boolean isInTransaction() {
return inTransaction;
}
@Override
public boolean isModifiedSQLExecuted() {
return modifiedSQLExecuted;
}
@Override
public void onConnectFailed(Throwable t) {
if (handler instanceof MySQLConnectionHandler) {
}
}
@Override
public void onConnectfinish() {
LOGGER.debug("连接后台真正完成");
try {
SocketChannel chan = (SocketChannel) this.channel;
ByteBuffer buf = PacketUtils.makeStartUpPacket(user, schema);
buf.flip();
chan.write(buf);
} catch (Exception e) {
LOGGER.error("Connected PostgreSQL Send StartUpPacket ERROR", e);
throw new RuntimeException(e);
}
}
protected final int getPacketLength(ByteBuffer buffer, int offset) {
// Pg 协议获取包长度的方法和mysql 不一样
return PIOUtils.redInteger4(buffer, offset + 1) + 1;
}
/**********
* 此查询用于心跳检查和获取连接后的健康检查
*/
@Override
public void query(String query) throws UnsupportedEncodingException {
RouteResultsetNode rrn = new RouteResultsetNode("default", ServerParse.SELECT, query);
synAndDoExecute(null, rrn, this.charsetIndex, this.txIsolation, true);
}
@Override
public void quit() {
if (isQuit.compareAndSet(false, true) && !isClosed()) {
if (state == BackendConnectionState.connected) {// 断开 与PostgreSQL连接
Terminate terminate = new Terminate();
ByteBuffer buf = this.allocate();
terminate.write(buf);
write(buf);
} else {
close("normal");
}
}
}
/*******
* 记录sql执行信息
*/
@Override
public void recordSql(String host, String schema, String statement) {
LOGGER.debug(String.format("executed sql: host=%s,schema=%s,statement=%s", host, schema, statement));
}
@Override
public void release() {
if (!metaDataSyned) {/*
* indicate connection not normalfinished ,and
* we can't know it's syn status ,so close it
*/
LOGGER.warn("can't sure connection syn result,so close it " + this);
this.responseHandler = null;
this.close("syn status unkown ");
return;
}
metaDataSyned = true;
attachment = null;
statusSync = null;
modifiedSQLExecuted = false;
setResponseHandler(null);
pool.releaseChannel(this);
}
@Override
public void rollback() {
ByteBuffer buf = this.allocate();
_ROLLBACK.write(buf);
this.write(buf);
}
@Override
public void setAttachment(Object attachment) {
this.attachment = attachment;
}
@Override
public void setBorrowed(boolean borrowed) {
this.borrowed = borrowed;
}
public void setInTransaction(boolean inTransaction) {
this.inTransaction = inTransaction;
}
@Override
public void setLastTime(long currentTimeMillis) {
this.lastTime = currentTimeMillis;
}
public void setPassword(String password) {
this.password = password;
}
public void setPool(PostgreSQLDataSource pool) {
this.pool = pool;
}
@Override
public boolean setResponseHandler(ResponseHandler commandHandler) {
this.responseHandler = commandHandler;
return true;
}
@Override
public void setSchema(String newSchema) {
String curSchema = schema;
if (curSchema == null) {
this.schema = newSchema;
this.oldSchema = newSchema;
} else {
this.oldSchema = curSchema;
this.schema = newSchema;
}
}
public void setServerSecretKey(int serverSecretKey) {
this.serverSecretKey = serverSecretKey;
}
public void setState(BackendConnectionState state) {
this.state = state;
}
public void setUser(String user) {
this.user = user;
}
private void synAndDoExecute(String xaTxID, RouteResultsetNode rrn, int clientCharSetIndex, int clientTxIsoLation,
boolean clientAutoCommit) {
String xaCmd = null;
boolean conAutoComit = this.autocommit;
String conSchema = this.schema;
// never executed modify sql,so auto commit
boolean expectAutocommit = !modifiedSQLExecuted || isFromSlaveDB() || clientAutoCommit;
if (!expectAutocommit && xaTxID != null && xaStatus == 0) {
clientTxIsoLation = Isolations.SERIALIZABLE;
xaCmd = "XA START " + xaTxID + ';';
currentXaTxId = xaTxID;
}
int schemaSyn = conSchema.equals(oldSchema) ? 0 : 1;
int charsetSyn = (this.charsetIndex == clientCharSetIndex) ? 0 : 1;
int txIsoLationSyn = (txIsolation == clientTxIsoLation) ? 0 : 1;
int autoCommitSyn = (conAutoComit == expectAutocommit) ? 0 : 1;
int synCount = schemaSyn + charsetSyn + txIsoLationSyn + autoCommitSyn;
if (synCount == 0) {
String sql = rrn.getStatement();
Query query = new Query(PgSqlApaterUtils.apater(sql));
ByteBuffer buf = this.allocate();// XXX 此处处理问题
query.write(buf);
this.write(buf);
return;
}
// TODO COOLLF 此处大锅待实现. 相关 事物, 切换 库,自动提交等功能实现
StringBuilder sb = new StringBuilder();
if (charsetSyn == 1) {
getCharsetCommand(sb, clientCharSetIndex);
}
if (txIsoLationSyn == 1) {
getTxIsolationCommand(sb, clientTxIsoLation);
}
if (autoCommitSyn == 1) {
getAutocommitCommand(sb, expectAutocommit);
}
if (xaCmd != null) {
sb.append(xaCmd);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("con need syn ,total syn cmd " + synCount + " commands " + sb.toString() + "schema change:"
+ ("" != null) + " con:" + this);
}
metaDataSyned = false;
statusSync = new StatusSync(xaCmd != null, conSchema, clientCharSetIndex, clientTxIsoLation, expectAutocommit,
synCount);
String sql = sb.append(PgSqlApaterUtils.apater(rrn.getStatement())).toString();
if(LOGGER.isDebugEnabled()){
LOGGER.debug("con={}, SQL={}", this, sql);
}
Query query = new Query(sql);
ByteBuffer buf = allocate();// 申请ByetBuffer
query.write(buf);
this.write(buf);
metaDataSyned = true;
}
public void close(String reason) {
if (!isClosed.get()) {
isQuit.set(true);
super.close(reason);
pool.connectionClosed(this);
if (this.responseHandler != null) {
this.responseHandler.connectionClose(this, reason);
responseHandler = null;
}
}
}
@Override
public boolean syncAndExcute() {
StatusSync sync = this.statusSync;
if (sync != null) {
boolean executed = sync.synAndExecuted(this);
if (executed) {
statusSync = null;
}
return executed;
}
return true;
}
@Override
public String toString() {
return "PostgreSQLBackendConnection [id=" + id + ", host=" + host + ", port=" + port + ", localPort="
+ localPort + "]";
}
}
| gpl-2.0 |
ctrueden/bioformats | components/forks/mdbtools/src/mdbtools/libmdb06util/mdbver.java | 1360 | /*
* #%L
* Fork of MDB Tools (Java port).
* %%
* Copyright (C) 2008 - 2013 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/*
* Created on Jan 14, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package mdbtools.libmdb06util;
/**
* @author calvin
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class mdbver
{
public static void main(String[] args)
{
}
}
| gpl-2.0 |
aosm/gcc_40 | libjava/java/util/logging/StreamHandler.java | 16999 | /* StreamHandler.java --
A class for publishing log messages to instances of java.io.OutputStream
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.util.logging;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
/**
* A <code>StreamHandler</code> publishes <code>LogRecords</code> to
* a instances of <code>java.io.OutputStream</code>.
*
* @author Sascha Brawer (brawer@acm.org)
*/
public class StreamHandler
extends Handler
{
private OutputStream out;
private Writer writer;
/**
* Indicates the current state of this StreamHandler. The value
* should be one of STATE_FRESH, STATE_PUBLISHED, or STATE_CLOSED.
*/
private int streamState = STATE_FRESH;
/**
* streamState having this value indicates that the StreamHandler
* has been created, but the publish(LogRecord) method has not been
* called yet. If the StreamHandler has been constructed without an
* OutputStream, writer will be null, otherwise it is set to a
* freshly created OutputStreamWriter.
*/
private static final int STATE_FRESH = 0;
/**
* streamState having this value indicates that the publish(LocRecord)
* method has been called at least once.
*/
private static final int STATE_PUBLISHED = 1;
/**
* streamState having this value indicates that the close() method
* has been called.
*/
private static final int STATE_CLOSED = 2;
/**
* Creates a <code>StreamHandler</code> without an output stream.
* Subclasses can later use {@link
* #setOutputStream(java.io.OutputStream)} to associate an output
* stream with this StreamHandler.
*/
public StreamHandler()
{
this(null, null);
}
/**
* Creates a <code>StreamHandler</code> that formats log messages
* with the specified Formatter and publishes them to the specified
* output stream.
*
* @param out the output stream to which the formatted log messages
* are published.
*
* @param formatter the <code>Formatter</code> that will be used
* to format log messages.
*/
public StreamHandler(OutputStream out, Formatter formatter)
{
this(out, "java.util.logging.StreamHandler", Level.INFO,
formatter, SimpleFormatter.class);
}
StreamHandler(
OutputStream out,
String propertyPrefix,
Level defaultLevel,
Formatter formatter, Class defaultFormatterClass)
{
this.level = LogManager.getLevelProperty(propertyPrefix + ".level",
defaultLevel);
this.filter = (Filter) LogManager.getInstanceProperty(
propertyPrefix + ".filter",
/* must be instance of */ Filter.class,
/* default: new instance of */ null);
if (formatter != null)
this.formatter = formatter;
else
this.formatter = (Formatter) LogManager.getInstanceProperty(
propertyPrefix + ".formatter",
/* must be instance of */ Formatter.class,
/* default: new instance of */ defaultFormatterClass);
try
{
String enc = LogManager.getLogManager().getProperty(propertyPrefix
+ ".encoding");
/* make sure enc actually is a valid encoding */
if ((enc != null) && (enc.length() > 0))
new String(new byte[0], enc);
this.encoding = enc;
}
catch (Exception _)
{
}
if (out != null)
{
try
{
changeWriter(out, getEncoding());
}
catch (UnsupportedEncodingException uex)
{
/* This should never happen, since the validity of the encoding
* name has been checked above.
*/
throw new RuntimeException(uex.getMessage());
}
}
}
private void checkOpen()
{
if (streamState == STATE_CLOSED)
throw new IllegalStateException(this.toString() + " has been closed");
}
private void checkFresh()
{
checkOpen();
if (streamState != STATE_FRESH)
throw new IllegalStateException("some log records have been published to " + this);
}
private void changeWriter(OutputStream out, String encoding)
throws UnsupportedEncodingException
{
OutputStreamWriter writer;
/* The logging API says that a null encoding means the default
* platform encoding. However, java.io.OutputStreamWriter needs
* another constructor for the default platform encoding,
* passing null would throw an exception.
*/
if (encoding == null)
writer = new OutputStreamWriter(out);
else
writer = new OutputStreamWriter(out, encoding);
/* Closing the stream has side effects -- do this only after
* creating a new writer has been successful.
*/
if ((streamState != STATE_FRESH) || (this.writer != null))
close();
this.writer = writer;
this.out = out;
this.encoding = encoding;
streamState = STATE_FRESH;
}
/**
* Sets the character encoding which this handler uses for publishing
* log records. The encoding of a <code>StreamHandler</code> must be
* set before any log records have been published.
*
* @param encoding the name of a character encoding, or <code>null</code>
* for the default encoding.
*
* @throws SecurityException if a security manager exists and
* the caller is not granted the permission to control the
* the logging infrastructure.
*
* @exception IllegalStateException if any log records have been
* published to this <code>StreamHandler</code> before. Please
* be aware that this is a pecularity of the GNU implementation.
* While the API specification indicates that it is an error
* if the encoding is set after records have been published,
* it does not mandate any specific behavior for that case.
*/
public void setEncoding(String encoding)
throws SecurityException, UnsupportedEncodingException
{
/* The inherited implementation first checks whether the invoking
* code indeed has the permission to control the logging infra-
* structure, and throws a SecurityException if this was not the
* case.
*
* Next, it verifies that the encoding is supported and throws
* an UnsupportedEncodingExcpetion otherwise. Finally, it remembers
* the name of the encoding.
*/
super.setEncoding(encoding);
checkFresh();
/* If out is null, setEncoding is being called before an output
* stream has been set. In that case, we need to check that the
* encoding is valid, and remember it if this is the case. Since
* this is exactly what the inherited implementation of
* Handler.setEncoding does, we can delegate.
*/
if (out != null)
{
/* The logging API says that a null encoding means the default
* platform encoding. However, java.io.OutputStreamWriter needs
* another constructor for the default platform encoding, passing
* null would throw an exception.
*/
if (encoding == null)
writer = new OutputStreamWriter(out);
else
writer = new OutputStreamWriter(out, encoding);
}
}
/**
* Changes the output stream to which this handler publishes
* logging records.
*
* @throws SecurityException if a security manager exists and
* the caller is not granted the permission to control
* the logging infrastructure.
*
* @throws NullPointerException if <code>out</code>
* is <code>null</code>.
*/
protected void setOutputStream(OutputStream out)
throws SecurityException
{
LogManager.getLogManager().checkAccess();
/* Throw a NullPointerException if out is null. */
out.getClass();
try
{
changeWriter(out, getEncoding());
}
catch (UnsupportedEncodingException ex)
{
/* This seems quite unlikely to happen, unless the underlying
* implementation of java.io.OutputStreamWriter changes its
* mind (at runtime) about the set of supported character
* encodings.
*/
throw new RuntimeException(ex.getMessage());
}
}
/**
* Publishes a <code>LogRecord</code> to the associated output
* stream, provided the record passes all tests for being loggable.
* The <code>StreamHandler</code> will localize the message of the
* log record and substitute any message parameters.
*
* <p>Most applications do not need to call this method directly.
* Instead, they will use use a {@link Logger}, which will create
* LogRecords and distribute them to registered handlers.
*
* <p>In case of an I/O failure, the <code>ErrorManager</code>
* of this <code>Handler</code> will be informed, but the caller
* of this method will not receive an exception.
*
* <p>If a log record is being published to a
* <code>StreamHandler</code> that has been closed earlier, the Sun
* J2SE 1.4 reference can be observed to silently ignore the
* call. The GNU implementation, however, intentionally behaves
* differently by informing the <code>ErrorManager</code> associated
* with this <code>StreamHandler</code>. Since the condition
* indicates a programming error, the programmer should be
* informed. It also seems extremely unlikely that any application
* would depend on the exact behavior in this rather obscure,
* erroneous case -- especially since the API specification does not
* prescribe what is supposed to happen.
*
* @param record the log event to be published.
*/
public void publish(LogRecord record)
{
String formattedMessage;
if (!isLoggable(record))
return;
if (streamState == STATE_FRESH)
{
try
{
writer.write(formatter.getHead(this));
}
catch (java.io.IOException ex)
{
reportError(null, ex, ErrorManager.WRITE_FAILURE);
return;
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.GENERIC_FAILURE);
return;
}
streamState = STATE_PUBLISHED;
}
try
{
formattedMessage = formatter.format(record);
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.FORMAT_FAILURE);
return;
}
try
{
writer.write(formattedMessage);
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.WRITE_FAILURE);
}
}
/**
* Checks whether or not a <code>LogRecord</code> would be logged
* if it was passed to this <code>StreamHandler</code> for publication.
*
* <p>The <code>StreamHandler</code> implementation first checks
* whether a writer is present and the handler's level is greater
* than or equal to the severity level threshold. In a second step,
* if a {@link Filter} has been installed, its {@link
* Filter#isLoggable(LogRecord) isLoggable} method is
* invoked. Subclasses of <code>StreamHandler</code> can override
* this method to impose their own constraints.
*
* @param record the <code>LogRecord</code> to be checked.
*
* @return <code>true</code> if <code>record</code> would
* be published by {@link #publish(LogRecord) publish},
* <code>false</code> if it would be discarded.
*
* @see #setLevel(Level)
* @see #setFilter(Filter)
* @see Filter#isLoggable(LogRecord)
*
* @throws NullPointerException if <code>record</code> is
* <code>null</code>. */
public boolean isLoggable(LogRecord record)
{
return (writer != null) && super.isLoggable(record);
}
/**
* Forces any data that may have been buffered to the underlying
* output device.
*
* <p>In case of an I/O failure, the <code>ErrorManager</code>
* of this <code>Handler</code> will be informed, but the caller
* of this method will not receive an exception.
*
* <p>If a <code>StreamHandler</code> that has been closed earlier
* is closed a second time, the Sun J2SE 1.4 reference can be
* observed to silently ignore the call. The GNU implementation,
* however, intentionally behaves differently by informing the
* <code>ErrorManager</code> associated with this
* <code>StreamHandler</code>. Since the condition indicates a
* programming error, the programmer should be informed. It also
* seems extremely unlikely that any application would depend on the
* exact behavior in this rather obscure, erroneous case --
* especially since the API specification does not prescribe what is
* supposed to happen.
*/
public void flush()
{
try
{
checkOpen();
if (writer != null)
writer.flush();
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.FLUSH_FAILURE);
}
}
/**
* Closes this <code>StreamHandler</code> after having forced any
* data that may have been buffered to the underlying output
* device.
*
* <p>As soon as <code>close</code> has been called,
* a <code>Handler</code> should not be used anymore. Attempts
* to publish log records, to flush buffers, or to modify the
* <code>Handler</code> in any other way may throw runtime
* exceptions after calling <code>close</code>.</p>
*
* <p>In case of an I/O failure, the <code>ErrorManager</code>
* of this <code>Handler</code> will be informed, but the caller
* of this method will not receive an exception.</p>
*
* <p>If a <code>StreamHandler</code> that has been closed earlier
* is closed a second time, the Sun J2SE 1.4 reference can be
* observed to silently ignore the call. The GNU implementation,
* however, intentionally behaves differently by informing the
* <code>ErrorManager</code> associated with this
* <code>StreamHandler</code>. Since the condition indicates a
* programming error, the programmer should be informed. It also
* seems extremely unlikely that any application would depend on the
* exact behavior in this rather obscure, erroneous case --
* especially since the API specification does not prescribe what is
* supposed to happen.
*
* @throws SecurityException if a security manager exists and
* the caller is not granted the permission to control
* the logging infrastructure.
*/
public void close()
throws SecurityException
{
LogManager.getLogManager().checkAccess();
try
{
/* Although flush also calls checkOpen, it catches
* any exceptions and reports them to the ErrorManager
* as flush failures. However, we want to report
* a closed stream as a close failure, not as a
* flush failure here. Therefore, we call checkOpen()
* before flush().
*/
checkOpen();
flush();
if (writer != null)
{
if (formatter != null)
{
/* Even if the StreamHandler has never published a record,
* it emits head and tail upon closing. An earlier version
* of the GNU Classpath implementation did not emitted
* anything. However, this had caused XML log files to be
* entirely empty instead of containing no log records.
*/
if (streamState == STATE_FRESH)
writer.write(formatter.getHead(this));
if (streamState != STATE_CLOSED)
writer.write(formatter.getTail(this));
}
streamState = STATE_CLOSED;
writer.close();
}
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.CLOSE_FAILURE);
}
}
}
| gpl-2.0 |
teamfx/openjfx-8u-dev-tests | functional/FXCssTests/test/test/css/controls/api/ScrollPanesAPICssTest.java | 5253 | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package test.css.controls.api;
import org.junit.Test;
import client.test.Keywords;
import client.test.Smoke;
import org.junit.BeforeClass;
import org.junit.Before;
import test.javaclient.shared.TestBase;
import static test.css.controls.ControlPage.ScrollPanes;
import test.javaclient.shared.screenshots.ScreenshotUtils;
/**
* Generated test
*/
public class ScrollPanesAPICssTest extends TestBase {
{
ScreenshotUtils.setComparatorDistance(0.003f);
}
@BeforeClass
public static void runUI() {
test.css.controls.api.APIStylesApp.main(null);
}
@Before
public void createPage () {
((test.css.controls.api.APIStylesApp)getApplication()).open(ScrollPanes);
}
/**
* test ScrollPane with css: -fx-border-color
*/
@Test
public void ScrollPanes_BORDER_COLOR() throws Exception {
testAdditionalAction(ScrollPanes.name(), "BORDER-COLOR", true);
}
/**
* test ScrollPane with css: -fx-border-width
*/
@Test
public void ScrollPanes_BORDER_WIDTH() throws Exception {
testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH", true);
}
/**
* test ScrollPane with css: -fx-border-width-dotted
*/
@Test
public void ScrollPanes_BORDER_WIDTH_dotted() throws Exception {
testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH-dotted", true);
}
/**
* test ScrollPane with css: -fx-border-width-dashed
*/
@Test
public void ScrollPanes_BORDER_WIDTH_dashed() throws Exception {
testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH-dashed", true);
}
/**
* test ScrollPane with css: -fx-border-inset
*/
@Test
public void ScrollPanes_BORDER_INSET() throws Exception {
testAdditionalAction(ScrollPanes.name(), "BORDER-INSET", true);
}
/**
* test ScrollPane with css: -fx-border-style-dashed
*/
@Test
public void ScrollPanes_BORDER_STYLE_DASHED() throws Exception {
testAdditionalAction(ScrollPanes.name(), "BORDER-STYLE-DASHED", true);
}
/**
* test ScrollPane with css: -fx-border-style-dotted
*/
@Test
public void ScrollPanes_BORDER_STYLE_DOTTED() throws Exception {
testAdditionalAction(ScrollPanes.name(), "BORDER-STYLE-DOTTED", true);
}
/**
* test ScrollPane with css: -fx-image-border
*/
@Test
public void ScrollPanes_IMAGE_BORDER() throws Exception {
testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER", true);
}
/**
* test ScrollPane with css: -fx-image-border-insets
*/
@Test
public void ScrollPanes_IMAGE_BORDER_INSETS() throws Exception {
testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-INSETS", true);
}
/**
* test ScrollPane with css: -fx-image-border-no-repeat
*/
@Test
public void ScrollPanes_IMAGE_BORDER_NO_REPEAT() throws Exception {
testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-NO-REPEAT", true);
}
/**
* test ScrollPane with css: -fx-image-border-repeat-x
*/
@Test
public void ScrollPanes_IMAGE_BORDER_REPEAT_X() throws Exception {
testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-REPEAT-X", true);
}
/**
* test ScrollPane with css: -fx-image-border-repeat-y
*/
@Test
public void ScrollPanes_IMAGE_BORDER_REPEAT_Y() throws Exception {
testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-REPEAT-Y", true);
}
/**
* test ScrollPane with css: -fx-image-border-round
*/
@Test
public void ScrollPanes_IMAGE_BORDER_ROUND() throws Exception {
testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-ROUND", true);
}
/**
* test ScrollPane with css: -fx-image-border-space
*/
@Test
public void ScrollPanes_IMAGE_BORDER_SPACE() throws Exception {
testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-SPACE", true);
}
public String getName() {
return "ControlCss";
}
}
| gpl-2.0 |
rfdrake/opennms | opennms-services/src/main/java/org/opennms/netmgt/threshd/ThresholdEvaluatorRelativeChange.java | 8358 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.threshd;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.xml.event.Event;
import org.springframework.util.Assert;
/**
* Implements a relative change threshold check. A 'value' setting of
* less than 1.0 means that a threshold will fire if the current value
* is less than or equal to the previous value multiplied by the 'value'
* setting. A 'value' setting greater than 1.0 causes the threshold to
* fire if the current value is greater than or equal to the previous
* value multiplied by the 'value' setting. A 'value' setting of 1.0
* (unity) is not allowed, as it represents no change. Zero valued
* samples (0.0) are ignored, as 0.0 multiplied by anything is 0.0 (if
* they were not ignored, an interface that gets no traffic would always
* trigger a threshold, for example).
*
* @author ranger
* @version $Id: $
*/
public class ThresholdEvaluatorRelativeChange implements ThresholdEvaluator {
private static final String TYPE = "relativeChange";
/** {@inheritDoc} */
@Override
public ThresholdEvaluatorState getThresholdEvaluatorState(BaseThresholdDefConfigWrapper threshold) {
return new ThresholdEvaluatorStateRelativeChange(threshold);
}
/** {@inheritDoc} */
@Override
public boolean supportsType(String type) {
return TYPE.equals(type);
}
public static class ThresholdEvaluatorStateRelativeChange extends AbstractThresholdEvaluatorState {
private BaseThresholdDefConfigWrapper m_thresholdConfig;
private double m_multiplier;
private double m_lastSample = 0.0;
private double m_previousTriggeringSample;
public ThresholdEvaluatorStateRelativeChange(BaseThresholdDefConfigWrapper threshold) {
Assert.notNull(threshold, "threshold argument cannot be null");
setThresholdConfig(threshold);
}
public void setThresholdConfig(BaseThresholdDefConfigWrapper thresholdConfig) {
Assert.notNull(thresholdConfig.getType(), "threshold must have a 'type' value set");
Assert.notNull(thresholdConfig.getDatasourceExpression(), "threshold must have a 'ds-name' value set");
Assert.notNull(thresholdConfig.getDsType(), "threshold must have a 'ds-type' value set");
Assert.isTrue(thresholdConfig.hasValue(), "threshold must have a 'value' value set");
Assert.isTrue(thresholdConfig.hasRearm(), "threshold must have a 'rearm' value set");
Assert.isTrue(thresholdConfig.hasTrigger(), "threshold must have a 'trigger' value set");
Assert.isTrue(TYPE.equals(thresholdConfig.getType()), "threshold for ds-name '" + thresholdConfig.getDatasourceExpression() + "' has type of '" + thresholdConfig.getType() + "', but this evaluator only supports thresholds with a 'type' value of '" + TYPE + "'");
Assert.isTrue(!Double.isNaN(thresholdConfig.getValue()), "threshold must have a 'value' value that is a number");
Assert.isTrue(thresholdConfig.getValue() != Double.POSITIVE_INFINITY && thresholdConfig.getValue() != Double.NEGATIVE_INFINITY, "threshold must have a 'value' value that is not positive or negative infinity");
Assert.isTrue(thresholdConfig.getValue() != 1.0, "threshold must not be unity (1.0)");
m_thresholdConfig = thresholdConfig;
setMultiplier(thresholdConfig.getValue());
}
@Override
public BaseThresholdDefConfigWrapper getThresholdConfig() {
return m_thresholdConfig;
}
@Override
public Status evaluate(double dsValue) {
//Fix for Bug 2275 so we handle negative numbers
//It will not handle values which cross the 0 boundary (from - to +, or v.v.) properly, but
// after some discussion, we can't come up with a sensible scenario when that would actually happen.
// If such a scenario eventuates, reconsider
dsValue=Math.abs(dsValue);
if (getLastSample() != 0.0) {
double threshold = getMultiplier() * getLastSample();
if (getMultiplier() < 1.0) {
if (dsValue <= threshold) {
setPreviousTriggeringSample(getLastSample());
setLastSample(dsValue);
return Status.TRIGGERED;
}
} else {
if (dsValue >= threshold) {
setPreviousTriggeringSample(getLastSample());
setLastSample(dsValue);
return Status.TRIGGERED;
}
}
setLastSample(dsValue);
}
setLastSample(dsValue);
return Status.NO_CHANGE;
}
public Double getLastSample() {
return m_lastSample;
}
public void setLastSample(double lastSample) {
m_lastSample = lastSample;
}
@Override
public Event getEventForState(Status status, Date date, double dsValue, CollectionResourceWrapper resource) {
if (status == Status.TRIGGERED) {
String uei=getThresholdConfig().getTriggeredUEI();
if(uei==null || "".equals(uei)) {
uei=EventConstants.RELATIVE_CHANGE_THRESHOLD_EVENT_UEI;
}
return createBasicEvent(uei, date, dsValue, resource);
} else {
return null;
}
}
private Event createBasicEvent(String uei, Date date, double dsValue, CollectionResourceWrapper resource) {
Map<String,String> params = new HashMap<String,String>();
params.put("previousValue", formatValue(getPreviousTriggeringSample()));
params.put("multiplier", Double.toString(getThresholdConfig().getValue()));
// params.put("trigger", Integer.toString(getThresholdConfig().getTrigger()));
// params.put("rearm", Double.toString(getThresholdConfig().getRearm()));
return createBasicEvent(uei, date, dsValue, resource, params);
}
public double getPreviousTriggeringSample() {
return m_previousTriggeringSample;
}
public void setPreviousTriggeringSample(double previousTriggeringSample) {
m_previousTriggeringSample = previousTriggeringSample;
}
public double getMultiplier() {
return m_multiplier;
}
public void setMultiplier(double multiplier) {
m_multiplier = multiplier;
}
@Override
public ThresholdEvaluatorState getCleanClone() {
return new ThresholdEvaluatorStateRelativeChange(m_thresholdConfig);
}
// FIXME This must be implemented correctly
@Override
public boolean isTriggered() {
return false;
}
// FIXME This must be implemented correctly
@Override
public void clearState() {
}
}
}
| gpl-2.0 |
ianopolous/JPC | src/org/jpc/emulator/execution/opcodes/vm/add_o32_rAX_Id.java | 1923 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.vm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class add_o32_rAX_Id extends Executable
{
final int immd;
public add_o32_rAX_Id(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
immd = Modrm.Id(input);
}
public Branch execute(Processor cpu)
{
cpu.flagOp1 = cpu.r_eax.get32();
cpu.flagOp2 = immd;
cpu.flagResult = (cpu.flagOp1 + cpu.flagOp2);
cpu.r_eax.set32(cpu.flagResult);
cpu.flagIns = UCodes.ADD32;
cpu.flagStatus = OSZAPC;
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
ysangkok/JPC | src/org/jpc/emulator/execution/opcodes/vm/fdiv_ST1_ST1.java | 2046 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.vm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class fdiv_ST1_ST1 extends Executable
{
public fdiv_ST1_ST1(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(1);
double freg1 = cpu.fpu.ST(1);
if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1)))
cpu.fpu.setInvalidOperation();
if ((freg0 == 0.0) && !Double.isNaN(freg1) && !Double.isInfinite(freg1))
cpu.fpu.setZeroDivide();
cpu.fpu.setST(1, freg0/freg1);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
rfdrake/opennms | opennms-icmp/opennms-icmp-api/src/main/java/org/opennms/netmgt/icmp/SinglePingResponseCallback.java | 4879 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.icmp;
import java.net.InetAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>SinglePingResponseCallback class.</p>
*
* @author <a href="mailto:ranger@opennms.org">Ben Reed</a>
* @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a>
*/
public class SinglePingResponseCallback implements PingResponseCallback {
private static final Logger LOG = LoggerFactory
.getLogger(SinglePingResponseCallback.class);
/**
* Value of round-trip-time for the ping in microseconds.
*/
private Long m_responseTime = null;
private InetAddress m_host;
private Throwable m_error = null;
private CountDownLatch m_latch = new CountDownLatch(1);
/**
* <p>Constructor for SinglePingResponseCallback.</p>
*
* @param host a {@link java.net.InetAddress} object.
*/
public SinglePingResponseCallback(InetAddress host) {
m_host = host;
}
/** {@inheritDoc} */
@Override
public void handleResponse(InetAddress address, EchoPacket response) {
try {
info("got response for address " + address + ", thread " + response.getIdentifier() + ", seq " + response.getSequenceNumber() + " with a responseTime "+response.elapsedTime(TimeUnit.MILLISECONDS)+"ms");
m_responseTime = (long)Math.round(response.elapsedTime(TimeUnit.MICROSECONDS));
} finally {
m_latch.countDown();
}
}
/** {@inheritDoc} */
@Override
public void handleTimeout(InetAddress address, EchoPacket request) {
try {
assert(request != null);
info("timed out pinging address " + address + ", thread " + request.getIdentifier() + ", seq " + request.getSequenceNumber());
} finally {
m_latch.countDown();
}
}
/** {@inheritDoc} */
@Override
public void handleError(InetAddress address, EchoPacket request, Throwable t) {
try {
m_error = t;
info("an error occurred pinging " + address, t);
} finally {
m_latch.countDown();
}
}
/**
* <p>waitFor</p>
*
* @param timeout a long.
* @throws java.lang.InterruptedException if any.
*/
public void waitFor(long timeout) throws InterruptedException {
m_latch.await(timeout, TimeUnit.MILLISECONDS);
}
/**
* <p>waitFor</p>
*
* @throws java.lang.InterruptedException if any.
*/
public void waitFor() throws InterruptedException {
info("waiting for ping to "+m_host+" to finish");
m_latch.await();
info("finished waiting for ping to "+m_host+" to finish");
}
public void rethrowError() throws Exception {
if (m_error instanceof Error) {
throw (Error)m_error;
} else if (m_error instanceof Exception) {
throw (Exception)m_error;
}
}
/**
* <p>Getter for the field <code>responseTime</code>.</p>
*
* @return a {@link java.lang.Long} object.
*/
public Long getResponseTime() {
return m_responseTime;
}
public Throwable getError() {
return m_error;
}
/**
* <p>info</p>
*
* @param msg a {@link java.lang.String} object.
*/
public void info(String msg) {
LOG.info(msg);
}
/**
* <p>info</p>
*
* @param msg a {@link java.lang.String} object.
* @param t a {@link java.lang.Throwable} object.
*/
public void info(String msg, Throwable t) {
LOG.info(msg, t);
}
}
| gpl-2.0 |
skyHALud/codenameone | CodenameOne/src/com/codename1/ui/VirtualKeyboard.java | 34489 | /*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores
* CA 94065 USA or visit www.oracle.com if you need additional information or
* have any questions.
*/
package com.codename1.ui;
import com.codename1.ui.animations.CommonTransitions;
import com.codename1.ui.animations.Transition;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.geom.Rectangle;
import com.codename1.impl.VirtualKeyboardInterface;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.plaf.Style;
import com.codename1.ui.plaf.UIManager;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* This class represent the Codename One Light Weight Virtual Keyboard
*
* @author Chen Fishbein
*/
public class VirtualKeyboard extends Dialog implements VirtualKeyboardInterface{
private static final String MARKER_COMMIT_ON_DISPOSE = "$VKB_COM$";
private static final String MARKER_TINT_COLOR = "$VKB_TINT$";
private static final String MARKER_VKB = "$VKB$";
private static Transition transitionIn = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, true, 500);
private static Transition transitionOut = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, false, 500);
private int inputType;
/**
* This keymap represents qwerty keyboard
*/
public static final String[][] DEFAULT_QWERTY = new String[][]{
{"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"},
{"a", "s", "d", "f", "g", "h", "j", "k", "l"},
{"$Shift$", "z", "x", "c", "v", "b", "n", "m", "$Delete$"},
{"$Mode$", "$T9$", "$Space$", "$OK$"}
};
/**
* This keymap represents numbers keyboard
*/
public static final String[][] DEFAULT_NUMBERS = new String[][]{
{"1", "2", "3",},
{"4", "5", "6",},
{"7", "8", "9",},
{"*", "0", "#",},
{"$Mode$", "$Space$", "$Delete$", "$OK$"}
};
/**
* This keymap represents numbers and symbols keyboard
*/
public static final String[][] DEFAULT_NUMBERS_SYMBOLS = new String[][]{
{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"},
{"-", "/", ":", ";", "(", ")", "$", "&", "@"},
{".", ",", "?", "!", "'", "\"", "$Delete$"},
{"$Mode$", "$Space$", "$OK$"}
};
/**
* This keymap represents symbols keyboard
*/
public static final String[][] DEFAULT_SYMBOLS = new String[][]{
{"[", "]", "{", "}", "#", "%", "^", "*", "+", "="},
{"_", "\\", "|", "~", "<", ">", "\u00A3", "\u00A5"},
{":-0", ";-)", ":-)", ":-(", ":P", ":D", "$Delete$"},
{"$Mode$", "$Space$", "$OK$"}
};
/**
* The String that represent the qwerty mode.
*/
public static final String QWERTY_MODE = "ABC";
/**
* The String that represent the numbers mode.
*/
public static final String NUMBERS_MODE = "123";
/**
* The String that represent the numbers sybols mode.
*/
public static final String NUMBERS_SYMBOLS_MODE = ".,123";
/**
* The String that represent the symbols mode.
*/
public static final String SYMBOLS_MODE = ".,?";
private static Hashtable modesMap = new Hashtable();
private static String[] defaultInputModeOrder = {QWERTY_MODE,
NUMBERS_SYMBOLS_MODE, NUMBERS_MODE, SYMBOLS_MODE};
private String currentMode = defaultInputModeOrder[0];
private String[] inputModeOrder = defaultInputModeOrder;
private TextField inputField;
private Container buttons = new Container(new BoxLayout(BoxLayout.Y_AXIS));
private TextPainter txtPainter = new TextPainter();
private boolean upperCase = false;
private Button currentButton;
public static final int INSERT_CHAR = 1;
public static final int DELETE_CHAR = 2;
public static final int CHANGE_MODE = 3;
public static final int SHIFT = 4;
public static final int OK = 5;
public static final int SPACE = 6;
public static final int T9 = 7;
private Hashtable specialButtons = new Hashtable();
private TextArea field;
private boolean finishedT9Edit = true;
private String originalText;
private boolean useSoftKeys = false;
private static boolean showTooltips = true;
private boolean okPressed;
private static Class vkbClass;
private VirtualKeyboard vkb;
public final static String NAME = "CodenameOne_VirtualKeyboard";
private boolean isShowing = false;
private static Hashtable defaultInputModes = null;
/**
* Creates a new instance of VirtualKeyboard
*/
public VirtualKeyboard() {
setLayout(new BorderLayout());
setDialogUIID("Container");
getContentPane().setUIID("VKB");
setAutoDispose(false);
setDisposeWhenPointerOutOfBounds(true);
setTransitionInAnimator(transitionIn);
setTransitionOutAnimator(transitionOut);
getTitleComponent().getParent().removeComponent(getTitleComponent());
if(showTooltips) {
setGlassPane(txtPainter);
}
}
public void setInputType(int inputType) {
if((inputType & TextArea.NUMERIC) == TextArea.NUMERIC ||
(inputType & TextArea.PHONENUMBER) == TextArea.PHONENUMBER) {
setInputModeOrder(new String []{NUMBERS_MODE});
return;
}
if((inputType & TextArea.DECIMAL) == TextArea.DECIMAL) {
setInputModeOrder(new String []{NUMBERS_SYMBOLS_MODE});
return;
}
setInputModeOrder(defaultInputModeOrder);
}
static class InputField extends TextField {
private TextArea field;
InputField(TextArea field) {
this.field = field;
setInputMode(field.getInputMode());
setConstraint(field.getConstraint());
}
public boolean hasFocus() {
return true;
}
public String getUIID() {
return "VKBTextInput";
}
public void deleteChar() {
super.deleteChar();
field.setText(getText());
if (field instanceof TextField) {
((TextField) field).setCursorPosition(getCursorPosition());
}
}
public void setCursorPosition(int i) {
super.setCursorPosition(i);
// this can happen since this method is invoked from a constructor of the base class...
if(field != null && field.getText().length() > i && field instanceof TextField) {
((TextField) field).setCursorPosition(i);
}
}
public void setText(String t) {
super.setText(t);
// this can happen since this method is invoked from a constructor of the base class...
if(field != null) {
// mirror events into the parent
field.setText(t);
}
}
public boolean validChar(String c) {
if (field instanceof TextField) {
return ((TextField) field).validChar(c);
}
return true;
}
}
/**
* Invoked internally by the implementation to indicate the text field that will be
* edited by the virtual keyboard
*
* @param field the text field instance
*/
public void setTextField(final TextArea field) {
this.field = field;
removeAll();
okPressed = false;
if(field instanceof TextField){
useSoftKeys = ((TextField)field).isUseSoftkeys();
((TextField)field).setUseSoftkeys(false);
}
originalText = field.getText();
inputField = new InputField(field);
inputField.setText(originalText);
inputField.setCursorPosition(field.getCursorPosition());
inputField.setConstraint(field.getConstraint());
inputField.setInputModeOrder(new String[]{"ABC"});
inputField.setMaxSize(field.getMaxSize());
initModes();
setInputType(field.getConstraint());
initSpecialButtons();
addComponent(BorderLayout.NORTH, inputField);
buttons.getStyle().setPadding(0, 0, 0, 0);
addComponent(BorderLayout.CENTER, buttons);
initInputButtons(upperCase);
inputField.setUseSoftkeys(false);
applyRTL(false);
}
/**
* @inheritDoc
*/
public void show() {
super.showPacked(BorderLayout.SOUTH, true);
}
/**
* @inheritDoc
*/
protected void autoAdjust(int w, int h) {
//if the t9 input is currently editing do not dispose dialog
if (finishedT9Edit) {
setTransitionOutAnimator(CommonTransitions.createEmpty());
dispose();
}
}
/**
* init all virtual keyboard modes, such as QWERTY_MODE, NUMBERS_SYMBOLS_MODE...
* to add an addtitional mode a developer needs to override this method and
* add a mode by calling addInputMode method
*/
protected void initModes() {
addInputMode(QWERTY_MODE, DEFAULT_QWERTY);
addInputMode(NUMBERS_SYMBOLS_MODE, DEFAULT_NUMBERS_SYMBOLS);
addInputMode(SYMBOLS_MODE, DEFAULT_SYMBOLS);
addInputMode(NUMBERS_MODE, DEFAULT_NUMBERS);
if(defaultInputModes != null) {
Enumeration e = defaultInputModes.keys();
while(e.hasMoreElements()) {
String key = (String)e.nextElement();
addInputMode(key, (String[][])defaultInputModes.get(key));
}
}
}
/**
* Sets the current virtual keyboard mode.
*
* @param mode the String that represents the mode(QWERTY_MODE,
* SYMBOLS_MODE, ...)
*/
protected void setCurrentMode(String mode) {
this.currentMode = mode;
}
/**
* Gets the current mode.
*
* @return the String that represents the current mode(QWERTY_MODE,
* SYMBOLS_MODE, ...)
*/
protected String getCurrentMode() {
return currentMode;
}
private void initInputButtons(boolean upperCase) {
buttons.removeAll();
int largestLine = 0;
String[][] currentKeyboardChars = (String[][]) modesMap.get(currentMode);
for (int i = 1; i < currentKeyboardChars.length; i++) {
if (currentKeyboardChars[i].length > currentKeyboardChars[largestLine].length) {
largestLine = i;
}
}
int length = currentKeyboardChars[largestLine].length;
if(length == 0) {
return;
}
Button dummy = createButton(new Command("dummy"), 0);
int buttonMargins = dummy.getUnselectedStyle().getMargin(dummy.isRTL(), LEFT) +
dummy.getUnselectedStyle().getMargin(dummy.isRTL(), RIGHT);
Container row = null;
int rowW = (Display.getInstance().getDisplayWidth() -
getDialogStyle().getPadding(false, LEFT) -
getDialogStyle().getPadding(false, RIGHT) -
getDialogStyle().getMargin(false, LEFT) -
getDialogStyle().getMargin(false, RIGHT));
int availableSpace = rowW - length * buttonMargins;
int buttonSpace = (availableSpace) / length;
for (int i = 0; i < currentKeyboardChars.length; i++) {
int rowWidth = rowW;
row = new Container(new BoxLayout(BoxLayout.X_AXIS));
row.getUnselectedStyle().setMargin(0, 0, 0, 0);
Vector specialsButtons = new Vector();
for (int j = 0; j < currentKeyboardChars[i].length; j++) {
String txt = currentKeyboardChars[i][j];
Button b = null;
if (txt.startsWith("$") && txt.endsWith("$") && txt.length() > 1) {
//add a special button
Button cmd = (Button) specialButtons.get(txt.substring(1, txt.length() - 1));
Command c = null;
int prefW = 0;
if(cmd != null){
c = cmd.getCommand();
int space = ((Integer) cmd.getClientProperty("space")).intValue();
if (space != -1) {
prefW = availableSpace * space / 100;
}
}
b = createButton(c, prefW, "VKBSpecialButton");
if (prefW != 0) {
rowWidth -= (b.getPreferredW() + buttonMargins);
} else {
//if we can't determind the size at this stage, wait until
//the loops ends and give the remains size to the special
//button
specialsButtons.addElement(b);
}
} else {
if (upperCase) {
txt = txt.toUpperCase();
}
b = createInputButton(txt, buttonSpace);
rowWidth -= (b.getPreferredW() + buttonMargins);
}
if (currentButton != null) {
if (currentButton.getCommand() != null &&
b.getCommand() != null &&
currentButton.getCommand().getId() == b.getCommand().getId()) {
currentButton = b;
}
if (currentButton.getText().equals(b.getText())) {
currentButton = b;
}
}
row.addComponent(b);
}
int emptySpace = Math.max(rowWidth, 0);
//if we have special buttons on the keyboard give them the size or
//else give the remain size to the row margins
if (specialsButtons.size() > 0) {
int prefW = emptySpace / specialsButtons.size();
for (int j = 0; j < specialsButtons.size(); j++) {
Button special = (Button) specialsButtons.elementAt(j);
special.setPreferredW(prefW);
}
} else {
row.getUnselectedStyle().setPadding(Component.LEFT, 0);
row.getUnselectedStyle().setPadding(Component.RIGHT, 0);
row.getUnselectedStyle().setMarginUnit(new byte[]{Style.UNIT_TYPE_PIXELS,
Style.UNIT_TYPE_PIXELS,
Style.UNIT_TYPE_PIXELS,
Style.UNIT_TYPE_PIXELS});
row.getUnselectedStyle().setMargin(Component.LEFT, emptySpace / 2);
row.getUnselectedStyle().setMargin(Component.RIGHT, emptySpace / 2);
}
buttons.addComponent(row);
}
applyRTL(false);
}
private Button createInputButton(String text, int prefSize) {
Button b = createButton(new Command(text, INSERT_CHAR), prefSize);
b.putClientProperty("glasspane", "true");
return b;
}
private Button createButton(Command cmd, int prefSize) {
return createButton(cmd, prefSize, "VKBButton");
}
private Button createButton(Command cmd, int prefSize, String uiid) {
Button btn;
if(cmd != null){
btn = new Button(cmd);
}else{
btn = new Button();
btn.setVisible(false);
}
final Button b = btn;
b.setUIID(uiid);
b.setEndsWith3Points(false);
b.setAlignment(Component.CENTER);
prefSize = Math.max(prefSize, b.getPreferredW());
b.setPreferredW(prefSize);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
currentButton = b;
}
});
return b;
}
/**
* Add an input mode to the virtual keyboard
*
* @param mode a string that represents the identifier of the mode
* @param inputChars 2 dimensional String array that contains buttons String
* and special buttons (a special button is identified with $...$ marks
* e.g: "$Space$")
*/
public static void addDefaultInputMode(String mode, String[][] inputChars) {
if(defaultInputModes == null) {
defaultInputModes = new Hashtable();
}
defaultInputModes.put(mode, inputChars);
}
/**
* Add an input mode to the virtual keyboard
*
* @param mode a string that represents the identifier of the mode
* @param inputChars 2 dimentional String array that contains buttons String
* and special buttons (a special button is identified with $...$ marks
* e.g: "$Space$")
*/
public void addInputMode(String mode, String[][] inputChars) {
modesMap.put(mode, inputChars);
}
/**
* This method adds a special button to the virtual keyboard
*
* @param key the string identifier from within the relevant input mode
* @param cmd the Command to invoke when this button is invoked.
*/
public void addSpecialButton(String key, Command cmd) {
addSpecialButton(key, cmd, -1);
}
/**
* This method adds a special button to the virtual keyboard
*
* @param key the string identifier from within the relevant input mode
* @param cmd the Command to invoke when this button is invoked.
* @param space how much space in percentage from the overall row
* the special button should occupy
*/
public void addSpecialButton(String key, Command cmd, int space) {
Button b = new Button(cmd);
b.putClientProperty("space", new Integer(space));
specialButtons.put(key, b);
}
private String getNextMode(String current) {
for (int i = 0; i < inputModeOrder.length - 1; i++) {
String mode = inputModeOrder[i];
if(mode.equals(current)){
return inputModeOrder[i + 1];
}
}
return inputModeOrder[0];
}
/**
* @inheritDoc
*/
public void pointerPressed(int x, int y) {
super.pointerPressed(x, y);
Component cmp = getComponentAt(x, y);
if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) {
txtPainter.showButtonOnGlasspane((Button) cmp);
}
}
/**
* @inheritDoc
*/
public void pointerDragged(int x, int y) {
super.pointerDragged(x, y);
Component cmp = getComponentAt(x, y);
if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) {
txtPainter.showButtonOnGlasspane((Button) cmp);
}
}
/**
* @inheritDoc
*/
public void pointerReleased(int x, int y) {
if(showTooltips) {
txtPainter.clear();
}
super.pointerReleased(x, y);
}
/**
* This method initialize all the virtual keyboard special buttons.
*/
protected void initSpecialButtons() {
//specialButtons.clear();
addSpecialButton("Shift", new Command("SH", SHIFT), 15);
addSpecialButton("Delete", new Command("Del", DELETE_CHAR), 15);
addSpecialButton("T9", new Command("T9", T9), 15);
addSpecialButton("Mode", new Command(getNextMode(currentMode), CHANGE_MODE));
addSpecialButton("Space", new Command("Space", SPACE), 50);
addSpecialButton("OK", new Command("Ok", OK));
}
/**
* Returns the order in which input modes are toggled
*
* @return the order of the input modes
*/
public String[] getInputModeOrder() {
return inputModeOrder;
}
/**
* Sets the order in which input modes are toggled and allows disabling/hiding
* an input mode
*
* @param order the order for the input modes in this field
*/
public void setInputModeOrder(String[] order) {
inputModeOrder = order;
setCurrentMode(order[0]);
}
/**
* Returns the order in which input modes are toggled by default
*
* @return the default order of the input mode
*/
public static String[] getDefaultInputModeOrder() {
return defaultInputModeOrder;
}
/**
* Sets the order in which input modes are toggled by default and allows
* disabling/hiding an input mode
*
* @param order the order for the input modes in all future created fields
*/
public static void setDefaultInputModeOrder(String[] order) {
defaultInputModeOrder = order;
}
class TextPainter implements Painter {
private Label label = new Label();
private boolean paint = true;
public TextPainter() {
label = new Label();
label.setUIID("VKBtooltip");
}
public void showButtonOnGlasspane(Button button) {
if(label.getText().equals(button.getText())){
return;
}
paint = true;
repaint(label.getAbsoluteX()-2,
label.getAbsoluteY()-2,
label.getWidth()+4,
label.getHeight()+4);
label.setText(button.getText());
label.setSize(label.getPreferredSize());
label.setX(button.getAbsoluteX() + (button.getWidth() - label.getWidth()) / 2);
label.setY(button.getAbsoluteY() - label.getPreferredH() * 4 / 3);
repaint(label.getAbsoluteX()-2,
label.getAbsoluteY()-2,
label.getPreferredW()+4,
label.getPreferredH()+4);
}
public void paint(Graphics g, Rectangle rect) {
if (paint) {
label.paintComponent(g);
}
}
private void clear() {
paint = false;
repaint();
}
}
private void updateText(String txt) {
field.setText(txt);
if(field instanceof TextField){
((TextField)field).setCursorPosition(txt.length());
}
if(okPressed){
field.fireActionEvent();
if(field instanceof TextField){
((TextField)field).fireDoneEvent();
}
}
}
/**
* @inheritDoc
*/
protected void actionCommand(Command cmd) {
super.actionCommand(cmd);
switch (cmd.getId()) {
case OK:
okPressed = true;
updateText(inputField.getText());
dispose();
break;
case INSERT_CHAR:
Button btn = currentButton;
String text = btn.getText();
if (inputField.getText().length() == 0) {
inputField.setText(text);
inputField.setCursorPosition(text.length());
} else {
inputField.insertChars(text);
}
break;
case SPACE:
if (inputField.getText().length() == 0) {
inputField.setText(" ");
} else {
inputField.insertChars(" ");
}
break;
case DELETE_CHAR:
inputField.deleteChar();
break;
case CHANGE_MODE:
currentMode = getNextMode(currentMode);
Display.getInstance().callSerially(new Runnable() {
public void run() {
initInputButtons(upperCase);
String next = getNextMode(currentMode);
currentButton.setText(next);
currentButton.getCommand().setCommandName(next);
setTransitionOutAnimator(CommonTransitions.createEmpty());
setTransitionInAnimator(CommonTransitions.createEmpty());
revalidate();
show();
}
});
return;
case SHIFT:
if (currentMode.equals(QWERTY_MODE)) {
upperCase = !upperCase;
Display.getInstance().callSerially(new Runnable() {
public void run() {
initInputButtons(upperCase);
revalidate();
}
});
}
return;
case T9:
finishedT9Edit = false;
if(field != null){
Display.getInstance().editString(field, field.getMaxSize(), field.getConstraint(), field.getText());
}else{
Display.getInstance().editString(inputField, inputField.getMaxSize(), inputField.getConstraint(), inputField.getText());
}
dispose();
finishedT9Edit = true;
}
}
/**
* @inheritDoc
*/
public void dispose() {
if (field != null) {
if (!okPressed && !isCommitOnDispose(field) && finishedT9Edit) {
field.setText(originalText);
}
if(field instanceof TextField){
((TextField)field).setUseSoftkeys(useSoftKeys);
}
setTransitionInAnimator(transitionIn);
field = null;
}
currentMode = inputModeOrder[0];
super.dispose();
}
/**
* @inheritDoc
*/
protected void onShow() {
super.onShow();
setTransitionOutAnimator(transitionOut);
}
/**
* This method returns the Virtual Keyboard TextField.
*
* @return the the Virtual Keyboard TextField.
*/
protected TextField getInputField() {
return inputField;
}
/**
* Indicates whether the VKB should commit changes to the text field when the VKB
* is closed not via the OK button. This might be useful for some situations such
* as searches
*
* @param tf the text field to mark as commit on dispose
* @param b the value of commit on dispose, true to always commit changes
*/
public static void setCommitOnDispose(TextField tf, boolean b) {
tf.putClientProperty(MARKER_COMMIT_ON_DISPOSE, new Boolean(b));
}
/**
* This method is used to bind a specific instance of a virtual keyboard to a specific TextField.
* For example if a specific TextField requires only numeric input consider using this method as follows:
*
* TextField tf = new TextField();
* tf.setConstraint(TextField.NUMERIC);
* tf.setInputModeOrder(new String[]{"123"});
* VirtualKeyboard vkb = new VirtualKeyboard();
* vkb.setInputModeOrder(new String[]{VirtualKeyboard.NUMBERS_MODE});
* VirtualKeyboard.bindVirtualKeyboard(tf, vkb);
*
* @param t the TextField to bind a VirualKeyboard to.
* @param vkb the binded VirualKeyboard.
*/
public static void bindVirtualKeyboard(TextArea t, VirtualKeyboard vkb) {
t.putClientProperty(MARKER_VKB, vkb);
}
/**
* This method returns the Textfield associated VirtualKeyboard,
* see bindVirtualKeyboard(TextField tf, VirtualKeyboard vkb) method.
*
* @param t a TextField.that might have an associated VirtualKeyboard instance
* @return a VirtualKeyboard instance or null if not exists.
*/
public static VirtualKeyboard getVirtualKeyboard(TextArea t) {
return (VirtualKeyboard) t.getClientProperty(MARKER_VKB);
}
/**
* Indicates whether the given text field should commit on dispose
*
* @param tf the text field
* @return true if the text field should save the data despite the fact that it
* was disposed in an irregular way
*/
public static boolean isCommitOnDispose(TextArea tf) {
Boolean b = (Boolean)tf.getClientProperty(MARKER_COMMIT_ON_DISPOSE);
return (b != null) && b.booleanValue();
}
/**
* Sets the tint color for the virtual keyboard when shown on top of this text field
* see the form tint methods for more information
*
* @param tf the relevant text field
* @param tint the tint color with an alpha channel
*/
public static void setVKBTint(TextField tf, int tint) {
tf.putClientProperty(MARKER_TINT_COLOR, new Integer(tint));
}
/**
* The tint color for the virtual keyboard when shown on top of this text field
* see the form tint methods for more information
*
* @param tf the relevant text field
* @return the tint color with an alpha channel
*/
public static int getVKBTint(TextArea tf) {
Integer v = (Integer)tf.getClientProperty(MARKER_TINT_COLOR);
if(v != null) {
return v.intValue();
}
Form current = Display.getInstance().getCurrent();
return current.getUIManager().getLookAndFeel().getDefaultFormTintColor();
}
/**
* Indicates whether tooltips should be shown when the keys in the VKB are pressed
*
* @return the showTooltips
*/
public static boolean isShowTooltips() {
return showTooltips;
}
/**
* Indicates whether tooltips should be shown when the keys in the VKB are pressed
*
* @param aShowTooltips true to show tooltips
*/
public static void setShowTooltips(boolean aShowTooltips) {
showTooltips = aShowTooltips;
}
/**
* The transition in for the VKB
*
* @return the transitionIn
*/
public static Transition getTransitionIn() {
return transitionIn;
}
/**
* The transition in for the VKB
*
* @param aTransitionIn the transitionIn to set
*/
public static void setTransitionIn(Transition aTransitionIn) {
transitionIn = aTransitionIn;
}
/**
* The transition out for the VKB
*
* @return the transitionOut
*/
public static Transition getTransitionOut() {
return transitionOut;
}
/**
* The transition out for the VKB
*
* @param aTransitionOut the transitionOut to set
*/
public static void setTransitionOut(Transition aTransitionOut) {
transitionOut = aTransitionOut;
}
/**
* Shows the virtual keyboard that is assoiciated with the displayed TextField
* or displays the default virtual keyboard.
*
* @param show it show is true open the relevant keyboard, if close dispose
* the displayed keyboard
*/
public void showKeyboard(boolean show) {
isShowing = show;
Form current = Display.getInstance().getCurrent();
if (show) {
Component foc = current.getFocused();
if(foc instanceof Container) {
foc = ((Container)foc).getLeadComponent();
}
TextArea txtCmp = (TextArea) foc;
if (txtCmp != null) {
if(vkb != null && vkb.contains(txtCmp)){
return;
}
vkb = VirtualKeyboard.getVirtualKeyboard(txtCmp);
if(vkb == null){
vkb = createVirtualKeyboard();
}
vkb.setTextField(txtCmp);
int oldTint = current.getTintColor();
current.setTintColor(VirtualKeyboard.getVKBTint(txtCmp));
boolean third = com.codename1.ui.Display.getInstance().isThirdSoftButton();
com.codename1.ui.Display.getInstance().setThirdSoftButton(false);
boolean qwerty = txtCmp.isQwertyInput();
if(txtCmp instanceof TextField){
((TextField) txtCmp).setQwertyInput(true);
}
vkb.showDialog();
if (txtCmp instanceof TextField) {
((TextField) txtCmp).setQwertyInput(qwerty);
}
com.codename1.ui.Display.getInstance().setThirdSoftButton(third);
current.setTintColor(oldTint);
}
}
}
/**
* Sets the default virtual keyboard class for the com.codename1.ui.VirtualKeyboard
* type
* This class is used as the default virtual keyboard class if the current
* platform VirtualKeyboard is com.codename1.ui.VirtualKeyboard.
* Platform VirtualKeyboard is defined here:
* Display.getIntance().setDefaultVirtualKeyboard(VirtualKeyboardInterface vkb)
*
* @param vkbClazz this class must extend VirtualKeyboard.
*/
public static void setDefaultVirtualKeyboardClass(Class vkbClazz){
vkbClass = vkbClazz;
}
private VirtualKeyboard createVirtualKeyboard() {
try {
if(vkbClass != null){
return (VirtualKeyboard) vkbClass.newInstance();
}else{
return new VirtualKeyboard();
}
} catch (Exception ex) {
ex.printStackTrace();
return new VirtualKeyboard();
}
}
/**
* @see VirtualKeyboardInterface
*/
public String getVirtualKeyboardName() {
return NAME;
}
/**
* @see VirtualKeyboardInterface
*/
public boolean isVirtualKeyboardShowing() {
return isShowing;
}
}
| gpl-2.0 |
md-5/jdk10 | src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir/src/org/graalvm/compiler/lir/asm/ArrayDataPointerConstant.java | 3453 | /*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.lir.asm;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import org.graalvm.compiler.core.common.type.DataPointerConstant;
/**
* Class for chunks of data that go into the data section.
*/
public class ArrayDataPointerConstant extends DataPointerConstant {
private final byte[] data;
public ArrayDataPointerConstant(byte[] array, int alignment) {
super(alignment);
data = array.clone();
}
public ArrayDataPointerConstant(short[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 2);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asShortBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(int[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asIntBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(float[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asFloatBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(double[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asDoubleBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(long[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asLongBuffer().put(array);
data = byteBuffer.array();
}
@Override
public boolean isDefaultForKind() {
return false;
}
@Override
public void serialize(ByteBuffer buffer) {
buffer.put(data);
}
@Override
public int getSerializedSize() {
return data.length;
}
@Override
public String toValueString() {
return "ArrayDataPointerConstant" + Arrays.toString(data);
}
}
| gpl-2.0 |
ysangkok/JPC | src/org/jpc/emulator/execution/opcodes/rm/rep_movsb_a32.java | 1819 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.rm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class rep_movsb_a32 extends Executable
{
final int segIndex;
public rep_movsb_a32(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
segIndex = Prefices.getSegment(prefices, Processor.DS_INDEX);
}
public Branch execute(Processor cpu)
{
Segment seg = cpu.segs[segIndex];
StaticOpcodes.rep_movsb_a32(cpu, seg);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
GiGatR00n/Aion-Core-v4.7.5 | AC-Game/data/scripts/system/handlers/quest/beluslan/_2533BeritrasCurse.java | 5403 | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
*
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package quest.beluslan;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.HandlerResult;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.model.DialogAction;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.services.QuestService;
import com.aionemu.gameserver.world.zone.ZoneName;
/**
* @author Ritsu
*
*/
public class _2533BeritrasCurse extends QuestHandler {
private final static int questId = 2533;
public _2533BeritrasCurse() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(204801).addOnQuestStart(questId); //Gigrite
qe.registerQuestNpc(204801).addOnTalkEvent(questId);
qe.registerQuestItem(182204425, questId);//Empty Durable Potion Bottle
qe.registerOnQuestTimerEnd(questId);
}
@Override
public HandlerResult onItemUseEvent(final QuestEnv env, Item item) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs != null && qs.getStatus() == QuestStatus.START) {
if (player.isInsideZone(ZoneName.get("BERITRAS_WEAPON_220040000"))) {
QuestService.questTimerStart(env, 300);
return HandlerResult.fromBoolean(useQuestItem(env, item, 0, 1, false, 182204426, 1, 0));
}
}
return HandlerResult.SUCCESS; // ??
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
int targetId = 0;
if (env.getVisibleObject() instanceof Npc) {
targetId = ((Npc) env.getVisibleObject()).getNpcId();
}
final QuestState qs = player.getQuestStateList().getQuestState(questId);
DialogAction dialog = env.getDialog();
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
if (targetId == 204801) {
if (dialog == DialogAction.QUEST_SELECT) {
return sendQuestDialog(env, 4762);
} else if (dialog == DialogAction.QUEST_ACCEPT_1) {
if (!giveQuestItem(env, 182204425, 1)) {
return true;
}
return sendQuestStartDialog(env);
} else {
return sendQuestStartDialog(env);
}
}
} else if (qs.getStatus() == QuestStatus.START) {
int var = qs.getQuestVarById(0);
if (targetId == 204801) {
switch (dialog) {
case QUEST_SELECT:
if (var == 1) {
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return sendQuestDialog(env, 1352);
}
case SELECT_QUEST_REWARD: {
QuestService.questTimerEnd(env);
return sendQuestDialog(env, 5);
}
}
}
} else if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 204801) {
return sendQuestEndDialog(env);
}
}
return false;
}
@Override
public boolean onQuestTimerEndEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs != null && qs.getStatus() == QuestStatus.START) {
removeQuestItem(env, 182204426, 1);
QuestService.abandonQuest(player, questId);
player.getController().updateNearbyQuests();
return true;
}
return false;
}
}
| gpl-2.0 |
rfdrake/opennms | opennms-dao-api/src/main/java/org/opennms/netmgt/dao/api/MemoDao.java | 1404 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao.api;
import org.opennms.netmgt.model.OnmsMemo;
/**
* @author <a href="mailto:Markus@OpenNMS.com">Markus Neumann</a>
*/
public interface MemoDao extends OnmsDao<OnmsMemo, Integer> {
}
| gpl-2.0 |
atsoc0ocsav/IEEE-Firefighter | ieeefirefighter-beta/pc/pccomm-src/lejos/robotics/mapping/ShapefileLoader.java | 9323 | package lejos.robotics.mapping;
import java.io.*;
import java.util.ArrayList;
import lejos.geom.Line;
import lejos.geom.Rectangle;
/*
* WARNING: THIS CLASS IS SHARED BETWEEN THE classes AND pccomms PROJECTS.
* DO NOT EDIT THE VERSION IN pccomms AS IT WILL BE OVERWRITTEN WHEN THE PROJECT IS BUILT.
*/
/**
* <p>This class loads map data from a Shapefile and produces a LineMap object, which can
* be used by the leJOS navigation package.</p>
*
* <p>There are many map editors which can use the Shapefile format (OpenEV, Global Mapper). Once you
* have created a map, export it as Shapefile. This will produce three files ending in .shp .shx and
* .dbf. The only file used by this class is .shp.</p>
*
* <p>NOTE: Shapefiles can only contain one type of shape data (polygon or polyline, not both). A single file can't
* mix polylines with polygons.</p>
*
* <p>This class' code can parse points and multipoints. However, a LineMap object can't deal with
* points (only lines) so points and multipoints are discarded.</p>
*
* @author BB
*
*/
public class ShapefileLoader {
/* OTHER POTENTIAL MAP FILE FORMATS TO ADD:
* (none have really been researched yet for viability)
* KML
* GML
* WMS? (more of a service than a file)
* MIF/MID (MapInfo)
* SVG (Scalable Vector Graphics)
* EPS (Encapsulated Post Script)
* DXF (Autodesk)
* AI (Adobe Illustrator)
*
*/
// 2D shape types types:
private static final byte NULL_SHAPE = 0;
private static final byte POINT = 1;
private static final byte POLYLINE = 3;
private static final byte POLYGON = 5;
private static final byte MULTIPOINT = 8;
private final int SHAPEFILE_ID = 0x0000270a;
DataInputStream data_is = null;
/**
* Creates a ShapefileLoader object using an input stream. Likely you will use a FileInputStream
* which points to the *.shp file containing the map data.
* @param in
*/
public ShapefileLoader(InputStream in) {
this.data_is = new DataInputStream(in);
}
/**
* Retrieves a LineMap object from the Shapefile input stream.
* @return the line map
* @throws IOException
*/
public LineMap readLineMap() throws IOException {
ArrayList <Line> lines = new ArrayList <Line> ();
int fileCode = data_is.readInt(); // Big Endian
if(fileCode != SHAPEFILE_ID) throw new IOException("File is not a Shapefile");
data_is.skipBytes(20); // Five int32 unused by Shapefile
/*int fileLength =*/ data_is.readInt();
//System.out.println("Length: " + fileLength); // TODO: Docs say length is in 16-bit words. Unsure if this is strictly correct. Seems higher than what hex editor shows.
/*int version =*/ readLEInt();
//System.out.println("Version: " + version);
/*int shapeType =*/ readLEInt();
//System.out.println("Shape type: " + shapeType);
// These x and y min/max values define bounding rectangle:
double xMin = readLEDouble();
double yMin = readLEDouble();
double xMax = readLEDouble();
double yMax = readLEDouble();
// Create bounding rectangle:
Rectangle rect = new Rectangle((float)xMin, (float)yMin, (float)(xMax - xMin), (float)(yMax - yMin));
/*double zMin =*/ readLEDouble();
/*double zMax =*/ readLEDouble();
/*double mMin =*/ readLEDouble();
/*double mMax =*/ readLEDouble();
// TODO These values seem to be rounded down to nearest 0.5. Must round them up?
//System.out.println("Xmin " + xMin + " Ymin " + yMin);
//System.out.println("Xmax " + xMax + " Ymax " + yMax);
try { // TODO: This is a cheesy way to detect EOF condition. Not very good coding.
while(2 > 1) { // TODO: Temp code to keep it looping. Should really detect EOF condition.
// NOW ONTO READING INDIVIDUAL SHAPES:
// Record Header (2 values):
/*int recordNum =*/ data_is.readInt();
int recordLen = data_is.readInt(); // TODO: in 16-bit words. Might cause bug if number of shapes gets bigger than 16-bit short?
// Record (variable length depending on shape type):
int recShapeType = readLEInt();
// Now to read the actual shape data
switch (recShapeType) {
case NULL_SHAPE:
break;
case POINT:
// DO WE REALLY NEED TO DEAL WITH POINT? Feature might use them possibly.
/*double pointX =*/ readLEDouble(); // TODO: skip bytes instead
/*double pointY =*/ readLEDouble();
break;
case POLYLINE:
// NOTE: Data structure for polygon/polyline is identical. Code should work for both.
case POLYGON:
// Polygons can contain multiple polygons, such as a donut with outer ring and inner ring for hole.
// Max bounding rect: 4 doubles in a row. TODO: Discard bounding rect. values and skip instead.
/*double polyxMin =*/ readLEDouble();
/*double polyyMin =*/ readLEDouble();
/*double polyxMax =*/ readLEDouble();
/*double polyyMax =*/ readLEDouble();
int numParts = readLEInt();
int numPoints = readLEInt();
// Retrieve array of indexes for each part in the polygon
int [] partIndex = new int[numParts];
for(int i=0;i<numParts;i++) {
partIndex[i] = readLEInt();
}
// Now go through numParts times pulling out points
double firstX=0;
double firstY=0;
for(int i=0;i<numPoints-1;i++) {
// Could check here if onto new polygon (i = next index). If so, do something with line formation.
for(int j=0;j<numParts;j++) {
if(i == partIndex[j]) {
firstX = readLEDouble();
firstY = readLEDouble();
continue;
}
}
double secondX = readLEDouble();
double secondY = readLEDouble();
Line myLine = new Line((float)firstX, (float)firstY, (float)secondX, (float)secondY);
lines.add(myLine);
firstX = secondX;
firstY = secondY;
}
break;
case MULTIPOINT:
// TODO: DO WE REALLY NEED TO DEAL WITH MULTIPOINT? Comment out and skip bytes?
/*double multixMin = */readLEDouble();
/*double multiyMin = */readLEDouble();
/*double multixMax = */readLEDouble();
/*double multiyMax = */readLEDouble();
int multiPoints = readLEInt();
double [] xVals = new double[multiPoints];
double [] yVals = new double[multiPoints];
for(int i=0;i<multiPoints;i++) {
xVals[i] = readLEDouble();
yVals[i] = readLEDouble();
}
break;
default:
// IGNORE REST OF SHAPE TYPES and skip over data using recordLen value
//System.out.println("Some other unknown shape");
data_is.skipBytes(recordLen); // TODO: Check if this works on polyline or point
}
} // END OF WHILE
} catch(EOFException e) {
// End of File, just needs to continue
}
Line [] arrList = new Line [lines.size()];
return new LineMap(lines.toArray(arrList), rect);
}
/**
* Translates a little endian int into a big endian int
*
* @return int A big endian int
*/
private int readLEInt() throws IOException {
int byte1, byte2, byte3, byte4;
synchronized (this) {
byte1 = data_is.read();
byte2 = data_is.read();
byte3 = data_is.read();
byte4 = data_is.read();
}
if (byte4 == -1) {
throw new EOFException();
}
return (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1;
}
/**
* Reads a little endian double into a big endian double
*
* @return double A big endian double
*/
private final double readLEDouble() throws IOException {
return Double.longBitsToDouble(this.readLELong());
}
/**
* Translates a little endian long into a big endian long
*
* @return long A big endian long
*/
private long readLELong() throws IOException {
long byte1 = data_is.read();
long byte2 = data_is.read();
long byte3 = data_is.read();
long byte4 = data_is.read();
long byte5 = data_is.read();
long byte6 = data_is.read();
long byte7 = data_is.read();
long byte8 = data_is.read();
if (byte8 == -1) {
throw new EOFException();
}
return (byte8 << 56) + (byte7 << 48) + (byte6 << 40) + (byte5 << 32)
+ (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1;
}
}
| gpl-2.0 |
FauxFaux/jdk9-jdk | test/java/util/ResourceBundle/modules/visibility/src/test/module-info.java | 1283 | /*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
module test {
// jdk.test.resources.classes.MyResourcesProvider is in named.bundles.
requires named.bundles;
uses jdk.test.resources.classes.MyResourcesProvider;
uses jdk.test.resources.props.MyResourcesProvider;
}
| gpl-2.0 |
sqe-team/sqe | codedefects.history/src/org/nbheaven/sqe/codedefects/history/action/SnapshotAction.java | 3600 | /* Copyright 2005,2006 Sven Reimers, Florian Vogler
*
* This file is part of the Software Quality Environment Project.
*
* The Software Quality Environment Project is free software:
* you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation,
* either version 2 of the License, or (at your option) any later version.
*
* The Software Quality Environment Project is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package org.nbheaven.sqe.codedefects.history.action;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.Collection;
import javax.swing.AbstractAction;
import javax.swing.Action;
import org.nbheaven.sqe.codedefects.core.util.SQECodedefectSupport;
import org.nbheaven.sqe.codedefects.history.util.CodeDefectHistoryPersistence;
import org.netbeans.api.project.Project;
import org.openide.util.ContextAwareAction;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
/**
*
* @author Sven Reimers
*/
public class SnapshotAction extends AbstractAction implements LookupListener, ContextAwareAction {
private Lookup context;
private Lookup.Result<Project> lkpInfo;
public SnapshotAction() {
this(Utilities.actionsGlobalContext());
}
public SnapshotAction(Lookup context) {
putValue("noIconInMenu", Boolean.TRUE); // NOI18N
putValue(Action.SHORT_DESCRIPTION,
NbBundle.getMessage(SnapshotAction.class, "HINT_Action"));
putValue(SMALL_ICON, ImageUtilities.image2Icon(ImageUtilities.loadImage("org/nbheaven/sqe/codedefects/history/resources/camera.png")));
this.context = context;
//The thing we want to listen for the presence or absence of
//on the global selection
Lookup.Template<Project> tpl = new Lookup.Template<Project>(Project.class);
lkpInfo = context.lookup(tpl);
lkpInfo.addLookupListener(this);
resultChanged(null);
}
@Override
public Action createContextAwareInstance(Lookup context) {
return new SnapshotAction(context);
}
@Override
public void resultChanged(LookupEvent ev) {
updateEnableState();
}
public String getName() {
return NbBundle.getMessage(SnapshotAction.class, "LBL_Action");
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (null != getActiveProject()) {
Project project = getActiveProject();
CodeDefectHistoryPersistence.addSnapshot(project);
}
}
private void updateEnableState() {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(() -> updateEnableState());
return;
}
setEnabled(SQECodedefectSupport.isQualityAwareProject(getActiveProject()));
}
private Project getActiveProject() {
Collection<? extends Project> projects = lkpInfo.allInstances();
if (projects.size() == 1) {
Project project = projects.iterator().next();
return project;
}
return null;
}
}
| gpl-2.0 |
bigdataviewer/SPIM_Registration | src/main/java/spim/fiji/plugin/ThinOut_Detections.java | 15827 | /*-
* #%L
* Fiji distribution of ImageJ for the life sciences.
* %%
* Copyright (C) 2007 - 2017 Fiji developers.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package spim.fiji.plugin;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import mpicbg.spim.data.sequence.Channel;
import mpicbg.spim.data.sequence.ViewDescription;
import mpicbg.spim.data.sequence.ViewId;
import mpicbg.spim.data.sequence.VoxelDimensions;
import mpicbg.spim.io.IOFunctions;
import net.imglib2.KDTree;
import net.imglib2.RealPoint;
import net.imglib2.neighborsearch.KNearestNeighborSearchOnKDTree;
import spim.fiji.plugin.queryXML.LoadParseQueryXML;
import spim.fiji.plugin.thinout.ChannelProcessThinOut;
import spim.fiji.plugin.thinout.Histogram;
import spim.fiji.spimdata.SpimData2;
import spim.fiji.spimdata.interestpoints.InterestPoint;
import spim.fiji.spimdata.interestpoints.InterestPointList;
import spim.fiji.spimdata.interestpoints.ViewInterestPointLists;
import spim.fiji.spimdata.interestpoints.ViewInterestPoints;
public class ThinOut_Detections implements PlugIn
{
public static boolean[] defaultShowHistogram;
public static int[] defaultSubSampling;
public static String[] defaultNewLabels;
public static int[] defaultRemoveKeep;
public static double[] defaultCutoffThresholdMin, defaultCutoffThresholdMax;
public static String[] removeKeepChoice = new String[]{ "Remove Range", "Keep Range" };
public static double defaultThresholdMinValue = 0;
public static double defaultThresholdMaxValue = 5;
public static int defaultSubSamplingValue = 1;
public static String defaultNewLabelText = "thinned-out";
public static int defaultRemoveKeepValue = 0; // 0 == remove, 1 == keep
@Override
public void run( final String arg )
{
final LoadParseQueryXML xml = new LoadParseQueryXML();
if ( !xml.queryXML( "", true, false, true, true ) )
return;
final SpimData2 data = xml.getData();
final List< ViewId > viewIds = SpimData2.getAllViewIdsSorted( data, xml.getViewSetupsToProcess(), xml.getTimePointsToProcess() );
// ask which channels have the objects we are searching for
final List< ChannelProcessThinOut > channels = getChannelsAndLabels( data, viewIds );
if ( channels == null )
return;
// get the actual min/max thresholds for cutting out
if ( !getThinOutThresholds( data, viewIds, channels ) )
return;
// thin out detections and save the new interestpoint files
if ( !thinOut( data, viewIds, channels, true ) )
return;
// write new xml
SpimData2.saveXML( data, xml.getXMLFileName(), xml.getClusterExtension() );
}
public static boolean thinOut( final SpimData2 spimData, final List< ViewId > viewIds, final List< ChannelProcessThinOut > channels, final boolean save )
{
final ViewInterestPoints vip = spimData.getViewInterestPoints();
for ( final ChannelProcessThinOut channel : channels )
{
final double minDistance = channel.getMin();
final double maxDistance = channel.getMax();
final boolean keepRange = channel.keepRange();
for ( final ViewId viewId : viewIds )
{
final ViewDescription vd = spimData.getSequenceDescription().getViewDescription( viewId );
if ( !vd.isPresent() || vd.getViewSetup().getChannel().getId() != channel.getChannel().getId() )
continue;
final ViewInterestPointLists vipl = vip.getViewInterestPointLists( viewId );
final InterestPointList oldIpl = vipl.getInterestPointList( channel.getLabel() );
if ( oldIpl.getInterestPoints() == null )
oldIpl.loadInterestPoints();
final VoxelDimensions voxelSize = vd.getViewSetup().getVoxelSize();
// assemble the list of points (we need two lists as the KDTree sorts the list)
// we assume that the order of list2 and points is preserved!
final List< RealPoint > list1 = new ArrayList< RealPoint >();
final List< RealPoint > list2 = new ArrayList< RealPoint >();
final List< double[] > points = new ArrayList< double[] >();
for ( final InterestPoint ip : oldIpl.getInterestPoints() )
{
list1.add ( new RealPoint(
ip.getL()[ 0 ] * voxelSize.dimension( 0 ),
ip.getL()[ 1 ] * voxelSize.dimension( 1 ),
ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) );
list2.add ( new RealPoint(
ip.getL()[ 0 ] * voxelSize.dimension( 0 ),
ip.getL()[ 1 ] * voxelSize.dimension( 1 ),
ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) );
points.add( ip.getL() );
}
// make the KDTree
final KDTree< RealPoint > tree = new KDTree< RealPoint >( list1, list1 );
// Nearest neighbor for each point, populate the new list
final KNearestNeighborSearchOnKDTree< RealPoint > nn = new KNearestNeighborSearchOnKDTree< RealPoint >( tree, 2 );
final InterestPointList newIpl = new InterestPointList(
oldIpl.getBaseDir(),
new File(
oldIpl.getFile().getParentFile(),
"tpId_" + viewId.getTimePointId() + "_viewSetupId_" + viewId.getViewSetupId() + "." + channel.getNewLabel() ) );
newIpl.setInterestPoints( new ArrayList< InterestPoint >() );
int id = 0;
for ( int j = 0; j < list2.size(); ++j )
{
final RealPoint p = list2.get( j );
nn.search( p );
// first nearest neighbor is the point itself, we need the second nearest
final double d = nn.getDistance( 1 );
if ( ( keepRange && d >= minDistance && d <= maxDistance ) || ( !keepRange && ( d < minDistance || d > maxDistance ) ) )
{
newIpl.getInterestPoints().add( new InterestPoint( id++, points.get( j ).clone() ) );
}
}
if ( keepRange )
newIpl.setParameters( "thinned-out '" + channel.getLabel() + "', kept range from " + minDistance + " to " + maxDistance );
else
newIpl.setParameters( "thinned-out '" + channel.getLabel() + "', removed range from " + minDistance + " to " + maxDistance );
vipl.addInterestPointList( channel.getNewLabel(), newIpl );
IOFunctions.println( new Date( System.currentTimeMillis() ) + ": TP=" + vd.getTimePointId() + " ViewSetup=" + vd.getViewSetupId() +
", Detections: " + oldIpl.getInterestPoints().size() + " >>> " + newIpl.getInterestPoints().size() );
if ( save && !newIpl.saveInterestPoints() )
{
IOFunctions.println( "Error saving interest point list: " + new File( newIpl.getBaseDir(), newIpl.getFile().toString() + newIpl.getInterestPointsExt() ) );
return false;
}
}
}
return true;
}
public static boolean getThinOutThresholds( final SpimData2 spimData, final List< ViewId > viewIds, final List< ChannelProcessThinOut > channels )
{
for ( final ChannelProcessThinOut channel : channels )
if ( channel.showHistogram() )
plotHistogram( spimData, viewIds, channel );
if ( defaultCutoffThresholdMin == null || defaultCutoffThresholdMin.length != channels.size() ||
defaultCutoffThresholdMax == null || defaultCutoffThresholdMax.length != channels.size() )
{
defaultCutoffThresholdMin = new double[ channels.size() ];
defaultCutoffThresholdMax = new double[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
{
defaultCutoffThresholdMin[ i ] = defaultThresholdMinValue;
defaultCutoffThresholdMax[ i ] = defaultThresholdMaxValue;
}
}
if ( defaultRemoveKeep == null || defaultRemoveKeep.length != channels.size() )
{
defaultRemoveKeep = new int[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultRemoveKeep[ i ] = defaultRemoveKeepValue;
}
final GenericDialog gd = new GenericDialog( "Define cut-off threshold" );
for ( int c = 0; c < channels.size(); ++c )
{
final ChannelProcessThinOut channel = channels.get( c );
gd.addChoice( "Channel_" + channel.getChannel().getName() + "_", removeKeepChoice, removeKeepChoice[ defaultRemoveKeep[ c ] ] );
gd.addNumericField( "Channel_" + channel.getChannel().getName() + "_range_lower_threshold", defaultCutoffThresholdMin[ c ], 2 );
gd.addNumericField( "Channel_" + channel.getChannel().getName() + "_range_upper_threshold", defaultCutoffThresholdMax[ c ], 2 );
gd.addMessage( "" );
}
gd.showDialog();
if ( gd.wasCanceled() )
return false;
for ( int c = 0; c < channels.size(); ++c )
{
final ChannelProcessThinOut channel = channels.get( c );
final int removeKeep = defaultRemoveKeep[ c ] = gd.getNextChoiceIndex();
if ( removeKeep == 1 )
channel.setKeepRange( true );
else
channel.setKeepRange( false );
channel.setMin( defaultCutoffThresholdMin[ c ] = gd.getNextNumber() );
channel.setMax( defaultCutoffThresholdMax[ c ] = gd.getNextNumber() );
if ( channel.getMin() >= channel.getMax() )
{
IOFunctions.println( "You selected the minimal threshold larger than the maximal threshold for channel " + channel.getChannel().getName() );
IOFunctions.println( "Stopping." );
return false;
}
else
{
if ( channel.keepRange() )
IOFunctions.println( "Channel " + channel.getChannel().getName() + ": keep only distances from " + channel.getMin() + " >>> " + channel.getMax() );
else
IOFunctions.println( "Channel " + channel.getChannel().getName() + ": remove distances from " + channel.getMin() + " >>> " + channel.getMax() );
}
}
return true;
}
public static Histogram plotHistogram( final SpimData2 spimData, final List< ViewId > viewIds, final ChannelProcessThinOut channel )
{
final ViewInterestPoints vip = spimData.getViewInterestPoints();
// list of all distances
final ArrayList< Double > distances = new ArrayList< Double >();
final Random rnd = new Random( System.currentTimeMillis() );
String unit = null;
for ( final ViewId viewId : viewIds )
{
final ViewDescription vd = spimData.getSequenceDescription().getViewDescription( viewId );
if ( !vd.isPresent() || vd.getViewSetup().getChannel().getId() != channel.getChannel().getId() )
continue;
final ViewInterestPointLists vipl = vip.getViewInterestPointLists( viewId );
final InterestPointList ipl = vipl.getInterestPointList( channel.getLabel() );
final VoxelDimensions voxelSize = vd.getViewSetup().getVoxelSize();
if ( ipl.getInterestPoints() == null )
ipl.loadInterestPoints();
if ( unit == null )
unit = vd.getViewSetup().getVoxelSize().unit();
// assemble the list of points
final List< RealPoint > list = new ArrayList< RealPoint >();
for ( final InterestPoint ip : ipl.getInterestPoints() )
{
list.add ( new RealPoint(
ip.getL()[ 0 ] * voxelSize.dimension( 0 ),
ip.getL()[ 1 ] * voxelSize.dimension( 1 ),
ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) );
}
// make the KDTree
final KDTree< RealPoint > tree = new KDTree< RealPoint >( list, list );
// Nearest neighbor for each point
final KNearestNeighborSearchOnKDTree< RealPoint > nn = new KNearestNeighborSearchOnKDTree< RealPoint >( tree, 2 );
for ( final RealPoint p : list )
{
// every n'th point only
if ( rnd.nextDouble() < 1.0 / (double)channel.getSubsampling() )
{
nn.search( p );
// first nearest neighbor is the point itself, we need the second nearest
distances.add( nn.getDistance( 1 ) );
}
}
}
final Histogram h = new Histogram( distances, 100, "Distance Histogram [Channel=" + channel.getChannel().getName() + "]", unit );
h.showHistogram();
IOFunctions.println( "Channel " + channel.getChannel().getName() + ": min distance=" + h.getMin() + ", max distance=" + h.getMax() );
return h;
}
public static ArrayList< ChannelProcessThinOut > getChannelsAndLabels(
final SpimData2 spimData,
final List< ViewId > viewIds )
{
// build up the dialog
final GenericDialog gd = new GenericDialog( "Choose segmentations to thin out" );
final List< Channel > channels = SpimData2.getAllChannelsSorted( spimData, viewIds );
final int nAllChannels = spimData.getSequenceDescription().getAllChannelsOrdered().size();
if ( Interest_Point_Registration.defaultChannelLabels == null || Interest_Point_Registration.defaultChannelLabels.length != nAllChannels )
Interest_Point_Registration.defaultChannelLabels = new int[ nAllChannels ];
if ( defaultShowHistogram == null || defaultShowHistogram.length != channels.size() )
{
defaultShowHistogram = new boolean[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultShowHistogram[ i ] = true;
}
if ( defaultSubSampling == null || defaultSubSampling.length != channels.size() )
{
defaultSubSampling = new int[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultSubSampling[ i ] = defaultSubSamplingValue;
}
if ( defaultNewLabels == null || defaultNewLabels.length != channels.size() )
{
defaultNewLabels = new String[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultNewLabels[ i ] = defaultNewLabelText;
}
// check which channels and labels are available and build the choices
final ArrayList< String[] > channelLabels = new ArrayList< String[] >();
int j = 0;
for ( final Channel channel : channels )
{
final String[] labels = Interest_Point_Registration.getAllInterestPointLabelsForChannel(
spimData,
viewIds,
channel,
"thin out" );
if ( Interest_Point_Registration.defaultChannelLabels[ j ] >= labels.length )
Interest_Point_Registration.defaultChannelLabels[ j ] = 0;
String ch = channel.getName().replace( ' ', '_' );
gd.addCheckbox( "Channel_" + ch + "_Display_distance_histogram", defaultShowHistogram[ j ] );
gd.addChoice( "Channel_" + ch + "_Interest_points", labels, labels[ Interest_Point_Registration.defaultChannelLabels[ j ] ] );
gd.addStringField( "Channel_" + ch + "_New_label", defaultNewLabels[ j ], 20 );
gd.addNumericField( "Channel_" + ch + "_Subsample histogram", defaultSubSampling[ j ], 0, 5, "times" );
channelLabels.add( labels );
++j;
}
gd.showDialog();
if ( gd.wasCanceled() )
return null;
// assemble which channels have been selected with with label
final ArrayList< ChannelProcessThinOut > channelsToProcess = new ArrayList< ChannelProcessThinOut >();
j = 0;
for ( final Channel channel : channels )
{
final boolean showHistogram = defaultShowHistogram[ j ] = gd.getNextBoolean();
final int channelChoice = Interest_Point_Registration.defaultChannelLabels[ j ] = gd.getNextChoiceIndex();
final String newLabel = defaultNewLabels[ j ] = gd.getNextString();
final int subSampling = defaultSubSampling[ j ] = (int)Math.round( gd.getNextNumber() );
if ( channelChoice < channelLabels.get( j ).length - 1 )
{
String label = channelLabels.get( j )[ channelChoice ];
if ( label.contains( Interest_Point_Registration.warningLabel ) )
label = label.substring( 0, label.indexOf( Interest_Point_Registration.warningLabel ) );
channelsToProcess.add( new ChannelProcessThinOut( channel, label, newLabel, showHistogram, subSampling ) );
}
++j;
}
return channelsToProcess;
}
public static void main( final String[] args )
{
new ThinOut_Detections().run( null );
}
}
| gpl-2.0 |
reboutli-crim/heideltime | src/main/java/de/unihd/dbs/heideltime/standalone/components/impl/XMIResultFormatter.java | 3537 | /*
* XMIResultFormatter.java
*
* Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU General Public License.
*
* authors: Andreas Fay, Jannik Strötgen
* email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de
*
* HeidelTime is a multilingual, cross-domain temporal tagger.
* For details, see http://dbs.ifi.uni-heidelberg.de/heideltime
*/
package de.unihd.dbs.heideltime.standalone.components.impl;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.uima.cas.impl.XmiCasSerializer;
import org.apache.uima.jcas.JCas;
import org.apache.uima.util.XMLSerializer;
import de.unihd.dbs.heideltime.standalone.components.ResultFormatter;
/**
* Result formatter based on XMI.
*
* @see {@link org.apache.uima.examples.xmi.XmiWriterCasConsumer}
*
* @author Andreas Fay, University of Heidelberg
* @version 1.0
*/
public class XMIResultFormatter implements ResultFormatter {
@Override
public String format(JCas jcas) throws Exception {
ByteArrayOutputStream outStream = null;
try {
// Write XMI
outStream = new ByteArrayOutputStream();
XmiCasSerializer ser = new XmiCasSerializer(jcas.getTypeSystem());
XMLSerializer xmlSer = new XMLSerializer(outStream, false);
ser.serialize(jcas.getCas(), xmlSer.getContentHandler());
// Convert output stream to string
// String newOut = outStream.toString("UTF-8");
String newOut = outStream.toString();
// System.err.println("NEWOUT:"+newOut);
//
// if (newOut.matches("^<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>.*$")){
// newOut = newOut.replaceFirst("<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>",
// "<\\?xml version=\"1.0\" encoding=\""+Charset.defaultCharset().name()+"\"\\?>");
// }
// if (newOut.matches("^.*?sofaString=\"(.*?)\".*$")){
// for (MatchResult r : findMatches(Pattern.compile("^(.*?sofaString=\")(.*?)(\".*)$"), newOut)){
// String stringBegin = r.group(1);
// String sofaString = r.group(2);
// System.err.println("SOFASTRING:"+sofaString);
// String stringEnd = r.group(3);
// // The sofaString is encoded as UTF-8.
// // However, at this point it has to be translated back into the defaultCharset.
// byte[] defaultDocText = new String(sofaString.getBytes(), "UTF-8").getBytes(Charset.defaultCharset().name());
// String docText = new String(defaultDocText);
// System.err.println("DOCTEXT:"+docText);
// newOut = stringBegin + docText + stringEnd;
//// newOut = newOut.replaceFirst("sofaString=\".*?\"", "sofaString=\"" + docText + "\"");
// }
// }
// System.err.println("NEWOUT:"+newOut);
return newOut;
} finally {
if (outStream != null) {
outStream.close();
}
}
}
/**
* Find all the matches of a pattern in a charSequence and return the
* results as list.
*
* @param pattern
* @param s
* @return
*/
public static Iterable<MatchResult> findMatches(Pattern pattern,
CharSequence s) {
List<MatchResult> results = new ArrayList<MatchResult>();
for (Matcher m = pattern.matcher(s); m.find();)
results.add(m.toMatchResult());
return results;
}
}
| gpl-3.0 |
superzadeh/processdash | teamdash/src/teamdash/wbs/columns/ErrorNotesColumn.java | 3288 | // Copyright (C) 2012 Tuma Solutions, LLC
// Team Functionality Add-ons for the Process Dashboard
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// Additional permissions also apply; see the README-license.txt
// file in the project root directory for more information.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
// The author(s) may be contacted at:
// processdash@tuma-solutions.com
// processdash-devel@lists.sourceforge.net
package teamdash.wbs.columns;
import teamdash.wbs.WBSModel;
import teamdash.wbs.WBSNode;
import teamdash.wbs.WBSNodeTest;
public class ErrorNotesColumn extends AbstractNotesColumn {
/** The ID we use for this column in the data model */
public static final String COLUMN_ID = "Error Notes";
/** The attribute this column uses to store task notes for a WBS node */
public static final String VALUE_ATTR = "Error Notes";
public ErrorNotesColumn(String authorName) {
super(VALUE_ATTR, authorName);
this.columnID = COLUMN_ID;
this.columnName = resources.getString("Error_Notes.Name");
}
@Override
protected String getEditDialogTitle() {
return columnName;
}
@Override
protected Object getEditDialogHeader(WBSNode node) {
return new Object[] {
resources.getStrings("Error_Notes.Edit_Dialog_Header"), " " };
}
public static String getTextAt(WBSNode node) {
return getTextAt(node, VALUE_ATTR);
}
public static String getTooltipAt(WBSNode node, boolean includeByline) {
return getTooltipAt(node, includeByline, VALUE_ATTR);
}
/**
* Find nodes that have errors attached, and expand their ancestors as
* needed to ensure that they are visible.
*
* @param wbs
* the WBSModel
* @param belowNode
* an optional starting point for the search, to limit expansion
* to a particular branch of the tree; can be null to search from
* the root
* @param condition
* an optional condition to test; only nodes matching the
* condition will be made visible. Can be null to show all nodes
* with errors
*/
public static void showNodesWithErrors(WBSModel wbs, WBSNode belowNode,
WBSNodeTest condition) {
if (belowNode == null)
belowNode = wbs.getRoot();
for (WBSNode node : wbs.getDescendants(belowNode)) {
String errText = getTextAt(node, VALUE_ATTR);
if (errText != null && errText.trim().length() > 0) {
if (condition == null || condition.test(node))
wbs.makeVisible(node);
}
}
}
}
| gpl-3.0 |
bserdar/lightblue-core | config/src/test/java/com/redhat/lightblue/config/CrudValidationTest.java | 3200 | /*
Copyright 2013 Red Hat, Inc. and/or its affiliates.
This file is part of lightblue.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.lightblue.config;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.redhat.lightblue.Request;
import com.redhat.lightblue.crud.DeleteRequest;
import com.redhat.lightblue.util.test.FileUtil;
import static com.redhat.lightblue.util.JsonUtils.json;
public class CrudValidationTest {
@Test
public void testValidInputWithNonValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, false);
String jsonString = FileUtil.readFile("valid-deletion-req.json");
JsonNode node = json(jsonString);
DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.assertNotNull(req);
}
@Test
public void testInvalidInputWithNonValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, false);
String jsonString = FileUtil.readFile("invalid-deletion-req.json");
JsonNode node = json(jsonString);
DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.assertNotNull(req);
}
@Test
public void testValidInputWithValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, true);
String jsonString = FileUtil.readFile("valid-deletion-req.json");
JsonNode node = json(jsonString);
DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.assertNotNull(req);
}
@Test
public void testInvalidInputWithValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, true);
String jsonString = FileUtil.readFile("invalid-deletion-req.json");
JsonNode node = json(jsonString);
try {
lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.fail();
} catch (Exception e) {
System.out.println(e);
}
}
}
| gpl-3.0 |
obiba/mica2 | mica-core/src/main/java/org/obiba/mica/micaConfig/service/PopulationConfigService.java | 1583 | /*
* Copyright (c) 2018 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.mica.micaConfig.service;
import org.obiba.mica.micaConfig.domain.PopulationConfig;
import org.obiba.mica.micaConfig.repository.PopulationConfigRepository;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
@Component
public class PopulationConfigService extends EntityConfigService<PopulationConfig> {
@Inject
PopulationConfigRepository populationConfigRepository;
@Override
protected PopulationConfigRepository getRepository() {
return populationConfigRepository;
}
@Override
protected String getDefaultId() {
return "default";
}
@Override
protected PopulationConfig createEmptyForm() {
return new PopulationConfig();
}
@Override
protected String getDefaultDefinitionResourcePath() {
return "classpath:config/population-form/definition.json";
}
@Override
protected String getMandatoryDefinitionResourcePath() {
return "classpath:config/population-form/definition-mandatory.json";
}
@Override
protected String getDefaultSchemaResourcePath() {
return "classpath:config/population-form/schema.json";
}
@Override
protected String getMandatorySchemaResourcePath() {
return "classpath:config/population-form/schema-mandatory.json";
}
}
| gpl-3.0 |
bordertechorg/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/RadioButtonExample.java | 2008 | package com.github.bordertech.wcomponents.examples;
import com.github.bordertech.wcomponents.RadioButtonGroup;
import com.github.bordertech.wcomponents.Size;
import com.github.bordertech.wcomponents.WLabel;
import com.github.bordertech.wcomponents.WPanel;
import com.github.bordertech.wcomponents.WRadioButton;
import com.github.bordertech.wcomponents.layout.FlowLayout;
import com.github.bordertech.wcomponents.layout.FlowLayout.Alignment;
/**
* {@link WRadioButton} example.
*
* @author Yiannis Paschalidis
* @since 1.0.0
*/
public class RadioButtonExample extends WPanel {
/**
* Creates a RadioButtonExample.
*/
public RadioButtonExample() {
this.setLayout(new FlowLayout(Alignment.VERTICAL));
WPanel panel = new WPanel();
RadioButtonGroup group1 = new RadioButtonGroup();
panel.add(group1);
WRadioButton rb1 = group1.addRadioButton(1);
panel.add(new WLabel("Default", rb1));
panel.add(rb1);
this.add(panel);
panel = new WPanel();
RadioButtonGroup group2 = new RadioButtonGroup();
panel.add(group2);
WRadioButton rb2 = group2.addRadioButton(1);
rb2.setSelected(true);
panel.add(new WLabel("Initially selected", rb2));
panel.add(rb2);
this.add(panel);
panel = new WPanel();
RadioButtonGroup group3 = new RadioButtonGroup();
panel.add(group3);
WRadioButton rb3 = group3.addRadioButton(1);
rb3.setDisabled(true);
rb3.setToolTip("This is disabled.");
panel.add(new WLabel("Disabled", rb3));
panel.add(rb3);
this.add(panel);
RadioButtonGroup group = new RadioButtonGroup();
WRadioButton rb4 = group.addRadioButton("A");
WRadioButton rb5 = group.addRadioButton("B");
WRadioButton rb6 = group.addRadioButton("C");
panel = new WPanel();
panel.setLayout(new FlowLayout(Alignment.LEFT, Size.MEDIUM));
add(new WLabel("Group"));
panel.add(new WLabel("A", rb4));
panel.add(rb4);
panel.add(new WLabel("B", rb5));
panel.add(rb5);
panel.add(new WLabel("C", rb6));
panel.add(rb6);
panel.add(group);
this.add(panel);
}
}
| gpl-3.0 |
dejan-brkic/studio2 | src/main/java/org/craftercms/studio/impl/v1/service/activity/ActivityServiceImpl.java | 20008 | /*
* Crafter Studio Web-content authoring solution
* Copyright (C) 2007-2016 Crafter Software Corporation.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.craftercms.studio.impl.v1.service.activity;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.craftercms.commons.validation.annotations.param.ValidateIntegerParam;
import org.craftercms.commons.validation.annotations.param.ValidateParams;
import org.craftercms.commons.validation.annotations.param.ValidateSecurePathParam;
import org.craftercms.commons.validation.annotations.param.ValidateStringParam;
import org.craftercms.studio.api.v1.constant.StudioConstants;
import org.craftercms.studio.api.v1.constant.DmConstants;
import org.craftercms.studio.api.v1.dal.AuditFeed;
import org.craftercms.studio.api.v1.dal.AuditFeedMapper;
import org.craftercms.studio.api.v1.exception.ServiceException;
import org.craftercms.studio.api.v1.exception.SiteNotFoundException;
import org.craftercms.studio.api.v1.log.Logger;
import org.craftercms.studio.api.v1.log.LoggerFactory;
import org.craftercms.studio.api.v1.service.AbstractRegistrableService;
import org.craftercms.studio.api.v1.service.activity.ActivityService;
import org.craftercms.studio.api.v1.service.content.ContentService;
import org.craftercms.studio.api.v1.service.deployment.DeploymentService;
import org.craftercms.studio.api.v1.service.objectstate.State;
import org.craftercms.studio.api.v1.service.site.SiteService;
import org.craftercms.studio.api.v1.to.ContentItemTO;
import org.craftercms.studio.api.v1.util.DebugUtils;
import org.craftercms.studio.api.v1.util.StudioConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.craftercms.studio.api.v1.service.security.SecurityService;
import static org.craftercms.studio.api.v1.constant.StudioConstants.CONTENT_TYPE_PAGE;
import static org.craftercms.studio.api.v1.util.StudioConfiguration.ACTIVITY_USERNAME_CASE_SENSITIVE;
public class ActivityServiceImpl extends AbstractRegistrableService implements ActivityService {
private static final Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);
protected static final int MAX_LEN_USER_ID = 255; // needs to match schema:
// feed_user_id,
// post_user_id
protected static final int MAX_LEN_SITE_ID = 255; // needs to match schema:
// site_network
protected static final int MAX_LEN_ACTIVITY_TYPE = 255; // needs to match
// schema:
// activity_type
protected static final int MAX_LEN_ACTIVITY_DATA = 4000; // needs to match
// schema:
// activity_data
protected static final int MAX_LEN_APP_TOOL_ID = 36; // needs to match
// schema: app_tool
/** activity post properties **/
protected static final String ACTIVITY_PROP_ACTIVITY_SUMMARY = "activitySummary";
protected static final String ACTIVITY_PROP_ID = "id";
protected static final String ACTIVITY_PROP_POST_DATE = "postDate";
protected static final String ACTIVITY_PROP_USER = "user";
protected static final String ACTIVITY_PROP_FEEDUSER = "feedUserId";
protected static final String ACTIVITY_PROP_CONTENTID = "contentId";
/** activity feed format **/
protected static final String ACTIVITY_FEED_FORMAT = "json";
@Autowired
protected AuditFeedMapper auditFeedMapper;
protected SiteService siteService;
protected ContentService contentService;
protected SecurityService securityService;
protected StudioConfiguration studioConfiguration;
protected DeploymentService deploymentService;
@Override
public void register() {
getServicesManager().registerService(ActivityService.class, this);
}
@Override
@ValidateParams
public void postActivity(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateSecurePathParam(name = "contentId") String contentId, ActivityType activity, ActivitySource source, Map<String,String> extraInfo) {
JSONObject activityPost = new JSONObject();
activityPost.put(ACTIVITY_PROP_USER, user);
activityPost.put(ACTIVITY_PROP_ID, contentId);
if (extraInfo != null) {
activityPost.putAll(extraInfo);
}
String contentType = null;
if (extraInfo != null) {
contentType = extraInfo.get(DmConstants.KEY_CONTENT_TYPE);
}
postActivity(activity.toString(), source.toString(), site, null, activityPost.toString(),contentId,contentType, user);
}
private void postActivity(String activityType, String activitySource, String siteNetwork, String appTool, String activityData,
String contentId, String contentType, String approver) {
String currentUser = (StringUtils.isEmpty(approver)) ? securityService.getCurrentUser() : approver;
try {
// optional - default to empty string
if (siteNetwork == null) {
siteNetwork = "";
} else if (siteNetwork.length() > MAX_LEN_SITE_ID) {
throw new ServiceException("Invalid site network - exceeds " + MAX_LEN_SITE_ID + " chars: "
+ siteNetwork);
}
// optional - default to empty string
if (appTool == null) {
appTool = "";
} else if (appTool.length() > MAX_LEN_APP_TOOL_ID) {
throw new ServiceException("Invalid app tool - exceeds " + MAX_LEN_APP_TOOL_ID + " chars: " + appTool);
}
// required
if (StringUtils.isEmpty(activityType)) {
throw new ServiceException("Invalid activity type - activity type is empty");
} else if (activityType.length() > MAX_LEN_ACTIVITY_TYPE) {
throw new ServiceException("Invalid activity type - exceeds " + MAX_LEN_ACTIVITY_TYPE + " chars: "
+ activityType);
}
// optional - default to empty string
if (activityData == null) {
activityData = "";
} else if (activityType.length() > MAX_LEN_ACTIVITY_DATA) {
throw new ServiceException("Invalid activity data - exceeds " + MAX_LEN_ACTIVITY_DATA + " chars: "
+ activityData);
}
// required
if (StringUtils.isEmpty(currentUser)) {
throw new ServiceException("Invalid user - user is empty");
} else if (currentUser.length() > MAX_LEN_USER_ID) {
throw new ServiceException("Invalid user - exceeds " + MAX_LEN_USER_ID + " chars: " + currentUser);
} else {
// user names are not case-sensitive
currentUser = currentUser.toLowerCase();
}
if (contentType == null) {
contentType = CONTENT_TYPE_PAGE;
}
} catch (ServiceException e) {
// log error and throw exception
logger.error("Error in getting feeds", e);
}
try {
ZonedDateTime postDate = ZonedDateTime.now(ZoneOffset.UTC);
AuditFeed activityPost = new AuditFeed();
activityPost.setUserId(currentUser);
activityPost.setSiteNetwork(siteNetwork);
activityPost.setSummary(activityData);
activityPost.setType(activityType);
activityPost.setCreationDate(postDate);
activityPost.setModifiedDate(postDate);
activityPost.setSummaryFormat("json");
activityPost.setContentId(contentId);
activityPost.setContentType(contentType);
activityPost.setSource(activitySource);
try {
activityPost.setCreationDate(ZonedDateTime.now(ZoneOffset.UTC));
long postId = insertFeedEntry(activityPost);
activityPost.setId(postId);
logger.debug("Posted: " + activityPost);
} catch (Exception e) {
throw new ServiceException("Failed to post activity: " + e, e);
}
}
catch (ServiceException e) {
// log error, subsume exception (for post activity)
logger.error("Error in posting feed", e);
}
}
private long insertFeedEntry(AuditFeed activityFeed) {
DebugUtils.addDebugStack(logger);
logger.debug("Insert activity " + activityFeed.getContentId());
Long id = auditFeedMapper.insertActivityFeed(activityFeed);
return (id != null ? id : -1);
}
@Override
@ValidateParams
public void renameContentId(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "oldUrl") String oldUrl, @ValidateSecurePathParam(name = "newUrl") String newUrl) {
DebugUtils.addDebugStack(logger);
logger.debug("Rename " + oldUrl + " to " + newUrl);
Map<String, String> params = new HashMap<String, String>();
params.put("newPath", newUrl);
params.put("site", site);
params.put("oldPath", oldUrl);
auditFeedMapper.renameContent(params);
}
@Override
@ValidateParams
public List<ContentItemTO> getActivities(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateIntegerParam(name = "num") int num, @ValidateStringParam(name = "sort") String sort, boolean ascending, boolean excludeLive, @ValidateStringParam(name = "filterType") String filterType) throws ServiceException {
int startPos = 0;
List<ContentItemTO> contentItems = new ArrayList<ContentItemTO>();
boolean hasMoreItems = true;
while(contentItems.size() < num && hasMoreItems){
int remainingItems = num - contentItems.size();
hasMoreItems = getActivityFeeds(user, site, startPos, num , filterType, excludeLive,contentItems,remainingItems);
startPos = startPos+num;
}
if(contentItems.size() > num){
return contentItems.subList(0, num);
}
return contentItems;
}
/**
*
* Returns all non-live items if hideLiveItems is true, else should return all feeds back
*
*/
protected boolean getActivityFeeds(String user, String site,int startPos, int size, String filterType,boolean hideLiveItems,List<ContentItemTO> contentItems,int remainingItem){
List<String> activityFeedEntries = new ArrayList<String>();
if (!getUserNamesAreCaseSensitive()) {
user = user.toLowerCase();
}
List<AuditFeed> activityFeeds = null;
activityFeeds = selectUserFeedEntries(user, ACTIVITY_FEED_FORMAT, site, startPos, size,
filterType, hideLiveItems);
for (AuditFeed activityFeed : activityFeeds) {
activityFeedEntries.add(activityFeed.getJSONString());
}
boolean hasMoreItems=true;
//if number of items returned is less than size it means that table has no more records
if(activityFeedEntries.size()<size){
hasMoreItems=false;
}
if (activityFeedEntries != null && activityFeedEntries.size() > 0) {
for (int index = 0; index < activityFeedEntries.size() && remainingItem!=0; index++) {
JSONObject feedObject = JSONObject.fromObject(activityFeedEntries.get(index));
String id = (feedObject.containsKey(ACTIVITY_PROP_CONTENTID)) ? feedObject.getString(ACTIVITY_PROP_CONTENTID) : "";
ContentItemTO item = createActivityItem(site, feedObject, id);
item.published = true;
item.setPublished(true);
ZonedDateTime pubDate = deploymentService.getLastDeploymentDate(site, id);
item.publishedDate = pubDate;
item.setPublishedDate(pubDate);
contentItems.add(item);
remainingItem--;
}
}
logger.debug("Total Item post live filter : " + contentItems.size() + " hasMoreItems : "+hasMoreItems);
return hasMoreItems;
}
/**
* create an activity from the given feed
*
* @param site
* @param feedObject
* @return activity
*/
protected ContentItemTO createActivityItem(String site, JSONObject feedObject, String id) {
try {
ContentItemTO item = contentService.getContentItem(site, id, 0);
if(item == null || item.isDeleted()) {
item = contentService.createDummyDmContentItemForDeletedNode(site, id);
String modifier = (feedObject.containsKey(ACTIVITY_PROP_FEEDUSER)) ? feedObject.getString(ACTIVITY_PROP_FEEDUSER) : "";
if(modifier != null && !modifier.isEmpty()) {
item.user = modifier;
}
String activitySummary = (feedObject.containsKey(ACTIVITY_PROP_ACTIVITY_SUMMARY)) ? feedObject.getString(ACTIVITY_PROP_ACTIVITY_SUMMARY) : "";
JSONObject summaryObject = JSONObject.fromObject(activitySummary);
if (summaryObject.containsKey(DmConstants.KEY_CONTENT_TYPE)) {
String contentType = (String)summaryObject.get(DmConstants.KEY_CONTENT_TYPE);
item.contentType = contentType;
}
if(summaryObject.containsKey(StudioConstants.INTERNAL_NAME)) {
String internalName = (String)summaryObject.get(StudioConstants.INTERNAL_NAME);
item.internalName = internalName;
}
if(summaryObject.containsKey(StudioConstants.BROWSER_URI)) {
String browserUri = (String)summaryObject.get(StudioConstants.BROWSER_URI);
item.browserUri = browserUri;
}
item.setLockOwner("");
}
String postDate = (feedObject.containsKey(ACTIVITY_PROP_POST_DATE)) ? feedObject.getString(ACTIVITY_PROP_POST_DATE) : "";
ZonedDateTime editedDate = ZonedDateTime.parse(postDate);
if (editedDate != null) {
item.eventDate = editedDate.withZoneSameInstant(ZoneOffset.UTC);
} else {
item.eventDate = editedDate;
}
return item;
} catch (Exception e) {
logger.error("Error fetching content item for [" + id + "]", e.getMessage());
return null;
}
}
private List<AuditFeed> selectUserFeedEntries(String feedUserId, String format, String siteId, int startPos, int feedSize, String contentType, boolean hideLiveItems) {
HashMap<String,Object> params = new HashMap<String,Object>();
params.put("userId",feedUserId);
params.put("summaryFormat",format);
params.put("siteNetwork",siteId);
params.put("startPos", startPos);
params.put("feedSize", feedSize);
params.put("activities", Arrays.asList(ActivityType.CREATED, ActivityType.DELETED, ActivityType.UPDATED, ActivityType.MOVED));
if(StringUtils.isNotEmpty(contentType) && !contentType.toLowerCase().equals("all")){
params.put("contentType",contentType.toLowerCase());
}
if (hideLiveItems) {
List<String> statesValues = new ArrayList<String>();
for (State state : State.LIVE_STATES) {
statesValues.add(state.name());
}
params.put("states", statesValues);
return auditFeedMapper.selectUserFeedEntriesHideLive(params);
} else {
return auditFeedMapper.selectUserFeedEntries(params);
}
}
@Override
@ValidateParams
public AuditFeed getDeletedActivity(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "path") String path) {
HashMap<String,String> params = new HashMap<String,String>();
params.put("contentId", path);
params.put("siteNetwork", site);
String activityType = ActivityType.DELETED.toString();
params.put("activityType", activityType);
return auditFeedMapper.getDeletedActivity(params);
}
@Override
@ValidateParams
public void deleteActivitiesForSite(@ValidateStringParam(name = "site") String site) {
Map<String, String> params = new HashMap<String, String>();
params.put("site", site);
auditFeedMapper.deleteActivitiesForSite(params);
}
@Override
@ValidateParams
public List<AuditFeed> getAuditLogForSite(@ValidateStringParam(name = "site") String site, @ValidateIntegerParam(name = "start") int start, @ValidateIntegerParam(name = "number") int number, @ValidateStringParam(name = "user") String user, List<String> actions)
throws SiteNotFoundException {
if (!siteService.exists(site)) {
throw new SiteNotFoundException();
} else {
Map<String, Object> params = new HashMap<String, Object>();
params.put("site", site);
params.put("start", start);
params.put("number", number);
if (StringUtils.isNotEmpty(user)) {
params.put("user", user);
}
if (CollectionUtils.isNotEmpty(actions)) {
params.put("actions", actions);
}
return auditFeedMapper.getAuditLogForSite(params);
}
}
@Override
@ValidateParams
public long getAuditLogForSiteTotal(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, List<String> actions)
throws SiteNotFoundException {
if (!siteService.exists(site)) {
throw new SiteNotFoundException();
} else {
Map<String, Object> params = new HashMap<String, Object>();
params.put("site", site);
if (StringUtils.isNotEmpty(user)) {
params.put("user", user);
}
if (CollectionUtils.isNotEmpty(actions)) {
params.put("actions", actions);
}
return auditFeedMapper.getAuditLogForSiteTotal(params);
}
}
public boolean getUserNamesAreCaseSensitive() {
boolean toReturn = Boolean.parseBoolean(studioConfiguration.getProperty(ACTIVITY_USERNAME_CASE_SENSITIVE));
return toReturn;
}
public SiteService getSiteService() {
return siteService;
}
public void setSiteService(final SiteService siteService) {
this.siteService = siteService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public SecurityService getSecurityService() {return securityService; }
public void setSecurityService(SecurityService securityService) { this.securityService = securityService; }
public StudioConfiguration getStudioConfiguration() { return studioConfiguration; }
public void setStudioConfiguration(StudioConfiguration studioConfiguration) { this.studioConfiguration = studioConfiguration; }
public DeploymentService getDeploymentService() { return deploymentService; }
public void setDeploymentService(DeploymentService deploymentService) { this.deploymentService = deploymentService; }
}
| gpl-3.0 |
WhisperSystems/Signal-Android | app/src/test/java/org/thoughtcrime/securesms/testutil/SystemOutLogger.java | 1332 | package org.thoughtcrime.securesms.testutil;
import org.signal.core.util.logging.Log;
public final class SystemOutLogger extends Log.Logger {
@Override
public void v(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('v', tag, message, t);
}
@Override
public void d(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('d', tag, message, t);
}
@Override
public void i(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('i', tag, message, t);
}
@Override
public void w(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('w', tag, message, t);
}
@Override
public void e(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('e', tag, message, t);
}
@Override
public void flush() { }
private void printlnFormatted(char level, String tag, String message, Throwable t) {
System.out.println(format(level, tag, message, t));
}
private String format(char level, String tag, String message, Throwable t) {
if (t != null) {
return String.format("%c[%s] %s %s:%s", level, tag, message, t.getClass().getSimpleName(), t.getMessage());
} else {
return String.format("%c[%s] %s", level, tag, message);
}
}
}
| gpl-3.0 |
ZarGate/OpenbravoPOS | src-pos/com/openbravo/pos/printer/escpos/CodesIthaca.java | 2760 | // Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2009 Openbravo, S.L.
// http://www.openbravo.com/product/pos
//
// This file is part of Openbravo POS.
//
// Openbravo POS is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Openbravo POS is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Openbravo POS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.printer.escpos;
public class CodesIthaca extends Codes {
private static final byte[] INITSEQUENCE = {};
private static final byte[] CHAR_SIZE_0 = {0x1D, 0x21, 0x00};
private static final byte[] CHAR_SIZE_1 = {0x1D, 0x21, 0x01};
private static final byte[] CHAR_SIZE_2 = {0x1D, 0x21, 0x30};
private static final byte[] CHAR_SIZE_3 = {0x1D, 0x21, 0x31};
public static final byte[] BOLD_SET = {0x1B, 0x45, 0x01};
public static final byte[] BOLD_RESET = {0x1B, 0x45, 0x00};
public static final byte[] UNDERLINE_SET = {0x1B, 0x2D, 0x01};
public static final byte[] UNDERLINE_RESET = {0x1B, 0x2D, 0x00};
private static final byte[] OPEN_DRAWER = {0x1B, 0x78, 0x01};
private static final byte[] PARTIAL_CUT = {0x1B, 0x50, 0x00};
private static final byte[] IMAGE_HEADER = {0x1D, 0x76, 0x30, 0x03};
private static final byte[] NEW_LINE = {0x0D, 0x0A}; // Print and carriage return
/** Creates a new instance of CodesIthaca */
public CodesIthaca() {
}
public byte[] getInitSequence() { return INITSEQUENCE; }
public byte[] getSize0() { return CHAR_SIZE_0; }
public byte[] getSize1() { return CHAR_SIZE_1; }
public byte[] getSize2() { return CHAR_SIZE_2; }
public byte[] getSize3() { return CHAR_SIZE_3; }
public byte[] getBoldSet() { return BOLD_SET; }
public byte[] getBoldReset() { return BOLD_RESET; }
public byte[] getUnderlineSet() { return UNDERLINE_SET; }
public byte[] getUnderlineReset() { return UNDERLINE_RESET; }
public byte[] getOpenDrawer() { return OPEN_DRAWER; }
public byte[] getCutReceipt() { return PARTIAL_CUT; }
public byte[] getNewLine() { return NEW_LINE; }
public byte[] getImageHeader() { return IMAGE_HEADER; }
public int getImageWidth() { return 256; }
}
| gpl-3.0 |
mkrakowitzer/jcliff | src/test/java/com/redhat/jcliff/DeploymentTest.java | 2307 | package com.redhat.jcliff;
import java.io.StringBufferInputStream;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.jboss.dmr.ModelNode;
public class DeploymentTest {
@Test
public void replace() throws Exception {
ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"} }"));
ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}"));
Deployment d=new Deployment(new Ctx(),true);
Map<String,Set<String>> map=d.findDeploymentsToReplace(newDeployments,existingDeployments);
Assert.assertEquals("app2",map.get("app2").iterator().next());
Assert.assertNull(map.get("app1"));
Assert.assertEquals(1,map.size());
}
@Test
public void newdeployments() throws Exception {
ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"} }"));
ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}"));
Deployment d=new Deployment(new Ctx(),true);
String[] news=d.getNewDeployments(newDeployments,existingDeployments.keys());
Assert.assertEquals(1,news.length);
Assert.assertEquals("app3",news[0]);
}
@Test
public void undeployments() throws Exception {
ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"}, \"app4\"=>\"deleted\" }"));
ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}"));
Deployment d=new Deployment(new Ctx(),true);
String[] und=d.getUndeployments(newDeployments,existingDeployments);
Assert.assertEquals(1,und.length);
Assert.assertEquals("app1",und[0]);
}
}
| gpl-3.0 |
Vexatos/Tropicraft | src/main/java/net/tropicraft/world/genlayer/GenLayerTropiVoronoiZoom.java | 6674 | package net.tropicraft.world.genlayer;
import net.minecraft.world.gen.layer.IntCache;
public class GenLayerTropiVoronoiZoom extends GenLayerTropicraft {
public enum Mode {
CARTESIAN, MANHATTAN;
}
public Mode zoomMode;
public GenLayerTropiVoronoiZoom(long seed, GenLayerTropicraft parent, Mode zoomMode)
{
super(seed);
super.parent = parent;
this.zoomMode = zoomMode;
this.setZoom(1);
}
/**
* Returns a list of integer values generated by this layer. These may be interpreted as temperatures, rainfall
* amounts, or biomeList[] indices based on the particular GenLayer subclass.
*/
public int[] getInts(int x, int y, int width, int length)
{
final int randomResolution = 1024;
final double half = 0.5D;
final double almostTileSize = 3.6D;
final double tileSize = 4D;
x -= 2;
y -= 2;
int scaledX = x >> 2;
int scaledY = y >> 2;
int scaledWidth = (width >> 2) + 2;
int scaledLength = (length >> 2) + 2;
int[] parentValues = this.parent.getInts(scaledX, scaledY, scaledWidth, scaledLength);
int bitshiftedWidth = scaledWidth - 1 << 2;
int bitshiftedLength = scaledLength - 1 << 2;
int[] aint1 = IntCache.getIntCache(bitshiftedWidth * bitshiftedLength);
int i;
for(int j = 0; j < scaledLength - 1; ++j) {
i = 0;
int baseValue = parentValues[i + 0 + (j + 0) * scaledWidth];
for(int advancedValueJ = parentValues[i + 0 + (j + 1) * scaledWidth]; i < scaledWidth - 1; ++i) {
this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY << 2));
double offsetY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
double offsetX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY << 2));
double offsetYY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
double offsetXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY + 1 << 2));
double offsetYX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
double offsetXX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY + 1 << 2));
double offsetYXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
double offsetXXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
int advancedValueI = parentValues[i + 1 + (j + 0) * scaledWidth] & 255;
int advancedValueIJ = parentValues[i + 1 + (j + 1) * scaledWidth] & 255;
for(int innerX = 0; innerX < 4; ++innerX) {
int index = ((j << 2) + innerX) * bitshiftedWidth + (i << 2);
for(int innerY = 0; innerY < 4; ++innerY) {
double baseDistance;
double distanceY;
double distanceX;
double distanceXY;
switch(zoomMode) {
case CARTESIAN:
baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY);
distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY);
distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX);
distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY);
break;
case MANHATTAN:
baseDistance = Math.abs(innerX - offsetX) + Math.abs(innerY - offsetY);
distanceY = Math.abs(innerX - offsetXY) + Math.abs(innerY - offsetYY);
distanceX = Math.abs(innerX - offsetXX) + Math.abs(innerY - offsetYX);
distanceXY = Math.abs(innerX - offsetXXY) + Math.abs(innerY - offsetYXY);
break;
default:
baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY);
distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY);
distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX);
distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY);
}
if(baseDistance < distanceY && baseDistance < distanceX && baseDistance < distanceXY) {
aint1[index++] = baseValue;
} else if(distanceY < baseDistance && distanceY < distanceX && distanceY < distanceXY) {
aint1[index++] = advancedValueI;
} else if(distanceX < baseDistance && distanceX < distanceY && distanceX < distanceXY) {
aint1[index++] = advancedValueJ;
} else {
aint1[index++] = advancedValueIJ;
}
}
}
baseValue = advancedValueI;
advancedValueJ = advancedValueIJ;
}
}
int[] aint2 = IntCache.getIntCache(width * length);
for(i = 0; i < length; ++i) {
System.arraycopy(aint1, (i + (y & 3)) * bitshiftedWidth + (x & 3), aint2, i * width, width);
}
return aint2;
}
@Override
public void setZoom(int zoom) {
this.zoom = zoom;
parent.setZoom(zoom * 4);
}
} | mpl-2.0 |