lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | ba2fe986bebe63bfa99fca44772d22a4eebbc3f9 | 0 | astrapi69/jaulp.wicket,astrapi69/jaulp-wicket,astrapi69/jaulp-wicket,astrapi69/jaulp.wicket,astrapi69/jaulp-wicket,astrapi69/jaulp.wicket | /**
* Copyright (C) 2010 Asterios Raptis
*
* 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.jaulp.wicket.base.pageparameters;
/**
* The Class ParameterKeys contains constants for the <code>PageParameters</code> keys.
*/
public class ParameterKeys
{
/** The Constant CONFIRMATION_CODE. */
public static final String CONFIRMATION_CODE = "forgotten";
/** The Constant USER_ID. */
public static final String USER_ID = "user_id";
/** The Constant USERNAME. */
public static final String USERNAME = "username";
/** The Constant ACTION. */
public static final String ACTION = "action";
/** The Constant INFO_MESSAGE. */
public static final String INFO_MESSAGE = "info_massage";
/** The Constant EMAIL. */
public static final String EMAIL = "email";
} | jaulp.wicket.base/src/main/java/org/jaulp/wicket/base/pageparameters/ParameterKeys.java | /**
* Copyright (C) 2010 Asterios Raptis
*
* 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.jaulp.wicket.base.pageparameters;
/**
* The Class ParameterKeys contains constants for the <code>PageParameters</code> keys.
*/
public class ParameterKeys
{
/** The Constant CONFIRMATION_CODE. */
public static final String CONFIRMATION_CODE = "forgotten";
/** The Constant USER_ID. */
public static final String USER_ID = "USER_ID";
/** The Constant USERNAME. */
public static final String USERNAME = "username";
/** The Constant ACTION. */
public static final String ACTION = "action";
/** The Constant INFO_MESSAGE. */
public static final String INFO_MESSAGE = "info_massage";
} | New parameter keys added. | jaulp.wicket.base/src/main/java/org/jaulp/wicket/base/pageparameters/ParameterKeys.java | New parameter keys added. |
|
Java | apache-2.0 | a8052f5eb515c723f0092ab049ec5d6086d4b77f | 0 | mythguided/hydra,mythguided/hydra,mythguided/hydra,mythguided/hydra | /*
* 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.addthis.hydra.job;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import com.addthis.basis.util.Parameter;
import com.addthis.hydra.job.chores.JobTaskMoveAssignment;
import com.addthis.hydra.job.mq.HostState;
import com.addthis.hydra.job.mq.JobKey;
import com.addthis.hydra.job.store.SpawnDataStore;
import com.addthis.maljson.JSONArray;
import com.addthis.maljson.JSONException;
import com.addthis.maljson.JSONObject;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.ImmutableSet;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Counter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HostFailWorker {
private static final Logger log = LoggerFactory.getLogger(HostFailWorker.class);
private final HostFailState hostFailState;
private AtomicBoolean newAdditions = new AtomicBoolean(false); // True if a host has been recently added to the queue
private final Spawn spawn;
// Perform host-failure related operations at a given interval
private final long hostFailDelayMillis = Parameter.longValue("host.fail.delay", 10_000);
// Quiet period between when host is failed in UI and when Spawn begins failure-related operations
private final long hostFailQuietPeriod = Parameter.longValue("host.fail.quiet.period", 20_000);
// Perform this many moves at a time
private final int tasksMovedPerHostIteration = Parameter.intValue("host.fail.tasks.moved", 3);
private final Timer failTimer = new Timer(true);
private static final String dataStoragePath = "/spawn/hostfailworker";
private static final Counter failHostCount = Metrics.newCounter(Spawn.class, "failHostCount");
// Various keys used to make JSON objects to send to the UI
private static final String infoHostsKey = "uuids";
private static final String infoDeadFsKey = "deadFs";
private static final String infoWarningKey = "warning";
private static final String infoPrefailCapacityKey = "prefail";
private static final String infoPostfailCapacityKey = "postfail";
private static final String infoFatalWarningKey = "fatal";
public HostFailWorker(Spawn spawn) {
hostFailState = new HostFailState();
this.spawn = spawn;
boolean loaded = hostFailState.loadState();
if (loaded) {
queueFailNextHost();
}
failTimer.scheduleAtFixedRate(new FailHostTask(true), hostFailDelayMillis, hostFailDelayMillis);
}
public void stop() {
failTimer.cancel();
}
/**
* Mark a series of hosts for failure
*
* @param hostIds A comma-separated list of host uuids
* @param fileSystemDead Whether the file systems of these hosts should be treated as unreachable
*/
public void markHostsToFail(String hostIds, boolean fileSystemDead) {
if (hostIds != null) {
for (String host : hostIds.split(",")) {
hostFailState.putHost(host, fileSystemDead);
spawn.sendHostUpdateEvent(spawn.getHostState(host));
}
queueFailNextHost();
}
}
/**
* Retrieve an enum describing whether/how a host has been failed (for programmatic purposes)
*
* @param hostId A host uuid to check
* @return A FailState object describing whether the host has been failed
*/
public FailState getFailureState(String hostId) {
return hostFailState.getState(hostId);
}
/**
* Retrieve a human-readable string describing whether/how a host has been failed
*
* @param hostId A host uuid to check
* @param up Whether the host is up
* @return A String describing the host's failure state (mainly for the UI)
*/
public String getFailureStateString(String hostId, boolean up) {
FailState failState = getFailureState(hostId);
switch (failState) {
case ALIVE:
return up ? "up" : "down";
case FAILING_FS_DEAD:
return "queued to fail (fs dead)";
case FAILING_FS_OKAY:
return "queued to fail (fs okay)";
default:
return "UNKNOWN";
}
}
/**
* Cancel the failure of one or more hosts
*
* @param hostIds A comma-separated list of host uuids
*/
public void removeHostsForFailure(String hostIds) {
if (hostIds != null) {
for (String host : hostIds.split(",")) {
hostFailState.removeHost(host);
spawn.sendHostUpdateEvent(spawn.getHostState(host));
}
}
}
/**
* Decide whether a given host can be failed based on whether other minions in the cluster are up
*
* @param failedHostUuid The host to be failed
* @return True only if there are no down hosts that would need to be up in order to correctly fail the host
*/
protected boolean checkHostStatesForFailure(String failedHostUuid) {
Collection<HostState> hostStates = spawn.listHostStatus(null);
for (HostState hostState : hostStates) {
if (!failedHostUuid.equals(hostState.getHostUuid()) && shouldBlockHostFailure(ImmutableSet.of(failedHostUuid), hostState)) {
log.warn("Unable to fail host: " + failedHostUuid + " because one of the minions (" + hostState.getHostUuid() + ") on " + hostState.getHost() + " is currently down. Retry when all minions are available");
return false;
}
}
return true;
}
/**
* Fail a host. For any tasks with replicas on that host, move these replicas elsewhere. For any tasks with live copies on the host,
* promote a replica, then make a new replica somewhere else.
*/
private void markHostDead(String failedHostUuid) {
if (failedHostUuid == null || !checkHostStatesForFailure(failedHostUuid)) {
return;
}
spawn.markHostStateDead(failedHostUuid);
hostFailState.removeHost(failedHostUuid);
failHostCount.inc();
}
/**
* Before failing host(s), check if a different host needs to be up to perform the failure operation.
*
* @param failedHostUUIDs The hosts being failed
* @param hostState The host to check
* @return True if the host is down
*/
private boolean shouldBlockHostFailure(Set<String> failedHostUUIDs, HostState hostState) {
if (hostState == null || hostState.isDead() || hostState.isUp()) {
return false;
}
for (JobKey jobKey : hostState.allJobKeys()) // never null due to implementation
{
JobTask task = spawn.getTask(jobKey);
if (task != null && (failedHostUUIDs.contains(task.getHostUUID()) || task.hasReplicaOnHosts(failedHostUUIDs))) {
// There is a task on a to-be-failed host that has a copy on a host that is down. We cannot fail for now.
return true;
}
}
return false;
}
/**
* After receiving a host failure request, queue an event to fail that host after a quiet period
*/
private void queueFailNextHost() {
if (newAdditions.compareAndSet(false, true)) {
failTimer.schedule(new FailHostTask(false), hostFailQuietPeriod);
}
}
/**
* Find the next host on the fail queue, considering filesystem-dead hosts first. Perform the correct actions and remove from the queue if appropriate.
*/
private void failNextHost() {
Pair<String, Boolean> hostToFail = hostFailState.nextHostToFail();
if (hostToFail != null) {
String failedHostUuid = hostToFail.getLeft();
boolean fileSystemDead = hostToFail.getRight();
if (!fileSystemDead && spawn.getSettings().getQuiesced()) {
// If filesystem is okay, don't do any moves while spawn is quiesced.
return;
}
HostState host = spawn.getHostState(failedHostUuid);
if (host == null) {
// Host is gone or has no more tasks. Simply mark it as failed.
markHostDead(failedHostUuid);
return;
}
if (fileSystemDead) {
// File system is dead. Relocate all tasks ASAP.
markHostDead(failedHostUuid);
spawn.getSpawnBalancer().fixTasksForFailedHost(spawn.listHostStatus(host.getMinionTypes()), failedHostUuid);
} else if (host.getAvailableTaskSlots() > 0) {
// File system is okay. Push some tasks off the host if it has some available capacity.
List<JobTaskMoveAssignment> assignments = spawn.getSpawnBalancer().pushTasksOffDiskForFilesystemOkayFailure(host, tasksMovedPerHostIteration);
spawn.executeReallocationAssignments(assignments);
if (assignments.isEmpty() && host.countTotalLive() == 0) {
// Found no tasks on the failed host, so fail it for real.
markHostDead(failedHostUuid);
spawn.getSpawnBalancer().fixTasksForFailedHost(spawn.listHostStatus(host.getMinionTypes()), failedHostUuid);
}
}
}
}
/**
* Retrieve information about the implications of failing a host, to inform/warn a user in the UI
*
* @param hostsToFail The hosts that will be failed
* @return A JSONObject with various data about the implications of the failure
*/
public JSONObject getInfoForHostFailure(String hostsToFail, boolean deadFilesystem) throws JSONException {
if (hostsToFail == null) {
return new JSONObject();
}
HashSet<String> ids = new HashSet<>(Arrays.asList(hostsToFail.split(",")));
long totalClusterAvail = 0, totalClusterUsed = 0, hostAvail = 0;
List<String> hostsDown = new ArrayList<>();
for (HostState host : spawn.listHostStatus(null)) {
// Sum up disk availability across the entire cluster and across the specified hosts
if (host.getMax() != null && host.getUsed() != null) {
if (getFailureState(host.getHostUuid()) == FailState.ALIVE) {
totalClusterAvail += host.getMax().getDisk();
totalClusterUsed += host.getUsed().getDisk();
}
if (ids.contains(host.getHostUuid())) {
hostAvail += host.getMax().getDisk();
}
}
if (!ids.contains(host.getHostUuid()) && shouldBlockHostFailure(ids, host)) {
hostsDown.add(host.getHostUuid() + " on " + host.getHost());
}
}
// Guard against division by zero in the case of unexpected values
totalClusterAvail = Math.max(1, totalClusterAvail);
hostAvail = Math.min(totalClusterAvail - 1, hostAvail);
return constructInfoMessage(hostsToFail, deadFilesystem, (double) (totalClusterUsed) / totalClusterAvail, (double) (totalClusterUsed) / (totalClusterAvail - hostAvail), hostsDown);
}
/**
* Create the info message about host message using some raw values
*
* @param prefailCapacity The capacity the cluster had before the failure
* @param postfailCapacity The capacity the cluster would have after the failure
* @param hostsDown Any hosts that are down that might temporarily prevent failure
* @return A JSONObject encapsulating the above information.
* @throws JSONException
*/
private JSONObject constructInfoMessage(String hostsToFail, boolean deadFilesystem, double prefailCapacity, double postfailCapacity, List<String> hostsDown) throws JSONException {
JSONObject obj = new JSONObject();
obj.put(infoHostsKey, hostsToFail);
obj.put(infoDeadFsKey, deadFilesystem);
obj.put(infoPrefailCapacityKey, prefailCapacity);
obj.put(infoPostfailCapacityKey, postfailCapacity);
if (Double.isNaN(postfailCapacity)) {
obj.put(infoFatalWarningKey, "Cannot fail all hosts from a cluster");
} else if (postfailCapacity >= 1) {
obj.put(infoFatalWarningKey, "Insufficient cluster disk capacity");
}
if (!hostsDown.isEmpty()) {
obj.put(infoWarningKey, "Some hosts are down. Host failure could be delayed until they return: " + hostsDown);
}
return obj;
}
/**
* A simple wrapper around failNextHost that is run by the failExecutor.
*/
private class FailHostTask extends TimerTask {
private final boolean skipIfNewAdditions;
public FailHostTask(boolean skipIfNewAdditions) {
this.skipIfNewAdditions = skipIfNewAdditions;
}
@Override
public void run() {
if (skipIfNewAdditions && newAdditions.get()) {
return;
}
try {
failNextHost();
} catch (Exception e) {
log.warn("Exception while failing host: " + e, e);
} finally {
newAdditions.set(false);
}
}
}
/**
* A class storing the internal state of the host failure queue. All changes are immediately saved to the SpawnDataStore
*/
private class HostFailState {
private static final String filesystemDeadKey = "deadFs";
private static final String filesystemOkayKey = "okayFs";
private final Map<Boolean, Set<String>> hostsToFailByType = new HashMap<>();
private final Set<String> failFsDead;
private final Set<String> failFsOkay;
public HostFailState() {
synchronized (hostsToFailByType) {
failFsDead = new TreeSet<>();
hostsToFailByType.put(false, failFsDead);
failFsOkay = new TreeSet<>();
hostsToFailByType.put(true, failFsOkay);
}
}
/**
* Add a new failed host
*
* @param hostId The host id to add
* @param deadFileSystem Whether the host's filesystem should be treated as dead
*/
public void putHost(String hostId, boolean deadFileSystem) {
synchronized (hostsToFailByType) {
if (deadFileSystem && failFsOkay.contains(hostId)) {
// Change a host from an fs-okay failure to an fs-dead failure
failFsOkay.remove(hostId);
failFsDead.add(hostId);
} else if (!deadFileSystem && failFsDead.contains(hostId)) {
log.warn("Ignoring eventual fail host on " + hostId + " because it is already marked as dead");
} else {
hostsToFailByType.get(deadFileSystem).add(hostId);
}
saveState();
}
}
/**
* Retrieve the next host to fail
*
* @return The uuid of the next host to fail, and whether the file system is dead. If the queue is empty, return null.
*/
public Pair<String, Boolean> nextHostToFail() {
synchronized (hostsToFailByType) {
if (!failFsOkay.isEmpty()) {
return Pair.of(failFsOkay.iterator().next(), true);
} else if (!failFsDead.isEmpty()) {
return Pair.of(failFsDead.iterator().next(), false);
}
return null;
}
}
/**
* Cancel the failure for a host
*
* @param hostId The uuid to cancel
*/
public void removeHost(String hostId) {
synchronized (hostsToFailByType) {
for (Set<String> hosts : hostsToFailByType.values()) {
hosts.remove(hostId);
}
saveState();
}
}
/**
* Load the stored state from the SpawnDataStore
*
* @return True if at least one host was loaded
*/
public boolean loadState() {
SpawnDataStore spawnDataStore = spawn.getSpawnDataStore();
if (spawnDataStore == null) {
return false;
}
String raw = spawnDataStore.get(dataStoragePath);
if (raw == null) {
return false;
}
synchronized (hostsToFailByType) {
try {
JSONObject decoded = new JSONObject(spawn.getSpawnDataStore().get(dataStoragePath));
loadHostsFromJSONArray(false, decoded.getJSONArray(filesystemOkayKey));
loadHostsFromJSONArray(true, decoded.getJSONArray(filesystemDeadKey));
} catch (Exception e) {
log.warn("Failed to load HostFailState: " + e + " raw=" + raw, e);
}
return !hostsToFailByType.isEmpty();
}
}
/**
* Internal method to convert a JSONArray from the SpawnDataStore to a list of hosts
*/
private void loadHostsFromJSONArray(boolean deadFileSystem, JSONArray arr) throws JSONException {
if (arr == null) {
return;
}
Set<String> modified = deadFileSystem ? failFsOkay : failFsDead;
for (int i = 0; i < arr.length(); i++) {
modified.add(arr.getString(i));
}
}
/**
* Save the state to the SpawnDataStore
*/
public void saveState() {
try {
synchronized (hostsToFailByType) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(filesystemOkayKey, new JSONArray(failFsDead));
jsonObject.put(filesystemDeadKey, new JSONArray(failFsOkay));
spawn.getSpawnDataStore().put(dataStoragePath, jsonObject.toString());
}
} catch (Exception e) {
log.warn("Failed to save HostFailState: " + e, e);
}
}
/**
* Get the state of failure for a host
*
* @param hostId The host to check
* @return ALIVE if the host is not being failed; otherwise, a description of the type of failure
*/
public FailState getState(String hostId) {
synchronized (hostsToFailByType) {
if (failFsOkay.contains(hostId)) {
return FailState.FAILING_FS_DEAD;
} else if (failFsDead.contains(hostId)) {
return FailState.FAILING_FS_OKAY;
} else {
return FailState.ALIVE;
}
}
}
}
public enum FailState {ALIVE, FAILING_FS_DEAD, FAILING_FS_OKAY}
}
| hydra-main/src/main/java/com/addthis/hydra/job/HostFailWorker.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.addthis.hydra.job;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import com.addthis.basis.util.Parameter;
import com.addthis.hydra.job.chores.JobTaskMoveAssignment;
import com.addthis.hydra.job.mq.HostState;
import com.addthis.hydra.job.mq.JobKey;
import com.addthis.hydra.job.store.SpawnDataStore;
import com.addthis.maljson.JSONArray;
import com.addthis.maljson.JSONException;
import com.addthis.maljson.JSONObject;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.ImmutableSet;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Counter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HostFailWorker {
private static final Logger log = LoggerFactory.getLogger(HostFailWorker.class);
private final HostFailState hostFailState;
private AtomicBoolean newAdditions = new AtomicBoolean(false); // True if a host has been recently added to the queue
private final Spawn spawn;
// Perform host-failure related operations at a given interval
private final long hostFailDelayMillis = Parameter.longValue("host.fail.delay", 10_000);
// Quiet period between when host is failed in UI and when Spawn begins failure-related operations
private final long hostFailQuietPeriod = Parameter.longValue("host.fail.quiet.period", 20_000);
// Perform this many moves at a time
private final int tasksMovedPerHostIteration = Parameter.intValue("host.fail.tasks.moved", 3);
private final Timer failTimer = new Timer(true);
private static final String dataStoragePath = "/spawn/hostfailworker";
private static final Counter failHostCount = Metrics.newCounter(Spawn.class, "failHostCount");
// Various keys used to make JSON objects to send to the UI
private static final String infoHostsKey = "uuids";
private static final String infoDeadFsKey = "deadFs";
private static final String infoWarningKey = "warning";
private static final String infoPrefailCapacityKey = "prefail";
private static final String infoPostfailCapacityKey = "postfail";
private static final String infoFatalWarningKey = "fatal";
public HostFailWorker(Spawn spawn) {
hostFailState = new HostFailState();
this.spawn = spawn;
boolean loaded = hostFailState.loadState();
if (loaded) {
queueFailNextHost();
}
failTimer.scheduleAtFixedRate(new FailHostTask(true), hostFailDelayMillis, hostFailDelayMillis);
}
public void stop() {
failTimer.cancel();
}
/**
* Mark a series of hosts for failure
*
* @param hostIds A comma-separated list of host uuids
* @param fileSystemDead Whether the file systems of these hosts should be treated as unreachable
*/
public void markHostsToFail(String hostIds, boolean fileSystemDead) {
if (hostIds != null) {
for (String host : hostIds.split(",")) {
hostFailState.putHost(host, fileSystemDead);
spawn.sendHostUpdateEvent(spawn.getHostState(host));
}
queueFailNextHost();
}
}
/**
* Retrieve an enum describing whether/how a host has been failed (for programmatic purposes)
*
* @param hostId A host uuid to check
* @return A FailState object describing whether the host has been failed
*/
public FailState getFailureState(String hostId) {
return hostFailState.getState(hostId);
}
/**
* Retrieve a human-readable string describing whether/how a host has been failed
*
* @param hostId A host uuid to check
* @param up Whether the host is up
* @return A String describing the host's failure state (mainly for the UI)
*/
public String getFailureStateString(String hostId, boolean up) {
FailState failState = getFailureState(hostId);
switch (failState) {
case ALIVE:
return up ? "up" : "down";
case FAILING_FS_DEAD:
return "queued to fail (fs dead)";
case FAILING_FS_OKAY:
return "queued to fail (fs okay)";
default:
return "UNKNOWN";
}
}
/**
* Cancel the failure of one or more hosts
*
* @param hostIds A comma-separated list of host uuids
*/
public void removeHostsForFailure(String hostIds) {
if (hostIds != null) {
for (String host : hostIds.split(",")) {
hostFailState.removeHost(host);
spawn.sendHostUpdateEvent(spawn.getHostState(host));
}
}
}
/**
* Decide whether a given host can be failed based on whether other minions in the cluster are up
*
* @param failedHostUuid The host to be failed
* @return True only if there are no down hosts that would need to be up in order to correctly fail the host
*/
protected boolean checkHostStatesForFailure(String failedHostUuid) {
Collection<HostState> hostStates = spawn.listHostStatus(null);
for (HostState hostState : hostStates) {
if (!failedHostUuid.equals(hostState.getHostUuid()) && shouldBlockHostFailure(ImmutableSet.of(failedHostUuid), hostState)) {
log.warn("Unable to fail host: " + failedHostUuid + " because one of the minions (" + hostState.getHostUuid() + ") on " + hostState.getHost() + " is currently down. Retry when all minions are available");
return false;
}
}
return true;
}
/**
* Fail a host. For any tasks with replicas on that host, move these replicas elsewhere. For any tasks with live copies on the host,
* promote a replica, then make a new replica somewhere else.
*/
private void markHostDead(String failedHostUuid) {
if (failedHostUuid == null || !checkHostStatesForFailure(failedHostUuid)) {
return;
}
spawn.markHostStateDead(failedHostUuid);
hostFailState.removeHost(failedHostUuid);
failHostCount.inc();
}
/**
* Before failing host(s), check if a different host needs to be up to perform the failure operation.
*
* @param failedHostUUIDs The hosts being failed
* @param hostState The host to check
* @return True if the host is down
*/
private boolean shouldBlockHostFailure(Set<String> failedHostUUIDs, HostState hostState) {
if (hostState == null || hostState.isDead() || hostState.isUp()) {
return false;
}
for (JobKey jobKey : hostState.allJobKeys()) // never null due to implementation
{
JobTask task = spawn.getTask(jobKey);
if (task != null && (failedHostUUIDs.contains(task.getHostUUID()) || task.hasReplicaOnHosts(failedHostUUIDs))) {
// There is a task on a to-be-failed host that has a copy on a host that is down. We cannot fail for now.
return true;
}
}
return false;
}
/**
* After receiving a host failure request, queue an event to fail that host after a quiet period
*/
private void queueFailNextHost() {
if (newAdditions.compareAndSet(false, true)) {
failTimer.schedule(new FailHostTask(false), hostFailQuietPeriod);
}
}
/**
* Find the next host on the fail queue, considering filesystem-dead hosts first. Perform the correct actions and remove from the queue if appropriate.
*/
private void failNextHost() {
Pair<String, Boolean> hostToFail = hostFailState.nextHostToFail();
if (hostToFail != null) {
String failedHostUuid = hostToFail.getLeft();
boolean fileSystemDead = hostToFail.getRight();
if (!fileSystemDead && spawn.getSettings().getQuiesced()) {
// If filesystem is okay, don't do any moves while spawn is quiesced.
return;
}
HostState host = spawn.getHostState(failedHostUuid);
if (host == null) {
// Host is gone or has no more tasks. Simply mark it as failed.
markHostDead(failedHostUuid);
return;
}
if (fileSystemDead) {
// File system is dead. Relocate all tasks ASAP.
markHostDead(failedHostUuid);
spawn.getSpawnBalancer().fixTasksForFailedHost(spawn.listHostStatus(host.getMinionTypes()), failedHostUuid);
} else if (host.getAvailableTaskSlots() > 0) {
// File system is okay. Push some tasks off the host if it has some available capacity.
List<JobTaskMoveAssignment> assignments = spawn.getSpawnBalancer().pushTasksOffDiskForFilesystemOkayFailure(host, tasksMovedPerHostIteration);
spawn.executeReallocationAssignments(assignments);
if (assignments.isEmpty() && host.countTotalLive() == 0) {
// Found no tasks on the failed host, so fail it for real.
markHostDead(failedHostUuid);
spawn.getSpawnBalancer().fixTasksForFailedHost(spawn.listHostStatus(host.getMinionTypes()), failedHostUuid);
}
}
}
}
/**
* Retrieve information about the implications of failing a host, to inform/warn a user in the UI
*
* @param hostsToFail The hosts that will be failed
* @return A JSONObject with various data about the implications of the failure
*/
public JSONObject getInfoForHostFailure(String hostsToFail, boolean deadFilesystem) throws JSONException {
if (hostsToFail == null) {
return new JSONObject();
}
HashSet<String> ids = new HashSet<>(Arrays.asList(hostsToFail.split(",")));
long totalClusterAvail = 0, totalClusterUsed = 0, hostAvail = 0;
List<String> hostsDown = new ArrayList<>();
for (HostState host : spawn.listHostStatus(null)) {
// Sum up disk availability across the entire cluster and across the specified hosts
if (host.getMax() != null && host.getUsed() != null) {
if (getFailureState(host.getHostUuid()) == FailState.ALIVE) {
totalClusterAvail += host.getMax().getDisk();
totalClusterUsed += host.getUsed().getDisk();
}
if (ids.contains(host.getHostUuid())) {
hostAvail += host.getMax().getDisk();
}
}
if (!ids.contains(host.getHostUuid()) && shouldBlockHostFailure(ids, host)) {
hostsDown.add(host.getHostUuid() + " on " + host.getHost());
}
}
// Guard against division by zero in the case of unexpected values
totalClusterAvail = Math.max(1, totalClusterAvail);
hostAvail = Math.min(totalClusterAvail - 1, hostAvail);
return constructInfoMessage(hostsToFail, deadFilesystem, (double) (totalClusterUsed) / totalClusterAvail, (double) (totalClusterUsed) / (totalClusterAvail - hostAvail), hostsDown);
}
/**
* Create the info message about host message using some raw values
*
* @param prefailCapacity The capacity the cluster had before the failure
* @param postfailCapacity The capacity the cluster would have after the failure
* @param hostsDown Any hosts that are down that might temporarily prevent failure
* @return A JSONObject encapsulating the above information.
* @throws JSONException
*/
private JSONObject constructInfoMessage(String hostsToFail, boolean deadFilesystem, double prefailCapacity, double postfailCapacity, List<String> hostsDown) throws JSONException {
JSONObject obj = new JSONObject();
obj.put(infoHostsKey, hostsToFail);
obj.put(infoDeadFsKey, deadFilesystem);
obj.put(infoPrefailCapacityKey, prefailCapacity);
obj.put(infoPostfailCapacityKey, postfailCapacity);
if (Double.isNaN(postfailCapacity)) {
obj.put(infoFatalWarningKey, "Cannot fail all hosts from a cluster");
} else if (postfailCapacity >= 1) {
obj.put(infoFatalWarningKey, "Insufficient cluster disk capacity");
}
if (!hostsDown.isEmpty()) {
obj.put(infoWarningKey, "Some hosts are down. Host failure could be delayed until they return: " + hostsDown);
}
return obj;
}
/**
* A simple wrapper around failNextHost that is run by the failExecutor.
*/
private class FailHostTask extends TimerTask {
private final boolean skipIfNewAdditions;
public FailHostTask(boolean skipIfNewAdditions) {
this.skipIfNewAdditions = skipIfNewAdditions;
}
@Override
public void run() {
if (skipIfNewAdditions && newAdditions.get()) {
return;
}
try {
failNextHost();
} catch (Exception e) {
log.warn("Exception while failing host: " + e, e);
} finally {
newAdditions.set(false);
}
}
}
/**
* A class storing the internal state of the host failure queue. All changes are immediately saved to the SpawnDataStore
*/
private class HostFailState {
private static final String filesystemDeadKey = "deadFs";
private static final String filesystemOkayKey = "okayFs";
private final Map<Boolean, Set<String>> hostsToFailByType = new HashMap<>();
private final Set<String> failFsDead;
private final Set<String> failFsOkay;
public HostFailState() {
synchronized (hostsToFailByType) {
failFsDead = new HashSet<>();
hostsToFailByType.put(false, failFsDead);
failFsOkay = new HashSet<>();
hostsToFailByType.put(true, failFsOkay);
}
}
/**
* Add a new failed host
*
* @param hostId The host id to add
* @param deadFileSystem Whether the host's filesystem should be treated as dead
*/
public void putHost(String hostId, boolean deadFileSystem) {
synchronized (hostsToFailByType) {
if (deadFileSystem && failFsOkay.contains(hostId)) {
// Change a host from an fs-okay failure to an fs-dead failure
failFsOkay.remove(hostId);
failFsDead.add(hostId);
} else if (!deadFileSystem && failFsDead.contains(hostId)) {
log.warn("Ignoring eventual fail host on " + hostId + " because it is already marked as dead");
} else {
hostsToFailByType.get(deadFileSystem).add(hostId);
}
saveState();
}
}
/**
* Retrieve the next host to fail
*
* @return The uuid of the next host to fail, and whether the file system is dead. If the queue is empty, return null.
*/
public Pair<String, Boolean> nextHostToFail() {
synchronized (hostsToFailByType) {
if (!failFsOkay.isEmpty()) {
return Pair.of(failFsOkay.iterator().next(), true);
} else if (!failFsDead.isEmpty()) {
return Pair.of(failFsDead.iterator().next(), false);
}
return null;
}
}
/**
* Cancel the failure for a host
*
* @param hostId The uuid to cancel
*/
public void removeHost(String hostId) {
synchronized (hostsToFailByType) {
for (Set<String> hosts : hostsToFailByType.values()) {
hosts.remove(hostId);
}
saveState();
}
}
/**
* Load the stored state from the SpawnDataStore
*
* @return True if at least one host was loaded
*/
public boolean loadState() {
SpawnDataStore spawnDataStore = spawn.getSpawnDataStore();
if (spawnDataStore == null) {
return false;
}
String raw = spawnDataStore.get(dataStoragePath);
if (raw == null) {
return false;
}
synchronized (hostsToFailByType) {
try {
JSONObject decoded = new JSONObject(spawn.getSpawnDataStore().get(dataStoragePath));
loadHostsFromJSONArray(false, decoded.getJSONArray(filesystemOkayKey));
loadHostsFromJSONArray(true, decoded.getJSONArray(filesystemDeadKey));
} catch (Exception e) {
log.warn("Failed to load HostFailState: " + e + " raw=" + raw, e);
}
return !hostsToFailByType.isEmpty();
}
}
/**
* Internal method to convert a JSONArray from the SpawnDataStore to a list of hosts
*/
private void loadHostsFromJSONArray(boolean deadFileSystem, JSONArray arr) throws JSONException {
if (arr == null) {
return;
}
Set<String> modified = deadFileSystem ? failFsOkay : failFsDead;
for (int i = 0; i < arr.length(); i++) {
modified.add(arr.getString(i));
}
}
/**
* Save the state to the SpawnDataStore
*/
public void saveState() {
try {
synchronized (hostsToFailByType) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(filesystemOkayKey, new JSONArray(failFsDead));
jsonObject.put(filesystemDeadKey, new JSONArray(failFsOkay));
spawn.getSpawnDataStore().put(dataStoragePath, jsonObject.toString());
}
} catch (Exception e) {
log.warn("Failed to save HostFailState: " + e, e);
}
}
/**
* Get the state of failure for a host
*
* @param hostId The host to check
* @return ALIVE if the host is not being failed; otherwise, a description of the type of failure
*/
public FailState getState(String hostId) {
synchronized (hostsToFailByType) {
if (failFsOkay.contains(hostId)) {
return FailState.FAILING_FS_DEAD;
} else if (failFsDead.contains(hostId)) {
return FailState.FAILING_FS_OKAY;
} else {
return FailState.ALIVE;
}
}
}
}
public enum FailState {ALIVE, FAILING_FS_DEAD, FAILING_FS_OKAY}
}
| Use TreeSet for consistent fsokay ordering.
| hydra-main/src/main/java/com/addthis/hydra/job/HostFailWorker.java | Use TreeSet for consistent fsokay ordering. |
|
Java | apache-2.0 | 0fbd79f669587db8867f70773ae0bf4f2de4cbed | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.util;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public final class PsiPrecedenceUtil {
public static final int PARENTHESIZED_PRECEDENCE = 0;
public static final int LITERAL_PRECEDENCE = 0;
public static final int METHOD_CALL_PRECEDENCE = 1;
public static final int POSTFIX_PRECEDENCE = 2;
public static final int PREFIX_PRECEDENCE = 3;
public static final int TYPE_CAST_PRECEDENCE = 4;
public static final int MULTIPLICATIVE_PRECEDENCE = 5;
public static final int ADDITIVE_PRECEDENCE = 6;
public static final int SHIFT_PRECEDENCE = 7;
public static final int RELATIONAL_PRECEDENCE = 8;
public static final int EQUALITY_PRECEDENCE = 9;
public static final int BINARY_AND_PRECEDENCE = 10;
public static final int BINARY_XOR_PRECEDENCE = 11;
public static final int BINARY_OR_PRECEDENCE = 12;
public static final int AND_PRECEDENCE = 13;
public static final int OR_PRECEDENCE = 14;
public static final int CONDITIONAL_PRECEDENCE = 15;
public static final int ASSIGNMENT_PRECEDENCE = 16;
public static final int LAMBDA_PRECEDENCE = 17; // jls-15.2
public static final int NUM_PRECEDENCES = 18;
private static final Map<IElementType, Integer> s_binaryOperatorPrecedence = new HashMap<>(NUM_PRECEDENCES);
static {
s_binaryOperatorPrecedence.put(JavaTokenType.PLUS, ADDITIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.MINUS, ADDITIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.ASTERISK, MULTIPLICATIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.DIV, MULTIPLICATIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.PERC, MULTIPLICATIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.ANDAND, AND_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.OROR, OR_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.AND, BINARY_AND_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.OR, BINARY_OR_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.XOR, BINARY_XOR_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.LTLT, SHIFT_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.GTGT, SHIFT_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.GTGTGT, SHIFT_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.GT, RELATIONAL_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.GE, RELATIONAL_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.LT, RELATIONAL_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.LE, RELATIONAL_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.EQEQ, EQUALITY_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.NE, EQUALITY_PRECEDENCE);
}
public static boolean isCommutativeOperator(@NotNull IElementType token) {
return token == JavaTokenType.PLUS || token == JavaTokenType.ASTERISK ||
token == JavaTokenType.EQEQ || token == JavaTokenType.NE ||
token == JavaTokenType.AND || token == JavaTokenType.OR || token == JavaTokenType.XOR;
}
public static boolean isCommutativeOperation(PsiPolyadicExpression expression) {
final IElementType tokenType = expression.getOperationTokenType();
if (!isCommutativeOperator(tokenType)) {
return false;
}
final PsiType type = expression.getType();
return type != null && !type.equalsToText(CommonClassNames.JAVA_LANG_STRING);
}
public static boolean isAssociativeOperation(PsiPolyadicExpression expression) {
final IElementType tokenType = expression.getOperationTokenType();
final PsiType type = expression.getType();
final PsiPrimitiveType primitiveType;
if (type instanceof PsiClassType) {
primitiveType = PsiPrimitiveType.getUnboxedType(type);
if (primitiveType == null) {
return false;
}
}
else if (type instanceof PsiPrimitiveType) {
primitiveType = (PsiPrimitiveType)type;
}
else {
return false;
}
if (JavaTokenType.PLUS == tokenType || JavaTokenType.ASTERISK == tokenType) {
return !PsiType.FLOAT.equals(primitiveType) && !PsiType.DOUBLE.equals(primitiveType);
}
else if (JavaTokenType.EQEQ == tokenType || JavaTokenType.NE == tokenType) {
return PsiType.BOOLEAN.equals(primitiveType);
}
else if (JavaTokenType.AND == tokenType || JavaTokenType.OR == tokenType || JavaTokenType.XOR == tokenType) {
return true;
}
else if (JavaTokenType.OROR == tokenType || JavaTokenType.ANDAND == tokenType) {
return true;
}
return false;
}
public static int getPrecedence(PsiExpression expression) {
if (expression instanceof PsiThisExpression ||
expression instanceof PsiLiteralExpression ||
expression instanceof PsiSuperExpression ||
expression instanceof PsiClassObjectAccessExpression ||
expression instanceof PsiArrayAccessExpression ||
expression instanceof PsiArrayInitializerExpression) {
return LITERAL_PRECEDENCE;
}
if (expression instanceof PsiReferenceExpression) {
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)expression;
if (referenceExpression.getQualifier() != null) {
return METHOD_CALL_PRECEDENCE;
}
else {
return LITERAL_PRECEDENCE;
}
}
if (expression instanceof PsiMethodCallExpression || expression instanceof PsiNewExpression) {
return METHOD_CALL_PRECEDENCE;
}
if (expression instanceof PsiTypeCastExpression) {
return TYPE_CAST_PRECEDENCE;
}
if (expression instanceof PsiPrefixExpression) {
return PREFIX_PRECEDENCE;
}
if (expression instanceof PsiPostfixExpression || expression instanceof PsiSwitchExpression) {
return POSTFIX_PRECEDENCE;
}
if (expression instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
return getPrecedenceForOperator(polyadicExpression.getOperationTokenType());
}
if (expression instanceof PsiInstanceOfExpression) {
return RELATIONAL_PRECEDENCE;
}
if (expression instanceof PsiConditionalExpression) {
return CONDITIONAL_PRECEDENCE;
}
if (expression instanceof PsiAssignmentExpression) {
return ASSIGNMENT_PRECEDENCE;
}
if (expression instanceof PsiParenthesizedExpression) {
return PARENTHESIZED_PRECEDENCE;
}
if (expression instanceof PsiLambdaExpression) {
return LAMBDA_PRECEDENCE;
}
return -1;
}
public static int getPrecedenceForOperator(@NotNull IElementType operator) {
final Integer precedence = s_binaryOperatorPrecedence.get(operator);
if (precedence == null) {
throw new IllegalArgumentException("unknown operator: " + operator);
}
return precedence.intValue();
}
public static boolean areParenthesesNeeded(PsiParenthesizedExpression expression, boolean ignoreClarifyingParentheses) {
final PsiElement parent = expression.getParent();
if (!(parent instanceof PsiExpression)) {
return false;
}
final PsiExpression child = expression.getExpression();
return child == null || areParenthesesNeeded(child, (PsiExpression)parent, ignoreClarifyingParentheses);
}
public static boolean areParenthesesNeeded(PsiExpression expression,
PsiExpression parentExpression,
boolean ignoreClarifyingParentheses) {
if (parentExpression instanceof PsiParenthesizedExpression || parentExpression instanceof PsiArrayInitializerExpression) {
return false;
}
if (parentExpression instanceof PsiArrayAccessExpression) {
final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression)parentExpression;
return PsiTreeUtil.isAncestor(arrayAccessExpression.getArrayExpression(), expression, false);
}
final int parentPrecedence = getPrecedence(parentExpression);
final int childPrecedence = getPrecedence(expression);
if (parentPrecedence > childPrecedence) {
if (ignoreClarifyingParentheses) {
if (expression instanceof PsiPolyadicExpression) {
if (parentExpression instanceof PsiPolyadicExpression ||
parentExpression instanceof PsiConditionalExpression ||
parentExpression instanceof PsiInstanceOfExpression) {
return true;
}
}
else if (expression instanceof PsiInstanceOfExpression) {
return true;
}
}
return false;
}
if (parentExpression instanceof PsiPolyadicExpression && expression instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression parentPolyadicExpression = (PsiPolyadicExpression)parentExpression;
final PsiType parentType = parentPolyadicExpression.getType();
if (parentType == null) {
return true;
}
final PsiPolyadicExpression childPolyadicExpression = (PsiPolyadicExpression)expression;
final PsiType childType = childPolyadicExpression.getType();
if (!parentType.equals(childType)) {
return true;
}
if (childType.equalsToText(CommonClassNames.JAVA_LANG_STRING) &&
!PsiTreeUtil.isAncestor(parentPolyadicExpression.getOperands()[0], childPolyadicExpression, true)) {
final PsiExpression[] operands = childPolyadicExpression.getOperands();
return !childType.equals(operands[0].getType()) && !childType.equals(operands[1].getType());
}
else if (childType.equals(PsiType.BOOLEAN)) {
final PsiExpression[] operands = childPolyadicExpression.getOperands();
for (PsiExpression operand : operands) {
PsiType operandType = operand.getType();
if (operandType != null && !PsiType.BOOLEAN.equals(operandType)) {
return true;
}
}
}
final IElementType parentOperator = parentPolyadicExpression.getOperationTokenType();
final IElementType childOperator = childPolyadicExpression.getOperationTokenType();
if (ignoreClarifyingParentheses) {
if (!childOperator.equals(parentOperator)) {
return true;
}
}
final PsiExpression[] parentOperands = parentPolyadicExpression.getOperands();
if (!PsiTreeUtil.isAncestor(parentOperands[0], expression, false)) {
if (!isAssociativeOperation(parentPolyadicExpression) ||
JavaTokenType.DIV == childOperator || JavaTokenType.PERC == childOperator) {
return true;
}
}
}
else if (parentExpression instanceof PsiConditionalExpression && expression instanceof PsiConditionalExpression) {
final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)parentExpression;
final PsiExpression condition = conditionalExpression.getCondition();
return PsiTreeUtil.isAncestor(condition, expression, true);
}
else if (expression instanceof PsiLambdaExpression) { // jls-15.16
if (parentExpression instanceof PsiTypeCastExpression) {
return false;
}
else if (parentExpression instanceof PsiConditionalExpression) { // jls-15.25
final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)parentExpression;
return PsiTreeUtil.isAncestor(conditionalExpression.getCondition(), expression, true);
}
}
return parentPrecedence < childPrecedence;
}
public static boolean areParenthesesNeeded(PsiJavaToken compoundAssignmentToken, PsiExpression rhs) {
if (rhs instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression binaryExpression = (PsiPolyadicExpression)rhs;
final int precedence1 = getPrecedenceForOperator(binaryExpression.getOperationTokenType());
final IElementType signTokenType = compoundAssignmentToken.getTokenType();
final IElementType newOperatorToken = TypeConversionUtil.convertEQtoOperation(signTokenType);
final int precedence2 = getPrecedenceForOperator(newOperatorToken);
return precedence1 >= precedence2 || !isCommutativeOperator(newOperatorToken);
}
else {
return rhs instanceof PsiConditionalExpression;
}
}
}
| java/java-psi-api/src/com/intellij/psi/util/PsiPrecedenceUtil.java | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.util;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public final class PsiPrecedenceUtil {
public static final int PARENTHESIZED_PRECEDENCE = 0;
public static final int LITERAL_PRECEDENCE = 0;
public static final int METHOD_CALL_PRECEDENCE = 1;
public static final int POSTFIX_PRECEDENCE = 2;
public static final int PREFIX_PRECEDENCE = 3;
public static final int TYPE_CAST_PRECEDENCE = 4;
public static final int MULTIPLICATIVE_PRECEDENCE = 5;
public static final int ADDITIVE_PRECEDENCE = 6;
public static final int SHIFT_PRECEDENCE = 7;
public static final int RELATIONAL_PRECEDENCE = 8;
public static final int EQUALITY_PRECEDENCE = 9;
public static final int BINARY_AND_PRECEDENCE = 10;
public static final int BINARY_XOR_PRECEDENCE = 11;
public static final int BINARY_OR_PRECEDENCE = 12;
public static final int AND_PRECEDENCE = 13;
public static final int OR_PRECEDENCE = 14;
public static final int CONDITIONAL_PRECEDENCE = 15;
public static final int ASSIGNMENT_PRECEDENCE = 16;
public static final int LAMBDA_PRECEDENCE = 17; // jls-15.2
public static final int NUM_PRECEDENCES = 18;
private static final Map<IElementType, Integer> s_binaryOperatorPrecedence = new HashMap<>(NUM_PRECEDENCES);
static {
s_binaryOperatorPrecedence.put(JavaTokenType.PLUS, ADDITIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.MINUS, ADDITIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.ASTERISK, MULTIPLICATIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.DIV, MULTIPLICATIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.PERC, MULTIPLICATIVE_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.ANDAND, AND_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.OROR, OR_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.AND, BINARY_AND_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.OR, BINARY_OR_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.XOR, BINARY_XOR_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.LTLT, SHIFT_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.GTGT, SHIFT_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.GTGTGT, SHIFT_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.GT, RELATIONAL_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.GE, RELATIONAL_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.LT, RELATIONAL_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.LE, RELATIONAL_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.EQEQ, EQUALITY_PRECEDENCE);
s_binaryOperatorPrecedence.put(JavaTokenType.NE, EQUALITY_PRECEDENCE);
}
public static boolean isCommutativeOperator(@NotNull IElementType token) {
return token == JavaTokenType.PLUS || token == JavaTokenType.ASTERISK ||
token == JavaTokenType.EQEQ || token == JavaTokenType.NE ||
token == JavaTokenType.AND || token == JavaTokenType.OR || token == JavaTokenType.XOR;
}
public static boolean isCommutativeOperation(PsiPolyadicExpression expression) {
final IElementType tokenType = expression.getOperationTokenType();
if (!isCommutativeOperator(tokenType)) {
return false;
}
final PsiType type = expression.getType();
return type != null && !type.equalsToText(CommonClassNames.JAVA_LANG_STRING);
}
public static boolean isAssociativeOperation(PsiPolyadicExpression expression) {
final IElementType tokenType = expression.getOperationTokenType();
final PsiType type = expression.getType();
final PsiPrimitiveType primitiveType;
if (type instanceof PsiClassType) {
primitiveType = PsiPrimitiveType.getUnboxedType(type);
if (primitiveType == null) {
return false;
}
}
else if (type instanceof PsiPrimitiveType) {
primitiveType = (PsiPrimitiveType)type;
}
else {
return false;
}
if (JavaTokenType.PLUS == tokenType || JavaTokenType.ASTERISK == tokenType) {
return !PsiType.FLOAT.equals(primitiveType) && !PsiType.DOUBLE.equals(primitiveType);
}
else if (JavaTokenType.EQEQ == tokenType || JavaTokenType.NE == tokenType) {
return PsiType.BOOLEAN.equals(primitiveType);
}
else if (JavaTokenType.AND == tokenType || JavaTokenType.OR == tokenType || JavaTokenType.XOR == tokenType) {
return true;
}
else if (JavaTokenType.OROR == tokenType || JavaTokenType.ANDAND == tokenType) {
return true;
}
return false;
}
public static int getPrecedence(PsiExpression expression) {
if (expression instanceof PsiThisExpression ||
expression instanceof PsiLiteralExpression ||
expression instanceof PsiSuperExpression ||
expression instanceof PsiClassObjectAccessExpression ||
expression instanceof PsiArrayAccessExpression ||
expression instanceof PsiArrayInitializerExpression) {
return LITERAL_PRECEDENCE;
}
if (expression instanceof PsiReferenceExpression) {
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)expression;
if (referenceExpression.getQualifier() != null) {
return METHOD_CALL_PRECEDENCE;
}
else {
return LITERAL_PRECEDENCE;
}
}
if (expression instanceof PsiMethodCallExpression || expression instanceof PsiNewExpression) {
return METHOD_CALL_PRECEDENCE;
}
if (expression instanceof PsiTypeCastExpression) {
return TYPE_CAST_PRECEDENCE;
}
if (expression instanceof PsiPrefixExpression) {
return PREFIX_PRECEDENCE;
}
if (expression instanceof PsiPostfixExpression || expression instanceof PsiSwitchExpression) {
return POSTFIX_PRECEDENCE;
}
if (expression instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
return getPrecedenceForOperator(polyadicExpression.getOperationTokenType());
}
if (expression instanceof PsiInstanceOfExpression) {
return RELATIONAL_PRECEDENCE;
}
if (expression instanceof PsiConditionalExpression) {
return CONDITIONAL_PRECEDENCE;
}
if (expression instanceof PsiAssignmentExpression) {
return ASSIGNMENT_PRECEDENCE;
}
if (expression instanceof PsiParenthesizedExpression) {
return PARENTHESIZED_PRECEDENCE;
}
if (expression instanceof PsiLambdaExpression) {
return LAMBDA_PRECEDENCE;
}
return -1;
}
public static int getPrecedenceForOperator(@NotNull IElementType operator) {
final Integer precedence = s_binaryOperatorPrecedence.get(operator);
if (precedence == null) {
throw new IllegalArgumentException("unknown operator: " + operator);
}
return precedence.intValue();
}
public static boolean areParenthesesNeeded(PsiParenthesizedExpression expression, boolean ignoreClarifyingParentheses) {
final PsiElement parent = expression.getParent();
if (!(parent instanceof PsiExpression)) {
return false;
}
final PsiExpression child = expression.getExpression();
return child == null || areParenthesesNeeded(child, (PsiExpression)parent, ignoreClarifyingParentheses);
}
public static boolean areParenthesesNeeded(PsiExpression expression,
PsiExpression parentExpression,
boolean ignoreClarifyingParentheses) {
if (parentExpression instanceof PsiParenthesizedExpression || parentExpression instanceof PsiArrayInitializerExpression) {
return false;
}
if (parentExpression instanceof PsiArrayAccessExpression) {
final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression)parentExpression;
return PsiTreeUtil.isAncestor(arrayAccessExpression.getArrayExpression(), expression, false);
}
final int parentPrecedence = getPrecedence(parentExpression);
final int childPrecedence = getPrecedence(expression);
if (parentPrecedence > childPrecedence) {
if (ignoreClarifyingParentheses) {
if (expression instanceof PsiPolyadicExpression) {
if (parentExpression instanceof PsiPolyadicExpression ||
parentExpression instanceof PsiConditionalExpression ||
parentExpression instanceof PsiInstanceOfExpression) {
return true;
}
}
else if (expression instanceof PsiInstanceOfExpression) {
return true;
}
}
return false;
}
if (parentExpression instanceof PsiPolyadicExpression && expression instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression parentPolyadicExpression = (PsiPolyadicExpression)parentExpression;
final PsiType parentType = parentPolyadicExpression.getType();
if (parentType == null) {
return true;
}
final PsiPolyadicExpression childPolyadicExpression = (PsiPolyadicExpression)expression;
final PsiType childType = childPolyadicExpression.getType();
if (!parentType.equals(childType)) {
return true;
}
if (childType.equalsToText(CommonClassNames.JAVA_LANG_STRING) &&
!PsiTreeUtil.isAncestor(parentPolyadicExpression.getOperands()[0], childPolyadicExpression, true)) {
final PsiExpression[] operands = childPolyadicExpression.getOperands();
for (int i = 0, length = operands.length; i < length; i++) {
final PsiExpression operand = operands[i];
final PsiType operandType = operand.getType();
if (operandType != null && operandType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
return false;
}
else if (!childType.equals(operandType) && i > 0) {
return true;
}
}
}
else if (childType.equals(PsiType.BOOLEAN)) {
final PsiExpression[] operands = childPolyadicExpression.getOperands();
for (PsiExpression operand : operands) {
PsiType operandType = operand.getType();
if (operandType != null && !PsiType.BOOLEAN.equals(operandType)) {
return true;
}
}
}
final IElementType parentOperator = parentPolyadicExpression.getOperationTokenType();
final IElementType childOperator = childPolyadicExpression.getOperationTokenType();
if (ignoreClarifyingParentheses) {
if (!childOperator.equals(parentOperator)) {
return true;
}
}
final PsiExpression[] parentOperands = parentPolyadicExpression.getOperands();
if (!PsiTreeUtil.isAncestor(parentOperands[0], expression, false)) {
if (!isAssociativeOperation(parentPolyadicExpression) ||
JavaTokenType.DIV == childOperator || JavaTokenType.PERC == childOperator) {
return true;
}
}
}
else if (parentExpression instanceof PsiConditionalExpression && expression instanceof PsiConditionalExpression) {
final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)parentExpression;
final PsiExpression condition = conditionalExpression.getCondition();
return PsiTreeUtil.isAncestor(condition, expression, true);
}
else if (expression instanceof PsiLambdaExpression) { // jls-15.16
if (parentExpression instanceof PsiTypeCastExpression) {
return false;
}
else if (parentExpression instanceof PsiConditionalExpression) { // jls-15.25
final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)parentExpression;
return PsiTreeUtil.isAncestor(conditionalExpression.getCondition(), expression, true);
}
}
return parentPrecedence < childPrecedence;
}
public static boolean areParenthesesNeeded(PsiJavaToken compoundAssignmentToken, PsiExpression rhs) {
if (rhs instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression binaryExpression = (PsiPolyadicExpression)rhs;
final int precedence1 = getPrecedenceForOperator(binaryExpression.getOperationTokenType());
final IElementType signTokenType = compoundAssignmentToken.getTokenType();
final IElementType newOperatorToken = TypeConversionUtil.convertEQtoOperation(signTokenType);
final int precedence2 = getPrecedenceForOperator(newOperatorToken);
return precedence1 >= precedence2 || !isCommutativeOperator(newOperatorToken);
}
else {
return rhs instanceof PsiConditionalExpression;
}
}
}
| IG: clean up sloppy code (IJ-CR-3338)
GitOrigin-RevId: 1077b439f9e30cbbaa803f5a7669ec68dbd3d387 | java/java-psi-api/src/com/intellij/psi/util/PsiPrecedenceUtil.java | IG: clean up sloppy code (IJ-CR-3338) |
|
Java | apache-2.0 | d9eeba5275a5f67bb9bd17f930b9ea4b62802017 | 0 | apache/commons-vfs,ecki/commons-vfs,ecki/commons-vfs,apache/commons-vfs | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp.test;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
import org.apache.commons.vfs2.provider.ftp.FtpFileProvider;
import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder;
import org.apache.commons.vfs2.provider.ftp.FtpFileType;
import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
import org.apache.commons.vfs2.test.ProviderTestSuite;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.junit.Assert;
import junit.framework.Test;
/**
* Tests for FTP file systems.
*/
public class FtpProviderTestCase extends AbstractProviderTestConfig {
private static int SocketPort;
/**
* Use %40 for @ in URLs
*/
private static String ConnectionUri;
private static FtpServer Server;
private static final String TEST_URI = "test.ftp.uri";
private static final String USER_PROPS_RES = "org.apache.ftpserver/users.properties";
static String getConnectionUri() {
return ConnectionUri;
}
static int getSocketPort() {
return SocketPort;
}
private static String getSystemTestUriOverride() {
return System.getProperty(TEST_URI);
}
/**
* Creates and starts an embedded Apache FTP Server (MINA).
*
* @param rootDirectory the local FTP server rootDirectory
* @param fileSystemFactory optional local FTP server FileSystemFactory
* @throws FtpException
*/
static void setUpClass(final String rootDirectory, final FileSystemFactory fileSystemFactory)
throws FtpException {
if (Server != null) {
return;
}
final FtpServerFactory serverFactory = new FtpServerFactory();
final PropertiesUserManagerFactory propertiesUserManagerFactory = new PropertiesUserManagerFactory();
final URL userPropsResource = ClassLoader.getSystemClassLoader().getResource(USER_PROPS_RES);
Assert.assertNotNull(USER_PROPS_RES, userPropsResource);
propertiesUserManagerFactory.setUrl(userPropsResource);
final UserManager userManager = propertiesUserManagerFactory.createUserManager();
final BaseUser user = (BaseUser) userManager.getUserByName("test");
// Pickup the home dir value at runtime even though we have it set in the user prop file
// The user prop file requires the "homedirectory" to be set
user.setHomeDirectory(rootDirectory);
userManager.save(user);
serverFactory.setUserManager(userManager);
if (fileSystemFactory != null) {
serverFactory.setFileSystem(fileSystemFactory);
}
final ListenerFactory factory = new ListenerFactory();
// set the port of the listener
factory.setPort(0);
// replace the default listener
serverFactory.addListener("default", factory.createListener());
// start the server
Server = serverFactory.createServer();
Server.start();
SocketPort = ((org.apache.ftpserver.impl.DefaultFtpServer) Server).getListener("default").getPort();
ConnectionUri = "ftp://test:test@localhost:" + SocketPort;
}
/**
* Creates the test suite for the ftp file system.
*/
public static Test suite() throws Exception {
return suite(new FtpProviderTestCase());
}
/**
* Creates the test suite for subclasses of the ftp file system.
*/
protected static Test suite(final FtpProviderTestCase testCase) throws Exception {
return new ProviderTestSuite(testCase) {
@Override
protected void setUp() throws Exception {
if (getSystemTestUriOverride() == null) {
setUpClass(testCase.getFtpRootDir(), testCase.getFtpFileSystem());
}
super.setUp();
}
@Override
protected void tearDown() throws Exception {
try {
// This will report running threads of the FTP server.
// However, shutting down the FTP server first will always
// report an exception closing the manager, because the
// server is already down
super.tearDown();
} finally {
tearDownClass();
}
}
};
}
/**
* Stops the embedded Apache FTP Server (MINA).
*/
static void tearDownClass() {
if (Server != null) {
Server.stop();
Server = null;
}
}
/**
* Returns the base folder for tests. You can override the DEFAULT_URI by using the system property name defined by
* TEST_URI.
*/
@Override
public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
String uri = getSystemTestUriOverride();
if (uri == null) {
uri = ConnectionUri;
}
final FileSystemOptions opts = new FileSystemOptions();
final FtpFileSystemConfigBuilder builder = FtpFileSystemConfigBuilder.getInstance();
builder.setUserDirIsRoot(opts, getUserDirIsRoot());
builder.setPassiveMode(opts, true);
// FtpFileType.BINARY is the default
builder.setFileType(opts, FtpFileType.BINARY);
builder.setConnectTimeout(opts, 10000);
builder.setControlEncoding(opts, "UTF-8");
return manager.resolveFile(uri, opts);
}
/**
* Gets the setting for UserDirIsRoot.
*/
protected boolean getUserDirIsRoot() {
return false;
}
/**
* Gets option file system factory for local FTP server.
*/
protected FileSystemFactory getFtpFileSystem() throws IOException {
// use default
return null;
}
/**
* Gets the root of the local FTP Server file system.
*/
protected String getFtpRootDir() {
return getTestDirectory();
}
/**
* Prepares the file system manager.
*/
@Override
public void prepare(final DefaultFileSystemManager manager) throws Exception {
manager.addProvider("ftp", new FtpFileProvider());
}
}
| commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftp/test/FtpProviderTestCase.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp.test;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
import org.apache.commons.vfs2.provider.ftp.FtpFileProvider;
import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder;
import org.apache.commons.vfs2.provider.ftp.FtpFileType;
import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
import org.apache.commons.vfs2.test.ProviderTestSuite;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.junit.Assert;
import junit.framework.Test;
/**
* Tests for FTP file systems.
*/
public class FtpProviderTestCase extends AbstractProviderTestConfig {
private static int SocketPort;
/**
* Use %40 for @ in URLs
*/
private static String ConnectionUri;
private static FtpServer Server;
private static final String TEST_URI = "test.ftp.uri";
private static final String USER_PROPS_RES = "org.apache.ftpserver/users.properties";
static String getConnectionUri() {
return ConnectionUri;
}
static int getSocketPort() {
return SocketPort;
}
private static String getSystemTestUriOverride() {
return System.getProperty(TEST_URI);
}
/**
* Creates and starts an embedded Apache FTP Server (MINA).
*
* @param rootDirectory the local FTP server rootDirectory
* @param fileSystemFactory optional local FTP server FileSystemFactory
* @throws FtpException
* @throws IOException
*/
static void setUpClass(final String rootDirectory, final FileSystemFactory fileSystemFactory)
throws FtpException, IOException {
if (Server != null) {
return;
}
final FtpServerFactory serverFactory = new FtpServerFactory();
final PropertiesUserManagerFactory propertiesUserManagerFactory = new PropertiesUserManagerFactory();
final URL userPropsResource = ClassLoader.getSystemClassLoader().getResource(USER_PROPS_RES);
Assert.assertNotNull(USER_PROPS_RES, userPropsResource);
propertiesUserManagerFactory.setUrl(userPropsResource);
final UserManager userManager = propertiesUserManagerFactory.createUserManager();
final BaseUser user = (BaseUser) userManager.getUserByName("test");
// Pickup the home dir value at runtime even though we have it set in the user prop file
// The user prop file requires the "homedirectory" to be set
user.setHomeDirectory(rootDirectory);
userManager.save(user);
serverFactory.setUserManager(userManager);
if (fileSystemFactory != null) {
serverFactory.setFileSystem(fileSystemFactory);
}
final ListenerFactory factory = new ListenerFactory();
// set the port of the listener
factory.setPort(0);
// replace the default listener
serverFactory.addListener("default", factory.createListener());
// start the server
Server = serverFactory.createServer();
Server.start();
SocketPort = ((org.apache.ftpserver.impl.DefaultFtpServer) Server).getListener("default").getPort();
ConnectionUri = "ftp://test:test@localhost:" + SocketPort;
}
/**
* Creates the test suite for the ftp file system.
*/
public static Test suite() throws Exception {
return suite(new FtpProviderTestCase());
}
/**
* Creates the test suite for subclasses of the ftp file system.
*/
protected static Test suite(final FtpProviderTestCase testCase) throws Exception {
return new ProviderTestSuite(testCase) {
@Override
protected void setUp() throws Exception {
if (getSystemTestUriOverride() == null) {
setUpClass(testCase.getFtpRootDir(), testCase.getFtpFileSystem());
}
super.setUp();
}
@Override
protected void tearDown() throws Exception {
try {
// This will report running threads of the FTP server.
// However, shutting down the FTP server first will always
// report an exception closing the manager, because the
// server is already down
super.tearDown();
} finally {
tearDownClass();
}
}
};
}
/**
* Stops the embedded Apache FTP Server (MINA).
*/
static void tearDownClass() {
if (Server != null) {
Server.stop();
Server = null;
}
}
/**
* Returns the base folder for tests. You can override the DEFAULT_URI by using the system property name defined by
* TEST_URI.
*/
@Override
public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
String uri = getSystemTestUriOverride();
if (uri == null) {
uri = ConnectionUri;
}
final FileSystemOptions opts = new FileSystemOptions();
final FtpFileSystemConfigBuilder builder = FtpFileSystemConfigBuilder.getInstance();
builder.setUserDirIsRoot(opts, getUserDirIsRoot());
builder.setPassiveMode(opts, true);
// FtpFileType.BINARY is the default
builder.setFileType(opts, FtpFileType.BINARY);
builder.setConnectTimeout(opts, 10000);
builder.setControlEncoding(opts, "UTF-8");
return manager.resolveFile(uri, opts);
}
/**
* Gets the setting for UserDirIsRoot.
*/
protected boolean getUserDirIsRoot() {
return false;
}
/**
* Gets option file system factory for local FTP server.
*/
protected FileSystemFactory getFtpFileSystem() throws IOException {
// use default
return null;
}
/**
* Gets the root of the local FTP Server file system.
*/
protected String getFtpRootDir() {
return getTestDirectory();
}
/**
* Prepares the file system manager.
*/
@Override
public void prepare(final DefaultFileSystemManager manager) throws Exception {
manager.addProvider("ftp", new FtpFileProvider());
}
}
| Remove unused exceptions in tests.
| commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftp/test/FtpProviderTestCase.java | Remove unused exceptions in tests. |
|
Java | mit | 67b09451b6777c59533e7882f990278a81c4756f | 0 | aserg-ufmg/RefDiff,aserg-ufmg/RefDiff,aserg-ufmg/RefDiff,aserg-ufmg/RefDiff,aserg-ufmg/RefDiff,aserg-ufmg/RefDiff | package refdiff.evaluation.benchmark;
import java.util.EnumSet;
import refdiff.core.RefDiff;
import refdiff.core.api.RefactoringType;
import refdiff.evaluation.utils.RefactoringSet;
import refdiff.evaluation.utils.ResultComparator;
public class TestWithCalibrationDataset {
public static void main(String[] args) {
CalibrationDataset dataset = new CalibrationDataset();
ResultComparator rc = new ResultComparator();
rc.expect(dataset.getCommits());
RefDiff refdiff = new RefDiff();
for (RefactoringSet commit : dataset.getCommits()) {
rc.compareWith("refdiff", ResultComparator.collectRmResult(refdiff, commit.getProject(), commit.getRevision()));
}
EnumSet<RefactoringType> types = EnumSet.complementOf(EnumSet.of(RefactoringType.RENAME_CLASS, RefactoringType.RENAME_METHOD));
rc.printSummary(System.out, types);
rc.printDetails(System.out, types);
}
}
| refdiff-evaluation/src/main/java/refdiff/evaluation/benchmark/TestWithCalibrationDataset.java | package refdiff.evaluation.benchmark;
import java.util.EnumSet;
import refdiff.core.RefDiff;
import refdiff.core.api.RefactoringType;
import refdiff.evaluation.utils.RefactoringSet;
import refdiff.evaluation.utils.ResultComparator;
public class TestWithCalibrationDataset {
public static void main(String[] args) {
CalibrationDataset dataset = new CalibrationDataset();
ResultComparator rc = new ResultComparator();
rc.expect(dataset.getCommits());
RefDiff refdiff = new RefDiff();
for (RefactoringSet commit : dataset.getCommits()) {
rc.compareWith("refdiff", ResultComparator.collectRmResult(refdiff, commit.getProject(), commit.getRevision()));
}
rc.printSummary(System.out, EnumSet.allOf(RefactoringType.class));
rc.printDetails(System.out, EnumSet.allOf(RefactoringType.class));
}
}
| Calibration | refdiff-evaluation/src/main/java/refdiff/evaluation/benchmark/TestWithCalibrationDataset.java | Calibration |
|
Java | mit | 24f3e3e35b7db5fead75ed9704ac7f521a434162 | 0 | caxqueiroz/ethereumj,loxal/FreeEthereum,loxal/ethereumj,loxal/FreeEthereum,loxal/FreeEthereum,chengtalent/ethereumj | package org.ethereum.sync;
import org.ethereum.config.Constants;
import org.ethereum.config.NoAutoscan;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Block;
import org.ethereum.core.BlockHeader;
import org.ethereum.core.Blockchain;
import org.ethereum.core.TransactionReceipt;
import org.ethereum.facade.Ethereum;
import org.ethereum.facade.EthereumFactory;
import org.ethereum.listener.EthereumListenerAdapter;
import org.ethereum.net.eth.handler.Eth62;
import org.ethereum.net.eth.handler.EthHandler;
import org.ethereum.net.eth.message.*;
import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.DisconnectMessage;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.Channel;
import org.junit.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static java.math.BigInteger.ONE;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.ethereum.net.eth.EthVersion.V61;
import static org.ethereum.net.eth.EthVersion.V62;
import static org.ethereum.sync.SyncStateName.BLOCK_RETRIEVING;
import static org.ethereum.sync.SyncStateName.HASH_RETRIEVING;
import static org.ethereum.sync.SyncStateName.IDLE;
import static org.ethereum.util.FileUtil.recursiveDelete;
import static org.junit.Assert.fail;
import static org.spongycastle.util.encoders.Hex.decode;
/**
* @author Mikhail Kalinin
* @since 14.12.2015
*/
@Ignore("Long network tests")
public class GapRecoveryTest {
private static BigInteger minDifficultyBackup;
private static Node nodeA;
private static List<Block> mainB1B10;
private static List<Block> forkB1B5B8_;
private static Block b10;
private static Block b8_;
private Ethereum ethereumA;
private Ethereum ethereumB;
private EthHandler ethA;
private String testDbA;
private String testDbB;
@BeforeClass
public static void setup() throws IOException, URISyntaxException {
minDifficultyBackup = Constants.MINIMUM_DIFFICULTY;
Constants.MINIMUM_DIFFICULTY = ONE;
nodeA = new Node("enode://3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6@localhost:30334");
SysPropConfigA.props.overrideParams(
"peer.listen.port", "30334",
"peer.privateKey", "3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c",
// nodeId: 3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6
"genesis", "genesis-light.json"
);
SysPropConfigB.props.overrideParams(
"peer.listen.port", "30335",
"peer.privateKey", "6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec",
"genesis", "genesis-light.json",
"sync.enabled", "true"
);
mainB1B10 = loadBlocks("sync/main-b1-b10.dmp");
forkB1B5B8_ = loadBlocks("sync/fork-b1-b5-b8_.dmp");
b10 = mainB1B10.get(mainB1B10.size() - 1);
b8_ = forkB1B5B8_.get(forkB1B5B8_.size() - 1);
}
private static List<Block> loadBlocks(String path) throws URISyntaxException, IOException {
URL url = ClassLoader.getSystemResource(path);
File file = new File(url.toURI());
List<String> strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
List<Block> blocks = new ArrayList<>(strData.size());
for (String rlp : strData) {
blocks.add(new Block(decode(rlp)));
}
return blocks;
}
@AfterClass
public static void cleanup() {
Constants.MINIMUM_DIFFICULTY = minDifficultyBackup;
}
@Before
public void setupTest() throws InterruptedException {
testDbA = "test_db_" + new BigInteger(32, new Random());
testDbB = "test_db_" + new BigInteger(32, new Random());
SysPropConfigA.props.setDataBaseDir(testDbA);
SysPropConfigB.props.setDataBaseDir(testDbB);
}
@After
public void cleanupTest() {
recursiveDelete(testDbA);
recursiveDelete(testDbB);
SysPropConfigA.eth62 = null;
}
// positive gap, A on main, B on main
// expected: B downloads missed blocks from A => B on main
@Test
public void test1() throws InterruptedException {
setupPeers();
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10, B == genesis
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// positive gap, A on fork, B on main
// positive gap, A on fork, B on fork (same story)
// expected: B downloads missed blocks from A => B on A's fork
@Test
public void test2() throws InterruptedException {
setupPeers();
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
// A == b8', B == genesis
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b8_)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlock(b8_);
semaphore.await(10, SECONDS);
// check if B == b8'
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// positive gap, A on main, B on fork
// expected: B finds common ancestor and downloads missed blocks from A => B on main
@Test
public void test3() throws InterruptedException {
setupPeers();
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
for (Block b : forkB1B5B8_) {
blockchainB.tryToConnect(b);
}
// A == b10, B == b8'
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on main, B on main
// expected: B skips A's block as already imported => B on main
@Test
public void test4() throws InterruptedException {
setupPeers();
final Block b5 = mainB1B10.get(4);
Block b9 = mainB1B10.get(8);
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
if (b.isEqual(b5)) break;
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b9)) break;
}
// A == b5, B == b9
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlockHashes(b5);
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on fork, B on main
// negative gap, A on fork, B on fork (same story)
// expected: B downloads A's fork and imports it as NOT_BEST => B on its chain
@Test
public void test5() throws InterruptedException {
setupPeers();
Block b9 = mainB1B10.get(8);
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b9)) break;
}
// A == b8', B == b9
final CountDownLatch semaphore = new CountDownLatch(1);
final CountDownLatch semaphoreB8_ = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
if (block.isEqual(b8_)) {
semaphoreB8_.countDown();
}
}
});
ethA.sendNewBlockHashes(b8_);
semaphoreB8_.await(10, SECONDS);
if(semaphoreB8_.getCount() > 0) {
fail("PeerB didn't import b8'");
}
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on main, B on fork
// expected: B finds common ancestor and downloads A's blocks => B on main
@Test
public void test6() throws InterruptedException {
setupPeers();
final Block b7 = mainB1B10.get(6);
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
if (b.isEqual(b7)) break;
}
for (Block b : forkB1B5B8_) {
blockchainB.tryToConnect(b);
}
// A == b7, B == b8'
final CountDownLatch semaphore = new CountDownLatch(1);
final CountDownLatch semaphoreB7 = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b7)) {
semaphoreB7.countDown();
}
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlockHashes(b7);
semaphoreB7.await(10, SECONDS);
// check if B == b7
if(semaphoreB7.getCount() > 0) {
fail("PeerB didn't recover a gap");
}
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// positive gap, A on fork, B on main
// A does a re-branch to main
// expected: B downloads main blocks from A => B on main
@Test
public void test7() throws InterruptedException {
setupPeers();
Block b4 = mainB1B10.get(3);
// A == B == genesis
final Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b4)) break;
}
// A == b8', B == b4
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onRecvMessage(Channel channel, Message message) {
if (message instanceof NewBlockMessage) {
// it's time to do a re-branch
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
}
}
});
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlock(b8_);
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on fork, B on main
// A does a re-branch to main
// expected: B downloads A's fork and imports it as NOT_BEST => B on main
@Test
public void test8() throws InterruptedException {
setupPeers();
final Block b7_ = forkB1B5B8_.get(6);
Block b8 = mainB1B10.get(7);
// A == B == genesis
final Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
if (b.isEqual(b7_)) break;
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b8)) break;
}
// A == b7', B == b8
final CountDownLatch semaphore = new CountDownLatch(1);
final CountDownLatch semaphoreB7_ = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b7_)) {
// it's time to do a re-branch
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
semaphoreB7_.countDown();
}
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlockHashes(b7_);
semaphoreB7_.await(10, SECONDS);
if(semaphoreB7_.getCount() > 0) {
fail("PeerB didn't import b7'");
}
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// positive gap, A on fork, B on main
// A doesn't send common ancestor
// expected: B drops A and all its blocks => B on main
@Test
public void test9() throws InterruptedException {
// handler which don't send an ancestor
SysPropConfigA.eth62 = new Eth62() {
@Override
protected void processGetBlockHeaders(GetBlockHeadersMessage msg) {
List<BlockHeader> headers = new ArrayList<>();
for (int i = 7; i < mainB1B10.size(); i++) {
headers.add(mainB1B10.get(i).getHeader());
}
BlockHeadersMessage response = new BlockHeadersMessage(headers);
sendMessage(response);
}
};
setupPeers();
Block b6 = mainB1B10.get(5);
// A == B == genesis
final Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b6)) break;
}
// A == b8', B == b6
ethA.sendNewBlock(b8_);
final CountDownLatch semaphoreDisconnect = new CountDownLatch(1);
ethereumA.addListener(new EthereumListenerAdapter() {
@Override
public void onRecvMessage(Channel channel, Message message) {
if (message instanceof DisconnectMessage) {
semaphoreDisconnect.countDown();
}
}
});
semaphoreDisconnect.await(10, SECONDS);
// check if peer was dropped
if(semaphoreDisconnect.getCount() > 0) {
fail("PeerA is not dropped");
}
// back to usual handler
SysPropConfigA.eth62 = null;
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
final CountDownLatch semaphoreConnect = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onPeerAddedToSyncPool(Channel peer) {
semaphoreConnect.countDown();
}
});
ethereumB.connect(nodeA);
// await connection
semaphoreConnect.await(10, SECONDS);
if(semaphoreConnect.getCount() > 0) {
fail("PeerB is not able to connect to PeerA");
}
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on fork, B on main
// A doesn't send the gap block in ancestor response
// expected: B drops A and all its blocks => B on main
@Test
public void test10() throws InterruptedException {
// handler which don't send a gap block
SysPropConfigA.eth62 = new Eth62() {
@Override
protected void processGetBlockHeaders(GetBlockHeadersMessage msg) {
if (msg.getBlockNumber() == b8_.getNumber() && msg.getMaxHeaders() == 1) {
super.processGetBlockHeaders(msg);
return;
}
List<BlockHeader> headers = new ArrayList<>();
for (int i = 0; i < forkB1B5B8_.size() - 1; i++) {
headers.add(forkB1B5B8_.get(i).getHeader());
}
BlockHeadersMessage response = new BlockHeadersMessage(headers);
sendMessage(response);
}
};
setupPeers();
Block b9 = mainB1B10.get(8);
// A == B == genesis
final Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b9)) break;
}
// A == b8', B == b9
ethA.sendNewBlockHashes(b8_);
final CountDownLatch semaphoreDisconnect = new CountDownLatch(1);
ethereumA.addListener(new EthereumListenerAdapter() {
@Override
public void onRecvMessage(Channel channel, Message message) {
if (message instanceof DisconnectMessage) {
semaphoreDisconnect.countDown();
}
}
});
semaphoreDisconnect.await(10, SECONDS);
// check if peer was dropped
if(semaphoreDisconnect.getCount() > 0) {
fail("PeerA is not dropped");
}
// back to usual handler
SysPropConfigA.eth62 = null;
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
final CountDownLatch semaphoreConnect = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onPeerAddedToSyncPool(Channel peer) {
semaphoreConnect.countDown();
}
});
ethereumB.connect(nodeA);
// await connection
semaphoreConnect.await(10, SECONDS);
if(semaphoreConnect.getCount() > 0) {
fail("PeerB is not able to connect to PeerA");
}
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// A sends block with low TD to B
// expected: B skips this block
@Test
public void test11() throws InterruptedException {
Block b5 = mainB1B10.get(4);
final Block b6_ = forkB1B5B8_.get(5);
setupPeers();
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
final Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b5)) break;
}
// A == b8', B == b5
final CountDownLatch semaphore1 = new CountDownLatch(1);
final CountDownLatch semaphore2 = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b6_)) {
if (semaphore1.getCount() > 0) {
semaphore1.countDown();
} else {
semaphore2.countDown();
}
}
}
});
ethA.sendNewBlock(b6_);
semaphore1.await(10, SECONDS);
if(semaphore1.getCount() > 0) {
fail("PeerB doesn't accept block with higher TD");
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
}
// B == b10
ethA.sendNewBlock(b6_);
semaphore2.await(5, SECONDS);
// check if B skips b6'
if(semaphore2.getCount() == 0) {
fail("PeerB doesn't skip block with lower TD");
}
}
private void setupPeers() throws InterruptedException {
ethereumA = EthereumFactory.createEthereum(SysPropConfigA.props, SysPropConfigA.class);
ethereumB = EthereumFactory.createEthereum(SysPropConfigB.props, SysPropConfigB.class);
ethereumA.addListener(new EthereumListenerAdapter() {
@Override
public void onEthStatusUpdated(Channel channel, StatusMessage statusMessage) {
ethA = (EthHandler) channel.getEthHandler();
}
});
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onPeerAddedToSyncPool(Channel peer) {
semaphore.countDown();
}
});
ethereumB.connect(nodeA);
semaphore.await(10, SECONDS);
if(semaphore.getCount() > 0) {
fail("Failed to set up peers");
}
}
@Configuration
@NoAutoscan
public static class SysPropConfigA {
static SystemProperties props = new SystemProperties();
static Eth62 eth62 = null;
@Bean
public SystemProperties systemProperties() {
return props;
}
@Bean
@Scope("prototype")
public Eth62 eth62() throws IllegalAccessException, InstantiationException {
if (eth62 != null) return eth62;
return new Eth62();
}
}
@Configuration
@NoAutoscan
public static class SysPropConfigB {
static SystemProperties props = new SystemProperties();
@Bean
public SystemProperties systemProperties() {
return props;
}
// don't allow sync to change its initial state during the sync
@Bean
public StateInitiator stateInitiator() {
return new StateInitiator() {
@Override
public SyncStateName initiate() {
return IDLE;
}
};
}
// do not transfer from IDLE state implicitly
@Bean
public Map<SyncStateName, SyncState> syncStates(SyncManager syncManager) {
Map<SyncStateName, SyncState> states = new IdentityHashMap<>();
states.put(IDLE, new AbstractSyncState(IDLE) {
@Override
public void doMaintain() {
super.doMaintain();
if ((!syncManager.queue.isHashesEmpty() && syncManager.pool.hasCompatible(V61)) ||
(!syncManager.queue.isHeadersEmpty() && syncManager.pool.hasCompatible(V62))) {
// there are new hashes in the store
// it's time to download blocks
syncManager.changeState(BLOCK_RETRIEVING);
}
}
});
states.put(HASH_RETRIEVING, new HashRetrievingState());
states.put(BLOCK_RETRIEVING, new BlockRetrievingState());
for (SyncState state : states.values()) {
((AbstractSyncState)state).setSyncManager(syncManager);
}
return states;
}
}
}
| ethereumj-core/src/test/java/org/ethereum/sync/GapRecoveryTest.java | package org.ethereum.sync;
import org.ethereum.config.Constants;
import org.ethereum.config.NoAutoscan;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Block;
import org.ethereum.core.BlockHeader;
import org.ethereum.core.Blockchain;
import org.ethereum.core.TransactionReceipt;
import org.ethereum.facade.Ethereum;
import org.ethereum.facade.EthereumFactory;
import org.ethereum.listener.EthereumListenerAdapter;
import org.ethereum.net.eth.handler.Eth61;
import org.ethereum.net.eth.handler.Eth62;
import org.ethereum.net.eth.handler.EthHandler;
import org.ethereum.net.eth.message.*;
import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.DisconnectMessage;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.Channel;
import org.junit.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static java.math.BigInteger.ONE;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.ethereum.net.eth.EthVersion.V60;
import static org.ethereum.net.eth.EthVersion.V61;
import static org.ethereum.net.eth.EthVersion.V62;
import static org.ethereum.sync.SyncStateName.BLOCK_RETRIEVING;
import static org.ethereum.sync.SyncStateName.HASH_RETRIEVING;
import static org.ethereum.sync.SyncStateName.IDLE;
import static org.ethereum.util.FileUtil.recursiveDelete;
import static org.junit.Assert.fail;
import static org.spongycastle.util.encoders.Hex.decode;
/**
* @author Mikhail Kalinin
* @since 14.12.2015
*/
@Ignore("Long network tests")
public class GapRecoveryTest {
private static BigInteger minDifficultyBackup;
private static Node nodeA;
private static List<Block> mainB1B10;
private static List<Block> forkB1B5B8_;
private static Block b10;
private static Block b8_;
private Ethereum ethereumA;
private Ethereum ethereumB;
private EthHandler ethA;
private String testDbA;
private String testDbB;
@BeforeClass
public static void setup() throws IOException, URISyntaxException {
minDifficultyBackup = Constants.MINIMUM_DIFFICULTY;
Constants.MINIMUM_DIFFICULTY = ONE;
nodeA = new Node("enode://3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6@localhost:30334");
SysPropConfigA.props.overrideParams(
"peer.listen.port", "30334",
"peer.privateKey", "3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c",
// nodeId: 3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6
"genesis", "genesis-light.json"
);
SysPropConfigB.props.overrideParams(
"peer.listen.port", "30335",
"peer.privateKey", "6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec",
"genesis", "genesis-light.json",
"sync.enabled", "true"
);
mainB1B10 = loadBlocks("sync/main-b1-b10.dmp");
forkB1B5B8_ = loadBlocks("sync/fork-b1-b5-b8_.dmp");
b10 = mainB1B10.get(mainB1B10.size() - 1);
b8_ = forkB1B5B8_.get(forkB1B5B8_.size() - 1);
}
private static List<Block> loadBlocks(String path) throws URISyntaxException, IOException {
URL url = ClassLoader.getSystemResource(path);
File file = new File(url.toURI());
List<String> strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
List<Block> blocks = new ArrayList<>(strData.size());
for (String rlp : strData) {
blocks.add(new Block(decode(rlp)));
}
return blocks;
}
@AfterClass
public static void cleanup() {
Constants.MINIMUM_DIFFICULTY = minDifficultyBackup;
}
@Before
public void setupTest() throws InterruptedException {
testDbA = "test_db_" + new BigInteger(32, new Random());
testDbB = "test_db_" + new BigInteger(32, new Random());
SysPropConfigA.props.setDataBaseDir(testDbA);
SysPropConfigB.props.setDataBaseDir(testDbB);
}
@After
public void cleanupTest() {
recursiveDelete(testDbA);
recursiveDelete(testDbB);
SysPropConfigA.eth62 = null;
SysPropConfigA.eth61 = null;
}
// positive gap, A on main, B on main
// expected: B downloads missed blocks from A => B on main
@Test
public void test1() throws InterruptedException {
setupPeers();
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10, B == genesis
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// positive gap, A on fork, B on main
// positive gap, A on fork, B on fork (same story)
// expected: B downloads missed blocks from A => B on A's fork
@Test
public void test2() throws InterruptedException {
setupPeers();
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
// A == b8', B == genesis
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b8_)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlock(b8_);
semaphore.await(10, SECONDS);
// check if B == b8'
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// positive gap, A on main, B on fork
// expected: B finds common ancestor and downloads missed blocks from A => B on main
@Test
public void test3() throws InterruptedException {
setupPeers();
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
for (Block b : forkB1B5B8_) {
blockchainB.tryToConnect(b);
}
// A == b10, B == b8'
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on main, B on main
// expected: B skips A's block as already imported => B on main
@Test
public void test4() throws InterruptedException {
setupPeers();
final Block b5 = mainB1B10.get(4);
Block b9 = mainB1B10.get(8);
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
if (b.isEqual(b5)) break;
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b9)) break;
}
// A == b5, B == b9
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlockHashes(b5);
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on fork, B on main
// negative gap, A on fork, B on fork (same story)
// expected: B downloads A's fork and imports it as NOT_BEST => B on its chain
@Test
public void test5() throws InterruptedException {
setupPeers();
Block b9 = mainB1B10.get(8);
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b9)) break;
}
// A == b8', B == b9
final CountDownLatch semaphore = new CountDownLatch(1);
final CountDownLatch semaphoreB8_ = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
if (block.isEqual(b8_)) {
semaphoreB8_.countDown();
}
}
});
ethA.sendNewBlockHashes(b8_);
semaphoreB8_.await(10, SECONDS);
if(semaphoreB8_.getCount() > 0) {
fail("PeerB didn't import b8'");
}
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on main, B on fork
// expected: B finds common ancestor and downloads A's blocks => B on main
@Test
public void test6() throws InterruptedException {
setupPeers();
final Block b7 = mainB1B10.get(6);
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
if (b.isEqual(b7)) break;
}
for (Block b : forkB1B5B8_) {
blockchainB.tryToConnect(b);
}
// A == b7, B == b8'
final CountDownLatch semaphore = new CountDownLatch(1);
final CountDownLatch semaphoreB7 = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b7)) {
semaphoreB7.countDown();
}
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlockHashes(b7);
semaphoreB7.await(10, SECONDS);
// check if B == b7
if(semaphoreB7.getCount() > 0) {
fail("PeerB didn't recover a gap");
}
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// positive gap, A on fork, B on main
// A does a re-branch to main
// expected: B downloads main blocks from A => B on main
@Test
public void test7() throws InterruptedException {
setupPeers();
Block b4 = mainB1B10.get(3);
// A == B == genesis
final Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b4)) break;
}
// A == b8', B == b4
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onRecvMessage(Channel channel, Message message) {
if (message instanceof NewBlockMessage) {
// it's time to do a re-branch
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
}
}
});
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlock(b8_);
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on fork, B on main
// A does a re-branch to main
// expected: B downloads A's fork and imports it as NOT_BEST => B on main
@Test
public void test8() throws InterruptedException {
setupPeers();
final Block b7_ = forkB1B5B8_.get(6);
Block b8 = mainB1B10.get(7);
// A == B == genesis
final Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
if (b.isEqual(b7_)) break;
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b8)) break;
}
// A == b7', B == b8
final CountDownLatch semaphore = new CountDownLatch(1);
final CountDownLatch semaphoreB7_ = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b7_)) {
// it's time to do a re-branch
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
semaphoreB7_.countDown();
}
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlockHashes(b7_);
semaphoreB7_.await(10, SECONDS);
if(semaphoreB7_.getCount() > 0) {
fail("PeerB didn't import b7'");
}
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// positive gap, A on fork, B on main
// A doesn't send common ancestor
// expected: B drops A and all its blocks => B on main
@Test
public void test9() throws InterruptedException {
// not for Eth60 logic
if (Integer.valueOf(V60.getCode()).equals(SysPropConfigA.props.syncVersion())) {
return;
}
// handler which don't send an ancestor
SysPropConfigA.eth62 = new Eth62() {
@Override
protected void processGetBlockHeaders(GetBlockHeadersMessage msg) {
List<BlockHeader> headers = new ArrayList<>();
for (int i = 7; i < mainB1B10.size(); i++) {
headers.add(mainB1B10.get(i).getHeader());
}
BlockHeadersMessage response = new BlockHeadersMessage(headers);
sendMessage(response);
}
};
SysPropConfigA.eth61 = new Eth61() {
@Override
protected void processGetBlockHashesByNumber(GetBlockHashesByNumberMessage msg) {
List<byte[]> hashes = new ArrayList<>();
for (int i = 7; i < mainB1B10.size(); i++) {
hashes.add(mainB1B10.get(i).getHash());
}
BlockHashesMessage msgHashes = new BlockHashesMessage(hashes);
sendMessage(msgHashes);
}
};
setupPeers();
Block b6 = mainB1B10.get(5);
// A == B == genesis
final Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b6)) break;
}
// A == b8', B == b6
ethA.sendNewBlock(b8_);
final CountDownLatch semaphoreDisconnect = new CountDownLatch(1);
ethereumA.addListener(new EthereumListenerAdapter() {
@Override
public void onRecvMessage(Channel channel, Message message) {
if (message instanceof DisconnectMessage) {
semaphoreDisconnect.countDown();
}
}
});
semaphoreDisconnect.await(10, SECONDS);
// check if peer was dropped
if(semaphoreDisconnect.getCount() > 0) {
fail("PeerA is not dropped");
}
// back to usual handler
SysPropConfigA.eth62 = null;
SysPropConfigA.eth61 = null;
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
final CountDownLatch semaphoreConnect = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onPeerAddedToSyncPool(Channel peer) {
semaphoreConnect.countDown();
}
});
ethereumB.connect(nodeA);
// await connection
semaphoreConnect.await(10, SECONDS);
if(semaphoreConnect.getCount() > 0) {
fail("PeerB is not able to connect to PeerA");
}
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// negative gap, A on fork, B on main
// A doesn't send the gap block in ancestor response
// expected: B drops A and all its blocks => B on main
@Test
public void test10() throws InterruptedException {
// not for Eth60 logic
if (Integer.valueOf(V60.getCode()).equals(SysPropConfigA.props.syncVersion())) {
return;
}
// handler which don't send a gap block
SysPropConfigA.eth62 = new Eth62() {
@Override
protected void processGetBlockHeaders(GetBlockHeadersMessage msg) {
if (msg.getBlockNumber() == b8_.getNumber() && msg.getMaxHeaders() == 1) {
super.processGetBlockHeaders(msg);
return;
}
List<BlockHeader> headers = new ArrayList<>();
for (int i = 0; i < forkB1B5B8_.size() - 1; i++) {
headers.add(forkB1B5B8_.get(i).getHeader());
}
BlockHeadersMessage response = new BlockHeadersMessage(headers);
sendMessage(response);
}
};
SysPropConfigA.eth61 = new Eth61() {
@Override
protected void processGetBlockHashes(GetBlockHashesMessage msg) {
List<byte[]> hashes = new ArrayList<>();
for (int i = 0; i < forkB1B5B8_.size() - 1; i++) {
hashes.add(forkB1B5B8_.get(i).getHash());
}
BlockHashesMessage msgHashes = new BlockHashesMessage(hashes);
sendMessage(msgHashes);
}
};
setupPeers();
Block b9 = mainB1B10.get(8);
// A == B == genesis
final Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b9)) break;
}
// A == b8', B == b9
ethA.sendNewBlockHashes(b8_);
final CountDownLatch semaphoreDisconnect = new CountDownLatch(1);
ethereumA.addListener(new EthereumListenerAdapter() {
@Override
public void onRecvMessage(Channel channel, Message message) {
if (message instanceof DisconnectMessage) {
semaphoreDisconnect.countDown();
}
}
});
semaphoreDisconnect.await(10, SECONDS);
// check if peer was dropped
if(semaphoreDisconnect.getCount() > 0) {
fail("PeerA is not dropped");
}
// back to usual handler
SysPropConfigA.eth62 = null;
SysPropConfigA.eth61 = null;
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
final CountDownLatch semaphoreConnect = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onPeerAddedToSyncPool(Channel peer) {
semaphoreConnect.countDown();
}
});
ethereumB.connect(nodeA);
// await connection
semaphoreConnect.await(10, SECONDS);
if(semaphoreConnect.getCount() > 0) {
fail("PeerB is not able to connect to PeerA");
}
for (Block b : mainB1B10) {
blockchainA.tryToConnect(b);
}
// A == b10
ethA.sendNewBlock(b10);
semaphore.await(10, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
// A sends block with low TD to B
// expected: B skips this block
@Test
public void test11() throws InterruptedException {
Block b5 = mainB1B10.get(4);
final Block b6_ = forkB1B5B8_.get(5);
setupPeers();
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
final Blockchain blockchainB = (Blockchain) ethereumB.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
if (b.isEqual(b5)) break;
}
// A == b8', B == b5
final CountDownLatch semaphore1 = new CountDownLatch(1);
final CountDownLatch semaphore2 = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b6_)) {
if (semaphore1.getCount() > 0) {
semaphore1.countDown();
} else {
semaphore2.countDown();
}
}
}
});
ethA.sendNewBlock(b6_);
semaphore1.await(10, SECONDS);
if(semaphore1.getCount() > 0) {
fail("PeerB doesn't accept block with higher TD");
}
for (Block b : mainB1B10) {
blockchainB.tryToConnect(b);
}
// B == b10
ethA.sendNewBlock(b6_);
semaphore2.await(5, SECONDS);
// check if B skips b6'
if(semaphore2.getCount() == 0) {
fail("PeerB doesn't skip block with lower TD");
}
}
private void setupPeers() throws InterruptedException {
ethereumA = EthereumFactory.createEthereum(SysPropConfigA.props, SysPropConfigA.class);
ethereumB = EthereumFactory.createEthereum(SysPropConfigB.props, SysPropConfigB.class);
ethereumA.addListener(new EthereumListenerAdapter() {
@Override
public void onEthStatusUpdated(Channel channel, StatusMessage statusMessage) {
ethA = (EthHandler) channel.getEthHandler();
}
});
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onPeerAddedToSyncPool(Channel peer) {
semaphore.countDown();
}
});
ethereumB.connect(nodeA);
semaphore.await(10, SECONDS);
if(semaphore.getCount() > 0) {
fail("Failed to set up peers");
}
}
@Configuration
@NoAutoscan
public static class SysPropConfigA {
static SystemProperties props = new SystemProperties();
static Eth62 eth62 = null;
static Eth61 eth61 = null;
@Bean
public SystemProperties systemProperties() {
return props;
}
@Bean
@Scope("prototype")
public Eth62 eth62() throws IllegalAccessException, InstantiationException {
if (eth62 != null) return eth62;
return new Eth62();
}
@Bean
@Scope("prototype")
public Eth61 eth61() throws IllegalAccessException, InstantiationException {
if (eth61 != null) return eth61;
return new Eth61();
}
}
@Configuration
@NoAutoscan
public static class SysPropConfigB {
static SystemProperties props = new SystemProperties();
@Bean
public SystemProperties systemProperties() {
return props;
}
// don't allow sync to change its initial state during the sync
@Bean
public StateInitiator stateInitiator() {
return new StateInitiator() {
@Override
public SyncStateName initiate() {
return IDLE;
}
};
}
// do not transfer from IDLE state implicitly
@Bean
public Map<SyncStateName, SyncState> syncStates(SyncManager syncManager) {
Map<SyncStateName, SyncState> states = new IdentityHashMap<>();
states.put(IDLE, new AbstractSyncState(IDLE) {
@Override
public void doMaintain() {
super.doMaintain();
if ((!syncManager.queue.isHashesEmpty() && syncManager.pool.hasCompatible(V61)) ||
(!syncManager.queue.isHeadersEmpty() && syncManager.pool.hasCompatible(V62))) {
// there are new hashes in the store
// it's time to download blocks
syncManager.changeState(BLOCK_RETRIEVING);
}
}
});
states.put(HASH_RETRIEVING, new HashRetrievingState());
states.put(BLOCK_RETRIEVING, new BlockRetrievingState());
for (SyncState state : states.values()) {
((AbstractSyncState)state).setSyncManager(syncManager);
}
return states;
}
}
}
| Remove eth legacy support from sync tests
| ethereumj-core/src/test/java/org/ethereum/sync/GapRecoveryTest.java | Remove eth legacy support from sync tests |
|
Java | mit | 8a8a1cc1d16c4fd78e7818bb9e12f2851aa32a0b | 0 | iMultiPlay/Evolution | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package evolution2.pkg0;
/**
*
* @author david
*/
public class Evolution20 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Genome test = new Genome();
System.out.println(test.genomeSorted);
}
}
| src/evolution2/pkg0/Evolution20.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package evolution2.pkg0;
/**
*
* @author david
*/
public class Evolution20 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
| It outputs things now
| src/evolution2/pkg0/Evolution20.java | It outputs things now |
|
Java | epl-1.0 | 781883dadbadabca557c010f99f8178c359ba96a | 0 | Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt | package org.eclipse.birt.data.engine.executor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.data.engine.api.IBaseDataSetDesign;
import org.eclipse.birt.data.engine.api.IColumnDefinition;
import org.eclipse.birt.data.engine.api.IComputedColumn;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.odi.IResultClass;
public class DataSetCacheObjectWithDummyData implements IDataSetCacheObject
{
private IResultClass resultClass;
private IDataSetCacheObject base;
public DataSetCacheObjectWithDummyData( IBaseDataSetDesign dataSetDesign, IDataSetCacheObject base ) throws DataException
{
this.base = base;
this.resultClass = this.populateResultClass( dataSetDesign, base.getResultClass( ) );
}
public boolean isCachedDataReusable( int requiredCapability )
{
return this.base.isCachedDataReusable( requiredCapability );
}
public boolean needUpdateCache( int requiredCapability )
{
return this.base.needUpdateCache( requiredCapability );
}
public IResultClass getResultClass( ) throws DataException
{
return this.resultClass;
}
public void release( )
{
this.base.release( );
}
public IDataSetCacheObject getSourceDataSetCacheObject( )
{
return this.base;
}
private IResultClass populateResultClass( IBaseDataSetDesign dataSetDesign, IResultClass baseResultClass ) throws DataException
{
List resultHints = dataSetDesign.getResultSetHints( );
List computedColumns = dataSetDesign.getComputedColumns();
List columnsList = new ArrayList( );
for( int i = 1; i <= baseResultClass.getFieldCount( ); i++ )
{
columnsList.add( baseResultClass.getFieldMetaData( i ) );
}
Iterator it = resultHints.iterator( );
for ( int j = 0; it.hasNext( ); j++ )
{
IColumnDefinition columnDefn = (IColumnDefinition) it.next( );
if( baseResultClass.getFieldIndex( columnDefn.getColumnName( ) ) != -1 ||
baseResultClass.getFieldIndex( columnDefn.getAlias( ) ) != -1 )
continue;
ResultFieldMetadata columnMetaData = new ResultFieldMetadata( j + 1,
columnDefn.getColumnName( ),
columnDefn.getDisplayName( ),
DataType.getClass( columnDefn.getDataType( ) ),
null /* nativeTypeName */,
true, columnDefn.getAnalysisType( ),
columnDefn.getAnalysisColumn( ),
columnDefn.isIndexColumn( ),
columnDefn.isCompressedColumn( ) );
columnsList.add( columnMetaData );
columnMetaData.setAlias( columnDefn.getAlias( ) );
}
// Add computed columns
int count = columnsList.size();
it = computedColumns.iterator();
for ( int j = resultHints.size(); it.hasNext( ); j++ )
{
IComputedColumn compColumn = (IComputedColumn)it.next();
if( baseResultClass.getFieldIndex( compColumn.getName( ) ) != -1 )
continue;
ResultFieldMetadata columnMetaData = new ResultFieldMetadata(
++count,
compColumn.getName(),
compColumn.getName(),
DataType.getClass( compColumn.getDataType( ) ),
null /* nativeTypeName */,
true, -1 );
columnsList.add( columnMetaData );
}
return new ResultClass( columnsList );
}
}
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/DataSetCacheObjectWithDummyData.java | package org.eclipse.birt.data.engine.executor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.data.engine.api.IBaseDataSetDesign;
import org.eclipse.birt.data.engine.api.IColumnDefinition;
import org.eclipse.birt.data.engine.api.IComputedColumn;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.odi.IResultClass;
public class DataSetCacheObjectWithDummyData implements IDataSetCacheObject
{
private IResultClass resultClass;
private IDataSetCacheObject base;
public DataSetCacheObjectWithDummyData( IBaseDataSetDesign dataSetDesign, IDataSetCacheObject base ) throws DataException
{
this.base = base;
this.resultClass = this.populateResultClass( dataSetDesign, base.getResultClass( ) );
}
public boolean isCachedDataReusable( int requiredCapability )
{
return this.base.isCachedDataReusable( requiredCapability );
}
public boolean needUpdateCache( int requiredCapability )
{
return this.base.needUpdateCache( requiredCapability );
}
public IResultClass getResultClass( ) throws DataException
{
return this.resultClass;
}
public void release( )
{
this.base.release( );
}
public IDataSetCacheObject getSourceDataSetCacheObject( )
{
return this.base;
}
private IResultClass populateResultClass( IBaseDataSetDesign dataSetDesign, IResultClass baseResultClass ) throws DataException
{
List resultHints = dataSetDesign.getResultSetHints( );
List computedColumns = dataSetDesign.getComputedColumns();
List columnsList = new ArrayList( );
for( int i = 1; i <= baseResultClass.getFieldCount( ); i++ )
{
columnsList.add( baseResultClass.getFieldMetaData( i ) );
}
Iterator it = resultHints.iterator( );
for ( int j = 0; it.hasNext( ); j++ )
{
IColumnDefinition columnDefn = (IColumnDefinition) it.next( );
if( baseResultClass.getFieldIndex( columnDefn.getColumnName( ) ) != -1 )
continue;
ResultFieldMetadata columnMetaData = new ResultFieldMetadata( j + 1,
columnDefn.getColumnName( ),
columnDefn.getDisplayName( ),
DataType.getClass( columnDefn.getDataType( ) ),
null /* nativeTypeName */,
true, columnDefn.getAnalysisType( ),
columnDefn.getAnalysisColumn( ),
columnDefn.isIndexColumn( ),
columnDefn.isCompressedColumn( ) );
columnsList.add( columnMetaData );
columnMetaData.setAlias( columnDefn.getAlias( ) );
}
// Add computed columns
int count = columnsList.size();
it = computedColumns.iterator();
for ( int j = resultHints.size(); it.hasNext( ); j++ )
{
IComputedColumn compColumn = (IComputedColumn)it.next();
if( baseResultClass.getFieldIndex( compColumn.getName( ) ) != -1 )
continue;
ResultFieldMetadata columnMetaData = new ResultFieldMetadata(
++count,
compColumn.getName(),
compColumn.getName(),
DataType.getClass( compColumn.getDataType( ) ),
null /* nativeTypeName */,
true, -1 );
columnsList.add( columnMetaData );
}
return new ResultClass( columnsList );
}
}
| Alias are not recognize and create new column in metadata
This will fix that issue.
Signed-off-by: sguan <[email protected]> | data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/DataSetCacheObjectWithDummyData.java | Alias are not recognize and create new column in metadata |
|
Java | agpl-3.0 | 9ebecd12228b0fd8f097bd918b64f9337b5cefbb | 0 | ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,kuali/kfs,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,kuali/kfs,quikkian-ua-devops/will-financials,smith750/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,kkronenb/kfs,kuali/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,quikkian-ua-devops/kfs,smith750/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,smith750/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,smith750/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork | /*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kfs.module.purap.document;
import static org.kuali.kfs.sys.fixture.UserNameFixture.parke;
import static org.kuali.kfs.sys.fixture.UserNameFixture.appleton;
import static org.kuali.kfs.sys.fixture.UserNameFixture.rorenfro;
import java.util.HashMap;
import java.util.Map;
import org.kuali.rice.kns.service.DocumentService;
import org.kuali.kfs.module.purap.PurapAuthorizationConstants;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.document.authorization.PurchaseOrderDocumentActionAuthorizer;
import org.kuali.kfs.module.purap.document.service.PurchaseOrderService;
import org.kuali.kfs.module.purap.fixture.PaymentRequestDocumentFixture;
import org.kuali.kfs.module.purap.fixture.PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture;
import org.kuali.kfs.module.purap.fixture.RequisitionDocumentFixture;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.context.KualiTestBase;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.AccountingDocumentTestUtils;
import org.kuali.kfs.sys.document.workflow.WorkflowTestUtils;
import org.kuali.kfs.sys.suite.RelatesTo;
import org.kuali.kfs.sys.suite.RelatesTo.JiraIssue;
/**
* This class is used to test the authorization of the
* buttons in Purchase Order Documents. It will invoke the canXXX
* methods in PurchaseOrderDocumentActionAuthorizer to
* test whether certain buttons could be displayed.
*/
@ConfigureContext(session = parke)
public class PurchaseOrderDocumentActionAuthorizerTest extends KualiTestBase {
private PurchaseOrderDocument purchaseOrderDocument = null;
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
purchaseOrderDocument = null;
super.tearDown();
}
/**
* Tests that the retransmit button is displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testValidForRetransmit() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
PurchaseOrderDocument po = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_RETRANSMIT.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(po, editMode, documentActions);
assertTrue(auth.canRetransmit());
}
/**
* Tests that the print retransmit button is displayed when the purchase order
* is not an APO. It should allow purchasing users (in this case we use parke)
* to see the button if the purchase order is not an APO.
*
* @throws Exception
*/
@RelatesTo(JiraIssue.KULPURAP3146)
@ConfigureContext(session = parke, shouldCommitTransactions=false)
public final void testValidForPrintingRetransmitNonAPO() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
editMode.put(PurapAuthorizationConstants.PurchaseOrderEditMode.DISPLAY_RETRANSMIT_TAB, true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_RETRANSMIT.createPurchaseOrderDocument();
poDocument.prepareForSave();
DocumentService documentService = SpringContext.getBean(DocumentService.class);
AccountingDocumentTestUtils.routeDocument(poDocument, "saving copy source document", null, documentService);
WorkflowTestUtils.waitForStatusChange(poDocument.getDocumentHeader().getWorkflowDocument(), "F");
assertTrue("Document should now be final.", poDocument.getDocumentHeader().getWorkflowDocument().stateIsFinal());
PurchaseOrderService purchaseOrderService = SpringContext.getBean(PurchaseOrderService.class);
PurchaseOrderDocument poRetransmitDocument = purchaseOrderService.createAndRoutePotentialChangeDocument(poDocument.getDocumentNumber(), PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT, null, null, "RTPE");
poRetransmitDocument.setStatusCode("CGIN");
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poRetransmitDocument, editMode, documentActions);
assertTrue(auth.canPrintRetransmit());
}
/**
* Tests that the print retransmit button is displayed when the purchase order is an
* APO and the user can be anyone (here it is set as rorenfro prior to checking for the authorizer).
* It should allow anyone to see the print retransmit button if it's an APO.
*
* @throws Exception
*/
@RelatesTo(JiraIssue.KULPURAP3146)
@ConfigureContext(session = parke, shouldCommitTransactions=false)
public final void testValidForPrintingRetransmitAPO() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
editMode.put(PurapAuthorizationConstants.PurchaseOrderEditMode.DISPLAY_RETRANSMIT_TAB, true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_RETRANSMIT.createPurchaseOrderDocument();
poDocument.prepareForSave();
DocumentService documentService = SpringContext.getBean(DocumentService.class);
AccountingDocumentTestUtils.routeDocument(poDocument, "saving copy source document", null, documentService);
WorkflowTestUtils.waitForStatusChange(poDocument.getDocumentHeader().getWorkflowDocument(), "F");
assertTrue("Document should now be final.", poDocument.getDocumentHeader().getWorkflowDocument().stateIsFinal());
PurchaseOrderService purchaseOrderService = SpringContext.getBean(PurchaseOrderService.class);
PurchaseOrderDocument poRetransmitDocument = purchaseOrderService.createAndRoutePotentialChangeDocument(poDocument.getDocumentNumber(), PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT, null, null, "RTPE");
poRetransmitDocument.setStatusCode("CGIN");
poRetransmitDocument.setPurchaseOrderAutomaticIndicator(true);
changeCurrentUser(rorenfro);
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poRetransmitDocument, editMode, documentActions);
assertTrue(auth.canPrintRetransmit());
}
/**
* Tests that the print button for first transmit is displayed.
*
* @throws Exception
*/
@RelatesTo(JiraIssue.KULPURAP3143)
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testFirstTransmitPrintPO() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_FIRST_TRANSMIT_PRINT.createPurchaseOrderDocument();
DocumentService documentService = SpringContext.getBean(DocumentService.class);
poDocument.prepareForSave();
AccountingDocumentTestUtils.routeDocument(poDocument, "saving copy source document", null, documentService);
WorkflowTestUtils.waitForStatusChange(poDocument.getDocumentHeader().getWorkflowDocument(), "F");
assertTrue("Document should now be final.", poDocument.getDocumentHeader().getWorkflowDocument().stateIsFinal());
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode, documentActions);
assertTrue(auth.canFirstTransmitPrintPo());
}
/**
* Tests that the open order button is displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testReopen() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_REOPEN.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode, documentActions);
assertTrue(auth.canReopen());
}
/**
* Tests that the close order button is displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testClose() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
DocumentService documentService = SpringContext.getBean(DocumentService.class);
//We create and save this req to obtain a number from the AP document link identifier sequencer in the database
RequisitionDocument dummyReqDocument = RequisitionDocumentFixture.REQ_ONLY_REQUIRED_FIELDS.createRequisitionDocument();
documentService.saveDocument(dummyReqDocument);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_CLOSE.createPurchaseOrderDocument();
poDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(dummyReqDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
poDocument.prepareForSave();
AccountingDocumentTestUtils.routeDocument(poDocument, "saving copy source document", null, documentService);
WorkflowTestUtils.waitForStatusChange(poDocument.getDocumentHeader().getWorkflowDocument(), "F");
changeCurrentUser(appleton);
PaymentRequestDocument preq = PaymentRequestDocumentFixture.PREQ_FOR_PO_CLOSE_DOC.createPaymentRequestDocument();
preq.setPurchaseOrderIdentifier(poDocument.getPurapDocumentIdentifier());
preq.setProcessingCampusCode("BL");
preq.setAccountsPayablePurchasingDocumentLinkIdentifier(poDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
preq.prepareForSave();
AccountingDocumentTestUtils.saveDocument(preq, documentService);
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode, documentActions);
assertTrue(auth.canClose());
}
/**
* Tests that the payment hold buttons are displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testPaymentHold() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_CLOSE.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode, documentActions);
assertTrue(auth.canHoldPayment());
}
/**
* Tests that the void button is displayed when the purchase order
* is in Pending Print status.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testVoidPendingPrint() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_VOID_PENDING_PRINT.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode, documentActions);
assertTrue(auth.canVoid());
}
/**
* Tests that the void button is displayed when the purchase order
* is in OPEN status and there is no payment request associated
* with the purchase order.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testVoidOpenNoPreq() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_VOID_OPEN_NO_PREQ.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode, documentActions);
assertTrue(auth.canVoid());
}
/**
* Tests that the remove hold button is displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testRemoveHold() throws Exception {
Map editMode = new HashMap();
Map documentActions = new HashMap();
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_REMOVE_HOLD.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode, documentActions);
assertTrue(auth.canRemoveHold());
}
}
| test/integration/src/org/kuali/kfs/module/purap/document/PurchaseOrderDocumentActionAuthorizerTest.java | /*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kfs.module.purap.document;
import static org.kuali.kfs.sys.fixture.UserNameFixture.parke;
import static org.kuali.kfs.sys.fixture.UserNameFixture.appleton;
import static org.kuali.kfs.sys.fixture.UserNameFixture.rorenfro;
import java.util.HashMap;
import java.util.Map;
import org.kuali.rice.kns.service.DocumentService;
import org.kuali.kfs.module.purap.PurapAuthorizationConstants;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.document.authorization.PurchaseOrderDocumentActionAuthorizer;
import org.kuali.kfs.module.purap.document.service.PurchaseOrderService;
import org.kuali.kfs.module.purap.fixture.PaymentRequestDocumentFixture;
import org.kuali.kfs.module.purap.fixture.PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture;
import org.kuali.kfs.module.purap.fixture.RequisitionDocumentFixture;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.context.KualiTestBase;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.AccountingDocumentTestUtils;
import org.kuali.kfs.sys.document.workflow.WorkflowTestUtils;
import org.kuali.kfs.sys.suite.RelatesTo;
import org.kuali.kfs.sys.suite.RelatesTo.JiraIssue;
/**
* This class is used to test the authorization of the
* buttons in Purchase Order Documents. It will invoke the canXXX
* methods in PurchaseOrderDocumentActionAuthorizer to
* test whether certain buttons could be displayed.
*/
@ConfigureContext(session = parke)
public class PurchaseOrderDocumentActionAuthorizerTest extends KualiTestBase {
private PurchaseOrderDocument purchaseOrderDocument = null;
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
purchaseOrderDocument = null;
super.tearDown();
}
/**
* Tests that the retransmit button is displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testValidForRetransmit() throws Exception {
Map editMode = new HashMap();
editMode.put("fullEntry", true);
PurchaseOrderDocument po = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_RETRANSMIT.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(po, editMode);
assertTrue(auth.canRetransmit());
}
/**
* Tests that the print retransmit button is displayed when the purchase order
* is not an APO. It should allow purchasing users (in this case we use parke)
* to see the button if the purchase order is not an APO.
*
* @throws Exception
*/
@RelatesTo(JiraIssue.KULPURAP3146)
@ConfigureContext(session = parke, shouldCommitTransactions=false)
public final void testValidForPrintingRetransmitNonAPO() throws Exception {
Map editMode = new HashMap();
editMode.put(PurapAuthorizationConstants.PurchaseOrderEditMode.DISPLAY_RETRANSMIT_TAB, true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_RETRANSMIT.createPurchaseOrderDocument();
poDocument.prepareForSave();
DocumentService documentService = SpringContext.getBean(DocumentService.class);
AccountingDocumentTestUtils.routeDocument(poDocument, "saving copy source document", null, documentService);
WorkflowTestUtils.waitForStatusChange(poDocument.getDocumentHeader().getWorkflowDocument(), "F");
assertTrue("Document should now be final.", poDocument.getDocumentHeader().getWorkflowDocument().stateIsFinal());
PurchaseOrderService purchaseOrderService = SpringContext.getBean(PurchaseOrderService.class);
PurchaseOrderDocument poRetransmitDocument = purchaseOrderService.createAndRoutePotentialChangeDocument(poDocument.getDocumentNumber(), PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT, null, null, "RTPE");
poRetransmitDocument.setStatusCode("CGIN");
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poRetransmitDocument, editMode);
assertTrue(auth.canPrintRetransmit());
}
/**
* Tests that the print retransmit button is displayed when the purchase order is an
* APO and the user can be anyone (here it is set as rorenfro prior to checking for the authorizer).
* It should allow anyone to see the print retransmit button if it's an APO.
*
* @throws Exception
*/
@RelatesTo(JiraIssue.KULPURAP3146)
@ConfigureContext(session = parke, shouldCommitTransactions=false)
public final void testValidForPrintingRetransmitAPO() throws Exception {
Map editMode = new HashMap();
editMode.put(PurapAuthorizationConstants.PurchaseOrderEditMode.DISPLAY_RETRANSMIT_TAB, true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_RETRANSMIT.createPurchaseOrderDocument();
poDocument.prepareForSave();
DocumentService documentService = SpringContext.getBean(DocumentService.class);
AccountingDocumentTestUtils.routeDocument(poDocument, "saving copy source document", null, documentService);
WorkflowTestUtils.waitForStatusChange(poDocument.getDocumentHeader().getWorkflowDocument(), "F");
assertTrue("Document should now be final.", poDocument.getDocumentHeader().getWorkflowDocument().stateIsFinal());
PurchaseOrderService purchaseOrderService = SpringContext.getBean(PurchaseOrderService.class);
PurchaseOrderDocument poRetransmitDocument = purchaseOrderService.createAndRoutePotentialChangeDocument(poDocument.getDocumentNumber(), PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT, null, null, "RTPE");
poRetransmitDocument.setStatusCode("CGIN");
poRetransmitDocument.setPurchaseOrderAutomaticIndicator(true);
changeCurrentUser(rorenfro);
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poRetransmitDocument, editMode);
assertTrue(auth.canPrintRetransmit());
}
/**
* Tests that the print button for first transmit is displayed.
*
* @throws Exception
*/
@RelatesTo(JiraIssue.KULPURAP3143)
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testFirstTransmitPrintPO() throws Exception {
Map editMode = new HashMap();
editMode.put("fullEntry", true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_FIRST_TRANSMIT_PRINT.createPurchaseOrderDocument();
DocumentService documentService = SpringContext.getBean(DocumentService.class);
poDocument.prepareForSave();
AccountingDocumentTestUtils.routeDocument(poDocument, "saving copy source document", null, documentService);
WorkflowTestUtils.waitForStatusChange(poDocument.getDocumentHeader().getWorkflowDocument(), "F");
assertTrue("Document should now be final.", poDocument.getDocumentHeader().getWorkflowDocument().stateIsFinal());
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode);
assertTrue(auth.canFirstTransmitPrintPo());
}
/**
* Tests that the open order button is displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testReopen() throws Exception {
Map editMode = new HashMap();
editMode.put("fullEntry", true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_REOPEN.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode);
assertTrue(auth.canReopen());
}
/**
* Tests that the close order button is displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testClose() throws Exception {
Map editMode = new HashMap();
editMode.put("fullEntry", true);
DocumentService documentService = SpringContext.getBean(DocumentService.class);
//We create and save this req to obtain a number from the AP document link identifier sequencer in the database
RequisitionDocument dummyReqDocument = RequisitionDocumentFixture.REQ_ONLY_REQUIRED_FIELDS.createRequisitionDocument();
documentService.saveDocument(dummyReqDocument);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_CLOSE.createPurchaseOrderDocument();
poDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(dummyReqDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
poDocument.prepareForSave();
AccountingDocumentTestUtils.routeDocument(poDocument, "saving copy source document", null, documentService);
WorkflowTestUtils.waitForStatusChange(poDocument.getDocumentHeader().getWorkflowDocument(), "F");
changeCurrentUser(appleton);
PaymentRequestDocument preq = PaymentRequestDocumentFixture.PREQ_FOR_PO_CLOSE_DOC.createPaymentRequestDocument();
preq.setPurchaseOrderIdentifier(poDocument.getPurapDocumentIdentifier());
preq.setProcessingCampusCode("BL");
preq.setAccountsPayablePurchasingDocumentLinkIdentifier(poDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
preq.prepareForSave();
AccountingDocumentTestUtils.saveDocument(preq, documentService);
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode);
assertTrue(auth.canClose());
}
/**
* Tests that the payment hold buttons are displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testPaymentHold() throws Exception {
Map editMode = new HashMap();
editMode.put("fullEntry", true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_CLOSE.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode);
assertTrue(auth.canHoldPayment());
}
/**
* Tests that the void button is displayed when the purchase order
* is in Pending Print status.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testVoidPendingPrint() throws Exception {
Map editMode = new HashMap();
editMode.put("fullEntry", true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_VOID_PENDING_PRINT.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode);
assertTrue(auth.canVoid());
}
/**
* Tests that the void button is displayed when the purchase order
* is in OPEN status and there is no payment request associated
* with the purchase order.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testVoidOpenNoPreq() throws Exception {
Map editMode = new HashMap();
editMode.put("fullEntry", true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_VOID_OPEN_NO_PREQ.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode);
assertTrue(auth.canVoid());
}
/**
* Tests that the remove hold button is displayed.
*
* @throws Exception
*/
@ConfigureContext(session = parke, shouldCommitTransactions=true)
public final void testRemoveHold() throws Exception {
Map editMode = new HashMap();
editMode.put("fullEntry", true);
PurchaseOrderDocument poDocument = PurchaseOrderForPurchaseOrderDocumentActionAuthorizerFixture.PO_VALID_REMOVE_HOLD.createPurchaseOrderDocument();
PurchaseOrderDocumentActionAuthorizer auth = new PurchaseOrderDocumentActionAuthorizer(poDocument, editMode);
assertTrue(auth.canRemoveHold());
}
}
| fixed compiler errors in PO action authorization test, to be consistent with KIM changes
| test/integration/src/org/kuali/kfs/module/purap/document/PurchaseOrderDocumentActionAuthorizerTest.java | fixed compiler errors in PO action authorization test, to be consistent with KIM changes |
|
Java | lgpl-2.1 | a24a4659f5e8229cbd302d8a3939762e2a0c785b | 0 | xph906/SootNew,anddann/soot,plast-lab/soot,xph906/SootNew,mbenz89/soot,xph906/SootNew,mbenz89/soot,mbenz89/soot,plast-lab/soot,cfallin/soot,cfallin/soot,cfallin/soot,anddann/soot,anddann/soot,plast-lab/soot,cfallin/soot,anddann/soot,mbenz89/soot,xph906/SootNew | /* Soot - a J*va Optimization Framework
* Copyright (C) 2005 Nomair Naeem
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot.dava.toolkits.base.AST.transformations;
import soot.*;
import java.util.*;
import soot.dava.internal.SET.*;
import soot.dava.internal.AST.*;
import soot.dava.toolkits.base.AST.analysis.*;
/*
Nomair A. Naeem 21-FEB-2005
In the depthFirstAdaptor children of a ASTNode
are gotten in three ways
a, ASTStatementSequenceNode uses one way see caseASTStatementSequenceNode in DepthFirstAdapter
b, ASTTryNode uses another way see caseASTTryNode in DepthFirstAdapter
c, All other nodes use normalRetrieving method to retrieve the children
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
Current tasks of the cleaner
Invoke IfElsebreaker
*/
public class ASTCleanerTwo extends DepthFirstAdapter{
public ASTCleanerTwo(){
}
public ASTCleanerTwo(boolean verbose){
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node){
}
/*
Note the ASTNode in this case can be any of the following:
ASTMethodNode ASTSwitchNode ASTIfNode
ASTIfElseNode ASTUnconditionalWhileNode ASTWhileNode
ASTDoWhileNode ASTForLoopNode ASTLabeledBlockNode
ASTSynchronizedBlockNode
*/
public void normalRetrieving(ASTNode node){
if(node instanceof ASTSwitchNode){
dealWithSwitchNode((ASTSwitchNode)node);
return;
}
//from the Node get the subBodes
Iterator sbit = node.get_SubBodies().iterator();
//onlyASTIfElseNode has 2 subBodies but we need to deal with that
int subBodyNumber=0;
while (sbit.hasNext()) {
List subBody = (List)sbit.next();
Iterator it = subBody.iterator();
int nodeNumber=0;
//go over the ASTNodes in this subBody and apply
while (it.hasNext()){
ASTNode temp = (ASTNode) it.next();
if(temp instanceof ASTIfElseNode){
IfElseBreaker breaker = new IfElseBreaker();
boolean success=false;
if(breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode)temp)){
success=true;
}
else if(breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode)temp)){
success=true;
}
if(G.v().ASTTransformations_modified)
return;
if(!success){
//System.out.println("not successful");
}
if(success){
List newBody = breaker.createNewBody(subBody,nodeNumber);
if(newBody!= null){
if(node instanceof ASTIfElseNode){
if(subBodyNumber==0){
//the if body was modified
List subBodies = node.get_SubBodies();
List ifElseBody = (List)subBodies.get(1);
((ASTIfElseNode)node).replaceBody(newBody,ifElseBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 1");
return;
}
else if(subBodyNumber==1){
//else body was modified
List subBodies = node.get_SubBodies();
List ifBody = (List)subBodies.get(0);
((ASTIfElseNode)node).replaceBody(ifBody,newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 2");
return;
}
else{
throw new RuntimeException("Please report benchmark to programmer");
}
}
else{
if(node instanceof ASTMethodNode){
((ASTMethodNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 3");
return;
}
else if(node instanceof ASTSynchronizedBlockNode){
((ASTSynchronizedBlockNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 4");
return;
}
else if(node instanceof ASTLabeledBlockNode){
((ASTLabeledBlockNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 5");
return;
}
else if(node instanceof ASTUnconditionalLoopNode){
((ASTUnconditionalLoopNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 6");
return;
}
else if(node instanceof ASTIfNode){
((ASTIfNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 7");
return;
}
else if(node instanceof ASTWhileNode){
((ASTWhileNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 8");
return;
}
else if(node instanceof ASTDoWhileNode){
((ASTDoWhileNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 9");
return;
}
else if(node instanceof ASTForLoopNode){
((ASTForLoopNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 11");
return;
}
else {
throw new RuntimeException("Please report benchmark to programmer");
}
}
}//newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
subBodyNumber++;
}//end of going over subBodies
}
public void caseASTTryNode(ASTTryNode node){
inASTTryNode(node);
//get try body
List tryBody = node.get_TryBody();
Iterator it = tryBody.iterator();
int nodeNumber=0;
//go over the ASTNodes and apply
while (it.hasNext()){
ASTNode temp = (ASTNode) it.next();
if(temp instanceof ASTIfElseNode){
IfElseBreaker breaker = new IfElseBreaker();
boolean success=false;
if(breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode)temp)){
success=true;
}
else if(breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode)temp)){
success=true;
}
if(G.v().ASTTransformations_modified)
return;
if(success){
List newBody = breaker.createNewBody(tryBody,nodeNumber);
if(newBody!= null){
//something did not go wrong
node.replaceTryBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 10");
return;
}//newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
Map exceptionMap = node.get_ExceptionMap();
Map paramMap = node.get_ParamMap();
//get catch list and apply on the following
// a, type of exception caught
// b, local of exception
// c, catchBody
List catchList = node.get_CatchList();
Iterator itBody=null;
it = catchList.iterator();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container)it.next();
SootClass sootClass = ((SootClass)exceptionMap.get(catchBody));
Type type = sootClass.getType();
//apply on type of exception
caseType(type);
//apply on local of exception
Local local = (Local)paramMap.get(catchBody);
decideCaseExprOrRef(local);
//apply on catchBody
List body = (List)catchBody.o;
itBody = body.iterator();
nodeNumber=0;
//go over the ASTNodes and apply
while (itBody.hasNext()){
ASTNode temp = (ASTNode) itBody.next();
if(temp instanceof ASTIfElseNode){
IfElseBreaker breaker = new IfElseBreaker();
boolean success=false;
if(breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode)temp)){
success=true;
}
else if(breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode)temp)){
success=true;
}
if(G.v().ASTTransformations_modified)
return;
if(success){
List newBody = breaker.createNewBody(body,nodeNumber);
if(newBody!= null){
//something did not go wrong
catchBody.replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 11");
return;
}//newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
}
outASTTryNode(node);
}
private void dealWithSwitchNode(ASTSwitchNode node){
//do a depthfirst on elements of the switchNode
List indexList = node.getIndexList();
Map index2BodyList = node.getIndex2BodyList();
Iterator it = indexList.iterator();
while (it.hasNext()) {//going through all the cases of the switch statement
Object currentIndex = it.next();
List body = (List) index2BodyList.get( currentIndex);
if (body != null){
//this body is a list of ASTNodes
Iterator itBody = body.iterator();
int nodeNumber=0;
//go over the ASTNodes and apply
while (itBody.hasNext()){
ASTNode temp = (ASTNode) itBody.next();
if(temp instanceof ASTIfElseNode){
IfElseBreaker breaker = new IfElseBreaker();
boolean success=false;
if(breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode)temp)){
success=true;
}
else if(breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode)temp)){
success=true;
}
if(G.v().ASTTransformations_modified)
return;
if(success){
List newBody = breaker.createNewBody(body,nodeNumber);
if(newBody!= null){
//put this body in the Map
index2BodyList.put(currentIndex,newBody);
//replace in actual switchNode
node.replaceIndex2BodyList(index2BodyList);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 12");
return;
}//newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
}
}
}
}
| src/soot/dava/toolkits/base/AST/transformations/ASTCleanerTwo.java | package soot.dava.toolkits.base.AST.transformations;
import soot.*;
import java.util.*;
import soot.dava.internal.SET.*;
import soot.dava.internal.AST.*;
import soot.dava.toolkits.base.AST.analysis.*;
/*
Nomair A. Naeem 21-FEB-2005
In the depthFirstAdaptor children of a ASTNode
are gotten in three ways
a, ASTStatementSequenceNode uses one way see caseASTStatementSequenceNode in DepthFirstAdapter
b, ASTTryNode uses another way see caseASTTryNode in DepthFirstAdapter
c, All other nodes use normalRetrieving method to retrieve the children
TO MAKE CODE EFFECIENT BLOCK THE ANALYSIS TO GOING INTO STATEMENTS
this is done by overriding the caseASTStatementSequenceNode
Current tasks of the cleaner
Invoke IfElsebreaker
*/
public class ASTCleanerTwo extends DepthFirstAdapter{
public ASTCleanerTwo(){
}
public ASTCleanerTwo(boolean verbose){
super(verbose);
}
public void caseASTStatementSequenceNode(ASTStatementSequenceNode node){
}
/*
Note the ASTNode in this case can be any of the following:
ASTMethodNode ASTSwitchNode ASTIfNode
ASTIfElseNode ASTUnconditionalWhileNode ASTWhileNode
ASTDoWhileNode ASTForLoopNode ASTLabeledBlockNode
ASTSynchronizedBlockNode
*/
public void normalRetrieving(ASTNode node){
if(node instanceof ASTSwitchNode){
dealWithSwitchNode((ASTSwitchNode)node);
return;
}
//from the Node get the subBodes
Iterator sbit = node.get_SubBodies().iterator();
//onlyASTIfElseNode has 2 subBodies but we need to deal with that
int subBodyNumber=0;
while (sbit.hasNext()) {
List subBody = (List)sbit.next();
Iterator it = subBody.iterator();
int nodeNumber=0;
//go over the ASTNodes in this subBody and apply
while (it.hasNext()){
ASTNode temp = (ASTNode) it.next();
if(temp instanceof ASTIfElseNode){
IfElseBreaker breaker = new IfElseBreaker();
boolean success=false;
if(breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode)temp)){
success=true;
}
else if(breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode)temp)){
success=true;
}
if(G.v().ASTTransformations_modified)
return;
if(!success){
//System.out.println("not successful");
}
if(success){
List newBody = breaker.createNewBody(subBody,nodeNumber);
if(newBody!= null){
if(node instanceof ASTIfElseNode){
if(subBodyNumber==0){
//the if body was modified
List subBodies = node.get_SubBodies();
List ifElseBody = (List)subBodies.get(1);
((ASTIfElseNode)node).replaceBody(newBody,ifElseBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 1");
return;
}
else if(subBodyNumber==1){
//else body was modified
List subBodies = node.get_SubBodies();
List ifBody = (List)subBodies.get(0);
((ASTIfElseNode)node).replaceBody(ifBody,newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 2");
return;
}
else{
throw new RuntimeException("Please report benchmark to programmer");
}
}
else{
if(node instanceof ASTMethodNode){
((ASTMethodNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 3");
return;
}
else if(node instanceof ASTSynchronizedBlockNode){
((ASTSynchronizedBlockNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 4");
return;
}
else if(node instanceof ASTLabeledBlockNode){
((ASTLabeledBlockNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 5");
return;
}
else if(node instanceof ASTUnconditionalLoopNode){
((ASTUnconditionalLoopNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 6");
return;
}
else if(node instanceof ASTIfNode){
((ASTIfNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 7");
return;
}
else if(node instanceof ASTWhileNode){
((ASTWhileNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 8");
return;
}
else if(node instanceof ASTDoWhileNode){
((ASTDoWhileNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 9");
return;
}
else if(node instanceof ASTForLoopNode){
((ASTForLoopNode)node).replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 11");
return;
}
else {
throw new RuntimeException("Please report benchmark to programmer");
}
}
}//newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
subBodyNumber++;
}//end of going over subBodies
}
public void caseASTTryNode(ASTTryNode node){
inASTTryNode(node);
//get try body
List tryBody = node.get_TryBody();
Iterator it = tryBody.iterator();
int nodeNumber=0;
//go over the ASTNodes and apply
while (it.hasNext()){
ASTNode temp = (ASTNode) it.next();
if(temp instanceof ASTIfElseNode){
IfElseBreaker breaker = new IfElseBreaker();
boolean success=false;
if(breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode)temp)){
success=true;
}
else if(breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode)temp)){
success=true;
}
if(G.v().ASTTransformations_modified)
return;
if(success){
List newBody = breaker.createNewBody(tryBody,nodeNumber);
if(newBody!= null){
//something did not go wrong
node.replaceTryBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 10");
return;
}//newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
Map exceptionMap = node.get_ExceptionMap();
Map paramMap = node.get_ParamMap();
//get catch list and apply on the following
// a, type of exception caught
// b, local of exception
// c, catchBody
List catchList = node.get_CatchList();
Iterator itBody=null;
it = catchList.iterator();
while (it.hasNext()) {
ASTTryNode.container catchBody = (ASTTryNode.container)it.next();
SootClass sootClass = ((SootClass)exceptionMap.get(catchBody));
Type type = sootClass.getType();
//apply on type of exception
caseType(type);
//apply on local of exception
Local local = (Local)paramMap.get(catchBody);
decideCaseExprOrRef(local);
//apply on catchBody
List body = (List)catchBody.o;
itBody = body.iterator();
nodeNumber=0;
//go over the ASTNodes and apply
while (itBody.hasNext()){
ASTNode temp = (ASTNode) itBody.next();
if(temp instanceof ASTIfElseNode){
IfElseBreaker breaker = new IfElseBreaker();
boolean success=false;
if(breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode)temp)){
success=true;
}
else if(breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode)temp)){
success=true;
}
if(G.v().ASTTransformations_modified)
return;
if(success){
List newBody = breaker.createNewBody(body,nodeNumber);
if(newBody!= null){
//something did not go wrong
catchBody.replaceBody(newBody);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 11");
return;
}//newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
}
outASTTryNode(node);
}
private void dealWithSwitchNode(ASTSwitchNode node){
//do a depthfirst on elements of the switchNode
List indexList = node.getIndexList();
Map index2BodyList = node.getIndex2BodyList();
Iterator it = indexList.iterator();
while (it.hasNext()) {//going through all the cases of the switch statement
Object currentIndex = it.next();
List body = (List) index2BodyList.get( currentIndex);
if (body != null){
//this body is a list of ASTNodes
Iterator itBody = body.iterator();
int nodeNumber=0;
//go over the ASTNodes and apply
while (itBody.hasNext()){
ASTNode temp = (ASTNode) itBody.next();
if(temp instanceof ASTIfElseNode){
IfElseBreaker breaker = new IfElseBreaker();
boolean success=false;
if(breaker.isIfElseBreakingPossiblePatternOne((ASTIfElseNode)temp)){
success=true;
}
else if(breaker.isIfElseBreakingPossiblePatternTwo((ASTIfElseNode)temp)){
success=true;
}
if(G.v().ASTTransformations_modified)
return;
if(success){
List newBody = breaker.createNewBody(body,nodeNumber);
if(newBody!= null){
//put this body in the Map
index2BodyList.put(currentIndex,newBody);
//replace in actual switchNode
node.replaceIndex2BodyList(index2BodyList);
G.v().ASTTransformations_modified = true;
//System.out.println("BROKE IFELSE 12");
return;
}//newBody was not null
}
}
temp.apply(this);
nodeNumber++;
}
}
}
}
} | - add copyright notice
| src/soot/dava/toolkits/base/AST/transformations/ASTCleanerTwo.java | - add copyright notice |
|
Java | apache-2.0 | b668cc2659417de43ccf64435cb02e87e56a26a0 | 0 | Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,Sargul/dbeaver | /*
* Copyright (C) 2010-2014 Serge Rieder
* [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jkiss.dbeaver.ui.search;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.ControlEnableState;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.model.struct.DBSDataSourceContainer;
import org.jkiss.dbeaver.runtime.RuntimeUtils;
import org.jkiss.dbeaver.ui.DBIcon;
import org.jkiss.dbeaver.ui.IHelpContextIds;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.dialogs.HelpEnabledDialog;
import java.util.ArrayList;
import java.util.List;
public class DatabaseSearchDialog extends HelpEnabledDialog implements IObjectSearchContainer {
static final Log log = LogFactory.getLog(DatabaseSearchDialog.class);
private static final int SEARCH_ID = 1000;
private static final String PROVIDER_PREF_NAME = "search.dialog.cur-provider";
private static final String NEW_TAB_PREF_NAME = "search.dialog.results.newTab";
private static final String DIALOG_ID = "DBeaver.SearchDialog";//$NON-NLS-1$
private volatile static DatabaseSearchDialog instance;
private boolean searchEnabled = true;
private Button searchButton;
private TabFolder providersFolder;
private Button openNewTabCheck;
private List<ObjectSearchProvider> providers;
private DatabaseSearchDialog(Shell shell, DBSDataSourceContainer currentDataSource)
{
super(shell, IHelpContextIds.CTX_SQL_EDITOR);
setShellStyle(SWT.DIALOG_TRIM | SWT.MAX | SWT.RESIZE | getDefaultOrientation());
}
@Override
protected IDialogSettings getDialogBoundsSettings()
{
return UIUtils.getDialogSettings(DIALOG_ID);
}
@Override
protected Control createDialogArea(Composite parent)
{
Composite group = (Composite) super.createDialogArea(parent);
Shell shell = getShell();
shell.setText(CoreMessages.dialog_search_objects_title);
shell.setImage(DBIcon.FIND.getImage());
shell.addShellListener(new ShellAdapter() {
@Override
public void shellActivated(ShellEvent e)
{
if (searchButton != null && !searchButton.isDisposed()) {
getShell().setDefaultButton(searchButton);
}
}
});
//shell.setDefaultButton(searchButton);
IPreferenceStore store = DBeaverCore.getGlobalPreferenceStore();
providersFolder = new TabFolder(group, SWT.TOP);
providersFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
providers = new ArrayList<ObjectSearchProvider>(ObjectSearchRegistry.getInstance().getProviders());
for (ObjectSearchProvider provider : providers) {
IObjectSearchPage searchPage;
try {
searchPage = provider.createSearchPage();
} catch (DBException e) {
log.error("Can't create search page '" + provider.getId() + "'", e);
continue;
}
searchPage.setSearchContainer(this);
searchPage.loadState(store);
searchPage.createControl(providersFolder);
TabItem item = new TabItem(providersFolder, SWT.NONE);
item.setData("provider", provider);
item.setData("page", searchPage);
item.setText(provider.getLabel());
Image icon = provider.getIcon();
if (icon != null) {
item.setImage(icon);
}
item.setControl(searchPage.getControl());
}
int provIndex = 0;
String curProvider = store.getString(PROVIDER_PREF_NAME);
for (int i = 0; i < providers.size(); i++) {
if (providers.get(i).getId().equals(curProvider)) {
provIndex = i;
}
}
providersFolder.setSelection(provIndex);
return providersFolder;
}
@Override
protected void createButtonsForButtonBar(Composite parent)
{
// New tab check
((GridLayout) parent.getLayout()).numColumns++;
openNewTabCheck = UIUtils.createCheckbox(parent, "Open results in new tab", DBeaverCore.getGlobalPreferenceStore().getBoolean(NEW_TAB_PREF_NAME));
// Buttons
searchButton = createButton(parent, SEARCH_ID, "Search", true);
searchButton.setEnabled(searchEnabled);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
}
@Override
public boolean close()
{
saveState();
return super.close();
}
@Override
public void setSearchEnabled(boolean enabled)
{
if (searchButton != null) {
searchButton.setEnabled(enabled);
}
searchEnabled = enabled;
}
public void saveState()
{
IPreferenceStore store = DBeaverCore.getGlobalPreferenceStore();
store.setValue(NEW_TAB_PREF_NAME, openNewTabCheck.getSelection());
for (TabItem item : providersFolder.getItems()) {
IObjectSearchPage page = (IObjectSearchPage) item.getData("page");
page.saveState(store);
}
store.setValue(PROVIDER_PREF_NAME, providers.get(providersFolder.getSelectionIndex()).getId());
RuntimeUtils.savePreferenceStore(store);
}
@Override
protected void buttonPressed(int buttonId)
{
if (buttonId == SEARCH_ID) {
performSearch();
}
super.buttonPressed(buttonId);
}
private void performSearch()
{
TabItem selectedItem = providersFolder.getItem(providersFolder.getSelectionIndex());
ObjectSearchProvider provider = (ObjectSearchProvider) selectedItem.getData("provider");
IObjectSearchPage page = (IObjectSearchPage) selectedItem.getData("page");
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
DatabaseSearchView resultsView;
try {
resultsView = (DatabaseSearchView)activePage.showView(DatabaseSearchView.VIEW_ID);
activePage.bringToTop(resultsView);
} catch (PartInitException e) {
UIUtils.showErrorDialog(getShell(), "Search", "Can't open search view", e);
return;
}
IObjectSearchQuery query;
try {
query = page.createQuery();
} catch (DBException e) {
UIUtils.showErrorDialog(getShell(), "Search", "Can't create search query", e);
return;
}
IObjectSearchResultPage resultsPage;
try {
resultsPage = resultsView.openResultPage(provider, query, openNewTabCheck.getSelection());
} catch (DBException e) {
UIUtils.showErrorDialog(getShell(), "Search", "Can't open search results page", e);
return;
}
saveState();
// Run search job
setSearchEnabled(false);
final ControlEnableState disableState = ControlEnableState.disable(providersFolder);
DatabaseSearchJob job = new DatabaseSearchJob(query, resultsPage);
job.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event)
{
UIUtils.runInUI(getShell(), new Runnable() {
@Override
public void run()
{
if (!providersFolder.isDisposed()) {
setSearchEnabled(true);
disableState.restore();
}
}
});
}
});
job.schedule();
}
public static void open(Shell shell, DBSDataSourceContainer currentDataSource)
{
if (ObjectSearchRegistry.getInstance().getProviders().isEmpty()) {
UIUtils.showMessageBox(shell, "Search error", "No search providers found", SWT.ICON_ERROR);
return;
}
if (instance != null) {
instance.getShell().setActive();
return;
}
DatabaseSearchDialog dialog = new DatabaseSearchDialog(shell, currentDataSource);
instance = dialog;
try {
dialog.open();
} finally {
instance = null;
}
}
}
| plugins/org.jkiss.dbeaver.core.application/src/org/jkiss/dbeaver/ui/search/DatabaseSearchDialog.java | /*
* Copyright (C) 2010-2014 Serge Rieder
* [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jkiss.dbeaver.ui.search;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.ControlEnableState;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.model.struct.DBSDataSourceContainer;
import org.jkiss.dbeaver.runtime.RuntimeUtils;
import org.jkiss.dbeaver.ui.DBIcon;
import org.jkiss.dbeaver.ui.IHelpContextIds;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.dialogs.HelpEnabledDialog;
import java.util.List;
public class DatabaseSearchDialog extends HelpEnabledDialog implements IObjectSearchContainer {
static final Log log = LogFactory.getLog(DatabaseSearchDialog.class);
private static final int SEARCH_ID = 1000;
private static final String NEW_TAB_PREF_NAME = "search.dialog.results.newTab";
private static final String DIALOG_ID = "DBeaver.SearchDialog";//$NON-NLS-1$
private volatile static DatabaseSearchDialog instance;
private boolean searchEnabled = true;
private Button searchButton;
private TabFolder providersFolder;
private Button openNewTabCheck;
private DatabaseSearchDialog(Shell shell, DBSDataSourceContainer currentDataSource)
{
super(shell, IHelpContextIds.CTX_SQL_EDITOR);
setShellStyle(SWT.DIALOG_TRIM | SWT.MAX | SWT.RESIZE | getDefaultOrientation());
}
@Override
protected IDialogSettings getDialogBoundsSettings()
{
return UIUtils.getDialogSettings(DIALOG_ID);
}
@Override
protected Control createDialogArea(Composite parent)
{
Composite group = (Composite) super.createDialogArea(parent);
Shell shell = getShell();
shell.setText(CoreMessages.dialog_search_objects_title);
shell.setImage(DBIcon.FIND.getImage());
shell.addShellListener(new ShellAdapter() {
@Override
public void shellActivated(ShellEvent e)
{
if (searchButton != null && !searchButton.isDisposed()) {
getShell().setDefaultButton(searchButton);
}
}
});
//shell.setDefaultButton(searchButton);
IPreferenceStore store = DBeaverCore.getGlobalPreferenceStore();
providersFolder = new TabFolder(group, SWT.TOP);
providersFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
List<ObjectSearchProvider> providers = ObjectSearchRegistry.getInstance().getProviders();
for (ObjectSearchProvider provider : providers) {
IObjectSearchPage searchPage;
try {
searchPage = provider.createSearchPage();
} catch (DBException e) {
log.error("Can't create search page '" + provider.getId() + "'", e);
continue;
}
searchPage.setSearchContainer(this);
searchPage.loadState(store);
searchPage.createControl(providersFolder);
TabItem item = new TabItem(providersFolder, SWT.NONE);
item.setData("provider", provider);
item.setData("page", searchPage);
item.setText(provider.getLabel());
Image icon = provider.getIcon();
if (icon != null) {
item.setImage(icon);
}
item.setControl(searchPage.getControl());
}
providersFolder.setSelection(0);
return providersFolder;
}
@Override
protected void createButtonsForButtonBar(Composite parent)
{
// New tab check
((GridLayout) parent.getLayout()).numColumns++;
openNewTabCheck = UIUtils.createCheckbox(parent, "Open results in new tab", DBeaverCore.getGlobalPreferenceStore().getBoolean(NEW_TAB_PREF_NAME));
// Buttons
searchButton = createButton(parent, SEARCH_ID, "Search", true);
searchButton.setEnabled(searchEnabled);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
}
@Override
public boolean close()
{
saveState();
return super.close();
}
@Override
public void setSearchEnabled(boolean enabled)
{
if (searchButton != null) {
searchButton.setEnabled(enabled);
}
searchEnabled = enabled;
}
public void saveState()
{
IPreferenceStore store = DBeaverCore.getGlobalPreferenceStore();
store.setValue(NEW_TAB_PREF_NAME, openNewTabCheck.getSelection());
for (TabItem item : providersFolder.getItems()) {
IObjectSearchPage page = (IObjectSearchPage) item.getData("page");
page.saveState(store);
}
RuntimeUtils.savePreferenceStore(store);
}
@Override
protected void buttonPressed(int buttonId)
{
if (buttonId == SEARCH_ID) {
performSearch();
}
super.buttonPressed(buttonId);
}
private void performSearch()
{
TabItem selectedItem = providersFolder.getItem(providersFolder.getSelectionIndex());
ObjectSearchProvider provider = (ObjectSearchProvider) selectedItem.getData("provider");
IObjectSearchPage page = (IObjectSearchPage) selectedItem.getData("page");
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
DatabaseSearchView resultsView;
try {
resultsView = (DatabaseSearchView)activePage.showView(DatabaseSearchView.VIEW_ID);
activePage.bringToTop(resultsView);
} catch (PartInitException e) {
UIUtils.showErrorDialog(getShell(), "Search", "Can't open search view", e);
return;
}
IObjectSearchQuery query;
try {
query = page.createQuery();
} catch (DBException e) {
UIUtils.showErrorDialog(getShell(), "Search", "Can't create search query", e);
return;
}
IObjectSearchResultPage resultsPage;
try {
resultsPage = resultsView.openResultPage(provider, query, openNewTabCheck.getSelection());
} catch (DBException e) {
UIUtils.showErrorDialog(getShell(), "Search", "Can't open search results page", e);
return;
}
saveState();
// Run search job
setSearchEnabled(false);
final ControlEnableState disableState = ControlEnableState.disable(providersFolder);
DatabaseSearchJob job = new DatabaseSearchJob(query, resultsPage);
job.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event)
{
UIUtils.runInUI(getShell(), new Runnable() {
@Override
public void run()
{
if (!providersFolder.isDisposed()) {
setSearchEnabled(true);
disableState.restore();
}
}
});
}
});
job.schedule();
}
public static void open(Shell shell, DBSDataSourceContainer currentDataSource)
{
if (ObjectSearchRegistry.getInstance().getProviders().isEmpty()) {
UIUtils.showMessageBox(shell, "Search error", "No search providers found", SWT.ICON_ERROR);
return;
}
if (instance != null) {
instance.getShell().setActive();
return;
}
DatabaseSearchDialog dialog = new DatabaseSearchDialog(shell, currentDataSource);
instance = dialog;
try {
dialog.open();
} finally {
instance = null;
}
}
}
| Search dialog prefs
Former-commit-id: d112c75396146822b776a43dfd660bf00c249d31 | plugins/org.jkiss.dbeaver.core.application/src/org/jkiss/dbeaver/ui/search/DatabaseSearchDialog.java | Search dialog prefs |
|
Java | apache-2.0 | dc6b42d538b5566877442de90283208aeb5c757d | 0 | ModernMT/MMT,ModernMT/MMT,ModernMT/MMT,ModernMT/MMT,ModernMT/MMT | package eu.modernmt.model.corpus.impl.parallel;
import eu.modernmt.io.*;
import eu.modernmt.lang.LanguageDirection;
import eu.modernmt.lang.UnsupportedLanguageException;
import eu.modernmt.model.corpus.BaseMultilingualCorpus;
import eu.modernmt.model.corpus.Corpus;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.IOException;
/**
* Created by davide on 24/02/16.
*/
public class ParallelFileCorpus extends BaseMultilingualCorpus {
private final FileProxy source;
private final FileProxy target;
private final String name;
private final LanguageDirection language;
public ParallelFileCorpus(File directory, String name, LanguageDirection language) {
this(name, language, new File(directory, name + "." + language.source.toLanguageTag()),
new File(directory, name + "." + language.target.toLanguageTag()));
}
public ParallelFileCorpus(LanguageDirection language, File source, File target) {
this(FilenameUtils.removeExtension(source.getName()), language, source, target);
}
public ParallelFileCorpus(LanguageDirection language, FileProxy source, FileProxy target) {
this(FilenameUtils.removeExtension(source.getFilename()), language, source, target);
}
public ParallelFileCorpus(String name, LanguageDirection language, File source, File target) {
this(name, language, FileProxy.wrap(source), FileProxy.wrap(target));
}
public ParallelFileCorpus(String name, LanguageDirection language, FileProxy source, FileProxy target) {
this.name = name;
this.language = language;
this.source = source;
this.target = target;
}
public LanguageDirection getLanguage() {
return language;
}
public FileProxy getSourceFile() {
return source;
}
public FileProxy getTargetFile() {
return target;
}
@Override
public Corpus getCorpus(LanguageDirection language, boolean source) {
if (this.language.equals(language))
return new FileCorpus(source ? this.source : this.target, name, source ? language.source : language.target);
else
throw new UnsupportedLanguageException(language);
}
@Override
public String getName() {
return name;
}
@Override
public MultilingualLineReader getContentReader() throws IOException {
return new ParallelFileLineReader(language, source, target);
}
@Override
public MultilingualLineWriter getContentWriter(boolean append) throws IOException {
return new ParallelFileLineWriter(append, language, source, target);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParallelFileCorpus that = (ParallelFileCorpus) o;
if (!source.equals(that.source)) return false;
return target.equals(that.target);
}
@Override
public int hashCode() {
int result = source.hashCode();
result = 31 * result + target.hashCode();
return result;
}
@Override
public String toString() {
return name + '[' + language.toString() + ']';
}
private static class ParallelFileLineReader implements MultilingualLineReader {
private final LanguageDirection language;
private final UnixLineReader sourceReader;
private final UnixLineReader targetReader;
private int index;
private ParallelFileLineReader(LanguageDirection language, FileProxy source, FileProxy target) throws IOException {
this.language = language;
boolean success = false;
try {
this.sourceReader = new UnixLineReader(source.getInputStream(), UTF8Charset.get());
this.targetReader = new UnixLineReader(target.getInputStream(), UTF8Charset.get());
this.index = 0;
success = true;
} finally {
if (!success)
this.close();
}
}
@Override
public StringPair read() throws IOException {
String source = sourceReader.readLine();
String target = targetReader.readLine();
if (source == null && target == null) {
return null;
} else if (source != null && target != null) {
this.index++;
return new StringPair(language, source, target);
} else {
throw new IOException("Invalid parallel corpus: unmatched line at " + (this.index + 1));
}
}
@Override
public void close() {
IOUtils.closeQuietly(this.sourceReader);
IOUtils.closeQuietly(this.targetReader);
}
}
private static class ParallelFileLineWriter implements MultilingualLineWriter {
private final LanguageDirection language;
private final LineWriter sourceWriter;
private final LineWriter targetWriter;
private ParallelFileLineWriter(boolean append, LanguageDirection language, FileProxy source, FileProxy target) throws IOException {
this.language = language;
boolean success = false;
try {
this.sourceWriter = new UnixLineWriter(source.getOutputStream(append), UTF8Charset.get());
this.targetWriter = new UnixLineWriter(target.getOutputStream(append), UTF8Charset.get());
success = true;
} finally {
if (!success)
this.close();
}
}
@Override
public void write(StringPair pair) throws IOException {
if (language.isEqualOrMoreGenericThan(pair.language)) {
sourceWriter.writeLine(pair.source);
targetWriter.writeLine(pair.target);
} else if (language.isEqualOrMoreGenericThan(pair.language.reversed())) {
sourceWriter.writeLine(pair.target);
targetWriter.writeLine(pair.source);
} else {
throw new IOException("Unsupported language: " + pair.language);
}
}
@Override
public void flush() throws IOException {
sourceWriter.flush();
targetWriter.flush();
}
@Override
public void close() {
IOUtils.closeQuietly(this.sourceWriter);
IOUtils.closeQuietly(this.targetWriter);
}
}
}
| src/commons/src/main/java/eu/modernmt/model/corpus/impl/parallel/ParallelFileCorpus.java | package eu.modernmt.model.corpus.impl.parallel;
import eu.modernmt.io.*;
import eu.modernmt.lang.LanguageDirection;
import eu.modernmt.lang.UnsupportedLanguageException;
import eu.modernmt.model.corpus.BaseMultilingualCorpus;
import eu.modernmt.model.corpus.Corpus;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.IOException;
/**
* Created by davide on 24/02/16.
*/
public class ParallelFileCorpus extends BaseMultilingualCorpus {
private final FileProxy source;
private final FileProxy target;
private final String name;
private final LanguageDirection language;
public ParallelFileCorpus(File directory, String name, LanguageDirection language) {
this(name, language, new File(directory, name + "." + language.source.toLanguageTag()),
new File(directory, name + "." + language.target.toLanguageTag()));
}
public ParallelFileCorpus(LanguageDirection language, File source, File target) {
this(FilenameUtils.removeExtension(source.getName()), language, source, target);
}
public ParallelFileCorpus(LanguageDirection language, FileProxy source, FileProxy target) {
this(FilenameUtils.removeExtension(source.getFilename()), language, source, target);
}
public ParallelFileCorpus(String name, LanguageDirection language, File source, File target) {
this(name, language, FileProxy.wrap(source), FileProxy.wrap(target));
}
public ParallelFileCorpus(String name, LanguageDirection language, FileProxy source, FileProxy target) {
this.name = name;
this.language = language;
this.source = source;
this.target = target;
}
public LanguageDirection getLanguage() {
return language;
}
public FileProxy getSourceFile() {
return source;
}
public FileProxy getTargetFile() {
return target;
}
@Override
public Corpus getCorpus(LanguageDirection language, boolean source) {
if (this.language.equals(language))
return new FileCorpus(source ? this.source : this.target, name, source ? language.source : language.target);
else
throw new UnsupportedLanguageException(language);
}
@Override
public String getName() {
return name;
}
@Override
public MultilingualLineReader getContentReader() throws IOException {
return new ParallelFileLineReader(language, source, target);
}
@Override
public MultilingualLineWriter getContentWriter(boolean append) throws IOException {
return new ParallelFileLineWriter(append, language, source, target);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParallelFileCorpus that = (ParallelFileCorpus) o;
if (!source.equals(that.source)) return false;
return target.equals(that.target);
}
@Override
public int hashCode() {
int result = source.hashCode();
result = 31 * result + target.hashCode();
return result;
}
@Override
public String toString() {
return name + '[' + language.toString() + ']';
}
private static class ParallelFileLineReader implements MultilingualLineReader {
private final LanguageDirection language;
private final UnixLineReader sourceReader;
private final UnixLineReader targetReader;
private int index;
private ParallelFileLineReader(LanguageDirection language, FileProxy source, FileProxy target) throws IOException {
this.language = language;
boolean success = false;
try {
this.sourceReader = new UnixLineReader(source.getInputStream(), UTF8Charset.get());
this.targetReader = new UnixLineReader(target.getInputStream(), UTF8Charset.get());
this.index = 0;
success = true;
} finally {
if (!success)
this.close();
}
}
@Override
public StringPair read() throws IOException {
String source = sourceReader.readLine();
String target = targetReader.readLine();
if (source == null && target == null) {
return null;
} else if (source != null && target != null) {
this.index++;
return new StringPair(language, source, target);
} else {
throw new IOException("Invalid parallel corpus: unmatched line at " + (this.index + 1));
}
}
@Override
public void close() {
IOUtils.closeQuietly(this.sourceReader);
IOUtils.closeQuietly(this.targetReader);
}
}
private static class ParallelFileLineWriter implements MultilingualLineWriter {
private final LanguageDirection language;
private final LineWriter sourceWriter;
private final LineWriter targetWriter;
private ParallelFileLineWriter(boolean append, LanguageDirection language, FileProxy source, FileProxy target) throws IOException {
this.language = language;
boolean success = false;
try {
this.sourceWriter = new UnixLineWriter(source.getOutputStream(append), UTF8Charset.get());
this.targetWriter = new UnixLineWriter(target.getOutputStream(append), UTF8Charset.get());
success = true;
} finally {
if (!success)
this.close();
}
}
@Override
public void write(StringPair pair) throws IOException {
if (language.isEqualOrMoreGenericThan(pair.language)) {
sourceWriter.writeLine(pair.source);
targetWriter.writeLine(pair.target);
} else if (language.isEqualOrMoreGenericThan(language.reversed())) {
sourceWriter.writeLine(pair.target);
targetWriter.writeLine(pair.source);
} else {
throw new IOException("Unsupported language: " + pair.language);
}
}
@Override
public void flush() throws IOException {
sourceWriter.flush();
targetWriter.flush();
}
@Override
public void close() {
IOUtils.closeQuietly(this.sourceWriter);
IOUtils.closeQuietly(this.targetWriter);
}
}
}
| Fixed ParallelFileLineWriter write
| src/commons/src/main/java/eu/modernmt/model/corpus/impl/parallel/ParallelFileCorpus.java | Fixed ParallelFileLineWriter write |
|
Java | apache-2.0 | 8f3a111c60bc63bf44a4734ccc5bf39b3ac6a9d6 | 0 | ham1/jmeter,etnetera/jmeter,ham1/jmeter,apache/jmeter,etnetera/jmeter,apache/jmeter,benbenw/jmeter,apache/jmeter,ham1/jmeter,ham1/jmeter,etnetera/jmeter,benbenw/jmeter,apache/jmeter,benbenw/jmeter,etnetera/jmeter,apache/jmeter,benbenw/jmeter,ham1/jmeter,etnetera/jmeter | /*
* 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.jmeter.assertions;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.assertions.gui.AssertionGui;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.AbstractScopedAssertion;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.IntegerProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.NullProperty;
import org.apache.jmeter.testelement.property.StringProperty;
import org.apache.jmeter.util.Document;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.oro.text.MalformedCachePatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test element to handle Response Assertions.
* See {@link AssertionGui} for GUI.
*/
public class ResponseAssertion extends AbstractScopedAssertion implements Serializable, Assertion {
private static final Logger log = LoggerFactory.getLogger(ResponseAssertion.class);
private static final long serialVersionUID = 242L;
private static final String TEST_FIELD = "Assertion.test_field"; // $NON-NLS-1$
// Values for TEST_FIELD
// N.B. we cannot change the text value as it is in test plans
private static final String SAMPLE_URL = "Assertion.sample_label"; // $NON-NLS-1$
private static final String RESPONSE_DATA = "Assertion.response_data"; // $NON-NLS-1$
private static final String RESPONSE_DATA_AS_DOCUMENT = "Assertion.response_data_as_document"; // $NON-NLS-1$
private static final String RESPONSE_CODE = "Assertion.response_code"; // $NON-NLS-1$
private static final String RESPONSE_MESSAGE = "Assertion.response_message"; // $NON-NLS-1$
private static final String RESPONSE_HEADERS = "Assertion.response_headers"; // $NON-NLS-1$
private static final String REQUEST_HEADERS = "Assertion.request_headers"; // $NON-NLS-1$
private static final String REQUEST_DATA = "Assertion.request_data"; // $NON-NLS-1$
private static final String ASSUME_SUCCESS = "Assertion.assume_success"; // $NON-NLS-1$
private static final String TEST_STRINGS = "Asserion.test_strings"; // $NON-NLS-1$
private static final String TEST_TYPE = "Assertion.test_type"; // $NON-NLS-1$
private static final String CUSTOM_MESSAGE = "Assertion.custom_message"; // $NON-NLS-1$
/**
* Mask values for TEST_TYPE
* they are mutually exclusive
*/
private static final int MATCH = 1; // 1 << 0; // NOSONAR We want this comment
private static final int CONTAINS = 1 << 1;
private static final int NOT = 1 << 2;
private static final int EQUALS = 1 << 3;
private static final int SUBSTRING = 1 << 4;
private static final int OR = 1 << 5;
// Mask should contain all types (but not NOT nor OR)
private static final int TYPE_MASK = CONTAINS | EQUALS | MATCH | SUBSTRING;
private static final int EQUALS_SECTION_DIFF_LEN
= JMeterUtils.getPropDefault("assertion.equals_section_diff_len", 100);
/** Signifies truncated text in diff display. */
private static final String EQUALS_DIFF_TRUNC = "...";
private static final String RECEIVED_STR = "****** received : ";
private static final String COMPARISON_STR = "****** comparison: ";
private static final String DIFF_DELTA_START
= JMeterUtils.getPropDefault("assertion.equals_diff_delta_start", "[[[");
private static final String DIFF_DELTA_END
= JMeterUtils.getPropDefault("assertion.equals_diff_delta_end", "]]]");
public ResponseAssertion() {
setProperty(new CollectionProperty(TEST_STRINGS, new ArrayList<String>()));
}
@Override
public void clear() {
super.clear();
setProperty(new CollectionProperty(TEST_STRINGS, new ArrayList<String>()));
}
private void setTestField(String testField) {
setProperty(TEST_FIELD, testField);
}
public void setTestFieldURL(){
setTestField(SAMPLE_URL);
}
public void setTestFieldResponseCode(){
setTestField(RESPONSE_CODE);
}
public void setTestFieldResponseData(){
setTestField(RESPONSE_DATA);
}
public void setTestFieldResponseDataAsDocument(){
setTestField(RESPONSE_DATA_AS_DOCUMENT);
}
public void setTestFieldResponseMessage(){
setTestField(RESPONSE_MESSAGE);
}
public void setTestFieldResponseHeaders(){
setTestField(RESPONSE_HEADERS);
}
public void setTestFieldRequestHeaders() {
setTestField(REQUEST_HEADERS);
}
public void setTestFieldRequestData() {
setTestField(REQUEST_DATA);
}
public void setCustomFailureMessage(String customFailureMessage) {
setProperty(CUSTOM_MESSAGE, customFailureMessage);
}
public String getCustomFailureMessage() {
return getPropertyAsString(CUSTOM_MESSAGE);
}
public boolean isTestFieldURL(){
return SAMPLE_URL.equals(getTestField());
}
public boolean isTestFieldResponseCode(){
return RESPONSE_CODE.equals(getTestField());
}
public boolean isTestFieldResponseData(){
return RESPONSE_DATA.equals(getTestField());
}
public boolean isTestFieldResponseDataAsDocument() {
return RESPONSE_DATA_AS_DOCUMENT.equals(getTestField());
}
public boolean isTestFieldResponseMessage(){
return RESPONSE_MESSAGE.equals(getTestField());
}
public boolean isTestFieldResponseHeaders(){
return RESPONSE_HEADERS.equals(getTestField());
}
public boolean isTestFieldRequestHeaders(){
return REQUEST_HEADERS.equals(getTestField());
}
public boolean isTestFieldRequestData(){
return REQUEST_DATA.equals(getTestField());
}
private void setTestType(int testType) {
setProperty(new IntegerProperty(TEST_TYPE, testType));
}
private void setTestTypeMasked(int testType) {
int value = getTestType() & ~TYPE_MASK | testType;
setProperty(new IntegerProperty(TEST_TYPE, value));
}
public void addTestString(String testString) {
getTestStrings().addProperty(new StringProperty(String.valueOf(testString.hashCode()), testString));
}
public void clearTestStrings() {
getTestStrings().clear();
}
@Override
public AssertionResult getResult(SampleResult response) {
return evaluateResponse(response);
}
public String getTestField() {
return getPropertyAsString(TEST_FIELD);
}
public int getTestType() {
JMeterProperty type = getProperty(TEST_TYPE);
if (type instanceof NullProperty) {
return CONTAINS;
}
return type.getIntValue();
}
public CollectionProperty getTestStrings() {
return (CollectionProperty) getProperty(TEST_STRINGS);
}
public boolean isEqualsType() {
return (getTestType() & EQUALS) != 0;
}
public boolean isSubstringType() {
return (getTestType() & SUBSTRING) != 0;
}
public boolean isContainsType() {
return (getTestType() & CONTAINS) != 0;
}
public boolean isMatchType() {
return (getTestType() & MATCH) != 0;
}
public boolean isNotType() {
return (getTestType() & NOT) != 0;
}
public boolean isOrType() {
return (getTestType() & OR) != 0;
}
public void setToContainsType() {
setTestTypeMasked(CONTAINS);
}
public void setToMatchType() {
setTestTypeMasked(MATCH);
}
public void setToEqualsType() {
setTestTypeMasked(EQUALS);
}
public void setToSubstringType() {
setTestTypeMasked(SUBSTRING);
}
public void setToNotType() {
setTestType(getTestType() | NOT);
}
public void unsetNotType() {
setTestType(getTestType() & ~NOT);
}
public void setToOrType() {
setTestType(getTestType() | OR);
}
public void unsetOrType() {
setTestType(getTestType() & ~OR);
}
public boolean getAssumeSuccess() {
return getPropertyAsBoolean(ASSUME_SUCCESS, false);
}
public void setAssumeSuccess(boolean b) {
setProperty(ASSUME_SUCCESS, b);
}
/**
* Make sure the response satisfies the specified assertion requirements.
*
* @param response an instance of SampleResult
* @return an instance of AssertionResult
*/
private AssertionResult evaluateResponse(SampleResult response) {
AssertionResult result = new AssertionResult(getName());
if (getAssumeSuccess()) {
response.setSuccessful(true);// Allow testing of failure codes
}
String toCheck = getStringToCheck(response);
result.setFailure(false);
result.setError(false);
boolean notTest = (NOT & getTestType()) > 0;
boolean orTest = (OR & getTestType()) > 0;
boolean contains = isContainsType(); // do it once outside loop
boolean equals = isEqualsType();
boolean substring = isSubstringType();
boolean matches = isMatchType();
log.debug("Test Type Info: contains={}, notTest={}, orTest={}", contains, notTest, orTest);
if (StringUtils.isEmpty(toCheck)) {
if (notTest) { // Not should always succeed against an empty result
return result;
}
if (log.isDebugEnabled()) {
log.debug("Not checking empty response field in: {}", response.getSampleLabel());
}
return result.setResultForNull();
}
try {
// Get the Matcher for this thread
Perl5Matcher localMatcher = JMeterUtils.getMatcher();
boolean hasTrue = false;
List<String> allCheckMessage = new ArrayList<>();
for (JMeterProperty jMeterProperty : getTestStrings()) {
String stringPattern = jMeterProperty.getStringValue();
Pattern pattern = null;
if (contains || matches) {
pattern = JMeterUtils.getPatternCache().getPattern(stringPattern, Perl5Compiler.READ_ONLY_MASK);
}
boolean found;
if (contains) {
found = localMatcher.contains(toCheck, pattern);
} else if (equals) {
found = toCheck.equals(stringPattern);
} else if (substring) {
found = toCheck.contains(stringPattern);
} else {
found = localMatcher.matches(toCheck, pattern);
}
boolean pass = notTest ? !found : found;
if (orTest) {
if (!pass) {
log.debug("Failed: {}", stringPattern);
allCheckMessage.add(getFailText(stringPattern, toCheck));
} else {
hasTrue=true;
break;
}
} else {
if (!pass) {
log.debug("Failed: {}", stringPattern);
result.setFailure(true);
String customMsg = getCustomFailureMessage();
if (StringUtils.isEmpty(customMsg)) {
result.setFailureMessage(getFailText(stringPattern, toCheck));
} else {
result.setFailureMessage(customMsg);
}
break;
}
log.debug("Passed: {}", stringPattern);
}
}
if (orTest && !hasTrue){
StringBuilder errorMsg = new StringBuilder();
for(String tmp : allCheckMessage){
errorMsg.append(tmp).append('\t');
}
result.setFailure(true);
String customMsg = getCustomFailureMessage();
if (StringUtils.isEmpty(customMsg)) {
result.setFailureMessage(errorMsg.toString());
} else {
result.setFailureMessage(customMsg);
}
}
} catch (MalformedCachePatternException e) {
result.setError(true);
result.setFailure(false);
result.setFailureMessage("Bad test configuration " + e);
}
return result;
}
private String getStringToCheck(SampleResult response) {
String toCheck; // The string to check (Url or data)
// What are we testing against?
if (isScopeVariable()){
toCheck = getThreadContext().getVariables().get(getVariableName());
} else if (isTestFieldResponseData()) {
toCheck = response.getResponseDataAsString(); // (bug25052)
} else if (isTestFieldResponseDataAsDocument()) {
toCheck = Document.getTextFromDocument(response.getResponseData());
} else if (isTestFieldResponseCode()) {
toCheck = response.getResponseCode();
} else if (isTestFieldResponseMessage()) {
toCheck = response.getResponseMessage();
} else if (isTestFieldRequestHeaders()) {
toCheck = response.getRequestHeaders();
} else if (isTestFieldRequestData()) {
toCheck = response.getSamplerData();
} else if (isTestFieldResponseHeaders()) {
toCheck = response.getResponseHeaders();
} else { // Assume it is the URL
toCheck = "";
final URL url = response.getURL();
if (url != null){
toCheck = url.toString();
}
}
return toCheck;
}
/**
* Generate the failure reason from the TestType
*
* @param stringPattern
* @return the message for the assertion report
*/
private String getFailText(String stringPattern, String toCheck) {
StringBuilder sb = new StringBuilder(200);
sb.append("Test failed: ");
if (isScopeVariable()){
sb.append("variable(").append(getVariableName()).append(')');
} else if (isTestFieldResponseData()) {
sb.append("text");
} else if (isTestFieldResponseCode()) {
sb.append("code");
} else if (isTestFieldResponseMessage()) {
sb.append("message");
} else if (isTestFieldRequestHeaders()) {
sb.append("request headers");
} else if (isTestFieldRequestData()) {
sb.append("request data");
} else if (isTestFieldResponseHeaders()) {
sb.append("headers");
} else if (isTestFieldResponseDataAsDocument()) {
sb.append("document");
} else // Assume it is the URL
{
sb.append("URL");
}
switch (getTestType()) {
case CONTAINS:
case SUBSTRING:
sb.append(" expected to contain ");
break;
case NOT | CONTAINS:
case NOT | SUBSTRING:
sb.append(" expected not to contain ");
break;
case MATCH:
sb.append(" expected to match ");
break;
case NOT | MATCH:
sb.append(" expected not to match ");
break;
case EQUALS:
sb.append(" expected to equal ");
break;
case NOT | EQUALS:
sb.append(" expected not to equal ");
break;
default:// should never happen...
sb.append(" expected something using ");
}
sb.append("/");
if (isEqualsType()){
sb.append(equalsComparisonText(toCheck, stringPattern));
} else {
sb.append(stringPattern);
}
sb.append("/");
return sb.toString();
}
private static String trunc(final boolean right, final String str) {
if (str.length() <= EQUALS_SECTION_DIFF_LEN) {
return str;
} else if (right) {
return str.substring(0, EQUALS_SECTION_DIFF_LEN) + EQUALS_DIFF_TRUNC;
} else {
return EQUALS_DIFF_TRUNC + str.substring(str.length() - EQUALS_SECTION_DIFF_LEN, str.length());
}
}
/**
* Returns some helpful logging text to determine where equality between two strings
* is broken, with one pointer working from the front of the strings and another working
* backwards from the end.
*
* @param received String received from sampler.
* @param comparison String specified for "equals" response assertion.
* @return Two lines of text separated by newlines, and then forward and backward pointers
* denoting first position of difference.
*/
private static StringBuilder equalsComparisonText(final String received, final String comparison)
{
final int recLength = received.length();
final int compLength = comparison.length();
final int minLength = Math.min(recLength, compLength);
final StringBuilder text = new StringBuilder(Math.max(recLength, compLength) * 2);
int firstDiff;
for (firstDiff = 0; firstDiff < minLength; firstDiff++) {
if (received.charAt(firstDiff) != comparison.charAt(firstDiff)){
break;
}
}
final String startingEqSeq;
if (firstDiff == 0) {
startingEqSeq = "";
} else {
startingEqSeq = trunc(false, received.substring(0, firstDiff));
}
int lastRecDiff = recLength - 1;
int lastCompDiff = compLength - 1;
while ((lastRecDiff > firstDiff) && (lastCompDiff > firstDiff)
&& received.charAt(lastRecDiff) == comparison.charAt(lastCompDiff))
{
lastRecDiff--;
lastCompDiff--;
}
String compDeltaSeq;
String endingEqSeq = trunc(true, received.substring(lastRecDiff + 1, recLength));
String recDeltaSeq;
if (endingEqSeq.length() == 0) {
recDeltaSeq = trunc(true, received.substring(firstDiff, recLength));
compDeltaSeq = trunc(true, comparison.substring(firstDiff, compLength));
}
else {
recDeltaSeq = trunc(true, received.substring(firstDiff, lastRecDiff + 1));
compDeltaSeq = trunc(true, comparison.substring(firstDiff, lastCompDiff + 1));
}
final StringBuilder pad = new StringBuilder(Math.abs(recDeltaSeq.length() - compDeltaSeq.length()));
for (int i = 0; i < pad.capacity(); i++){
pad.append(' ');
}
if (recDeltaSeq.length() > compDeltaSeq.length()){
compDeltaSeq += pad.toString();
} else {
recDeltaSeq += pad.toString();
}
text.append("\n\n");
text.append(RECEIVED_STR);
text.append(startingEqSeq);
text.append(DIFF_DELTA_START);
text.append(recDeltaSeq);
text.append(DIFF_DELTA_END);
text.append(endingEqSeq);
text.append("\n\n");
text.append(COMPARISON_STR);
text.append(startingEqSeq);
text.append(DIFF_DELTA_START);
text.append(compDeltaSeq);
text.append(DIFF_DELTA_END);
text.append(endingEqSeq);
text.append("\n\n");
return text;
}
}
| src/components/org/apache/jmeter/assertions/ResponseAssertion.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.assertions;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.assertions.gui.AssertionGui;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.AbstractScopedAssertion;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.IntegerProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.NullProperty;
import org.apache.jmeter.testelement.property.StringProperty;
import org.apache.jmeter.util.Document;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.oro.text.MalformedCachePatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test element to handle Response Assertions.
* See {@link AssertionGui} for GUI.
*/
public class ResponseAssertion extends AbstractScopedAssertion implements Serializable, Assertion {
private static final Logger log = LoggerFactory.getLogger(ResponseAssertion.class);
private static final long serialVersionUID = 242L;
private static final String TEST_FIELD = "Assertion.test_field"; // $NON-NLS-1$
// Values for TEST_FIELD
// N.B. we cannot change the text value as it is in test plans
private static final String SAMPLE_URL = "Assertion.sample_label"; // $NON-NLS-1$
private static final String RESPONSE_DATA = "Assertion.response_data"; // $NON-NLS-1$
private static final String RESPONSE_DATA_AS_DOCUMENT = "Assertion.response_data_as_document"; // $NON-NLS-1$
private static final String RESPONSE_CODE = "Assertion.response_code"; // $NON-NLS-1$
private static final String RESPONSE_MESSAGE = "Assertion.response_message"; // $NON-NLS-1$
private static final String RESPONSE_HEADERS = "Assertion.response_headers"; // $NON-NLS-1$
private static final String REQUEST_HEADERS = "Assertion.request_headers"; // $NON-NLS-1$
private static final String REQUEST_DATA = "Assertion.request_data"; // $NON-NLS-1$
private static final String ASSUME_SUCCESS = "Assertion.assume_success"; // $NON-NLS-1$
private static final String TEST_STRINGS = "Asserion.test_strings"; // $NON-NLS-1$
private static final String TEST_TYPE = "Assertion.test_type"; // $NON-NLS-1$
private static final String CUSTOM_MESSAGE = "Assertion.custom_message"; // $NON-NLS-1$
/**
* Mask values for TEST_TYPE
* they are mutually exclusive
*/
private static final int MATCH = 1; // 1 << 0; // NOSONAR We want this comment
private static final int CONTAINS = 1 << 1;
private static final int NOT = 1 << 2;
private static final int EQUALS = 1 << 3;
private static final int SUBSTRING = 1 << 4;
private static final int OR = 1 << 5;
// Mask should contain all types (but not NOT nor OR)
private static final int TYPE_MASK = CONTAINS | EQUALS | MATCH | SUBSTRING;
private static final int EQUALS_SECTION_DIFF_LEN
= JMeterUtils.getPropDefault("assertion.equals_section_diff_len", 100);
/** Signifies truncated text in diff display. */
private static final String EQUALS_DIFF_TRUNC = "...";
private static final String RECEIVED_STR = "****** received : ";
private static final String COMPARISON_STR = "****** comparison: ";
private static final String DIFF_DELTA_START
= JMeterUtils.getPropDefault("assertion.equals_diff_delta_start", "[[[");
private static final String DIFF_DELTA_END
= JMeterUtils.getPropDefault("assertion.equals_diff_delta_end", "]]]");
public ResponseAssertion() {
setProperty(new CollectionProperty(TEST_STRINGS, new ArrayList<String>()));
}
@Override
public void clear() {
super.clear();
setProperty(new CollectionProperty(TEST_STRINGS, new ArrayList<String>()));
}
private void setTestField(String testField) {
setProperty(TEST_FIELD, testField);
}
public void setTestFieldURL(){
setTestField(SAMPLE_URL);
}
public void setTestFieldResponseCode(){
setTestField(RESPONSE_CODE);
}
public void setTestFieldResponseData(){
setTestField(RESPONSE_DATA);
}
public void setTestFieldResponseDataAsDocument(){
setTestField(RESPONSE_DATA_AS_DOCUMENT);
}
public void setTestFieldResponseMessage(){
setTestField(RESPONSE_MESSAGE);
}
public void setTestFieldResponseHeaders(){
setTestField(RESPONSE_HEADERS);
}
public void setTestFieldRequestHeaders() {
setTestField(REQUEST_HEADERS);
}
public void setTestFieldRequestData() {
setTestField(REQUEST_DATA);
}
public void setCustomFailureMessage(String customFailureMessage) {
setProperty(CUSTOM_MESSAGE, customFailureMessage);
}
public String getCustomFailureMessage() {
return getPropertyAsString(CUSTOM_MESSAGE);
}
public boolean isTestFieldURL(){
return SAMPLE_URL.equals(getTestField());
}
public boolean isTestFieldResponseCode(){
return RESPONSE_CODE.equals(getTestField());
}
public boolean isTestFieldResponseData(){
return RESPONSE_DATA.equals(getTestField());
}
public boolean isTestFieldResponseDataAsDocument() {
return RESPONSE_DATA_AS_DOCUMENT.equals(getTestField());
}
public boolean isTestFieldResponseMessage(){
return RESPONSE_MESSAGE.equals(getTestField());
}
public boolean isTestFieldResponseHeaders(){
return RESPONSE_HEADERS.equals(getTestField());
}
public boolean isTestFieldRequestHeaders(){
return REQUEST_HEADERS.equals(getTestField());
}
public boolean isTestFieldRequestData(){
return REQUEST_DATA.equals(getTestField());
}
private void setTestType(int testType) {
setProperty(new IntegerProperty(TEST_TYPE, testType));
}
private void setTestTypeMasked(int testType) {
int value = getTestType() & ~TYPE_MASK | testType;
setProperty(new IntegerProperty(TEST_TYPE, value));
}
public void addTestString(String testString) {
getTestStrings().addProperty(new StringProperty(String.valueOf(testString.hashCode()), testString));
}
public void clearTestStrings() {
getTestStrings().clear();
}
@Override
public AssertionResult getResult(SampleResult response) {
return evaluateResponse(response);
}
public String getTestField() {
return getPropertyAsString(TEST_FIELD);
}
public int getTestType() {
JMeterProperty type = getProperty(TEST_TYPE);
if (type instanceof NullProperty) {
return CONTAINS;
}
return type.getIntValue();
}
public CollectionProperty getTestStrings() {
return (CollectionProperty) getProperty(TEST_STRINGS);
}
public boolean isEqualsType() {
return (getTestType() & EQUALS) != 0;
}
public boolean isSubstringType() {
return (getTestType() & SUBSTRING) != 0;
}
public boolean isContainsType() {
return (getTestType() & CONTAINS) != 0;
}
public boolean isMatchType() {
return (getTestType() & MATCH) != 0;
}
public boolean isNotType() {
return (getTestType() & NOT) != 0;
}
public boolean isOrType() {
return (getTestType() & OR) != 0;
}
public void setToContainsType() {
setTestTypeMasked(CONTAINS);
}
public void setToMatchType() {
setTestTypeMasked(MATCH);
}
public void setToEqualsType() {
setTestTypeMasked(EQUALS);
}
public void setToSubstringType() {
setTestTypeMasked(SUBSTRING);
}
public void setToNotType() {
setTestType(getTestType() | NOT);
}
public void unsetNotType() {
setTestType(getTestType() & ~NOT);
}
public void setToOrType() {
setTestType(getTestType() | OR);
}
public void unsetOrType() {
setTestType(getTestType() & ~OR);
}
public boolean getAssumeSuccess() {
return getPropertyAsBoolean(ASSUME_SUCCESS, false);
}
public void setAssumeSuccess(boolean b) {
setProperty(ASSUME_SUCCESS, b);
}
/**
* Make sure the response satisfies the specified assertion requirements.
*
* @param response an instance of SampleResult
* @return an instance of AssertionResult
*/
private AssertionResult evaluateResponse(SampleResult response) {
AssertionResult result = new AssertionResult(getName());
if (getAssumeSuccess()) {
response.setSuccessful(true);// Allow testing of failure codes
}
String toCheck = getStringToCheck(response);
result.setFailure(false);
result.setError(false);
boolean notTest = (NOT & getTestType()) > 0;
boolean orTest = (OR & getTestType()) > 0;
boolean contains = isContainsType(); // do it once outside loop
boolean equals = isEqualsType();
boolean substring = isSubstringType();
boolean matches = isMatchType();
log.debug("Test Type Info: contains={}, notTest={}, orTest={}", contains, notTest, orTest);
if (StringUtils.isEmpty(toCheck)) {
if (notTest) { // Not should always succeed against an empty result
return result;
}
if (log.isDebugEnabled()) {
log.debug("Not checking empty response field in: {}", response.getSampleLabel());
}
return result.setResultForNull();
}
try {
// Get the Matcher for this thread
Perl5Matcher localMatcher = JMeterUtils.getMatcher();
boolean hasTrue = false;
List<String> allCheckMessage = new ArrayList<>();
for (JMeterProperty jMeterProperty : getTestStrings()) {
String stringPattern = jMeterProperty.getStringValue();
Pattern pattern = null;
if (contains || matches) {
pattern = JMeterUtils.getPatternCache().getPattern(stringPattern, Perl5Compiler.READ_ONLY_MASK);
}
boolean found;
if (contains) {
found = localMatcher.contains(toCheck, pattern);
} else if (equals) {
found = toCheck.equals(stringPattern);
} else if (substring) {
found = toCheck.contains(stringPattern);
} else {
found = localMatcher.matches(toCheck, pattern);
}
boolean pass = notTest ? !found : found;
if (orTest) {
if (!pass) {
log.debug("Failed: {}", stringPattern);
allCheckMessage.add(getFailText(stringPattern,toCheck));
} else {
hasTrue=true;
break;
}
} else {
if (!pass) {
log.debug("Failed: {}", stringPattern);
result.setFailure(true);
String customMsg = getCustomFailureMessage();
if (StringUtils.isEmpty(customMsg)) {
result.setFailureMessage(getFailText(stringPattern,toCheck));
} else {
result.setFailureMessage(customMsg);
}
break;
}
log.debug("Passed: {}", stringPattern);
}
}
if (orTest && !hasTrue){
StringBuilder errorMsg = new StringBuilder();
for(String tmp : allCheckMessage){
errorMsg.append(tmp).append('\t');
}
result.setFailure(true);
String customMsg = getCustomFailureMessage();
if (StringUtils.isEmpty(customMsg)) {
result.setFailureMessage(errorMsg.toString());
} else {
result.setFailureMessage(customMsg);
}
}
} catch (MalformedCachePatternException e) {
result.setError(true);
result.setFailure(false);
result.setFailureMessage("Bad test configuration " + e);
}
return result;
}
private String getStringToCheck(SampleResult response) {
String toCheck; // The string to check (Url or data)
// What are we testing against?
if (isScopeVariable()){
toCheck = getThreadContext().getVariables().get(getVariableName());
} else if (isTestFieldResponseData()) {
toCheck = response.getResponseDataAsString(); // (bug25052)
} else if (isTestFieldResponseDataAsDocument()) {
toCheck = Document.getTextFromDocument(response.getResponseData());
} else if (isTestFieldResponseCode()) {
toCheck = response.getResponseCode();
} else if (isTestFieldResponseMessage()) {
toCheck = response.getResponseMessage();
} else if (isTestFieldRequestHeaders()) {
toCheck = response.getRequestHeaders();
} else if (isTestFieldRequestData()) {
toCheck = response.getSamplerData();
} else if (isTestFieldResponseHeaders()) {
toCheck = response.getResponseHeaders();
} else { // Assume it is the URL
toCheck = "";
final URL url = response.getURL();
if (url != null){
toCheck = url.toString();
}
}
return toCheck;
}
/**
* Generate the failure reason from the TestType
*
* @param stringPattern
* @return the message for the assertion report
*/
private String getFailText(String stringPattern, String toCheck) {
StringBuilder sb = new StringBuilder(200);
sb.append("Test failed: ");
if (isScopeVariable()){
sb.append("variable(").append(getVariableName()).append(')');
} else if (isTestFieldResponseData()) {
sb.append("text");
} else if (isTestFieldResponseCode()) {
sb.append("code");
} else if (isTestFieldResponseMessage()) {
sb.append("message");
} else if (isTestFieldRequestHeaders()) {
sb.append("request headers");
} else if (isTestFieldRequestData()) {
sb.append("request data");
} else if (isTestFieldResponseHeaders()) {
sb.append("headers");
} else if (isTestFieldResponseDataAsDocument()) {
sb.append("document");
} else // Assume it is the URL
{
sb.append("URL");
}
switch (getTestType()) {
case CONTAINS:
case SUBSTRING:
sb.append(" expected to contain ");
break;
case NOT | CONTAINS:
case NOT | SUBSTRING:
sb.append(" expected not to contain ");
break;
case MATCH:
sb.append(" expected to match ");
break;
case NOT | MATCH:
sb.append(" expected not to match ");
break;
case EQUALS:
sb.append(" expected to equal ");
break;
case NOT | EQUALS:
sb.append(" expected not to equal ");
break;
default:// should never happen...
sb.append(" expected something using ");
}
sb.append("/");
if (isEqualsType()){
sb.append(equalsComparisonText(toCheck, stringPattern));
} else {
sb.append(stringPattern);
}
sb.append("/");
return sb.toString();
}
private static String trunc(final boolean right, final String str) {
if (str.length() <= EQUALS_SECTION_DIFF_LEN) {
return str;
} else if (right) {
return str.substring(0, EQUALS_SECTION_DIFF_LEN) + EQUALS_DIFF_TRUNC;
} else {
return EQUALS_DIFF_TRUNC + str.substring(str.length() - EQUALS_SECTION_DIFF_LEN, str.length());
}
}
/**
* Returns some helpful logging text to determine where equality between two strings
* is broken, with one pointer working from the front of the strings and another working
* backwards from the end.
*
* @param received String received from sampler.
* @param comparison String specified for "equals" response assertion.
* @return Two lines of text separated by newlines, and then forward and backward pointers
* denoting first position of difference.
*/
private static StringBuilder equalsComparisonText(final String received, final String comparison)
{
final int recLength = received.length();
final int compLength = comparison.length();
final int minLength = Math.min(recLength, compLength);
final StringBuilder text = new StringBuilder(Math.max(recLength, compLength) * 2);
int firstDiff;
for (firstDiff = 0; firstDiff < minLength; firstDiff++) {
if (received.charAt(firstDiff) != comparison.charAt(firstDiff)){
break;
}
}
final String startingEqSeq;
if (firstDiff == 0) {
startingEqSeq = "";
} else {
startingEqSeq = trunc(false, received.substring(0, firstDiff));
}
int lastRecDiff = recLength - 1;
int lastCompDiff = compLength - 1;
while ((lastRecDiff > firstDiff) && (lastCompDiff > firstDiff)
&& received.charAt(lastRecDiff) == comparison.charAt(lastCompDiff))
{
lastRecDiff--;
lastCompDiff--;
}
String compDeltaSeq;
String endingEqSeq = trunc(true, received.substring(lastRecDiff + 1, recLength));
String recDeltaSeq;
if (endingEqSeq.length() == 0) {
recDeltaSeq = trunc(true, received.substring(firstDiff, recLength));
compDeltaSeq = trunc(true, comparison.substring(firstDiff, compLength));
}
else {
recDeltaSeq = trunc(true, received.substring(firstDiff, lastRecDiff + 1));
compDeltaSeq = trunc(true, comparison.substring(firstDiff, lastCompDiff + 1));
}
final StringBuilder pad = new StringBuilder(Math.abs(recDeltaSeq.length() - compDeltaSeq.length()));
for (int i = 0; i < pad.capacity(); i++){
pad.append(' ');
}
if (recDeltaSeq.length() > compDeltaSeq.length()){
compDeltaSeq += pad.toString();
} else {
recDeltaSeq += pad.toString();
}
text.append("\n\n");
text.append(RECEIVED_STR);
text.append(startingEqSeq);
text.append(DIFF_DELTA_START);
text.append(recDeltaSeq);
text.append(DIFF_DELTA_END);
text.append(endingEqSeq);
text.append("\n\n");
text.append(COMPARISON_STR);
text.append(startingEqSeq);
text.append(DIFF_DELTA_START);
text.append(compDeltaSeq);
text.append(DIFF_DELTA_END);
text.append(endingEqSeq);
text.append("\n\n");
return text;
}
}
| Spacepolice
Part of #356 on Github. Contributed by Graham Russell (graham at ham1.co.uk)
git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1823997 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: ecaa91ffac2af6667e0c144160fa25692a1b91dc | src/components/org/apache/jmeter/assertions/ResponseAssertion.java | Spacepolice |
|
Java | apache-2.0 | 453ae6335d2156f89d5dc4f6fcfc4359f31fac2c | 0 | caelum/vraptor4,Philippe2201/vraptor4,michelmedeiros/vraptor4,nykolaslima/vraptor4,clebersonpp/vraptor4,Jonss/vraptor4,nykolaslima/vraptor4,nykolaslima/vraptor4,tempbottle/vraptor4,garcia-jj/vraptor4-fork,Knoobie/vraptor4,khajavi/vraptor4,khajavi/vraptor4,michelmedeiros/vraptor4,rpeleias/vraptor4,garcia-jj/vraptor4-fork,caelum/vraptor4,rpeleias/vraptor4,felipeweb/vraptor4,Jonss/vraptor4,danilomunoz/vraptor4,caelum/vraptor4,felipeweb/vraptor4,Knoobie/vraptor4,Knoobie/vraptor4,danilomunoz/vraptor4,danilomunoz/vraptor4,danilomunoz/vraptor4,rpeleias/vraptor4,Philippe2201/vraptor4,felipeweb/vraptor4,Jonss/vraptor4,khajavi/vraptor4,caelum/vraptor4,Philippe2201/vraptor4,nykolaslima/vraptor4,Philippe2201/vraptor4,khajavi/vraptor4,nykolaslima/vraptor4,Jonss/vraptor4,garcia-jj/vraptor4-fork,danilomunoz/vraptor4,clebersonpp/vraptor4,felipeweb/vraptor4,clebersonpp/vraptor4,clebersonpp/vraptor4,garcia-jj/vraptor4-fork,michelmedeiros/vraptor4,khajavi/vraptor4,rpeleias/vraptor4,rpeleias/vraptor4,tempbottle/vraptor4,Knoobie/vraptor4,caelum/vraptor4,felipeweb/vraptor4,michelmedeiros/vraptor4,tempbottle/vraptor4,Jonss/vraptor4,Knoobie/vraptor4,michelmedeiros/vraptor4,Philippe2201/vraptor4,tempbottle/vraptor4,tempbottle/vraptor4,clebersonpp/vraptor4,garcia-jj/vraptor4-fork | package br.com.caelum.vraptor.interceptor;
import java.lang.reflect.Method;
import javax.inject.Inject;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.MethodInfo;
import br.com.caelum.vraptor.http.ParameterNameProvider;
import br.com.caelum.vraptor4.BeforeCall;
import br.com.caelum.vraptor4.controller.ControllerMethod;
@Intercepts(
before=ExecuteMethodInterceptor.class,
after=ParametersInstantiatorInterceptor.class
)
public class ReturnParamInterceptor {
@Inject private MethodInfo info;
@Inject private Result result;
@Inject private ParameterNameProvider nameProvider;
@BeforeCall
public void intercept(ControllerMethod cmethod) {
Object[] parameters = info.getParameters();
Method method = cmethod.getMethod();
String[] names = nameProvider.parameterNamesFor(method);
for(int i=0; i< names.length; i++) {
result.include(names[i], parameters[i]);
}
}
} | vraptor-core/src/main/java/br/com/caelum/vraptor/interceptor/ReturnParamInterceptor.java | package br.com.caelum.vraptor.interceptor;
import javax.inject.Inject;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.MethodInfo;
import br.com.caelum.vraptor.http.ParameterNameProvider;
import br.com.caelum.vraptor4.BeforeCall;
import br.com.caelum.vraptor4.controller.ControllerMethod;
@Intercepts(
before=ExecuteMethodInterceptor.class,
after=ParametersInstantiatorInterceptor.class
)
public class ReturnParamInterceptor {
@Inject private MethodInfo info;
@Inject private Result result;
@Inject private ParameterNameProvider nameProvider;
@BeforeCall
public void intercept(ControllerMethod method) {
Object[] parameters = info.getParameters();
String[] names = nameProvider.parameterNamesFor(method.getMethod());
for(int i=0; i< names.length; i++) {
result.include(names[i], parameters[i]);
}
}
} | extracting local variable
| vraptor-core/src/main/java/br/com/caelum/vraptor/interceptor/ReturnParamInterceptor.java | extracting local variable |
|
Java | apache-2.0 | 36e701b567c45e984828eaa067d2da83d2ae1217 | 0 | sopel39/presto,smartnews/presto,martint/presto,prestodb/presto,shixuan-fan/presto,11xor6/presto,raghavsethi/presto,raghavsethi/presto,shixuan-fan/presto,Praveen2112/presto,wyukawa/presto,zzhao0/presto,mvp/presto,raghavsethi/presto,arhimondr/presto,dain/presto,twitter-forks/presto,Yaliang/presto,losipiuk/presto,sopel39/presto,youngwookim/presto,prestodb/presto,11xor6/presto,miniway/presto,hgschmie/presto,mvp/presto,prestodb/presto,losipiuk/presto,haozhun/presto,ptkool/presto,ebyhr/presto,sopel39/presto,zzhao0/presto,treasure-data/presto,losipiuk/presto,nezihyigitbasi/presto,mvp/presto,ebyhr/presto,martint/presto,haozhun/presto,ptkool/presto,shixuan-fan/presto,mvp/presto,Praveen2112/presto,prestodb/presto,electrum/presto,zzhao0/presto,arhimondr/presto,treasure-data/presto,dain/presto,wyukawa/presto,Yaliang/presto,mvp/presto,stewartpark/presto,losipiuk/presto,erichwang/presto,nezihyigitbasi/presto,sopel39/presto,martint/presto,wyukawa/presto,erichwang/presto,youngwookim/presto,facebook/presto,sopel39/presto,treasure-data/presto,hgschmie/presto,Praveen2112/presto,erichwang/presto,treasure-data/presto,EvilMcJerkface/presto,11xor6/presto,smartnews/presto,nezihyigitbasi/presto,miniway/presto,ebyhr/presto,martint/presto,stewartpark/presto,Praveen2112/presto,smartnews/presto,facebook/presto,facebook/presto,haozhun/presto,electrum/presto,arhimondr/presto,youngwookim/presto,zzhao0/presto,ptkool/presto,haozhun/presto,miniway/presto,Yaliang/presto,wyukawa/presto,ptkool/presto,hgschmie/presto,arhimondr/presto,youngwookim/presto,twitter-forks/presto,stewartpark/presto,hgschmie/presto,EvilMcJerkface/presto,haozhun/presto,EvilMcJerkface/presto,prestodb/presto,raghavsethi/presto,treasure-data/presto,Yaliang/presto,treasure-data/presto,nezihyigitbasi/presto,facebook/presto,dain/presto,prestodb/presto,Praveen2112/presto,facebook/presto,nezihyigitbasi/presto,EvilMcJerkface/presto,Yaliang/presto,wyukawa/presto,erichwang/presto,raghavsethi/presto,smartnews/presto,twitter-forks/presto,EvilMcJerkface/presto,martint/presto,dain/presto,ptkool/presto,youngwookim/presto,electrum/presto,arhimondr/presto,electrum/presto,hgschmie/presto,smartnews/presto,dain/presto,electrum/presto,ebyhr/presto,twitter-forks/presto,11xor6/presto,11xor6/presto,shixuan-fan/presto,miniway/presto,erichwang/presto,losipiuk/presto,shixuan-fan/presto,twitter-forks/presto,stewartpark/presto,miniway/presto,stewartpark/presto,zzhao0/presto,ebyhr/presto | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.connector.thrift.util;
import com.facebook.presto.connector.thrift.api.PrestoThriftServiceException;
import com.facebook.presto.spi.PrestoException;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.drift.TApplicationException;
import io.airlift.drift.TException;
import io.airlift.drift.protocol.TTransportException;
import static com.facebook.presto.connector.thrift.ThriftErrorCode.THRIFT_SERVICE_CONNECTION_ERROR;
import static com.facebook.presto.connector.thrift.ThriftErrorCode.THRIFT_SERVICE_GENERIC_REMOTE_ERROR;
import static com.facebook.presto.connector.thrift.ThriftErrorCode.THRIFT_SERVICE_NO_AVAILABLE_HOSTS;
import static com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static com.google.common.util.concurrent.Futures.catchingAsync;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
public final class ThriftExceptions
{
private ThriftExceptions() {}
public static PrestoException toPrestoException(Exception e)
{
if ((e instanceof TTransportException) && "No hosts available".equals(e.getMessage())) {
throw new PrestoException(THRIFT_SERVICE_NO_AVAILABLE_HOSTS, e);
}
if ((e instanceof TApplicationException) || (e instanceof PrestoThriftServiceException)) {
return new PrestoException(THRIFT_SERVICE_GENERIC_REMOTE_ERROR, "Exception raised by remote Thrift server: " + e.getMessage(), e);
}
if (e instanceof TException) {
return new PrestoException(THRIFT_SERVICE_CONNECTION_ERROR, "Error communicating with remote Thrift server", e);
}
throw new PrestoException(GENERIC_INTERNAL_ERROR, e);
}
public static <T> ListenableFuture<T> catchingThriftException(ListenableFuture<T> future)
{
return catchingAsync(future, Exception.class, e -> immediateFailedFuture(toPrestoException(e)));
}
}
| presto-thrift-connector/src/main/java/com/facebook/presto/connector/thrift/util/ThriftExceptions.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.connector.thrift.util;
import com.facebook.presto.connector.thrift.api.PrestoThriftServiceException;
import com.facebook.presto.spi.PrestoException;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.drift.TApplicationException;
import io.airlift.drift.TException;
import io.airlift.drift.protocol.TTransportException;
import static com.facebook.presto.connector.thrift.ThriftErrorCode.THRIFT_SERVICE_CONNECTION_ERROR;
import static com.facebook.presto.connector.thrift.ThriftErrorCode.THRIFT_SERVICE_GENERIC_REMOTE_ERROR;
import static com.facebook.presto.connector.thrift.ThriftErrorCode.THRIFT_SERVICE_NO_AVAILABLE_HOSTS;
import static com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static com.google.common.util.concurrent.Futures.catchingAsync;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
public final class ThriftExceptions
{
private ThriftExceptions() {}
public static PrestoException toPrestoException(Exception e)
{
if ((e instanceof TTransportException) && "No hosts available".equals(e.getMessage())) {
throw new PrestoException(THRIFT_SERVICE_NO_AVAILABLE_HOSTS, e);
}
if ((e instanceof TApplicationException) || (e instanceof PrestoThriftServiceException)) {
return new PrestoException(THRIFT_SERVICE_GENERIC_REMOTE_ERROR, "Exception raised by remote Thrift server", e);
}
if (e instanceof TException) {
return new PrestoException(THRIFT_SERVICE_CONNECTION_ERROR, "Error communicating with remote Thrift server", e);
}
throw new PrestoException(GENERIC_INTERNAL_ERROR, e);
}
public static <T> ListenableFuture<T> catchingThriftException(ListenableFuture<T> future)
{
return catchingAsync(future, Exception.class, e -> immediateFailedFuture(toPrestoException(e)));
}
}
| Append original error message to thrift connector remote exception
| presto-thrift-connector/src/main/java/com/facebook/presto/connector/thrift/util/ThriftExceptions.java | Append original error message to thrift connector remote exception |
|
Java | apache-2.0 | 9bd07f5b833a2e95d0be04d4b3685ff89148c8fa | 0 | buybackoff/Aeron,real-logic/Aeron,mikeb01/Aeron,mikeb01/Aeron,tbrooks8/Aeron,real-logic/Aeron,oleksiyp/Aeron,EvilMcJerkface/Aeron,oleksiyp/Aeron,real-logic/Aeron,jerrinot/Aeron,mikeb01/Aeron,galderz/Aeron,UIKit0/Aeron,real-logic/Aeron,lennartj/Aeron,lennartj/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,UIKit0/Aeron,tbrooks8/Aeron,jerrinot/Aeron,UIKit0/Aeron,gkamal/Aeron,buybackoff/Aeron,tbrooks8/Aeron,jerrinot/Aeron,galderz/Aeron,galderz/Aeron,RussellWilby/Aeron,gkamal/Aeron,mikeb01/Aeron,lennartj/Aeron,RussellWilby/Aeron,buybackoff/Aeron,RussellWilby/Aeron,oleksiyp/Aeron,EvilMcJerkface/Aeron,galderz/Aeron,gkamal/Aeron | /*
* Copyright 2014 - 2015 Real Logic 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 uk.co.real_logic.aeron;
import uk.co.real_logic.aeron.logbuffer.FragmentHandler;
import uk.co.real_logic.agrona.ErrorHandler;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* Aeron Subscriber API for receiving messages from publishers on a given channel and streamId pair.
* Subscribers are created via an {@link Aeron} object, and received messages are delivered
* to the {@link FragmentHandler}.
* <p>
* By default fragmented messages are not reassembled before delivery. If an application must
* receive whole messages, whether or not they were fragmented, then the Subscriber
* should be created with a {@link FragmentAssemblyAdapter} or a custom implementation.
* <p>
* It is an applications responsibility to {@link #poll} the Subscriber for new messages.
* <p>
* Subscriptions are not threadsafe and should not be shared between subscribers.
*
* @see FragmentAssemblyAdapter
*/
public class Subscription implements AutoCloseable
{
private static final int TRUE = 1;
private static final int FALSE = 0;
private static final Connection[] EMPTY_ARRAY = new Connection[0];
private static final AtomicIntegerFieldUpdater<Subscription> IS_CLOSED_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(Subscription.class, "isClosed");
private final long registrationId;
private final int streamId;
private int roundRobinIndex = 0;
private volatile int isClosed = FALSE;
private final String channel;
private final ClientConductor clientConductor;
private final ErrorHandler errorHandler;
private volatile Connection[] connections = EMPTY_ARRAY;
Subscription(
final ClientConductor conductor,
final String channel,
final int streamId,
final long registrationId,
final ErrorHandler errorHandler)
{
this.clientConductor = conductor;
this.channel = channel;
this.streamId = streamId;
this.registrationId = registrationId;
this.errorHandler = errorHandler;
}
/**
* Media address for delivery to the channel.
*
* @return Media address for delivery to the channel.
*/
public String channel()
{
return channel;
}
/**
* Stream identity for scoping within the channel media address.
*
* @return Stream identity for scoping within the channel media address.
*/
public int streamId()
{
return streamId;
}
/**
* Each fragment read will be a whole message if it is under MTU length. If larger than MTU then it will come
* as a series of fragments ordered withing a session.
*
* @param fragmentHandler callback for handling each message fragment as it is read.
* @param fragmentLimit number of message fragments to limit for a single poll operation.
* @return the number of fragments received
* @throws IllegalStateException if the subscription is closed.
*/
public int poll(final FragmentHandler fragmentHandler, final int fragmentLimit)
{
ensureOpen();
final Connection[] connections = this.connections;
final int length = connections.length;
int fragmentsRead = 0;
if (length > 0)
{
int startingIndex = roundRobinIndex++;
if (startingIndex >= length)
{
roundRobinIndex = startingIndex = 0;
}
int i = startingIndex;
final ErrorHandler errorHandler = this.errorHandler;
do
{
fragmentsRead += connections[i].poll(fragmentHandler, fragmentLimit, errorHandler);
if (++i == length)
{
i = 0;
}
}
while (fragmentsRead < fragmentLimit && i != startingIndex);
}
return fragmentsRead;
}
/**
* Close the Subscription so that associated buffers can be released.
*
* This method is idempotent.
*/
public void close()
{
if (IS_CLOSED_UPDATER.compareAndSet(this, FALSE, TRUE))
{
synchronized (clientConductor)
{
for (final Connection connection : connections)
{
clientConductor.lingerResource(connection);
}
connections = EMPTY_ARRAY;
clientConductor.releaseSubscription(this);
}
}
}
long registrationId()
{
return registrationId;
}
void addConnection(final Connection connection)
{
final Connection[] oldArray = connections;
final int oldLength = oldArray.length;
final Connection[] newArray = new Connection[oldLength + 1];
System.arraycopy(oldArray, 0, newArray, 0, oldLength);
newArray[oldLength] = connection;
connections = newArray;
}
boolean removeConnection(final long correlationId)
{
final Connection[] oldArray = connections;
final int oldLength = oldArray.length;
Connection removedConnection = null;
int index = -1;
for (int i = 0; i < oldLength; i++)
{
if (oldArray[i].correlationId() == correlationId)
{
index = i;
removedConnection = oldArray[i];
}
}
if (null != removedConnection)
{
final int newLength = oldLength - 1;
final Connection[] newArray = new Connection[newLength];
System.arraycopy(oldArray, 0, newArray, 0, index);
System.arraycopy(oldArray, index + 1, newArray, index, newLength - index);
connections = newArray;
clientConductor.lingerResource(removedConnection);
return true;
}
return false;
}
boolean isConnected(final int sessionId)
{
boolean isConnected = false;
for (final Connection connection : connections)
{
if (sessionId == connection.sessionId())
{
isConnected = true;
break;
}
}
return isConnected;
}
boolean hasNoConnections()
{
return connections.length == 0;
}
private void ensureOpen()
{
if (TRUE == isClosed)
{
throw new IllegalStateException(String.format(
"Subscription is closed: channel=%s streamId=%d registrationId=%d", channel, streamId, registrationId));
}
}
}
| aeron-client/src/main/java/uk/co/real_logic/aeron/Subscription.java | /*
* Copyright 2014 - 2015 Real Logic 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 uk.co.real_logic.aeron;
import uk.co.real_logic.aeron.logbuffer.FragmentHandler;
import uk.co.real_logic.agrona.ErrorHandler;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* Aeron Subscriber API for receiving messages from publishers on a given channel and streamId pair.
* Subscribers are created via an {@link Aeron} object, and received messages are delivered
* to the {@link FragmentHandler}.
* <p>
* By default fragmented messages are not reassembled before delivery. If an application must
* receive whole messages, whether or not they were fragmented, then the Subscriber
* should be created with a {@link FragmentAssemblyAdapter} or a custom implementation.
* <p>
* It is an applications responsibility to {@link #poll} the Subscriber for new messages.
* <p>
* Subscriptions are not threadsafe and should not be shared between subscribers.
*
* @see FragmentAssemblyAdapter
*/
public class Subscription implements AutoCloseable
{
private static final int TRUE = 1;
private static final int FALSE = 0;
private static final Connection[] EMPTY_ARRAY = new Connection[0];
private static final AtomicIntegerFieldUpdater<Subscription> IS_CLOSED_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(Subscription.class, "isClosed");
private final long registrationId;
private final int streamId;
private int roundRobinIndex = 0;
private volatile int isClosed = FALSE;
private final String channel;
private final ClientConductor clientConductor;
private final ErrorHandler errorHandler;
private volatile Connection[] connections = EMPTY_ARRAY;
Subscription(
final ClientConductor conductor,
final String channel,
final int streamId,
final long registrationId,
final ErrorHandler errorHandler)
{
this.clientConductor = conductor;
this.channel = channel;
this.streamId = streamId;
this.registrationId = registrationId;
this.errorHandler = errorHandler;
}
/**
* Media address for delivery to the channel.
*
* @return Media address for delivery to the channel.
*/
public String channel()
{
return channel;
}
/**
* Stream identity for scoping within the channel media address.
*
* @return Stream identity for scoping within the channel media address.
*/
public int streamId()
{
return streamId;
}
/**
* Each fragment read will be a whole message if it is under MTU length. If larger than MTU then it will come
* as a series of fragments ordered withing a session.
*
* @param fragmentHandler callback for handling each message fragment as it is read.
* @param fragmentLimit number of message fragments to limit for a single poll operation.
* @return the number of fragments received
* @throws IllegalStateException if the subscription is closed.
*/
public int poll(final FragmentHandler fragmentHandler, final int fragmentLimit)
{
ensureOpen();
final Connection[] connections = this.connections;
final int length = connections.length;
int fragmentsRead = 0;
if (length > 0)
{
int startingIndex = roundRobinIndex++;
if (startingIndex >= length)
{
roundRobinIndex = startingIndex = 0;
}
int i = startingIndex;
final ErrorHandler errorHandler = this.errorHandler;
do
{
fragmentsRead += connections[i].poll(fragmentHandler, fragmentLimit, errorHandler);
if (++i == length)
{
i = 0;
}
}
while (fragmentsRead < fragmentLimit && i != startingIndex);
}
return fragmentsRead;
}
/**
* Close the Subscription so that associated buffers can be released.
*
* This method is idempotent.
*/
public void close()
{
if (IS_CLOSED_UPDATER.compareAndSet(this, FALSE, TRUE))
{
synchronized (clientConductor)
{
for (final Connection connection : connections)
{
clientConductor.lingerResource(connection);
}
connections = EMPTY_ARRAY;
clientConductor.releaseSubscription(this);
}
}
}
long registrationId()
{
return registrationId;
}
void addConnection(final Connection connection)
{
final Connection[] oldArray = connections;
final int oldLength = oldArray.length;
final Connection[] newArray = new Connection[oldLength + 1];
System.arraycopy(oldArray, 0, newArray, 0, oldLength);
newArray[oldLength] = connection;
connections = newArray;
}
boolean removeConnection(final long correlationId)
{
final Connection[] oldArray = connections;
final int oldLength = oldArray.length;
Connection removedConnection = null;
int index = -1;
for (int i = 0; i < oldLength; i++)
{
if (oldArray[i].correlationId() == correlationId)
{
index = i;
removedConnection = oldArray[i];
}
}
if (null != removedConnection)
{
final int newSize = oldLength - 1;
final Connection[] newArray = new Connection[newSize];
System.arraycopy(oldArray, 0, newArray, 0, index);
System.arraycopy(oldArray, index + 1, newArray, index, newSize - index);
connections = newArray;
clientConductor.lingerResource(removedConnection);
return true;
}
return false;
}
boolean isConnected(final int sessionId)
{
boolean isConnected = false;
for (final Connection connection : connections)
{
if (sessionId == connection.sessionId())
{
isConnected = true;
break;
}
}
return isConnected;
}
boolean hasNoConnections()
{
return connections.length == 0;
}
private void ensureOpen()
{
if (TRUE == isClosed)
{
throw new IllegalStateException(String.format(
"Subscription is closed: channel=%s streamId=%d registrationId=%d", channel, streamId, registrationId));
}
}
}
| [Java]: Naming.
| aeron-client/src/main/java/uk/co/real_logic/aeron/Subscription.java | [Java]: Naming. |
|
Java | apache-2.0 | 06803648cd16672f8875846b29fd6c3c5f5c0489 | 0 | xqbase/ddns,xqbase/ddns | package com.xqbase.ddns;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.xbill.DNS.AAAARecord;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.CNAMERecord;
import org.xbill.DNS.DClass;
import org.xbill.DNS.Flags;
import org.xbill.DNS.Header;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.Message;
import org.xbill.DNS.NSRecord;
import org.xbill.DNS.Name;
import org.xbill.DNS.Opcode;
import org.xbill.DNS.Rcode;
import org.xbill.DNS.Record;
import org.xbill.DNS.Section;
import org.xbill.DNS.Type;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.xqbase.metric.client.ManagementMonitor;
import com.xqbase.metric.client.MetricClient;
import com.xqbase.metric.common.Metric;
import com.xqbase.util.ByteArrayQueue;
import com.xqbase.util.Bytes;
import com.xqbase.util.Conf;
import com.xqbase.util.Log;
import com.xqbase.util.Numbers;
import com.xqbase.util.Runnables;
import com.xqbase.util.Service;
import com.xqbase.util.Time;
import com.xqbase.util.http.HttpPool;
class DataEntry {
SocketAddress addr;
byte[] data;
DataEntry(SocketAddress addr, byte[] data) {
this.addr = addr;
this.data = data;
}
}
public class DDNS {
private static final Record[] EMPTY_RECORDS = new Record[0];
private static ConcurrentHashMap<String, Record[]>
aDynamics = new ConcurrentHashMap<>();
private static HashMap<String, Record[]>
aRecords = new HashMap<>(), aWildcards = new HashMap<>(),
nsRecords = new HashMap<>(), mxRecords = new HashMap<>();
private static ArrayList<InetSocketAddress> dnss = new ArrayList<>();
private static LinkedBlockingQueue<DataEntry> dataQueue = new LinkedBlockingQueue<>();
private static Service service = new Service();
private static Properties dynamicRecords;
private static HashMap<String, Integer> countMap = new HashMap<>();
private static long propAccessed = 0, dosAccessed = 0;
private static int propPeriod, dosPeriod, dosRequests;
private static boolean verbose = false;
private static void updateRecords(Map<String, Record[]> records,
String host, String value, int ttl) throws IOException {
Name origin = new Name((host.endsWith(".") ? host : host + ".").replace('_', '-'));
ArrayList<Record> recordList = new ArrayList<>();
for (String s : value.split("[,;]")) {
if (s.matches(".*[A-Z|a-z].*")) {
CNAMERecord record = new CNAMERecord(origin, DClass.IN, ttl,
new Name(s.endsWith(".") ? s : s + "."));
recordList.add(record);
continue;
}
String[] ss = s.split("\\.");
if (ss.length < 4) {
continue;
}
byte[] ip = new byte[4];
for (int i = 0; i < 4; i ++) {
ip[i] = (byte) Numbers.parseInt(ss[i]);
}
recordList.add(new ARecord(origin, DClass.IN,
ttl, InetAddress.getByAddress(ip)));
}
if (!recordList.isEmpty()) {
records.put(host, recordList.toArray(EMPTY_RECORDS));
}
}
private static void updateDynamics(HttpPool addrApi, int ttl) {
ByteArrayQueue body = new ByteArrayQueue();
try {
if (addrApi.get("", null, body, null) >= 400) {
Log.w(body.toString());
return;
}
} catch (IOException e) {
Log.e(e);
return;
}
try {
JSONObject map = new JSONObject(body.toString());
Iterator<?> it = map.keys();
while (it.hasNext()) {
String host = (String) it.next();
String addr = map.optString(host);
if (addr != null) {
updateRecords(aDynamics, host, addr, ttl);
}
}
} catch (IOException | JSONException e) {
Log.e(e);
}
}
private static void loadProp() {
aRecords.clear();
aWildcards.clear();
nsRecords.clear();
mxRecords.clear();
Properties p = Conf.load("DDNS");
verbose = Conf.getBoolean(p.getProperty("verbose"), false);
int mxPriority = Numbers.parseInt(p.getProperty("priority.mx"), 10);
int staticTtl = Numbers.parseInt(p.getProperty("ttl.static"), 3600);
for (Map.Entry<?, ?> entry : p.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
try {
if (key.startsWith("ns_")) {
String host = key.substring(3);
Name origin = new Name(host.endsWith(".") ? host : host + ".");
ArrayList<Record> records = new ArrayList<>();
for (String target : value.split("[,;]")) {
records.add(new NSRecord(origin, DClass.IN, staticTtl,
new Name(target.endsWith(".") ? target : target + ".")));
}
if (!records.isEmpty()) {
nsRecords.put(host, records.toArray(EMPTY_RECORDS));
}
continue;
}
if (key.startsWith("mx_")) {
String host = key.substring(3);
Name origin = new Name(host.endsWith(".") ? host : host + ".");
ArrayList<Record> records = new ArrayList<>();
for (String target : value.split("[,;]")) {
records.add(new MXRecord(origin, DClass.IN, staticTtl, mxPriority,
new Name(target.endsWith(".") ? target : target + ".")));
}
if (!records.isEmpty()) {
mxRecords.put(host, records.toArray(EMPTY_RECORDS));
}
continue;
}
if (!key.startsWith("a_")) {
continue;
}
String host = key.substring(2);
if (host.startsWith("*.")) {
updateRecords(aWildcards, host.substring(2), value, staticTtl);
} else {
updateRecords(aRecords, host, value, staticTtl);
}
} catch (IOException e) {
Log.e(e);
}
}
}
private static boolean blocked(String ip) {
if (dosPeriod == 0 || dosRequests == 0) {
return false;
}
long now = System.currentTimeMillis();
if (now > dosAccessed + dosPeriod) {
countMap.clear();
dosAccessed = now;
}
Integer count_ = countMap.get(ip);
int count = (count_ == null ? 0 : count_.intValue());
count ++;
countMap.put(ip, Integer.valueOf(count));
if (count < dosRequests) {
// Remote IP Blocked
return false;
}
if (count % dosRequests == 0) {
Log.w("DoS Attack from " + ip + ", requests = " + count);
}
return true;
}
private static void dump(DatagramPacket packet, boolean send) {
if (!verbose) {
return;
}
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
out.println((send ? "Sent to " : "Received from ") +
packet.getAddress().getHostAddress());
byte[] data = Bytes.sub(packet.getData(), packet.getOffset(), packet.getLength());
Bytes.dump(out, data);
try {
out.println(new Message(data));
} catch (IOException e) {
out.println(e.getMessage());
}
Log.d(sw.toString());
}
private static Record[] resolveWildcard(Map<String, Record[]>
wildcards, String host, String[] domain) {
String host_ = host;
Record[] records = wildcards.get(host_);
while (records == null) {
int dot = host_.indexOf('.');
if (dot < 0) {
break;
}
host_ = host_.substring(dot + 1);
if (host_.isEmpty()) {
break;
}
records = wildcards.get(host_);
}
if (records != null && domain[0] == null) {
domain[0] = "*." + host_;
}
return records;
}
private static Message service(Message request, String[] domain) {
// Check Request Validity
Header header = request.getHeader();
if (header.getFlag(Flags.QR)) {
return null;
}
header.setFlag(Flags.QR);
Record question = request.getQuestion();
if (header.getRcode() != Rcode.NOERROR) {
header.setRcode(Rcode.FORMERR);
return request;
}
if (header.getOpcode() != Opcode.QUERY) {
header.setRcode(Rcode.NOTIMP);
return request;
}
// Get ANSWER Records
String host = question.getName().toString(true).toLowerCase();
Record[] answers;
int type = question.getType();
switch (type) {
case Type.A:
case Type.AAAA:
case Type.CNAME:
case Type.ANY:
answers = aRecords.get(host);
if (answers != null) {
domain[0] = host;
break;
}
answers = resolveWildcard(aWildcards, host, domain);
if (answers == null) {
answers = aDynamics.get(host);
break;
}
// Set name for wildcard
Name name;
try {
name = new Name(host.endsWith(".") ? host : host + ".");
} catch (IOException e) {
Log.w(e.getMessage());
break;
}
// Do not pollute "aWildcards"
Record[] cloned = new Record[answers.length];
for (int i = 0; i < answers.length; i ++) {
Record record = answers[i];
int dclass = record.getDClass();
long ttl = record.getTTL();
if (record instanceof ARecord) {
cloned[i] = new ARecord(name, dclass, ttl,
((ARecord) record).getAddress());
} else if (record instanceof CNAMERecord) {
cloned[i] = new CNAMERecord(name, dclass, ttl,
((CNAMERecord) record).getTarget());
} else {
Log.e("Not A or CNAME: " + answers[i]);
cloned[i] = answers[i];
}
}
answers = cloned;
break;
case Type.NS:
case Type.MX:
answers = (type == Type.NS ? nsRecords : mxRecords).get(host);
if (answers != null) {
domain[0] = host;
}
break;
default:
header.setRcode(Rcode.NOTIMP);
return request;
}
// AAAA: Convert IPv4 to IPv6
if (type == Type.AAAA && answers != null) {
// Do not pollute "aRecords", "aWildcards" or "aDynamics"
Record[] cloned = new Record[answers.length];
for (int i = 0; i < answers.length; i ++) {
Record record = cloned[i] = answers[i];
if (!(record instanceof ARecord)) {
continue;
}
InetAddress addr = ((ARecord) record).getAddress();
if (!(addr instanceof Inet4Address)) {
continue;
}
byte[] ip = ((Inet4Address) addr).getAddress();
try {
addr = Inet6Address.getByAddress(null,
new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1,
ip[0], ip[1], ip[2], ip[3]}, null);
cloned[i] = new AAAARecord(record.getName(),
record.getDClass(), record.getTTL(), addr);
} catch (IOException e) {
Log.e(e);
}
}
answers = cloned;
}
// Get AUTHORITY Records
Record[] authorities = resolveWildcard(nsRecords, host, domain);
if (answers == null && authorities == null) {
// Return NXDOMAIN if AUTHORITY not Found
header.setRcode(Rcode.NXDOMAIN);
return request;
}
// Prepare Response
boolean rd = header.getFlag(Flags.RD);
Message response = new Message(header.getID());
header = response.getHeader();
header.setRcode(Rcode.NOERROR);
header.setFlag(Flags.QR);
header.setFlag(Flags.AA);
if (rd) {
header.setFlag(Flags.RD);
}
response.addRecord(question, Section.QUESTION);
HashSet<Name> addNames = new HashSet<>();
// Set ANSWER
if (answers != null) {
for (Record record : answers) {
response.addRecord(record, Section.ANSWER);
if (record instanceof CNAMERecord) {
addNames.add(((CNAMERecord) record).getTarget());
} else if (record instanceof NSRecord) {
addNames.add(((NSRecord) record).getTarget());
} else if (record instanceof MXRecord) {
addNames.add(((MXRecord) record).getTarget());
}
}
}
// Set AUTHORITY
if (authorities != null) {
for (Record record : authorities) {
response.addRecord(record, Section.AUTHORITY);
addNames.add(((NSRecord) record).getTarget());
}
}
// Set ADDITIONAL
for (Name name : addNames) {
Record[] additionals = aRecords.get(name.
toString(true).toLowerCase());
if (additionals != null) {
for (Record record : additionals) {
response.addRecord(record, Section.ADDITIONAL);
}
}
}
return response;
}
private static void serviceDns(SocketAddress addr, byte[] reqData, byte[] respData) {
for (InetSocketAddress dns : dnss) {
try (DatagramSocket socket = new DatagramSocket()) {
socket.setSoTimeout(1000);
socket.send(new DatagramPacket(reqData, reqData.length, dns));
byte[] data = new byte[65536];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (SocketTimeoutException e) {
continue;
}
dataQueue.add(new DataEntry(addr, Bytes.left(data, packet.getLength())));
return;
} catch (IOException e) {
Log.e(e);
}
}
dataQueue.add(new DataEntry(addr, respData));
}
private static void response(HttpExchange exchange, int status, byte[] data) {
try {
exchange.sendResponseHeaders(status, data == null ? -1 : data.length);
if (data != null) {
exchange.getResponseBody().write(data);
}
} catch (IOException e) {
Log.w(e.getMessage());
}
exchange.close();
}
private static void serviceHttp(HttpExchange exchange, String auth, int ttl) {
if (auth != null) {
List<String> auths = exchange.getRequestHeaders().get("Authorization");
if (auths == null || auths.isEmpty() || !auth.equals(auths.get(0))) {
exchange.getResponseHeaders().add("WWW-Authenticate", "Basic");
response(exchange, 401, null);
return;
}
}
URI uri = exchange.getRequestURI();
String query = uri.getQuery();
if (query == null) {
exchange.getResponseHeaders().add("Content-Type", "application/json");
response(exchange, 200,
new JSONObject(dynamicRecords).toString().getBytes());
return;
}
String[] s = query.split("=");
if (s.length != 2) {
response(exchange, 400, null);
return;
}
dynamicRecords.setProperty(s[0], s[1]);
Conf.store("DynamicRecords", dynamicRecords);
try {
updateRecords(aDynamics, s[0], s[1], ttl);
response(exchange, 200, null);
} catch (IOException e) {
Log.w(e.getMessage());
response(exchange, 400, null);
}
}
public static void main(String[] args) {
if (!service.startup(args)) {
return;
}
Logger logger = Log.getAndSet(Conf.openLogger("DDNS.", 16777216, 10));
ExecutorService executor = Executors.newCachedThreadPool();
ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(1);
Properties p = Conf.load("DDNS");
int port = Numbers.parseInt(p.getProperty("port"), 53);
int dynamicTtl = Numbers.parseInt(p.getProperty("ttl.dynamic"), 10);
propPeriod = Numbers.parseInt(p.getProperty("prop.period")) * 1000;
// DoS
dosPeriod = Numbers.parseInt(p.getProperty("dos.period")) * 1000;
dosRequests = Numbers.parseInt(p.getProperty("dos.requests"));
// API Client
String addrApiUrl = p.getProperty("api.addr");
if (addrApiUrl != null) {
HttpPool addrApi = new HttpPool(addrApiUrl, dynamicTtl * 2000);
executor.execute(Runnables.wrap(() -> {
long lastAccessed = 0;
while (!service.isInterrupted()) {
long now = System.currentTimeMillis();
if (now - lastAccessed > dynamicTtl * 1000) {
lastAccessed = now;
updateDynamics(addrApi, dynamicTtl);
}
Time.sleep(16);
}
addrApi.close();
}));
}
// External DNS
String dns = p.getProperty("dns");
if (dns != null && !dns.isEmpty()) {
for (String s : dns.split("[,;]")) {
dnss.add(new InetSocketAddress(s, 53));
}
}
// Load Static and Dynamic Records
loadProp();
dynamicRecords = Conf.load("DynamicRecords");
try {
for (Map.Entry<?, ?> entry : dynamicRecords.entrySet()) {
updateRecords(aDynamics, (String) entry.getKey(),
(String) entry.getValue(), dynamicTtl);
}
} catch (IOException e) {
Log.e(e);
}
// HTTP Updating Service
int httpPort = Numbers.parseInt(p.getProperty("http.port"), 5380);
HttpServer httpServer = null;
if (httpPort > 0) {
String auth = p.getProperty("http.auth");
String auth_ = auth == null ? null :
"Basic " + Base64.encode(auth.getBytes());
try {
httpServer = HttpServer.create(new InetSocketAddress(httpPort), 50);
httpServer.createContext("/", exchange -> serviceHttp(exchange, auth_, dynamicTtl));
httpServer.start();
} catch (IOException e) {
Log.w("Failed to start HttpServer (" + httpPort + "): " + e.getMessage());
}
}
// Metric
ArrayList<InetSocketAddress> addrs = new ArrayList<>();
String addresses = p.getProperty("metric.collectors");
if (addresses != null) {
String[] s = addresses.split("[,;]");
for (int i = 0; i < s.length; i ++) {
String[] ss = s[i].split("[:/]");
if (ss.length >= 2) {
addrs.add(new InetSocketAddress(ss[0],
Numbers.parseInt(ss[1], 5514)));
}
}
}
MetricClient.startup(addrs.toArray(new InetSocketAddress[0]));
timer.scheduleAtFixedRate(Runnables.wrap(new ManagementMonitor("ddns.server")),
0, 5000, TimeUnit.MILLISECONDS);
// For Debug on localhost (192.168.0.1:53 is bound by Microsoft Loopback Adapter)
// try (DatagramSocket socket = new DatagramSocket(new InetSocketAddress("127.0.0.1", port))) {
try (DatagramSocket socket = new DatagramSocket(port)) {
service.register(socket);
service.execute(Runnables.wrap(() -> {
try {
while (true) {
DataEntry dataEntry = dataQueue.take();
try {
DatagramPacket packet = new DatagramPacket(dataEntry.data,
dataEntry.data.length, dataEntry.addr);
socket.send(packet);
dump(packet, true);
} catch (IOException e) {
Log.w(e);
}
}
} catch (InterruptedException e) {
// Exit Polling
}
}));
Log.i("DDNS Started on UDP port " + port);
while (!Thread.interrupted()) {
// Load Properties
if (propPeriod > 0) {
long now = System.currentTimeMillis();
if (now > propAccessed + propPeriod) {
loadProp();
propAccessed = now;
}
}
// Receive
byte[] buf = new byte[65536];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
// Blocked, or closed by shutdown handler
socket.receive(packet);
// DoS Filtering
SocketAddress remote = packet.getSocketAddress();
if (blocked(((InetSocketAddress) remote).getAddress().getHostAddress())) {
continue;
}
dump(packet, false);
byte[] reqData = Bytes.left(buf, packet.getLength());
Message request;
try {
request = new Message(reqData);
} catch (IOException e) {
Log.w(e.getMessage());
continue;
}
// Call Service in Trunk Thread
String[] domain = {null};
Message response = service(request, domain);
if (response == null) {
continue;
}
int rcode = response.getRcode();
Record question = request.getQuestion();
Metric.put("ddns.resolve", 1, "rcode", Rcode.string(rcode),
"name", "" + domain[0], "type", question == null ?
"null" : Type.string(question.getType()));
byte[] respData = response.toWire();
if (dnss.isEmpty() || rcode < Rcode.NXDOMAIN) {
// Send
dataQueue.offer(new DataEntry(remote, respData));
} else {
// Call DNS Service in Branch Thread
executor.execute(Runnables.wrap(() -> serviceDns(remote, reqData, respData)));
}
}
} catch (IOException e) {
Log.w("Failed to open DatagramSocket (" + port +
") or receive DatagramPacket: " + e.getMessage());
service.shutdownNow(); // Interrupt when failed
} catch (Error | RuntimeException e) {
Log.e(e);
service.shutdownNow(); // Interrupt when failed
}
if (httpServer != null) {
httpServer.stop(0);
}
MetricClient.shutdown();
Runnables.shutdown(executor);
Runnables.shutdown(timer);
Log.i("DDNS Stopped");
Conf.closeLogger(Log.getAndSet(logger));
service.shutdown();
}
} | src/main/java/com/xqbase/ddns/DDNS.java | package com.xqbase.ddns;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.xbill.DNS.AAAARecord;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.CNAMERecord;
import org.xbill.DNS.DClass;
import org.xbill.DNS.Flags;
import org.xbill.DNS.Header;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.Message;
import org.xbill.DNS.NSRecord;
import org.xbill.DNS.Name;
import org.xbill.DNS.Opcode;
import org.xbill.DNS.Rcode;
import org.xbill.DNS.Record;
import org.xbill.DNS.Section;
import org.xbill.DNS.Type;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.xqbase.metric.client.ManagementMonitor;
import com.xqbase.metric.client.MetricClient;
import com.xqbase.metric.common.Metric;
import com.xqbase.util.ByteArrayQueue;
import com.xqbase.util.Bytes;
import com.xqbase.util.Conf;
import com.xqbase.util.Log;
import com.xqbase.util.Numbers;
import com.xqbase.util.Runnables;
import com.xqbase.util.Service;
import com.xqbase.util.Time;
import com.xqbase.util.http.HttpPool;
class DataEntry {
SocketAddress addr;
byte[] data;
DataEntry(SocketAddress addr, byte[] data) {
this.addr = addr;
this.data = data;
}
}
public class DDNS {
private static final Record[] EMPTY_RECORDS = new Record[0];
private static ConcurrentHashMap<String, Record[]>
aDynamics = new ConcurrentHashMap<>();
private static HashMap<String, Record[]>
aRecords = new HashMap<>(), aWildcards = new HashMap<>(),
nsRecords = new HashMap<>(), mxRecords = new HashMap<>();
private static ArrayList<InetSocketAddress> dnss = new ArrayList<>();
private static LinkedBlockingQueue<DataEntry> dataQueue = new LinkedBlockingQueue<>();
private static Service service = new Service();
private static Properties dynamicRecords;
private static HashMap<String, Integer> countMap = new HashMap<>();
private static long propAccessed = 0, dosAccessed = 0;
private static int propPeriod, dosPeriod, dosRequests;
private static boolean verbose = false;
private static void updateRecords(Map<String, Record[]> records,
String host, String value, int ttl) throws IOException {
Name origin = new Name((host.endsWith(".") ? host : host + ".").replace('_', '-'));
ArrayList<Record> recordList = new ArrayList<>();
for (String s : value.split("[,;]")) {
if (s.matches(".*[A-Z|a-z].*")) {
CNAMERecord record = new CNAMERecord(origin, DClass.IN, ttl,
new Name(s.endsWith(".") ? s : s + "."));
recordList.add(record);
continue;
}
String[] ss = s.split("\\.");
if (ss.length < 4) {
continue;
}
byte[] ip = new byte[4];
for (int i = 0; i < 4; i ++) {
ip[i] = (byte) Numbers.parseInt(ss[i]);
}
recordList.add(new ARecord(origin, DClass.IN,
ttl, InetAddress.getByAddress(ip)));
}
if (!recordList.isEmpty()) {
records.put(host, recordList.toArray(EMPTY_RECORDS));
}
}
private static void updateDynamics(HttpPool addrApi, int ttl) {
ByteArrayQueue body = new ByteArrayQueue();
try {
if (addrApi.get("", null, body, null) >= 400) {
Log.w(body.toString());
return;
}
} catch (IOException e) {
Log.e(e);
return;
}
try {
JSONObject map = new JSONObject(body.toString());
Iterator<?> it = map.keys();
while (it.hasNext()) {
String host = (String) it.next();
String addr = map.optString(host);
if (addr != null) {
updateRecords(aDynamics, host, addr, ttl);
}
}
} catch (IOException | JSONException e) {
Log.e(e);
}
}
private static void loadProp() {
aRecords.clear();
aWildcards.clear();
nsRecords.clear();
mxRecords.clear();
Properties p = Conf.load("DDNS");
verbose = Conf.getBoolean(p.getProperty("verbose"), false);
int mxPriority = Numbers.parseInt(p.getProperty("priority.mx"), 10);
int staticTtl = Numbers.parseInt(p.getProperty("ttl.static"), 3600);
for (Map.Entry<?, ?> entry : p.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
try {
if (key.startsWith("ns_")) {
String host = key.substring(3);
Name origin = new Name(host.endsWith(".") ? host : host + ".");
ArrayList<Record> records = new ArrayList<>();
for (String target : value.split("[,;]")) {
records.add(new NSRecord(origin, DClass.IN, staticTtl,
new Name(target.endsWith(".") ? target : target + ".")));
}
if (!records.isEmpty()) {
nsRecords.put(host, records.toArray(EMPTY_RECORDS));
}
continue;
}
if (key.startsWith("mx_")) {
String host = key.substring(3);
Name origin = new Name(host.endsWith(".") ? host : host + ".");
ArrayList<Record> records = new ArrayList<>();
for (String target : value.split("[,;]")) {
records.add(new MXRecord(origin, DClass.IN, staticTtl, mxPriority,
new Name(target.endsWith(".") ? target : target + ".")));
}
if (!records.isEmpty()) {
mxRecords.put(host, records.toArray(EMPTY_RECORDS));
}
continue;
}
if (!key.startsWith("a_")) {
continue;
}
String host = key.substring(2);
if (host.startsWith("*.")) {
updateRecords(aWildcards, host.substring(2), value, staticTtl);
} else {
updateRecords(aRecords, host, value, staticTtl);
}
} catch (IOException e) {
Log.e(e);
}
}
}
private static boolean blocked(String ip) {
if (dosPeriod == 0 || dosRequests == 0) {
return false;
}
long now = System.currentTimeMillis();
if (now > dosAccessed + dosPeriod) {
countMap.clear();
dosAccessed = now;
}
Integer count_ = countMap.get(ip);
int count = (count_ == null ? 0 : count_.intValue());
count ++;
countMap.put(ip, Integer.valueOf(count));
if (count < dosRequests) {
// Remote IP Blocked
return false;
}
if (count % dosRequests == 0) {
Log.w("DoS Attack from " + ip + ", requests = " + count);
}
return true;
}
private static void dump(DatagramPacket packet, boolean send) {
if (!verbose) {
return;
}
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
out.println((send ? "Sent to " : "Received from ") +
packet.getAddress().getHostAddress());
byte[] data = Bytes.sub(packet.getData(), packet.getOffset(), packet.getLength());
Bytes.dump(out, data);
try {
out.println(new Message(data));
} catch (IOException e) {
out.println(e.getMessage());
}
Log.d(sw.toString());
}
private static Record[] resolveWildcard(Map<String, Record[]>
wildcards, String host, String[] domain) {
String host_ = host;
Record[] records = wildcards.get(host_);
while (records == null) {
int dot = host_.indexOf('.');
if (dot < 0) {
break;
}
host_ = host_.substring(dot + 1);
if (host_.isEmpty()) {
break;
}
records = wildcards.get(host_);
}
if (records != null && domain[0] == null) {
domain[0] = "*." + host_;
}
return records;
}
private static Message service(Message request, String[] domain) {
// Check Request Validity
Header header = request.getHeader();
if (header.getFlag(Flags.QR)) {
return null;
}
header.setFlag(Flags.QR);
Record question = request.getQuestion();
if (header.getRcode() != Rcode.NOERROR) {
header.setRcode(Rcode.FORMERR);
return request;
}
if (header.getOpcode() != Opcode.QUERY) {
header.setRcode(Rcode.NOTIMP);
return request;
}
// Get ANSWER Records
String host = question.getName().toString(true).toLowerCase();
Record[] answers;
int type = question.getType();
switch (type) {
case Type.A:
case Type.AAAA:
case Type.CNAME:
case Type.ANY:
answers = aRecords.get(host);
if (answers != null) {
domain[0] = host;
break;
}
answers = resolveWildcard(aWildcards, host, domain);
if (answers == null) {
answers = aDynamics.get(host);
break;
}
// Set name for wildcard
Name name;
try {
name = new Name(host.endsWith(".") ? host : host + ".");
} catch (IOException e) {
Log.w(e.getMessage());
break;
}
// Do not pollute "aWildcards"
Record[] cloned = new Record[answers.length];
for (int i = 0; i < answers.length; i ++) {
Record record = answers[i];
int dclass = record.getDClass();
long ttl = record.getTTL();
if (record instanceof ARecord) {
cloned[i] = new ARecord(name, dclass, ttl,
((ARecord) record).getAddress());
} else if (record instanceof CNAMERecord) {
cloned[i] = new CNAMERecord(name, dclass, ttl,
((CNAMERecord) record).getTarget());
} else {
Log.e("Not A or CNAME: " + answers[i]);
cloned[i] = answers[i];
}
}
answers = cloned;
break;
case Type.NS:
case Type.MX:
answers = (type == Type.NS ? nsRecords : mxRecords).get(host);
if (answers != null) {
domain[0] = host;
}
break;
default:
header.setRcode(Rcode.NOTIMP);
return request;
}
// AAAA: Convert IPv4 to IPv6
if (type == Type.AAAA && answers != null) {
// Do not pollute "aRecords", "aWildcards" or "aDynamics"
Record[] cloned = new Record[answers.length];
for (int i = 0; i < answers.length; i ++) {
Record record = cloned[i] = answers[i];
if (!(record instanceof ARecord)) {
continue;
}
InetAddress addr = ((ARecord) record).getAddress();
if (!(addr instanceof Inet4Address)) {
continue;
}
byte[] ip = ((Inet4Address) addr).getAddress();
try {
addr = Inet6Address.getByAddress(null,
new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1,
ip[0], ip[1], ip[2], ip[3]}, null);
cloned[i] = new AAAARecord(record.getName(),
record.getDClass(), record.getTTL(), addr);
} catch (IOException e) {
Log.e(e);
}
}
answers = cloned;
}
// Get AUTHORITY Records
Record[] authorities = resolveWildcard(nsRecords, host, domain);
if (answers == null && authorities == null) {
// Return NXDOMAIN if AUTHORITY not Found
header.setRcode(Rcode.NXDOMAIN);
return request;
}
// Prepare Response
boolean rd = header.getFlag(Flags.RD);
Message response = new Message(header.getID());
header = response.getHeader();
header.setRcode(Rcode.NOERROR);
header.setFlag(Flags.QR);
header.setFlag(Flags.AA);
if (rd) {
header.setFlag(Flags.RD);
}
response.addRecord(question, Section.QUESTION);
HashSet<Name> addNames = new HashSet<>();
// Set ANSWER
if (answers != null) {
for (Record record : answers) {
response.addRecord(record, Section.ANSWER);
if (record instanceof CNAMERecord) {
addNames.add(((CNAMERecord) record).getTarget());
} else if (record instanceof NSRecord) {
addNames.add(((NSRecord) record).getTarget());
} else if (record instanceof MXRecord) {
addNames.add(((MXRecord) record).getTarget());
}
}
}
// Set AUTHORITY
if (authorities != null) {
for (Record record : authorities) {
response.addRecord(record, Section.AUTHORITY);
addNames.add(((NSRecord) record).getTarget());
}
}
// Set ADDITIONAL
for (Name name : addNames) {
Record[] additionals = aRecords.get(name.
toString(true).toLowerCase());
if (additionals != null) {
for (Record record : additionals) {
response.addRecord(record, Section.ADDITIONAL);
}
}
}
return response;
}
private static void serviceDns(SocketAddress addr, byte[] reqData, byte[] respData) {
for (InetSocketAddress dns : dnss) {
try (DatagramSocket socket = new DatagramSocket()) {
socket.setSoTimeout(1000);
socket.send(new DatagramPacket(reqData, reqData.length, dns));
byte[] data = new byte[65536];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (SocketTimeoutException e) {
continue;
}
dataQueue.add(new DataEntry(addr, Bytes.left(data, packet.getLength())));
return;
} catch (IOException e) {
Log.e(e);
}
}
dataQueue.add(new DataEntry(addr, respData));
}
private static void response(HttpExchange exchange, int status, byte[] data) {
try {
exchange.sendResponseHeaders(status, data == null ? -1 : data.length);
if (data != null) {
exchange.getResponseBody().write(data);
}
} catch (IOException e) {
Log.w(e.getMessage());
}
exchange.close();
}
private static void serviceHttp(HttpExchange exchange, String auth, int ttl) {
if (auth != null) {
List<String> auths = exchange.getRequestHeaders().get("Authorization");
if (auths == null || auths.isEmpty() || !auth.equals(auths.get(0))) {
exchange.getResponseHeaders().add("WWW-Authenticate", "Basic");
response(exchange, 401, null);
return;
}
}
URI uri = exchange.getRequestURI();
String query = uri.getQuery();
if (query == null) {
exchange.getResponseHeaders().add("Content-Type", "application/json");
response(exchange, 200,
new JSONObject(dynamicRecords).toString().getBytes());
return;
}
String[] s = query.split("=");
if (s.length != 2) {
response(exchange, 400, null);
return;
}
dynamicRecords.setProperty(s[0], s[1]);
Conf.store("DynamicRecords", dynamicRecords);
try {
updateRecords(aDynamics, s[0], s[1], ttl);
response(exchange, 200, null);
} catch (IOException e) {
Log.w(e.getMessage());
response(exchange, 400, null);
}
}
public static void main(String[] args) {
if (!service.startup(args)) {
return;
}
Logger logger = Log.getAndSet(Conf.openLogger("DDNS.", 16777216, 10));
ExecutorService executor = Executors.newCachedThreadPool();
ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(1);
Properties p = Conf.load("DDNS");
int port = Numbers.parseInt(p.getProperty("port"), 53);
int dynamicTtl = Numbers.parseInt(p.getProperty("ttl.dynamic"), 10);
propPeriod = Numbers.parseInt(p.getProperty("prop.period")) * 1000;
// DoS
dosPeriod = Numbers.parseInt(p.getProperty("dos.period")) * 1000;
dosRequests = Numbers.parseInt(p.getProperty("dos.requests"));
// API Client
String addrApiUrl = p.getProperty("api.addr");
if (addrApiUrl != null) {
HttpPool addrApi = new HttpPool(addrApiUrl, dynamicTtl * 2000);
executor.execute(Runnables.wrap(() -> {
long lastAccessed = 0;
while (!service.isInterrupted()) {
long now = System.currentTimeMillis();
if (now - lastAccessed > dynamicTtl * 1000) {
lastAccessed = now;
updateDynamics(addrApi, dynamicTtl);
}
Time.sleep(16);
}
addrApi.close();
}));
}
// External DNS
String dns = p.getProperty("dns");
if (dns != null && !dns.isEmpty()) {
for (String s : dns.split("[,;]")) {
dnss.add(new InetSocketAddress(s, 53));
}
}
// Load Static and Dynamic Records
loadProp();
dynamicRecords = Conf.load("DynamicRecords");
try {
for (Map.Entry<?, ?> entry : dynamicRecords.entrySet()) {
updateRecords(aDynamics, (String) entry.getKey(),
(String) entry.getValue(), dynamicTtl);
}
} catch (IOException e) {
Log.e(e);
}
// HTTP Updating Service
int httpPort = Numbers.parseInt(p.getProperty("http.port"), 5380);
HttpServer httpServer = null;
if (httpPort > 0) {
String auth = p.getProperty("http.auth");
String auth_ = auth == null ? null :
"Basic " + Base64.encode(auth.getBytes());
try {
httpServer = HttpServer.create(new InetSocketAddress(httpPort), 50);
httpServer.createContext("/", exchange -> serviceHttp(exchange, auth_, dynamicTtl));
httpServer.start();
} catch (IOException e) {
Log.w("Failed to start HttpServer (" + httpPort + "): " + e.getMessage());
}
}
// Metric
ArrayList<InetSocketAddress> addrs = new ArrayList<>();
String addresses = p.getProperty("metric.collectors");
if (addresses != null) {
String[] s = addresses.split("[,;]");
for (int i = 0; i < s.length; i ++) {
String[] ss = s[i].split("[:/]");
if (ss.length >= 2) {
addrs.add(new InetSocketAddress(ss[0],
Numbers.parseInt(ss[1], 5514)));
}
}
}
MetricClient.startup(addrs.toArray(new InetSocketAddress[0]));
timer.scheduleAtFixedRate(Runnables.wrap(new ManagementMonitor("ddns.server")),
0, 5000, TimeUnit.MILLISECONDS);
Log.i("DDNS Started");
// For Debug on localhost (192.168.0.1:53 is bound by Microsoft Loopback Adapter)
// try (DatagramSocket socket = new DatagramSocket(new InetSocketAddress("127.0.0.1", port))) {
try (DatagramSocket socket = new DatagramSocket(port)) {
service.register(socket);
service.execute(Runnables.wrap(() -> {
try {
while (true) {
DataEntry dataEntry = dataQueue.take();
try {
DatagramPacket packet = new DatagramPacket(dataEntry.data,
dataEntry.data.length, dataEntry.addr);
socket.send(packet);
dump(packet, true);
} catch (IOException e) {
Log.w(e);
}
}
} catch (InterruptedException e) {
// Exit Polling
}
}));
while (!Thread.interrupted()) {
// Load Properties
if (propPeriod > 0) {
long now = System.currentTimeMillis();
if (now > propAccessed + propPeriod) {
loadProp();
propAccessed = now;
}
}
// Receive
byte[] buf = new byte[65536];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
// Blocked, or closed by shutdown handler
socket.receive(packet);
// DoS Filtering
SocketAddress remote = packet.getSocketAddress();
if (blocked(((InetSocketAddress) remote).getAddress().getHostAddress())) {
continue;
}
dump(packet, false);
byte[] reqData = Bytes.left(buf, packet.getLength());
Message request;
try {
request = new Message(reqData);
} catch (IOException e) {
Log.w(e.getMessage());
continue;
}
// Call Service in Trunk Thread
String[] domain = {null};
Message response = service(request, domain);
if (response == null) {
continue;
}
int rcode = response.getRcode();
Record question = request.getQuestion();
Metric.put("ddns.resolve", 1, "rcode", Rcode.string(rcode),
"name", "" + domain[0], "type", question == null ?
"null" : Type.string(question.getType()));
byte[] respData = response.toWire();
if (dnss.isEmpty() || rcode < Rcode.NXDOMAIN) {
// Send
dataQueue.offer(new DataEntry(remote, respData));
} else {
// Call DNS Service in Branch Thread
executor.execute(Runnables.wrap(() -> serviceDns(remote, reqData, respData)));
}
}
} catch (IOException e) {
Log.w("Failed to open DatagramSocket (" + port +
") or receive DatagramPacket: " + e.getMessage());
service.shutdownNow(); // Interrupt when failed
} catch (Error | RuntimeException e) {
Log.e(e);
service.shutdownNow(); // Interrupt when failed
}
if (httpServer != null) {
httpServer.stop(0);
}
MetricClient.shutdown();
Runnables.shutdown(executor);
Runnables.shutdown(timer);
Log.i("DDNS Stopped");
Conf.closeLogger(Log.getAndSet(logger));
service.shutdown();
}
} | "DDNS Started" not logged if unable to bind | src/main/java/com/xqbase/ddns/DDNS.java | "DDNS Started" not logged if unable to bind |
|
Java | apache-2.0 | d8b967777b9cebfc19bf3a6dc64d8261748e7f89 | 0 | Distrotech/fop,spepping/fop-cs,argv-minus-one/fop,StrategyObject/fop,spepping/fop-cs,StrategyObject/fop,argv-minus-one/fop,argv-minus-one/fop,StrategyObject/fop,argv-minus-one/fop,StrategyObject/fop,argv-minus-one/fop,Distrotech/fop,Distrotech/fop,spepping/fop-cs,Distrotech/fop,spepping/fop-cs,StrategyObject/fop | /*-- $Id$ --
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "FOP" and "Apache Software Foundation" must not be used to
endorse or promote products derived from this software without prior
written permission. For written permission, please contact
[email protected].
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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
APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
DING, 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 software consists of voluntary contributions made by many individuals
on behalf of the Apache Software Foundation and was originally created by
James Tauber <[email protected]>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
/* image support modified from work of BoBoGi */
package org.apache.fop.pdf;
// images are the one place that FOP classes outside this package get
// referenced and I'd rather not do it
import org.apache.fop.image.FopImage;
import org.apache.fop.datatypes.ColorSpace;
// Java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.Hashtable;
import java.awt.Rectangle;
/**
* class representing a PDF document.
*
* The document is built up by calling various methods and then finally
* output to given filehandle using output method.
*
* A PDF document consists of a series of numbered objects preceded by a
* header and followed by an xref table and trailer. The xref table
* allows for quick access to objects by listing their character
* positions within the document. For this reason the PDF document must
* keep track of the character position of each object. The document
* also keeps direct track of the /Root, /Info and /Resources objects.
*/
public class PDFDocument {
/** the version of PDF supported */
protected static final String pdfVersion = "1.3";
/** the current character position */
protected int position = 0;
/** the character position of each object */
protected Vector location = new Vector();
/** the counter for object numbering */
protected int objectcount = 0;
/** the objects themselves */
protected Vector objects = new Vector();
/** character position of xref table */
protected int xref;
/** the /Root object */
protected PDFRoot root;
/** the /Info object */
protected PDFInfo info;
/** the /Resources object */
protected PDFResources resources;
/** the colorspace (0=RGB, 1=CMYK) **/
//protected int colorspace = 0;
protected ColorSpace colorspace = new ColorSpace(ColorSpace.DEVICE_RGB);
/** the counter for Pattern name numbering (e.g. 'Pattern1')*/
protected int patternCount = 0;
/** the counter for Shading name numbering */
protected int shadingCount = 0;
/** the counter for XObject numbering */
protected int xObjectCount = 0;
/** the XObjects */
protected Vector xObjects = new Vector();
/** the XObjects Map.
Should be modified (works only for image subtype) */
protected Hashtable xObjectsMap = new Hashtable();
/**
* creates an empty PDF document
*/
public PDFDocument() {
/* create the /Root, /Info and /Resources objects */
this.root = makeRoot();
this.info = makeInfo();
this.resources = makeResources();
}
/**
* set the producer of the document
*
* @param producer string indicating application producing the PDF
*/
public void setProducer(String producer) {
this.info.setProducer(producer);
}
/**
* make /Root object as next object
*
* @return the created /Root object
*/
protected PDFRoot makeRoot() {
/* create a PDFRoot with the next object number and add to
list of objects */
PDFRoot pdfRoot = new PDFRoot(++this.objectcount);
this.objects.addElement(pdfRoot);
/* create a new /Pages object to be root of Pages hierarchy
and add to list of objects */
PDFPages rootPages = new PDFPages(++this.objectcount);
this.objects.addElement(rootPages);
/* inform the /Root object of the /Pages root */
pdfRoot.setRootPages(rootPages);
return pdfRoot;
}
/**
* make an /Info object
*
* @param producer string indicating application producing the PDF
* @return the created /Info object
*/
protected PDFInfo makeInfo() {
/* create a PDFInfo with the next object number and add to
list of objects */
PDFInfo pdfInfo = new PDFInfo(++this.objectcount);
this.objects.addElement(pdfInfo);
return pdfInfo;
}
/**
* make a /Resources object
*
* @return the created /Resources object
*/
private PDFResources makeResources() {
/* create a PDFResources with the next object number and add
to list of objects */
PDFResources pdfResources = new PDFResources(++this.objectcount);
this.objects.addElement(pdfResources);
return pdfResources;
}
/**
* Make a Type 0 sampled function
*
* @param theDomain Vector objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theRange Vector objects of Double objects.
* This is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theSize A Vector object of Integer objects.
* This is the number of samples in each input dimension.
* I can't imagine there being more or less than two input dimensions,
* so maybe this should be an array of length 2.
*
* See page 265 of the PDF 1.3 Spec.
* @param theBitsPerSample An int specifying the number of bits user to represent each sample value.
* Limited to 1,2,4,8,12,16,24 or 32.
* See page 265 of the 1.3 PDF Spec.
* @param theOrder The order of interpolation between samples. Default is 1 (one). Limited
* to 1 (one) or 3, which means linear or cubic-spline interpolation.
*
* This attribute is optional.
*
* See page 265 in the PDF 1.3 spec.
* @param theEncode Vector objects of Double objects.
* This is the linear mapping of input values intop the domain
* of the function's sample table. Default is hard to represent in
* ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
* This attribute is optional.
*
* See page 265 in the PDF 1.3 spec.
* @param theDecode Vector objects of Double objects.
* This is a linear mapping of sample values into the range.
* The default is just the range.
*
* This attribute is optional.
* Read about it on page 265 of the PDF 1.3 spec.
* @param theFunctionDataStream The sample values that specify the function are provided in a stream.
*
* This is optional, but is almost always used.
*
* Page 265 of the PDF 1.3 spec has more.
* @param theFilter This is a vector of String objects which are the various filters that
* have are to be applied to the stream to make sense of it. Order matters,
* so watch out.
*
* This is not documented in the Function section of the PDF 1.3 spec,
* it was deduced from samples that this is sometimes used, even if we may never
* use it in FOP. It is added for completeness sake.
* @param theNumber The object number of this PDF object.
* @param theFunctionType This is the type of function (0,2,3, or 4).
* It should be 0 as this is the constructor for sampled functions.
*/
public PDFFunction makeFunction(int theFunctionType,
Vector theDomain, Vector theRange,
Vector theSize,int theBitsPerSample,
int theOrder,Vector theEncode,Vector theDecode,
StringBuffer theFunctionDataStream, Vector theFilter)
{//Type 0 function
PDFFunction function = new PDFFunction(
++this.objectcount, theFunctionType,
theDomain, theRange, theSize,
theBitsPerSample, theOrder,
theEncode, theDecode,
theFunctionDataStream, theFilter);
this.objects.addElement(function);
return(function);
}
/**
* make a type Exponential interpolation function
* (for shading usually)
*
* @param theDomain Vector objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theRange Vector of Doubles that is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theCZero This is a vector of Double objects which defines the function result
* when x=0.
*
* This attribute is optional.
* It's described on page 268 of the PDF 1.3 spec.
* @param theCOne This is a vector of Double objects which defines the function result
* when x=1.
*
* This attribute is optional.
* It's described on page 268 of the PDF 1.3 spec.
* @param theInterpolationExponentN This is the inerpolation exponent.
*
* This attribute is required.
* PDF Spec page 268
* @param theFunctionType The type of the function, which should be 2.
*/
public PDFFunction makeFunction(int theFunctionType,
Vector theDomain, Vector theRange,
Vector theCZero, Vector theCOne,
double theInterpolationExponentN)
{//type 2
PDFFunction function = new PDFFunction(
++this.objectcount,
theFunctionType,
theDomain, theRange,
theCZero, theCOne,
theInterpolationExponentN);
this.objects.addElement(function);
return(function);
}
/**
* Make a Type 3 Stitching function
*
* @param theDomain Vector objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theRange Vector objects of Double objects.
* This is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theFunctions A Vector of the PDFFunction objects that the stitching function stitches.
*
* This attributed is required.
* It is described on page 269 of the PDF spec.
* @param theBounds This is a vector of Doubles representing the numbers that,
* in conjunction with Domain define the intervals to which each function from
* the 'functions' object applies. It must be in order of increasing magnitude,
* and each must be within Domain.
*
* It basically sets how much of the gradient each function handles.
*
* This attributed is required.
* It's described on page 269 of the PDF 1.3 spec.
* @param theEncode Vector objects of Double objects.
* This is the linear mapping of input values intop the domain
* of the function's sample table. Default is hard to represent in
* ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
* This attribute is required.
*
* See page 270 in the PDF 1.3 spec.
* @param theFunctionType This is the function type. It should be 3,
* for a stitching function.
*/
public PDFFunction makeFunction(int theFunctionType,
Vector theDomain, Vector theRange,
Vector theFunctions, Vector theBounds,
Vector theEncode)
{//Type 3
PDFFunction function = new PDFFunction(
++this.objectcount,
theFunctionType,
theDomain, theRange,
theFunctions, theBounds,
theEncode);
this.objects.addElement(function);
return(function);
}
/**
* make a postscript calculator function
*
* @param theNumber
* @param theFunctionType
* @param theDomain
* @param theRange
* @param theFunctionDataStream
*/
public PDFFunction makeFunction(int theNumber, int theFunctionType,
Vector theDomain, Vector theRange,
StringBuffer theFunctionDataStream)
{ //Type 4
PDFFunction function = new PDFFunction(
++this.objectcount,
theFunctionType,
theDomain, theRange,
theFunctionDataStream);
this.objects.addElement(function);
return(function);
}
/**
* make a function based shading object
*
* @param theShadingType The type of shading object, which should be 1 for function
* based shading.
* @param theColorSpace The colorspace is 'DeviceRGB' or something similar.
* @param theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox Vector of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Whether or not to anti-alias.
* @param theDomain Optional vector of Doubles specifying the domain.
* @param theMatrix Vector of Doubles specifying the matrix.
* If it's a pattern, then the matrix maps it to pattern space.
* If it's a shading, then it maps it to current user space.
* It's optional, the default is the identity matrix
* @param theFunction The PDF Function that maps an (x,y) location to a color
*/
public PDFShading makeShading(int theShadingType, ColorSpace theColorSpace,
Vector theBackground, Vector theBBox, boolean theAntiAlias,
Vector theDomain, Vector theMatrix, PDFFunction theFunction)
{ //make Shading of Type 1
String theShadingName = new String("Sh"+(++this.shadingCount));
PDFShading shading = new PDFShading(++this.objectcount, theShadingName,
theShadingType, theColorSpace, theBackground, theBBox,
theAntiAlias, theDomain, theMatrix, theFunction);
this.objects.addElement(shading);
//add this shading to resources
this.resources.addShading(shading);
return(shading);
}
/**
* Make an axial or radial shading object.
*
* @param theShadingType 2 or 3 for axial or radial shading
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox Vector of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Default is false
* @param theCoords Vector of four (type 2) or 6 (type 3) Double
* @param theDomain Vector of Doubles specifying the domain
* @param theFunction the Stitching (PDFfunction type 3) function, even if it's stitching a single function
* @param theExtend Vector of Booleans of whether to extend teh start and end colors past the start and end points
* The default is [false, false]
*/
public PDFShading makeShading(int theShadingType,
ColorSpace theColorSpace, Vector theBackground,
Vector theBBox, boolean theAntiAlias,
Vector theCoords, Vector theDomain,
PDFFunction theFunction, Vector theExtend)
{ //make Shading of Type 2 or 3
String theShadingName = new String("Sh"+(++this.shadingCount));
PDFShading shading = new PDFShading(++this.objectcount, theShadingName,
theShadingType, theColorSpace,
theBackground, theBBox, theAntiAlias,
theCoords, theDomain,theFunction,theExtend);
this.resources.addShading(shading);
this.objects.addElement(shading);
return(shading);
}
/**
* Make a free-form gouraud shaded triangle mesh, coons patch mesh, or tensor patch mesh
* shading object
*
* @param theShadingType 4, 6, or 7 depending on whether it's
* Free-form gouraud-shaded triangle meshes, coons patch meshes,
* or tensor product patch meshes, respectively.
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox Vector of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Default is false
* @param theBitsPerCoordinate 1,2,4,8,12,16,24 or 32.
* @param theBitsPerComponent 1,2,4,8,12, and 16
* @param theBitsPerFlag 2,4,8.
* @param theDecode Vector of Doubles see PDF 1.3 spec pages 303 to 312.
* @param theFunction the PDFFunction
*/
public PDFShading makeShading(int theShadingType, ColorSpace theColorSpace,
Vector theBackground, Vector theBBox, boolean theAntiAlias,
int theBitsPerCoordinate, int theBitsPerComponent,
int theBitsPerFlag, Vector theDecode, PDFFunction theFunction)
{ //make Shading of type 4,6 or 7
String theShadingName = new String("Sh"+(++this.shadingCount));
PDFShading shading = new PDFShading(++this.objectcount, theShadingName,
theShadingType, theColorSpace,
theBackground, theBBox, theAntiAlias,
theBitsPerCoordinate,theBitsPerComponent,
theBitsPerFlag, theDecode, theFunction);
this.resources.addShading(shading);
this.objects.addElement(shading);
return(shading);
}
/**
* make a Lattice-Form Gouraud mesh shading object
*
* @param theShadingType 5 for lattice-Form Gouraud shaded-triangle mesh
* without spaces. "Shading1" or "Sh1" are good examples.
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox Vector of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Default is false
* @param theBitsPerCoordinate 1,2,4,8,12,16, 24, or 32
* @param theBitsPerComponent 1,2,4,8,12,24,32
* @param theDecode Vector of Doubles. See page 305 in PDF 1.3 spec.
* @param theVerticesPerRow number of vertices in each "row" of the lattice.
* @param theFunction The PDFFunction that's mapped on to this shape
*/
public PDFShading makeShading(int theShadingType, ColorSpace theColorSpace,
Vector theBackground, Vector theBBox, boolean theAntiAlias,
int theBitsPerCoordinate, int theBitsPerComponent,
Vector theDecode, int theVerticesPerRow, PDFFunction theFunction)
{ //make shading of Type 5
String theShadingName = new String("Sh"+(++this.shadingCount));
PDFShading shading= new PDFShading(++this.objectcount,
theShadingName, theShadingType, theColorSpace,
theBackground, theBBox, theAntiAlias,
theBitsPerCoordinate, theBitsPerComponent,
theDecode, theVerticesPerRow, theFunction);
this.resources.addShading(shading);
this.objects.addElement(shading);
return(shading);
}
/**
* Make a tiling pattern
*
* @param thePatternType the type of pattern, which is 1 for tiling.
* @param theResources the resources associated with this pattern
* @param thePaintType 1 or 2, colored or uncolored.
* @param theTilingType 1, 2, or 3, constant spacing, no distortion, or faster tiling
* @param theBBox Vector of Doubles: The pattern cell bounding box
* @param theXStep horizontal spacing
* @param theYStep vertical spacing
* @param theMatrix Optional Vector of Doubles transformation matrix
* @param theXUID Optional vector of Integers that uniquely identify the pattern
* @param thePatternDataStream The stream of pattern data to be tiled.
*/
public PDFPattern makePattern(
int thePatternType, //1
PDFResources theResources,
int thePaintType, int theTilingType,
Vector theBBox, double theXStep, double theYStep,
Vector theMatrix, Vector theXUID, StringBuffer thePatternDataStream)
{
String thePatternName = new String("Pa"+(++this.patternCount));
//int theNumber, String thePatternName,
//PDFResources theResources
PDFPattern pattern = new PDFPattern(++this.objectcount,
thePatternName,
theResources, 1,
thePaintType, theTilingType,
theBBox, theXStep, theYStep,
theMatrix, theXUID, thePatternDataStream);
this.resources.addPattern(pattern);
this.objects.addElement(pattern);
return(pattern);
}
/**
* Make a smooth shading pattern
*
* @param thePatternType the type of the pattern, which is 2, smooth shading
* @param theShading the PDF Shading object that comprises this pattern
* @param theXUID optional:the extended unique Identifier if used.
* @param theExtGState optional: the extended graphics state, if used.
* @param theMatrix Optional:Vector of Doubles that specify the matrix.
*/
public PDFPattern makePattern(int thePatternType,
PDFShading theShading, Vector theXUID,
StringBuffer theExtGState,Vector theMatrix)
{
String thePatternName = new String("Pa"+(++this.patternCount));
PDFPattern pattern = new PDFPattern(++this.objectcount,
thePatternName, 2, theShading, theXUID,
theExtGState, theMatrix);
this.resources.addPattern(pattern);
this.objects.addElement(pattern);
return(pattern);
}
public int getColorSpace()
{
return(this.colorspace.getColorSpace());
}
public void setColorSpace(int theColorspace)
{
this.colorspace.setColorSpace(theColorspace);
return;
}
public PDFPattern createGradient(boolean radial,
ColorSpace theColorspace,
Vector theColors,
Vector theBounds,
Vector theCoords)
{
PDFShading myShad;
PDFFunction myfunky;
PDFFunction myfunc;
Vector theCzero;
Vector theCone;
PDFPattern myPattern;
ColorSpace theColorSpace;
double interpolation = (double) 1.000;
Vector theFunctions = new Vector();
int currentPosition;
int lastPosition = theColors.size()-2;
//if 5 elements, the penultimate element is 3.
//do not go beyond that, because you always need
//to have a next color when creating the function.
for(currentPosition=0;
currentPosition < lastPosition;
currentPosition++)
{//for every consecutive color pair
PDFColor currentColor =
(PDFColor)theColors.elementAt(currentPosition);
PDFColor nextColor =
(PDFColor)theColors.elementAt(currentPosition+1);
//colorspace must be consistant
if (this.colorspace.getColorSpace() != currentColor.getColorSpace())
currentColor.setColorSpace(this.colorspace.getColorSpace());
if (this.colorspace.getColorSpace() != nextColor.getColorSpace())
nextColor.setColorSpace(this.colorspace.getColorSpace());
theCzero = currentColor.getVector();
theCone = nextColor.getVector();
myfunc = this.makeFunction(
2, null, null,
theCzero, theCone,
interpolation);
theFunctions.addElement(myfunc);
}//end of for every consecutive color pair
myfunky = this.makeFunction(3,
null, null,
theFunctions, theBounds,
null);
if(radial)
{
if(theCoords.size() ==6)
{
myShad = this.makeShading(
3, this.colorspace,
null, null, false,
theCoords, null, myfunky, null);
}
else
{ //if the center x, center y, and radius specifiy
//the gradient, then assume the same center x, center y,
//and radius of zero for the other necessary component
Vector newCoords = new Vector();
newCoords.addElement(theCoords.elementAt(0));
newCoords.addElement(theCoords.elementAt(1));
newCoords.addElement(theCoords.elementAt(2));
newCoords.addElement(theCoords.elementAt(0));
newCoords.addElement(theCoords.elementAt(1));
newCoords.addElement(new Double(0.0));
myShad = this.makeShading(
3, this.colorspace,
null, null, false,
newCoords, null, myfunky, null);
}
}
else
{
myShad = this.makeShading(
2, this.colorspace,
null, null, false,
theCoords, null, myfunky, null);
}
myPattern = this.makePattern(
2, myShad, null, null, null);
return(myPattern);
}
/**
* make a Type1 /Font object
*
* @param fontname internal name to use for this font (eg "F1")
* @param basefont name of the base font (eg "Helvetica")
* @param encoding character encoding scheme used by the font
* @return the created /Font object
*/
public PDFFont makeFont(String fontname, String basefont,
String encoding) {
/* create a PDFFont with the next object number and add to the
list of objects */
PDFFont font = new PDFFont(++this.objectcount, fontname,
basefont, encoding);
this.objects.addElement(font);
return font;
}
public int addImage(FopImage img) {
// check if already created
String url = img.getURL();
PDFXObject xObject = (PDFXObject) this.xObjectsMap.get(url);
if (xObject != null) return xObject.getXNumber();
// else, create a new one
xObject = new PDFXObject(++this.objectcount,
++this.xObjectCount, img);
this.objects.addElement(xObject);
this.xObjects.addElement(xObject);
this.xObjectsMap.put(url, xObject);
return xObjectCount;
}
/**
* make a /Page object
*
* @param resources resources object to use
* @param contents stream object with content
* @param pagewidth width of the page in points
* @param pageheight height of the page in points
*
* @return the created /Page object
*/
public PDFPage makePage(PDFResources resources,
PDFStream contents,
int pagewidth,
int pageheight) {
/* create a PDFPage with the next object number, the given
resources, contents and dimensions */
PDFPage page = new PDFPage(++this.objectcount, resources,
contents,
pagewidth, pageheight);
/* add it to the list of objects */
this.objects.addElement(page);
/* add the page to the Root */
this.root.addPage(page);
return page;
}
/**
* make a link object
*
* @param rect the clickable rectangle
* @param destination the destination file
*
* @return the PDFLink object created
*/
public PDFLink makeLink(Rectangle rect, String destination) {
PDFLink link = new PDFLink(++this.objectcount, rect);
this.objects.addElement(link);
PDFFileSpec fileSpec = new PDFFileSpec(++this.objectcount,
destination);
this.objects.addElement(fileSpec);
PDFAction action = new PDFAction(++this.objectcount,
fileSpec);
this.objects.addElement(action);
link.setAction(action);
return link;
}
/**
* make a stream object
*
* @return the stream object created
*/
public PDFStream makeStream() {
/* create a PDFStream with the next object number and add it
to the list of objects */
PDFStream obj = new PDFStream(++this.objectcount);
this.objects.addElement(obj);
return obj;
}
/**
* make an annotation list object
*
* @return the annotation list object created
*/
public PDFAnnotList makeAnnotList() {
/* create a PDFAnnotList with the next object number and add it
to the list of objects */
PDFAnnotList obj = new PDFAnnotList(++this.objectcount);
this.objects.addElement(obj);
return obj;
}
/**
* get the /Resources object for the document
*
* @return the /Resources object
*/
public PDFResources getResources() {
return this.resources;
}
/**
* write the entire document out
*
* @param writer the PrinterWriter to output the document to
*/
public void output(PrintWriter writer) throws IOException {
/* output the header and increment the character position by
the header's length */
this.position += outputHeader(writer);
this.resources.setXObjects(xObjects);
/* loop through the object numbers */
for (int i=1; i <= this.objectcount; i++) {
/* add the position of this object to the list of object
locations */
this.location.addElement(new Integer(this.position));
/* retrieve the object with the current number */
PDFObject object = (PDFObject)this.objects.elementAt(i-1);
/* output the object and increment the character position
by the object's length */
this.position += object.output(writer);
}
/* output the xref table and increment the character position
by the table's length */
this.position += outputXref(writer);
/* output the trailer and flush the Writer */
outputTrailer(writer);
writer.flush();
}
/**
* write the PDF header
*
* @param writer the PrintWriter to write the header to
* @return the number of characters written
*/
protected int outputHeader(PrintWriter writer) throws IOException {
String pdf = "%PDF-" + this.pdfVersion + "\n";
writer.write(pdf);
return pdf.length();
}
/**
* write the trailer
*
* @param writer the PrintWriter to write the trailer to
*/
protected void outputTrailer(PrintWriter writer) throws IOException {
/* construct the trailer */
String pdf = "trailer\n<<\n/Size " + (this.objectcount+1)
+ "\n/Root " + this.root.number + " " + this.root.generation
+ " R\n/Info " + this.info.number + " "
+ this.info.generation + " R\n>>\nstartxref\n" + this.xref
+ "\n%%EOF\n";
/* write the trailer */
writer.write(pdf);
}
/**
* write the xref table
*
* @param writer the PrintWriter to write the xref table to
* @return the number of characters written
*/
private int outputXref(PrintWriter writer) throws IOException {
/* remember position of xref table */
this.xref = this.position;
/* construct initial part of xref */
StringBuffer pdf = new StringBuffer("xref\n0 " + (this.objectcount+1)
+ "\n0000000000 65535 f \n");
/* loop through object numbers */
for (int i=1; i < this.objectcount+1; i++) {
/* contruct xref entry for object */
String padding = "0000000000";
String x = this.location.elementAt(i-1).toString();
String loc = padding.substring(x.length()) + x;
/* append to xref table */
pdf = pdf.append(loc + " 00000 n \n");
}
/* write the xref table and return the character length */
writer.write(pdf.toString());
return pdf.length();
}
}
| src/org/apache/fop/pdf/PDFDocument.java | /*-- $Id$ --
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "FOP" and "Apache Software Foundation" must not be used to
endorse or promote products derived from this software without prior
written permission. For written permission, please contact
[email protected].
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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
APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
DING, 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 software consists of voluntary contributions made by many individuals
on behalf of the Apache Software Foundation and was originally created by
James Tauber <[email protected]>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
/* image support modified from work of BoBoGi */
package org.apache.fop.pdf;
// images are the one place that FOP classes outside this package get
// referenced and I'd rather not do it
import org.apache.fop.image.FopImage;
import org.apache.fop.datatypes.ColorSpace;
// Java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import java.awt.Rectangle;
/**
* class representing a PDF document.
*
* The document is built up by calling various methods and then finally
* output to given filehandle using output method.
*
* A PDF document consists of a series of numbered objects preceded by a
* header and followed by an xref table and trailer. The xref table
* allows for quick access to objects by listing their character
* positions within the document. For this reason the PDF document must
* keep track of the character position of each object. The document
* also keeps direct track of the /Root, /Info and /Resources objects.
*/
public class PDFDocument {
/** the version of PDF supported */
protected static final String pdfVersion = "1.3";
/** the current character position */
protected int position = 0;
/** the character position of each object */
protected Vector location = new Vector();
/** the counter for object numbering */
protected int objectcount = 0;
/** the objects themselves */
protected Vector objects = new Vector();
/** character position of xref table */
protected int xref;
/** the /Root object */
protected PDFRoot root;
/** the /Info object */
protected PDFInfo info;
/** the /Resources object */
protected PDFResources resources;
/** the colorspace (0=RGB, 1=CMYK) **/
//protected int colorspace = 0;
protected ColorSpace colorspace = new ColorSpace(ColorSpace.DEVICE_RGB);
/** the counter for Pattern name numbering (e.g. 'Pattern1')*/
protected int patternCount = 0;
/** the counter for Shading name numbering */
protected int shadingCount = 0;
/** the counter for XObject numbering */
protected int xObjectCount = 0;
/** the XObjects */
protected Vector xObjects = new Vector();
/**
* creates an empty PDF document
*/
public PDFDocument() {
/* create the /Root, /Info and /Resources objects */
this.root = makeRoot();
this.info = makeInfo();
this.resources = makeResources();
}
/**
* set the producer of the document
*
* @param producer string indicating application producing the PDF
*/
public void setProducer(String producer) {
this.info.setProducer(producer);
}
/**
* make /Root object as next object
*
* @return the created /Root object
*/
protected PDFRoot makeRoot() {
/* create a PDFRoot with the next object number and add to
list of objects */
PDFRoot pdfRoot = new PDFRoot(++this.objectcount);
this.objects.addElement(pdfRoot);
/* create a new /Pages object to be root of Pages hierarchy
and add to list of objects */
PDFPages rootPages = new PDFPages(++this.objectcount);
this.objects.addElement(rootPages);
/* inform the /Root object of the /Pages root */
pdfRoot.setRootPages(rootPages);
return pdfRoot;
}
/**
* make an /Info object
*
* @param producer string indicating application producing the PDF
* @return the created /Info object
*/
protected PDFInfo makeInfo() {
/* create a PDFInfo with the next object number and add to
list of objects */
PDFInfo pdfInfo = new PDFInfo(++this.objectcount);
this.objects.addElement(pdfInfo);
return pdfInfo;
}
/**
* make a /Resources object
*
* @return the created /Resources object
*/
private PDFResources makeResources() {
/* create a PDFResources with the next object number and add
to list of objects */
PDFResources pdfResources = new PDFResources(++this.objectcount);
this.objects.addElement(pdfResources);
return pdfResources;
}
/**
* Make a Type 0 sampled function
*
* @param theDomain Vector objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theRange Vector objects of Double objects.
* This is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theSize A Vector object of Integer objects.
* This is the number of samples in each input dimension.
* I can't imagine there being more or less than two input dimensions,
* so maybe this should be an array of length 2.
*
* See page 265 of the PDF 1.3 Spec.
* @param theBitsPerSample An int specifying the number of bits user to represent each sample value.
* Limited to 1,2,4,8,12,16,24 or 32.
* See page 265 of the 1.3 PDF Spec.
* @param theOrder The order of interpolation between samples. Default is 1 (one). Limited
* to 1 (one) or 3, which means linear or cubic-spline interpolation.
*
* This attribute is optional.
*
* See page 265 in the PDF 1.3 spec.
* @param theEncode Vector objects of Double objects.
* This is the linear mapping of input values intop the domain
* of the function's sample table. Default is hard to represent in
* ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
* This attribute is optional.
*
* See page 265 in the PDF 1.3 spec.
* @param theDecode Vector objects of Double objects.
* This is a linear mapping of sample values into the range.
* The default is just the range.
*
* This attribute is optional.
* Read about it on page 265 of the PDF 1.3 spec.
* @param theFunctionDataStream The sample values that specify the function are provided in a stream.
*
* This is optional, but is almost always used.
*
* Page 265 of the PDF 1.3 spec has more.
* @param theFilter This is a vector of String objects which are the various filters that
* have are to be applied to the stream to make sense of it. Order matters,
* so watch out.
*
* This is not documented in the Function section of the PDF 1.3 spec,
* it was deduced from samples that this is sometimes used, even if we may never
* use it in FOP. It is added for completeness sake.
* @param theNumber The object number of this PDF object.
* @param theFunctionType This is the type of function (0,2,3, or 4).
* It should be 0 as this is the constructor for sampled functions.
*/
public PDFFunction makeFunction(int theFunctionType,
Vector theDomain, Vector theRange,
Vector theSize,int theBitsPerSample,
int theOrder,Vector theEncode,Vector theDecode,
StringBuffer theFunctionDataStream, Vector theFilter)
{//Type 0 function
PDFFunction function = new PDFFunction(
++this.objectcount, theFunctionType,
theDomain, theRange, theSize,
theBitsPerSample, theOrder,
theEncode, theDecode,
theFunctionDataStream, theFilter);
this.objects.addElement(function);
return(function);
}
/**
* make a type Exponential interpolation function
* (for shading usually)
*
* @param theDomain Vector objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theRange Vector of Doubles that is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theCZero This is a vector of Double objects which defines the function result
* when x=0.
*
* This attribute is optional.
* It's described on page 268 of the PDF 1.3 spec.
* @param theCOne This is a vector of Double objects which defines the function result
* when x=1.
*
* This attribute is optional.
* It's described on page 268 of the PDF 1.3 spec.
* @param theInterpolationExponentN This is the inerpolation exponent.
*
* This attribute is required.
* PDF Spec page 268
* @param theFunctionType The type of the function, which should be 2.
*/
public PDFFunction makeFunction(int theFunctionType,
Vector theDomain, Vector theRange,
Vector theCZero, Vector theCOne,
double theInterpolationExponentN)
{//type 2
PDFFunction function = new PDFFunction(
++this.objectcount,
theFunctionType,
theDomain, theRange,
theCZero, theCOne,
theInterpolationExponentN);
this.objects.addElement(function);
return(function);
}
/**
* Make a Type 3 Stitching function
*
* @param theDomain Vector objects of Double objects.
* This is the domain of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theRange Vector objects of Double objects.
* This is the Range of the function.
* See page 264 of the PDF 1.3 Spec.
* @param theFunctions A Vector of the PDFFunction objects that the stitching function stitches.
*
* This attributed is required.
* It is described on page 269 of the PDF spec.
* @param theBounds This is a vector of Doubles representing the numbers that,
* in conjunction with Domain define the intervals to which each function from
* the 'functions' object applies. It must be in order of increasing magnitude,
* and each must be within Domain.
*
* It basically sets how much of the gradient each function handles.
*
* This attributed is required.
* It's described on page 269 of the PDF 1.3 spec.
* @param theEncode Vector objects of Double objects.
* This is the linear mapping of input values intop the domain
* of the function's sample table. Default is hard to represent in
* ascii, but basically [0 (Size0 1) 0 (Size1 1)...].
* This attribute is required.
*
* See page 270 in the PDF 1.3 spec.
* @param theFunctionType This is the function type. It should be 3,
* for a stitching function.
*/
public PDFFunction makeFunction(int theFunctionType,
Vector theDomain, Vector theRange,
Vector theFunctions, Vector theBounds,
Vector theEncode)
{//Type 3
PDFFunction function = new PDFFunction(
++this.objectcount,
theFunctionType,
theDomain, theRange,
theFunctions, theBounds,
theEncode);
this.objects.addElement(function);
return(function);
}
/**
* make a postscript calculator function
*
* @param theNumber
* @param theFunctionType
* @param theDomain
* @param theRange
* @param theFunctionDataStream
*/
public PDFFunction makeFunction(int theNumber, int theFunctionType,
Vector theDomain, Vector theRange,
StringBuffer theFunctionDataStream)
{ //Type 4
PDFFunction function = new PDFFunction(
++this.objectcount,
theFunctionType,
theDomain, theRange,
theFunctionDataStream);
this.objects.addElement(function);
return(function);
}
/**
* make a function based shading object
*
* @param theShadingType The type of shading object, which should be 1 for function
* based shading.
* @param theColorSpace The colorspace is 'DeviceRGB' or something similar.
* @param theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox Vector of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Whether or not to anti-alias.
* @param theDomain Optional vector of Doubles specifying the domain.
* @param theMatrix Vector of Doubles specifying the matrix.
* If it's a pattern, then the matrix maps it to pattern space.
* If it's a shading, then it maps it to current user space.
* It's optional, the default is the identity matrix
* @param theFunction The PDF Function that maps an (x,y) location to a color
*/
public PDFShading makeShading(int theShadingType, ColorSpace theColorSpace,
Vector theBackground, Vector theBBox, boolean theAntiAlias,
Vector theDomain, Vector theMatrix, PDFFunction theFunction)
{ //make Shading of Type 1
String theShadingName = new String("Sh"+(++this.shadingCount));
PDFShading shading = new PDFShading(++this.objectcount, theShadingName,
theShadingType, theColorSpace, theBackground, theBBox,
theAntiAlias, theDomain, theMatrix, theFunction);
this.objects.addElement(shading);
//add this shading to resources
this.resources.addShading(shading);
return(shading);
}
/**
* Make an axial or radial shading object.
*
* @param theShadingType 2 or 3 for axial or radial shading
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox Vector of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Default is false
* @param theCoords Vector of four (type 2) or 6 (type 3) Double
* @param theDomain Vector of Doubles specifying the domain
* @param theFunction the Stitching (PDFfunction type 3) function, even if it's stitching a single function
* @param theExtend Vector of Booleans of whether to extend teh start and end colors past the start and end points
* The default is [false, false]
*/
public PDFShading makeShading(int theShadingType,
ColorSpace theColorSpace, Vector theBackground,
Vector theBBox, boolean theAntiAlias,
Vector theCoords, Vector theDomain,
PDFFunction theFunction, Vector theExtend)
{ //make Shading of Type 2 or 3
String theShadingName = new String("Sh"+(++this.shadingCount));
PDFShading shading = new PDFShading(++this.objectcount, theShadingName,
theShadingType, theColorSpace,
theBackground, theBBox, theAntiAlias,
theCoords, theDomain,theFunction,theExtend);
this.resources.addShading(shading);
this.objects.addElement(shading);
return(shading);
}
/**
* Make a free-form gouraud shaded triangle mesh, coons patch mesh, or tensor patch mesh
* shading object
*
* @param theShadingType 4, 6, or 7 depending on whether it's
* Free-form gouraud-shaded triangle meshes, coons patch meshes,
* or tensor product patch meshes, respectively.
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox Vector of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Default is false
* @param theBitsPerCoordinate 1,2,4,8,12,16,24 or 32.
* @param theBitsPerComponent 1,2,4,8,12, and 16
* @param theBitsPerFlag 2,4,8.
* @param theDecode Vector of Doubles see PDF 1.3 spec pages 303 to 312.
* @param theFunction the PDFFunction
*/
public PDFShading makeShading(int theShadingType, ColorSpace theColorSpace,
Vector theBackground, Vector theBBox, boolean theAntiAlias,
int theBitsPerCoordinate, int theBitsPerComponent,
int theBitsPerFlag, Vector theDecode, PDFFunction theFunction)
{ //make Shading of type 4,6 or 7
String theShadingName = new String("Sh"+(++this.shadingCount));
PDFShading shading = new PDFShading(++this.objectcount, theShadingName,
theShadingType, theColorSpace,
theBackground, theBBox, theAntiAlias,
theBitsPerCoordinate,theBitsPerComponent,
theBitsPerFlag, theDecode, theFunction);
this.resources.addShading(shading);
this.objects.addElement(shading);
return(shading);
}
/**
* make a Lattice-Form Gouraud mesh shading object
*
* @param theShadingType 5 for lattice-Form Gouraud shaded-triangle mesh
* without spaces. "Shading1" or "Sh1" are good examples.
* @param theColorSpace "DeviceRGB" or similar.
* @param theBackground theBackground An array of color components appropriate to the
* colorspace key specifying a single color value.
* This key is used by the f operator buy ignored by the sh operator.
* @param theBBox Vector of double's representing a rectangle
* in the coordinate space that is current at the
* time of shading is imaged. Temporary clipping
* boundary.
* @param theAntiAlias Default is false
* @param theBitsPerCoordinate 1,2,4,8,12,16, 24, or 32
* @param theBitsPerComponent 1,2,4,8,12,24,32
* @param theDecode Vector of Doubles. See page 305 in PDF 1.3 spec.
* @param theVerticesPerRow number of vertices in each "row" of the lattice.
* @param theFunction The PDFFunction that's mapped on to this shape
*/
public PDFShading makeShading(int theShadingType, ColorSpace theColorSpace,
Vector theBackground, Vector theBBox, boolean theAntiAlias,
int theBitsPerCoordinate, int theBitsPerComponent,
Vector theDecode, int theVerticesPerRow, PDFFunction theFunction)
{ //make shading of Type 5
String theShadingName = new String("Sh"+(++this.shadingCount));
PDFShading shading= new PDFShading(++this.objectcount,
theShadingName, theShadingType, theColorSpace,
theBackground, theBBox, theAntiAlias,
theBitsPerCoordinate, theBitsPerComponent,
theDecode, theVerticesPerRow, theFunction);
this.resources.addShading(shading);
this.objects.addElement(shading);
return(shading);
}
/**
* Make a tiling pattern
*
* @param thePatternType the type of pattern, which is 1 for tiling.
* @param theResources the resources associated with this pattern
* @param thePaintType 1 or 2, colored or uncolored.
* @param theTilingType 1, 2, or 3, constant spacing, no distortion, or faster tiling
* @param theBBox Vector of Doubles: The pattern cell bounding box
* @param theXStep horizontal spacing
* @param theYStep vertical spacing
* @param theMatrix Optional Vector of Doubles transformation matrix
* @param theXUID Optional vector of Integers that uniquely identify the pattern
* @param thePatternDataStream The stream of pattern data to be tiled.
*/
public PDFPattern makePattern(
int thePatternType, //1
PDFResources theResources,
int thePaintType, int theTilingType,
Vector theBBox, double theXStep, double theYStep,
Vector theMatrix, Vector theXUID, StringBuffer thePatternDataStream)
{
String thePatternName = new String("Pa"+(++this.patternCount));
//int theNumber, String thePatternName,
//PDFResources theResources
PDFPattern pattern = new PDFPattern(++this.objectcount,
thePatternName,
theResources, 1,
thePaintType, theTilingType,
theBBox, theXStep, theYStep,
theMatrix, theXUID, thePatternDataStream);
this.resources.addPattern(pattern);
this.objects.addElement(pattern);
return(pattern);
}
/**
* Make a smooth shading pattern
*
* @param thePatternType the type of the pattern, which is 2, smooth shading
* @param theShading the PDF Shading object that comprises this pattern
* @param theXUID optional:the extended unique Identifier if used.
* @param theExtGState optional: the extended graphics state, if used.
* @param theMatrix Optional:Vector of Doubles that specify the matrix.
*/
public PDFPattern makePattern(int thePatternType,
PDFShading theShading, Vector theXUID,
StringBuffer theExtGState,Vector theMatrix)
{
String thePatternName = new String("Pa"+(++this.patternCount));
PDFPattern pattern = new PDFPattern(++this.objectcount,
thePatternName, 2, theShading, theXUID,
theExtGState, theMatrix);
this.resources.addPattern(pattern);
this.objects.addElement(pattern);
return(pattern);
}
public int getColorSpace()
{
return(this.colorspace.getColorSpace());
}
public void setColorSpace(int theColorspace)
{
this.colorspace.setColorSpace(theColorspace);
return;
}
public PDFPattern createGradient(boolean radial,
ColorSpace theColorspace,
Vector theColors,
Vector theBounds,
Vector theCoords)
{
PDFShading myShad;
PDFFunction myfunky;
PDFFunction myfunc;
Vector theCzero;
Vector theCone;
PDFPattern myPattern;
ColorSpace theColorSpace;
double interpolation = (double) 1.000;
Vector theFunctions = new Vector();
int currentPosition;
int lastPosition = theColors.size()-2;
//if 5 elements, the penultimate element is 3.
//do not go beyond that, because you always need
//to have a next color when creating the function.
for(currentPosition=0;
currentPosition < lastPosition;
currentPosition++)
{//for every consecutive color pair
PDFColor currentColor =
(PDFColor)theColors.elementAt(currentPosition);
PDFColor nextColor =
(PDFColor)theColors.elementAt(currentPosition+1);
//colorspace must be consistant
if (this.colorspace.getColorSpace() != currentColor.getColorSpace())
currentColor.setColorSpace(this.colorspace.getColorSpace());
if (this.colorspace.getColorSpace() != nextColor.getColorSpace())
nextColor.setColorSpace(this.colorspace.getColorSpace());
theCzero = currentColor.getVector();
theCone = nextColor.getVector();
myfunc = this.makeFunction(
2, null, null,
theCzero, theCone,
interpolation);
theFunctions.addElement(myfunc);
}//end of for every consecutive color pair
myfunky = this.makeFunction(3,
null, null,
theFunctions, theBounds,
null);
if(radial)
{
if(theCoords.size() ==6)
{
myShad = this.makeShading(
3, this.colorspace,
null, null, false,
theCoords, null, myfunky, null);
}
else
{ //if the center x, center y, and radius specifiy
//the gradient, then assume the same center x, center y,
//and radius of zero for the other necessary component
Vector newCoords = new Vector();
newCoords.addElement(theCoords.elementAt(0));
newCoords.addElement(theCoords.elementAt(1));
newCoords.addElement(theCoords.elementAt(2));
newCoords.addElement(theCoords.elementAt(0));
newCoords.addElement(theCoords.elementAt(1));
newCoords.addElement(new Double(0.0));
myShad = this.makeShading(
3, this.colorspace,
null, null, false,
newCoords, null, myfunky, null);
}
}
else
{
myShad = this.makeShading(
2, this.colorspace,
null, null, false,
theCoords, null, myfunky, null);
}
myPattern = this.makePattern(
2, myShad, null, null, null);
return(myPattern);
}
/**
* make a Type1 /Font object
*
* @param fontname internal name to use for this font (eg "F1")
* @param basefont name of the base font (eg "Helvetica")
* @param encoding character encoding scheme used by the font
* @return the created /Font object
*/
public PDFFont makeFont(String fontname, String basefont,
String encoding) {
/* create a PDFFont with the next object number and add to the
list of objects */
PDFFont font = new PDFFont(++this.objectcount, fontname,
basefont, encoding);
this.objects.addElement(font);
return font;
}
public int addImage(FopImage img) {
PDFXObject xObject = new PDFXObject(++this.objectcount,
++this.xObjectCount, img);
this.objects.addElement(xObject);
this.xObjects.addElement(xObject);
return xObjectCount;
}
/**
* make a /Page object
*
* @param resources resources object to use
* @param contents stream object with content
* @param pagewidth width of the page in points
* @param pageheight height of the page in points
*
* @return the created /Page object
*/
public PDFPage makePage(PDFResources resources,
PDFStream contents,
int pagewidth,
int pageheight) {
/* create a PDFPage with the next object number, the given
resources, contents and dimensions */
PDFPage page = new PDFPage(++this.objectcount, resources,
contents,
pagewidth, pageheight);
/* add it to the list of objects */
this.objects.addElement(page);
/* add the page to the Root */
this.root.addPage(page);
return page;
}
/**
* make a link object
*
* @param rect the clickable rectangle
* @param destination the destination file
*
* @return the PDFLink object created
*/
public PDFLink makeLink(Rectangle rect, String destination) {
PDFLink link = new PDFLink(++this.objectcount, rect);
this.objects.addElement(link);
PDFFileSpec fileSpec = new PDFFileSpec(++this.objectcount,
destination);
this.objects.addElement(fileSpec);
PDFAction action = new PDFAction(++this.objectcount,
fileSpec);
this.objects.addElement(action);
link.setAction(action);
return link;
}
/**
* make a stream object
*
* @return the stream object created
*/
public PDFStream makeStream() {
/* create a PDFStream with the next object number and add it
to the list of objects */
PDFStream obj = new PDFStream(++this.objectcount);
this.objects.addElement(obj);
return obj;
}
/**
* make an annotation list object
*
* @return the annotation list object created
*/
public PDFAnnotList makeAnnotList() {
/* create a PDFAnnotList with the next object number and add it
to the list of objects */
PDFAnnotList obj = new PDFAnnotList(++this.objectcount);
this.objects.addElement(obj);
return obj;
}
/**
* get the /Resources object for the document
*
* @return the /Resources object
*/
public PDFResources getResources() {
return this.resources;
}
/**
* write the entire document out
*
* @param writer the PrinterWriter to output the document to
*/
public void output(PrintWriter writer) throws IOException {
/* output the header and increment the character position by
the header's length */
this.position += outputHeader(writer);
this.resources.setXObjects(xObjects);
/* loop through the object numbers */
for (int i=1; i <= this.objectcount; i++) {
/* add the position of this object to the list of object
locations */
this.location.addElement(new Integer(this.position));
/* retrieve the object with the current number */
PDFObject object = (PDFObject)this.objects.elementAt(i-1);
/* output the object and increment the character position
by the object's length */
this.position += object.output(writer);
}
/* output the xref table and increment the character position
by the table's length */
this.position += outputXref(writer);
/* output the trailer and flush the Writer */
outputTrailer(writer);
writer.flush();
}
/**
* write the PDF header
*
* @param writer the PrintWriter to write the header to
* @return the number of characters written
*/
protected int outputHeader(PrintWriter writer) throws IOException {
String pdf = "%PDF-" + this.pdfVersion + "\n";
writer.write(pdf);
return pdf.length();
}
/**
* write the trailer
*
* @param writer the PrintWriter to write the trailer to
*/
protected void outputTrailer(PrintWriter writer) throws IOException {
/* construct the trailer */
String pdf = "trailer\n<<\n/Size " + (this.objectcount+1)
+ "\n/Root " + this.root.number + " " + this.root.generation
+ " R\n/Info " + this.info.number + " "
+ this.info.generation + " R\n>>\nstartxref\n" + this.xref
+ "\n%%EOF\n";
/* write the trailer */
writer.write(pdf);
}
/**
* write the xref table
*
* @param writer the PrintWriter to write the xref table to
* @return the number of characters written
*/
private int outputXref(PrintWriter writer) throws IOException {
/* remember position of xref table */
this.xref = this.position;
/* construct initial part of xref */
StringBuffer pdf = new StringBuffer("xref\n0 " + (this.objectcount+1)
+ "\n0000000000 65535 f \n");
/* loop through object numbers */
for (int i=1; i < this.objectcount+1; i++) {
/* contruct xref entry for object */
String padding = "0000000000";
String x = this.location.elementAt(i-1).toString();
String loc = padding.substring(x.length()) + x;
/* append to xref table */
pdf = pdf.append(loc + " 00000 n \n");
}
/* write the xref table and return the character length */
writer.write(pdf.toString());
return pdf.length();
}
}
| modify this class to only create a new PDFXobject if needed
git-svn-id: 102839466c3b40dd9c7e25c0a1a6d26afc40150a@193374 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/fop/pdf/PDFDocument.java | modify this class to only create a new PDFXobject if needed |
|
Java | apache-2.0 | 24ce4717fef2d529d650f144b8ca61adfae59797 | 0 | robinverduijn/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,gstevey/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,gstevey/gradle,blindpirate/gradle | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.nativeplatform.test.googletest.internal;
import org.gradle.nativeplatform.NativeComponentSpec;
import org.gradle.nativeplatform.internal.AbstractNativeComponentSpec;
import org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec;
public class DefaultGoogleTestTestSuiteSpec extends AbstractNativeComponentSpec implements GoogleTestTestSuiteSpec {
private NativeComponentSpec testedComponent;
public String getDisplayName() {
return String.format("googleTest test suite '%s'", getName());
}
public NativeComponentSpec getTestedComponent() {
return testedComponent;
}
public void setTestedComponent(NativeComponentSpec testedComponent) {
this.testedComponent = testedComponent;
}
}
| subprojects/testing-native/src/main/java/org/gradle/nativeplatform/test/googletest/internal/DefaultGoogleTestTestSuiteSpec.java | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.nativeplatform.test.googletest.internal;
import org.gradle.nativeplatform.NativeComponentSpec;
import org.gradle.nativeplatform.internal.AbstractNativeComponentSpec;
import org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec;
public class DefaultGoogleTestTestSuiteSpec extends AbstractNativeComponentSpec implements GoogleTestTestSuiteSpec {
private NativeComponentSpec testedComponent;
public String getDisplayName() {
return String.format("googleTest test suite '%s'", getName());
}
public NativeComponentSpec getTestedComponent() {
return testedComponent;
}
public void setTestedComponent(NativeComponentSpec testedComponent) {
this.testedComponent = testedComponent;
}
}
| Whitespace.
| subprojects/testing-native/src/main/java/org/gradle/nativeplatform/test/googletest/internal/DefaultGoogleTestTestSuiteSpec.java | Whitespace. |
|
Java | apache-2.0 | b2d14381856c27c9088bc9e28372270e7506f9b6 | 0 | blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.ide.visualstudio.internal;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.util.VersionNumber;
import java.io.File;
import java.util.List;
import java.util.Set;
/**
* A model-agnostic adapter for binary information
*/
public interface VisualStudioTargetBinary {
/**
* Returns the Gradle project path for this binary
*/
@Input
String getProjectPath();
/**
* Returns the name of the Gradle component associated with this binary
*/
@Input
String getComponentName();
/**
* Returns the visual studio project name associated with this binary
*/
@Input
String getVisualStudioProjectName();
/**
* Returns the visual studio project configuration name associated with this binary
*/
@Input
String getVisualStudioConfigurationName();
/**
* Returns the target Visual Studio version of this binary.
*/
@Internal
VersionNumber getVisualStudioVersion();
/**
* Returns the target SDK version of this binary.
*/
@Internal
VersionNumber getSdkVersion();
/**
* Returns the project suffix to use when naming Visual Studio projects
*/
@Input
ProjectType getProjectType();
/**
* Returns the variant dimensions associated with this binary
*/
@Input
List<String> getVariantDimensions();
/**
* Returns the source files associated with this binary
*/
@Internal
FileCollection getSourceFiles();
/**
* Returns the resource files associated with this binary
*/
@Internal
FileCollection getResourceFiles();
/**
* Returns the header files associated with this binary
*/
@Internal
FileCollection getHeaderFiles();
/**
* Returns whether or not this binary represents an executable
*/
@Input
boolean isExecutable();
/**
* Returns a task that can be used to build this binary
*/
@Input
String getBuildTaskPath();
/**
* Returns a task that can be used to clean the outputs of this binary
*/
@Input
String getCleanTaskPath();
/**
* Returns whether or not this binary is a debuggable variant
*/
@Input
boolean isDebuggable();
/**
* Returns the main product of this binary (i.e. executable or library file)
*/
@Internal
File getOutputFile();
/**
* Returns the compiler definitions that should be used with this binary
*/
@Input
List<String> getCompilerDefines();
/**
* Returns the language standard of the source for this binary.
*/
@Input
LanguageStandard getLanguageStandard();
/**
* Returns the include paths that should be used with this binary
*/
@Internal
Set<File> getIncludePaths();
enum ProjectType {
EXE("Exe"), LIB("Lib"), DLL("Dll"), NONE("");
private final String suffix;
ProjectType(String suffix) {
this.suffix = suffix;
}
public String getSuffix() {
return suffix;
}
}
enum LanguageStandard {
NONE(""),
STD_CPP_14("stdcpp14"),
STD_CPP_17("stdcpp17"),
STD_CPP_LATEST("stdcpplatest");
private final String value;
LanguageStandard(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static LanguageStandard from(List<String> arguments) {
return arguments.stream().filter(it -> it.matches("^[-/]std:cpp.+")).findFirst().map(it -> {
if (it.endsWith("cpp14")) {
return LanguageStandard.STD_CPP_14;
} else if (it.endsWith("cpp17")) {
return LanguageStandard.STD_CPP_17;
} else if (it.endsWith("cpplatest")) {
return LanguageStandard.STD_CPP_LATEST;
}
return LanguageStandard.NONE;
}).orElse(LanguageStandard.NONE);
}
}
}
| subprojects/ide-native/src/main/java/org/gradle/ide/visualstudio/internal/VisualStudioTargetBinary.java | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.ide.visualstudio.internal;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.util.VersionNumber;
import java.io.File;
import java.util.List;
import java.util.Set;
/**
* A model-agnostic adapter for binary information
*/
public interface VisualStudioTargetBinary {
/**
* Returns the Gradle project path for this binary
*/
@Input
String getProjectPath();
/**
* Returns the name of the Gradle component associated with this binary
*/
@Input
String getComponentName();
/**
* Returns the visual studio project name associated with this binary
*/
@Input
String getVisualStudioProjectName();
/**
* Returns the visual studio project configuration name associated with this binary
*/
@Input
String getVisualStudioConfigurationName();
/**
* Returns the target Visual Studio version of this binary.
*/
VersionNumber getVisualStudioVersion();
/**
* Returns the target SDK version of this binary.
*/
VersionNumber getSdkVersion();
/**
* Returns the project suffix to use when naming Visual Studio projects
*/
@Input
ProjectType getProjectType();
/**
* Returns the variant dimensions associated with this binary
*/
@Input
List<String> getVariantDimensions();
/**
* Returns the source files associated with this binary
*/
@Internal
FileCollection getSourceFiles();
/**
* Returns the resource files associated with this binary
*/
@Internal
FileCollection getResourceFiles();
/**
* Returns the header files associated with this binary
*/
@Internal
FileCollection getHeaderFiles();
/**
* Returns whether or not this binary represents an executable
*/
@Input
boolean isExecutable();
/**
* Returns a task that can be used to build this binary
*/
@Input
String getBuildTaskPath();
/**
* Returns a task that can be used to clean the outputs of this binary
*/
@Input
String getCleanTaskPath();
/**
* Returns whether or not this binary is a debuggable variant
*/
@Input
boolean isDebuggable();
/**
* Returns the main product of this binary (i.e. executable or library file)
*/
@Internal
File getOutputFile();
/**
* Returns the compiler definitions that should be used with this binary
*/
@Input
List<String> getCompilerDefines();
/**
* Returns the language standard of the source for this binary.
*/
@Input
LanguageStandard getLanguageStandard();
/**
* Returns the include paths that should be used with this binary
*/
@Internal
Set<File> getIncludePaths();
enum ProjectType {
EXE("Exe"), LIB("Lib"), DLL("Dll"), NONE("");
private final String suffix;
ProjectType(String suffix) {
this.suffix = suffix;
}
public String getSuffix() {
return suffix;
}
}
enum LanguageStandard {
NONE(""),
STD_CPP_14("stdcpp14"),
STD_CPP_17("stdcpp17"),
STD_CPP_LATEST("stdcpplatest");
private final String value;
LanguageStandard(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static LanguageStandard from(List<String> arguments) {
return arguments.stream().filter(it -> it.matches("^[-/]std:cpp.+")).findFirst().map(it -> {
if (it.endsWith("cpp14")) {
return LanguageStandard.STD_CPP_14;
} else if (it.endsWith("cpp17")) {
return LanguageStandard.STD_CPP_17;
} else if (it.endsWith("cpplatest")) {
return LanguageStandard.STD_CPP_LATEST;
}
return LanguageStandard.NONE;
}).orElse(LanguageStandard.NONE);
}
}
}
| Fix VisualStudioTargetBinary annotations
| subprojects/ide-native/src/main/java/org/gradle/ide/visualstudio/internal/VisualStudioTargetBinary.java | Fix VisualStudioTargetBinary annotations |
|
Java | apache-2.0 | 1272a77d568b38e598f2984e00ee148ef0c2b9b5 | 0 | Navrattan-Yadav/rest-assured,pxy0592/rest-assured,eeichinger/rest-assured,BenSeverson/rest-assured,RocketRaccoon/rest-assured,suvarnaraju/rest-assured,paweld2/rest-assured,MattGong/rest-assured,nishantkashyap/rest-assured-1,janusnic/rest-assured,Igor-Petrov/rest-assured,jayway/rest-assured,MattGong/rest-assured,pxy0592/rest-assured,rest-assured/rest-assured,camunda-third-party/rest-assured,Navrattan-Yadav/rest-assured,nishantkashyap/rest-assured-1,janusnic/rest-assured,rest-assured/rest-assured,RocketRaccoon/rest-assured,dushmis/rest-assured,jayway/rest-assured,BenSeverson/rest-assured,caravenase/rest-assured,paweld2/rest-assured,Igor-Petrov/rest-assured,lucamilanesio/rest-assured,caravenase/rest-assured,caravena-nisum-com/rest-assured,suvarnaraju/rest-assured,eeichinger/rest-assured,camunda-third-party/rest-assured,rest-assured/rest-assured,caravena-nisum-com/rest-assured,dushmis/rest-assured | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.restassured.path.xml;
import com.jayway.restassured.assertion.XMLAssertion;
import com.jayway.restassured.internal.path.ObjectConverter;
import com.jayway.restassured.internal.path.xml.GroovyNodeSerializer;
import com.jayway.restassured.internal.path.xml.NodeBase;
import com.jayway.restassured.internal.path.xml.XmlPrettifier;
import com.jayway.restassured.internal.path.xml.mapping.XmlObjectDeserializer;
import com.jayway.restassured.mapper.factory.JAXBObjectMapperFactory;
import com.jayway.restassured.path.xml.config.XmlParserType;
import com.jayway.restassured.path.xml.config.XmlPathConfig;
import com.jayway.restassured.path.xml.element.Node;
import com.jayway.restassured.path.xml.element.NodeChildren;
import com.jayway.restassured.path.xml.exception.XmlPathException;
import groovy.lang.GroovyRuntimeException;
import groovy.util.XmlSlurper;
import groovy.util.slurpersupport.GPathResult;
import groovy.xml.XmlUtil;
import org.apache.commons.lang3.Validate;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.net.URI;
import java.util.*;
import java.util.Map.Entry;
import static com.jayway.restassured.internal.assertion.AssertParameter.notNull;
import static com.jayway.restassured.path.xml.XmlPath.CompatibilityMode.XML;
/**
* XmlPath is an alternative to using XPath for easily getting values from an XML document. It follows the Groovy syntax
* described <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">here</a>. <br>Let's say we have an XML defined as;
* <pre>
* <shopping>
* <category type="groceries">
* <item>
* <name>Chocolate</name>
* <price>10</price>
* </item>
* <item>
* <name>Coffee</name>
* <price>20</price>
* </item>
* </category>
* <category type="supplies">
* <item>
* <name>Paper</name>
* <price>5</price>
* </item>
* <item quantity="4">
* <name>Pens</name>
* <price>15</price>
* </item>
* </category>
* <category type="present">
* <item when="Aug 10">
* <name>Kathryn's Birthday</name>
* <price>200</price>
* </item>
* </category>
* </shopping>
* </pre>
* <p/>
* Get the name of the first category item:
* <pre>
* String name = with(XML).get("shopping.category.item[0].name");
* </pre>
* <p/>
* To get the number of category items:
* <pre>
* int items = with(XML).get("shopping.category.item.size()");
* </pre>
* <p/>
* Get a specific category:
* <pre>
* Node category = with(XML).get("shopping.category[0]");
* </pre>
* <p/>
* To get the number of categories with type attribute equal to 'groceries':
* <pre>
* int items = with(XML).get("shopping.category.findAll { it.@type == 'groceries' }.size()");
* </pre>
* <p/>
* Get all items with price greater than or equal to 10 and less than or equal to 20:
* <pre>
* List<Node> itemsBetweenTenAndTwenty = with(XML).get("shopping.category.item.findAll { item -> def price = item.price.toFloat(); price >= 10 && price <= 20 }");
* </pre>
* <p/>
* Get the chocolate price:
* <pre>
* int priceOfChocolate = with(XML).getInt("**.find { it.name == 'Chocolate' }.price"
* </pre>
* <p/>
* You can also parse HTML by setting compatibility mode to HTML:
* <pre>
* XmlPath xmlPath = new XmlPath(CompatibilityMode.HTML,<some html>);
* </pre>
*/
public class XmlPath {
public static XmlPathConfig config = null;
private final CompatibilityMode mode;
private LazyXmlParser lazyXmlParser;
private XmlPathConfig xmlPathConfig = null;
private String rootPath = "";
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public XmlPath(String text) {
this(XML, text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param stream The stream containing the XML document
*/
public XmlPath(InputStream stream) {
this(XML, stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public XmlPath(InputSource source) {
this(XML, source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public XmlPath(File file) {
this(XML, file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public XmlPath(Reader reader) {
this(XML, reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public XmlPath(URI uri) {
this(XML, uri);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param text The text containing the XML document
*/
public XmlPath(CompatibilityMode mode, String text) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseText(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param stream The stream containing the XML document
*/
public XmlPath(CompatibilityMode mode, InputStream stream) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseInputStream(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param source The source containing the XML document
*/
public XmlPath(CompatibilityMode mode, InputSource source) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseInputSource(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param file The file containing the XML document
*/
public XmlPath(CompatibilityMode mode, File file) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseFile(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param reader The reader containing the XML document
*/
public XmlPath(CompatibilityMode mode, Reader reader) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseReader(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param uri The URI containing the XML document
*/
public XmlPath(CompatibilityMode mode, URI uri) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseURI(uri);
}
/**
* Configure XmlPath to use a specific JAXB object mapper factory
*
* @param factory The JAXB object mapper factory instance
* @return a new XmlPath instance
*/
public XmlPath using(JAXBObjectMapperFactory factory) {
return new XmlPath(this, getXmlPathConfig().jaxbObjectMapperFactory(factory));
}
/**
* Configure XmlPath to with a specific XmlPathConfig.
*
* @param config The XmlPath config
* @return a new XmlPath instance
*/
public XmlPath using(XmlPathConfig config) {
return new XmlPath(this, config);
}
private XmlPath(XmlPath xmlPath, XmlPathConfig config) {
this.xmlPathConfig = config;
this.mode = xmlPath.mode;
this.lazyXmlParser = xmlPath.lazyXmlParser.changeCompatibilityMode(mode).changeConfig(config);
}
/**
* Get the entire XML graph as an Object
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @return The XML Node. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public Node get() {
return (Node) get("$");
}
/**
* Get the result of an XML path expression. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param <T> The type of the return value.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> T get(String path) {
notNull(path, "path");
return getFromPath(path, true);
}
/**
* Get the result of an XML path expression as a list. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param <T> The list type
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> List<T> getList(String path) {
return getAsList(path);
}
/**
* Get the result of an XML path expression as a list. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param genericType The generic list type
* @param <T> The type
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> List<T> getList(String path, Class<T> genericType) {
return getAsList(path, genericType);
}
/**
* Get the result of an XML path expression as a map. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param <K> The type of the expected key
* @param <V> The type of the expected value
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <K, V> Map<K, V> getMap(String path) {
return get(path);
}
/**
* Get the result of an XML path expression as a map. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param keyType The type of the expected key
* @param valueType The type of the expected value
* @param <K> The type of the expected key
* @param <V> The type of the expected value
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <K, V> Map<K, V> getMap(String path, Class<K> keyType, Class<V> valueType) {
final Map<K, V> originalMap = get(path);
final Map<K, V> newMap = new HashMap<K, V>();
for (Entry<K, V> entry : originalMap.entrySet()) {
final K key = entry.getKey() == null ? null : convertObjectTo(entry.getKey(), keyType);
final V value = entry.getValue() == null ? null : convertObjectTo(entry.getValue(), valueType);
newMap.put(key, value);
}
return Collections.unmodifiableMap(newMap);
}
/**
* Get an XML document as a Java Object.
*
* @param objectType The type of the java object.
* @param <T> The type of the java object
* @return A Java object representation of the XML document
*/
public <T> T getObject(String path, Class<T> objectType) {
Object object = getFromPath(path, false);
return getObjectAsType(object, objectType);
}
private <T> T getObjectAsType(Object object, Class<T> objectType) {
if (object == null) {
return null;
} else if (object instanceof GPathResult) {
try {
object = XmlUtil.serialize((GPathResult) object);
} catch (GroovyRuntimeException e) {
throw new IllegalArgumentException("Failed to convert XML to Java Object. If you're trying convert to a list then use the getList method instead.", e);
}
} else if (object instanceof groovy.util.slurpersupport.Node) {
object = GroovyNodeSerializer.toXML((groovy.util.slurpersupport.Node) object);
}
XmlPathConfig cfg = new XmlPathConfig(getXmlPathConfig());
if (cfg.hasCustomJaxbObjectMapperFactory()) {
cfg = cfg.defaultParserType(XmlParserType.JAXB);
}
if (!(object instanceof String)) {
throw new IllegalStateException("Internal error: XML object was not an instance of String, please report to the REST Assured mailing-list.");
}
return XmlObjectDeserializer.deserialize((String) object, objectType, cfg);
}
private <T> T getFromPath(String path, boolean convertToJavaObject) {
final GPathResult input = lazyXmlParser.invoke();
final XMLAssertion xmlAssertion = new XMLAssertion();
final String root = rootPath.equals("") ? rootPath : rootPath.endsWith(".") ? rootPath : rootPath + ".";
xmlAssertion.setKey(root + path);
return (T) xmlAssertion.getResult(input, convertToJavaObject, true);
}
/**
* Get the result of an XML path expression as an int. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public int getInt(String path) {
final Object object = get(path);
return convertObjectTo(object, Integer.class);
}
/**
* Get the result of an XML path expression as a boolean. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public boolean getBoolean(String path) {
Object object = get(path);
return convertObjectTo(object, Boolean.class);
}
/**
* Get the result of an XML path expression as a {@link Node}. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public Node getNode(String path) {
return convertObjectTo(get(path), Node.class);
}
/**
* Get the result of an XML path expression as a {@link com.jayway.restassured.path.xml.element.NodeChildren}. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public NodeChildren getNodeChildren(String path) {
return convertObjectTo(get(path), NodeChildren.class);
}
/**
* Get the result of an XML path expression as a char. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public char getChar(String path) {
Object object = get(path);
return convertObjectTo(object, Character.class);
}
/**
* Get the result of an XML path expression as a byte. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public byte getByte(String path) {
Object object = get(path);
return convertObjectTo(object, Byte.class);
}
/**
* Get the result of an XML path expression as a short. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public short getShort(String path) {
Object object = get(path);
return convertObjectTo(object, Short.class);
}
/**
* Get the result of an XML path expression as a float. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public float getFloat(String path) {
Object object = get(path);
return convertObjectTo(object, Float.class);
}
/**
* Get the result of an XML path expression as a double. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public double getDouble(String path) {
Object object = get(path);
return convertObjectTo(object, Double.class);
}
/**
* Get the result of an XML path expression as a long. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public long getLong(String path) {
Object object = get(path);
return convertObjectTo(object, Long.class);
}
/**
* Get the result of an XML path expression as a string. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public String getString(String path) {
Object object = get(path);
return convertObjectTo(object, String.class);
}
/**
* Get the XML as a prettified string.
*
* @return The XML as a prettified String.
*/
public String prettify() {
return XmlPrettifier.prettify(lazyXmlParser.invoke());
}
/**
* Get and print the XML as a prettified string.
*
* @return The XML as a prettified String.
*/
public String prettyPrint() {
final String pretty = prettify();
System.out.println(pretty);
return pretty;
}
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public static XmlPath given(String text) {
return new XmlPath(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param stream The stream containing the XML document
*/
public static XmlPath given(InputStream stream) {
return new XmlPath(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public static XmlPath given(InputSource source) {
return new XmlPath(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public static XmlPath given(File file) {
return new XmlPath(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public static XmlPath given(Reader reader) {
return new XmlPath(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public static XmlPath given(URI uri) {
return new XmlPath(uri);
}
public static XmlPath with(InputStream stream) {
return new XmlPath(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public static XmlPath with(String text) {
return new XmlPath(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public static XmlPath with(InputSource source) {
return new XmlPath(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public static XmlPath with(File file) {
return new XmlPath(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public static XmlPath with(Reader reader) {
return new XmlPath(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public static XmlPath with(URI uri) {
return new XmlPath(uri);
}
/**
* Instantiate a new XmlPath instance.
*
* @param stream The stream containing the XML document
*/
public static XmlPath from(InputStream stream) {
return new XmlPath(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public static XmlPath from(String text) {
return new XmlPath(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public static XmlPath from(InputSource source) {
return new XmlPath(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public static XmlPath from(File file) {
return new XmlPath(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public static XmlPath from(Reader reader) {
return new XmlPath(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public static XmlPath from(URI uri) {
return new XmlPath(uri);
}
private LazyXmlParser parseText(final String text) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parseText(text);
}
};
}
/**
* Set the root path of the document so that you don't need to write the entire path. E.g.
* <pre>
* final XmlPath xmlPath = new XmlPath(XML).setRoot("shopping.category.item");
* assertThat(xmlPath.getInt("size()"), equalTo(5));
* assertThat(xmlPath.getList("children().list()", String.class), hasItem("Pens"));
* </pre>
*
* @param rootPath The root path to use.
*/
public XmlPath setRoot(String rootPath) {
notNull(rootPath, "Root path");
this.rootPath = rootPath;
return this;
}
private <T> List<T> getAsList(String path) {
return getAsList(path, null);
}
private <T> List<T> getAsList(String path, final Class<?> explicitType) {
Object returnObject = get(path);
if (returnObject instanceof NodeChildren) {
final NodeChildren nodeChildren = (NodeChildren) returnObject;
returnObject = convertElementsListTo(nodeChildren.list(), explicitType);
} else if (!(returnObject instanceof List)) {
final List<T> asList = new ArrayList<T>();
if (returnObject != null) {
final T e;
if (explicitType == null) {
e = (T) returnObject.toString();
} else {
e = (T) convertObjectTo(returnObject, explicitType);
}
asList.add(e);
}
returnObject = asList;
} else if (explicitType != null) {
final List<?> returnObjectAsList = (List<?>) returnObject;
final List<T> convertedList = new ArrayList<T>();
for (Object o : returnObjectAsList) {
convertedList.add((T) convertObjectTo(o, explicitType));
}
returnObject = convertedList;
}
return returnObject == null ? null : Collections.unmodifiableList((List<T>) returnObject);
}
private List<Object> convertElementsListTo(List<Node> list, Class<?> explicitType) {
List<Object> convertedList = new ArrayList<Object>();
if (list != null && list.size() > 0) {
for (Node node : list) {
if (explicitType == null) {
convertedList.add(node.toString());
} else {
convertedList.add(convertObjectTo(node, explicitType));
}
}
}
return convertedList;
}
private <T> T convertObjectTo(Object object, Class<T> explicitType) {
if (object instanceof NodeBase && !ObjectConverter.canConvert(object, explicitType)) {
return getObjectAsType(((NodeBase) object).getBackingGroovyObject(), explicitType);
}
return ObjectConverter.convertObjectTo(object, explicitType);
}
private LazyXmlParser parseInputStream(final InputStream stream) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(stream);
}
};
}
private LazyXmlParser parseReader(final Reader reader) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(reader);
}
};
}
private LazyXmlParser parseFile(final File file) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(file);
}
};
}
private LazyXmlParser parseURI(final URI uri) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(uri.toString());
}
};
}
private LazyXmlParser parseInputSource(final InputSource source) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(source);
}
};
}
private XmlPathConfig getXmlPathConfig() {
XmlPathConfig cfg;
if (config == null && xmlPathConfig == null) {
cfg = new XmlPathConfig();
} else if (xmlPathConfig != null) {
cfg = xmlPathConfig;
} else {
cfg = config;
}
return cfg;
}
private static abstract class LazyXmlParser {
protected abstract GPathResult method(XmlSlurper slurper) throws Exception;
private volatile XmlPathConfig config;
private volatile CompatibilityMode compatibilityMode;
protected LazyXmlParser(XmlPathConfig config, CompatibilityMode compatibilityMode) {
this.config = config;
this.compatibilityMode = compatibilityMode;
}
public LazyXmlParser changeCompatibilityMode(CompatibilityMode mode) {
this.compatibilityMode = mode;
return this;
}
public LazyXmlParser changeConfig(XmlPathConfig config) {
this.config = config;
return this;
}
private GPathResult input;
private boolean isInputParsed;
public synchronized GPathResult invoke() {
if (isInputParsed) {
return input;
}
isInputParsed = true;
try {
final XmlSlurper slurper;
if (compatibilityMode == XML) {
slurper = new XmlSlurper();
} else {
XMLReader p = new org.ccil.cowan.tagsoup.Parser();
slurper = new XmlSlurper(p);
}
// Apply features
Map<String, Boolean> features = config.features();
for (Entry<String, Boolean> feature : features.entrySet()) {
slurper.setFeature(feature.getKey(), feature.getValue());
}
input = method(slurper);
return input;
} catch (Exception e) {
throw new XmlPathException("Failed to parse the XML document", e);
}
}
}
public static enum CompatibilityMode {
XML, HTML
}
/**
* Resets static XmlPath configuration to default values
*/
public static void reset() {
XmlPath.config = null;
}
} | xml-path/src/main/java/com/jayway/restassured/path/xml/XmlPath.java | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.restassured.path.xml;
import com.jayway.restassured.assertion.XMLAssertion;
import com.jayway.restassured.internal.path.ObjectConverter;
import com.jayway.restassured.internal.path.xml.GroovyNodeSerializer;
import com.jayway.restassured.internal.path.xml.NodeBase;
import com.jayway.restassured.internal.path.xml.XmlPrettifier;
import com.jayway.restassured.internal.path.xml.mapping.XmlObjectDeserializer;
import com.jayway.restassured.mapper.factory.JAXBObjectMapperFactory;
import com.jayway.restassured.path.xml.config.XmlParserType;
import com.jayway.restassured.path.xml.config.XmlPathConfig;
import com.jayway.restassured.path.xml.element.Node;
import com.jayway.restassured.path.xml.element.NodeChildren;
import com.jayway.restassured.path.xml.exception.XmlPathException;
import groovy.lang.GroovyRuntimeException;
import groovy.util.XmlSlurper;
import groovy.util.slurpersupport.GPathResult;
import groovy.xml.XmlUtil;
import org.apache.commons.lang3.Validate;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.net.URI;
import java.util.*;
import java.util.Map.Entry;
import static com.jayway.restassured.internal.assertion.AssertParameter.notNull;
import static com.jayway.restassured.path.xml.XmlPath.CompatibilityMode.XML;
/**
* XmlPath is an alternative to using XPath for easily getting values from an XML document. It follows the Groovy syntax
* described <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">here</a>. <br>Let's say we have an XML defined as;
* <pre>
* <shopping>
* <category type="groceries">
* <item>
* <name>Chocolate</name>
* <price>10</price>
* </item>
* <item>
* <name>Coffee</name>
* <price>20</price>
* </item>
* </category>
* <category type="supplies">
* <item>
* <name>Paper</name>
* <price>5</price>
* </item>
* <item quantity="4">
* <name>Pens</name>
* <price>15</price>
* </item>
* </category>
* <category type="present">
* <item when="Aug 10">
* <name>Kathryn's Birthday</name>
* <price>200</price>
* </item>
* </category>
* </shopping>
* </pre>
* <p/>
* Get the name of the first category item:
* <pre>
* String name = with(XML).get("shopping.category.item[0].name");
* </pre>
* <p/>
* To get the number of category items:
* <pre>
* int items = with(XML).get("shopping.category.item.size()");
* </pre>
* <p/>
* Get a specific category:
* <pre>
* Node category = with(XML).get("shopping.category[0]");
* </pre>
* <p/>
* To get the number of categories with type attribute equal to 'groceries':
* <pre>
* int items = with(XML).get("shopping.category.findAll { it.@type == 'groceries' }.size()");
* </pre>
* <p/>
* Get all items with price greater than or equal to 10 and less than or equal to 20:
* <pre>
* List<Node> itemsBetweenTenAndTwenty = with(XML).get("shopping.category.item.findAll { item -> def price = item.price.toFloat(); price >= 10 && price <= 20 }");
* </pre>
* <p/>
* Get the chocolate price:
* <pre>
* int priceOfChocolate = with(XML).getInt("**.find { it.name == 'Chocolate' }.price"
* </pre>
* <p/>
* You can also parse HTML by setting compatibility mode to HTML:
* <pre>
* XmlPath xmlPath = new XmlPath(CompatibilityMode.HTML,<some html>);
* </pre>
*/
public class XmlPath {
public static XmlPathConfig config = null;
private final CompatibilityMode mode;
private LazyJsonParser lazyJsonParser;
private XmlPathConfig xmlPathConfig = null;
private String rootPath = "";
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public XmlPath(String text) {
this(XML, text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param stream The stream containing the XML document
*/
public XmlPath(InputStream stream) {
this(XML, stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public XmlPath(InputSource source) {
this(XML, source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public XmlPath(File file) {
this(XML, file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public XmlPath(Reader reader) {
this(XML, reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public XmlPath(URI uri) {
this(XML, uri);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param text The text containing the XML document
*/
public XmlPath(CompatibilityMode mode, String text) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyJsonParser = parseText(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param stream The stream containing the XML document
*/
public XmlPath(CompatibilityMode mode, InputStream stream) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyJsonParser = parseInputStream(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param source The source containing the XML document
*/
public XmlPath(CompatibilityMode mode, InputSource source) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyJsonParser = parseInputSource(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param file The file containing the XML document
*/
public XmlPath(CompatibilityMode mode, File file) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyJsonParser = parseFile(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param reader The reader containing the XML document
*/
public XmlPath(CompatibilityMode mode, Reader reader) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyJsonParser = parseReader(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param uri The URI containing the XML document
*/
public XmlPath(CompatibilityMode mode, URI uri) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyJsonParser = parseURI(uri);
}
/**
* Configure XmlPath to use a specific JAXB object mapper factory
*
* @param factory The JAXB object mapper factory instance
* @return a new XmlPath instance
*/
public XmlPath using(JAXBObjectMapperFactory factory) {
return new XmlPath(this, getXmlPathConfig().jaxbObjectMapperFactory(factory));
}
/**
* Configure XmlPath to with a specific XmlPathConfig.
*
* @param config The XmlPath config
* @return a new XmlPath instance
*/
public XmlPath using(XmlPathConfig config) {
return new XmlPath(this, config);
}
private XmlPath(XmlPath xmlPath, XmlPathConfig config) {
this.xmlPathConfig = config;
this.mode = xmlPath.mode;
this.lazyJsonParser = xmlPath.lazyJsonParser.changeCompatibilityMode(mode).changeConfig(config);
}
/**
* Get the entire XML graph as an Object
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @return The XML Node. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public Node get() {
return (Node) get("$");
}
/**
* Get the result of an XML path expression. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param <T> The type of the return value.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> T get(String path) {
notNull(path, "path");
return getFromPath(path, true);
}
/**
* Get the result of an XML path expression as a list. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param <T> The list type
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> List<T> getList(String path) {
return getAsList(path);
}
/**
* Get the result of an XML path expression as a list. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param genericType The generic list type
* @param <T> The type
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> List<T> getList(String path, Class<T> genericType) {
return getAsList(path, genericType);
}
/**
* Get the result of an XML path expression as a map. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param <K> The type of the expected key
* @param <V> The type of the expected value
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <K, V> Map<K, V> getMap(String path) {
return get(path);
}
/**
* Get the result of an XML path expression as a map. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @param keyType The type of the expected key
* @param valueType The type of the expected value
* @param <K> The type of the expected key
* @param <V> The type of the expected value
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <K, V> Map<K, V> getMap(String path, Class<K> keyType, Class<V> valueType) {
final Map<K, V> originalMap = get(path);
final Map<K, V> newMap = new HashMap<K, V>();
for (Entry<K, V> entry : originalMap.entrySet()) {
final K key = entry.getKey() == null ? null : convertObjectTo(entry.getKey(), keyType);
final V value = entry.getValue() == null ? null : convertObjectTo(entry.getValue(), valueType);
newMap.put(key, value);
}
return Collections.unmodifiableMap(newMap);
}
/**
* Get an XML document as a Java Object.
*
* @param objectType The type of the java object.
* @param <T> The type of the java object
* @return A Java object representation of the XML document
*/
public <T> T getObject(String path, Class<T> objectType) {
Object object = getFromPath(path, false);
return getObjectAsType(object, objectType);
}
private <T> T getObjectAsType(Object object, Class<T> objectType) {
if (object == null) {
return null;
} else if (object instanceof GPathResult) {
try {
object = XmlUtil.serialize((GPathResult) object);
} catch (GroovyRuntimeException e) {
throw new IllegalArgumentException("Failed to convert XML to Java Object. If you're trying convert to a list then use the getList method instead.", e);
}
} else if (object instanceof groovy.util.slurpersupport.Node) {
object = GroovyNodeSerializer.toXML((groovy.util.slurpersupport.Node) object);
}
XmlPathConfig cfg = new XmlPathConfig(getXmlPathConfig());
if (cfg.hasCustomJaxbObjectMapperFactory()) {
cfg = cfg.defaultParserType(XmlParserType.JAXB);
}
if (!(object instanceof String)) {
throw new IllegalStateException("Internal error: XML object was not an instance of String, please report to the REST Assured mailing-list.");
}
return XmlObjectDeserializer.deserialize((String) object, objectType, cfg);
}
private <T> T getFromPath(String path, boolean convertToJavaObject) {
final GPathResult input = lazyJsonParser.invoke();
final XMLAssertion xmlAssertion = new XMLAssertion();
final String root = rootPath.equals("") ? rootPath : rootPath.endsWith(".") ? rootPath : rootPath + ".";
xmlAssertion.setKey(root + path);
return (T) xmlAssertion.getResult(input, convertToJavaObject, true);
}
/**
* Get the result of an XML path expression as an int. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public int getInt(String path) {
final Object object = get(path);
return convertObjectTo(object, Integer.class);
}
/**
* Get the result of an XML path expression as a boolean. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public boolean getBoolean(String path) {
Object object = get(path);
return convertObjectTo(object, Boolean.class);
}
/**
* Get the result of an XML path expression as a {@link Node}. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public Node getNode(String path) {
return convertObjectTo(get(path), Node.class);
}
/**
* Get the result of an XML path expression as a {@link com.jayway.restassured.path.xml.element.NodeChildren}. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public NodeChildren getNodeChildren(String path) {
return convertObjectTo(get(path), NodeChildren.class);
}
/**
* Get the result of an XML path expression as a char. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public char getChar(String path) {
Object object = get(path);
return convertObjectTo(object, Character.class);
}
/**
* Get the result of an XML path expression as a byte. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public byte getByte(String path) {
Object object = get(path);
return convertObjectTo(object, Byte.class);
}
/**
* Get the result of an XML path expression as a short. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public short getShort(String path) {
Object object = get(path);
return convertObjectTo(object, Short.class);
}
/**
* Get the result of an XML path expression as a float. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public float getFloat(String path) {
Object object = get(path);
return convertObjectTo(object, Float.class);
}
/**
* Get the result of an XML path expression as a double. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public double getDouble(String path) {
Object object = get(path);
return convertObjectTo(object, Double.class);
}
/**
* Get the result of an XML path expression as a long. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public long getLong(String path) {
Object object = get(path);
return convertObjectTo(object, Long.class);
}
/**
* Get the result of an XML path expression as a string. For syntax details please refer to
* <a href="http://groovy.codehaus.org/Updating+XML+with+XmlSlurper">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public String getString(String path) {
Object object = get(path);
return convertObjectTo(object, String.class);
}
/**
* Get the XML as a prettified string.
*
* @return The XML as a prettified String.
*/
public String prettify() {
return XmlPrettifier.prettify(lazyJsonParser.invoke());
}
/**
* Get and print the XML as a prettified string.
*
* @return The XML as a prettified String.
*/
public String prettyPrint() {
final String pretty = prettify();
System.out.println(pretty);
return pretty;
}
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public static XmlPath given(String text) {
return new XmlPath(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param stream The stream containing the XML document
*/
public static XmlPath given(InputStream stream) {
return new XmlPath(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public static XmlPath given(InputSource source) {
return new XmlPath(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public static XmlPath given(File file) {
return new XmlPath(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public static XmlPath given(Reader reader) {
return new XmlPath(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public static XmlPath given(URI uri) {
return new XmlPath(uri);
}
public static XmlPath with(InputStream stream) {
return new XmlPath(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public static XmlPath with(String text) {
return new XmlPath(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public static XmlPath with(InputSource source) {
return new XmlPath(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public static XmlPath with(File file) {
return new XmlPath(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public static XmlPath with(Reader reader) {
return new XmlPath(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public static XmlPath with(URI uri) {
return new XmlPath(uri);
}
/**
* Instantiate a new XmlPath instance.
*
* @param stream The stream containing the XML document
*/
public static XmlPath from(InputStream stream) {
return new XmlPath(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public static XmlPath from(String text) {
return new XmlPath(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public static XmlPath from(InputSource source) {
return new XmlPath(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public static XmlPath from(File file) {
return new XmlPath(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public static XmlPath from(Reader reader) {
return new XmlPath(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public static XmlPath from(URI uri) {
return new XmlPath(uri);
}
private LazyJsonParser parseText(final String text) {
return new LazyJsonParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parseText(text);
}
};
}
/**
* Set the root path of the document so that you don't need to write the entire path. E.g.
* <pre>
* final XmlPath xmlPath = new XmlPath(XML).setRoot("shopping.category.item");
* assertThat(xmlPath.getInt("size()"), equalTo(5));
* assertThat(xmlPath.getList("children().list()", String.class), hasItem("Pens"));
* </pre>
*
* @param rootPath The root path to use.
*/
public XmlPath setRoot(String rootPath) {
notNull(rootPath, "Root path");
this.rootPath = rootPath;
return this;
}
private <T> List<T> getAsList(String path) {
return getAsList(path, null);
}
private <T> List<T> getAsList(String path, final Class<?> explicitType) {
Object returnObject = get(path);
if (returnObject instanceof NodeChildren) {
final NodeChildren nodeChildren = (NodeChildren) returnObject;
returnObject = convertElementsListTo(nodeChildren.list(), explicitType);
} else if (!(returnObject instanceof List)) {
final List<T> asList = new ArrayList<T>();
if (returnObject != null) {
final T e;
if (explicitType == null) {
e = (T) returnObject.toString();
} else {
e = (T) convertObjectTo(returnObject, explicitType);
}
asList.add(e);
}
returnObject = asList;
} else if (explicitType != null) {
final List<?> returnObjectAsList = (List<?>) returnObject;
final List<T> convertedList = new ArrayList<T>();
for (Object o : returnObjectAsList) {
convertedList.add((T) convertObjectTo(o, explicitType));
}
returnObject = convertedList;
}
return returnObject == null ? null : Collections.unmodifiableList((List<T>) returnObject);
}
private List<Object> convertElementsListTo(List<Node> list, Class<?> explicitType) {
List<Object> convertedList = new ArrayList<Object>();
if (list != null && list.size() > 0) {
for (Node node : list) {
if (explicitType == null) {
convertedList.add(node.toString());
} else {
convertedList.add(convertObjectTo(node, explicitType));
}
}
}
return convertedList;
}
private <T> T convertObjectTo(Object object, Class<T> explicitType) {
if (object instanceof NodeBase && !ObjectConverter.canConvert(object, explicitType)) {
return getObjectAsType(((NodeBase) object).getBackingGroovyObject(), explicitType);
}
return ObjectConverter.convertObjectTo(object, explicitType);
}
private LazyJsonParser parseInputStream(final InputStream stream) {
return new LazyJsonParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(stream);
}
};
}
private LazyJsonParser parseReader(final Reader reader) {
return new LazyJsonParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(reader);
}
};
}
private LazyJsonParser parseFile(final File file) {
return new LazyJsonParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(file);
}
};
}
private LazyJsonParser parseURI(final URI uri) {
return new LazyJsonParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(uri.toString());
}
};
}
private LazyJsonParser parseInputSource(final InputSource source) {
return new LazyJsonParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(source);
}
};
}
private XmlPathConfig getXmlPathConfig() {
XmlPathConfig cfg;
if (config == null && xmlPathConfig == null) {
cfg = new XmlPathConfig();
} else if (xmlPathConfig != null) {
cfg = xmlPathConfig;
} else {
cfg = config;
}
return cfg;
}
private static abstract class LazyJsonParser {
protected abstract GPathResult method(XmlSlurper slurper) throws Exception;
private volatile XmlPathConfig config;
private volatile CompatibilityMode compatibilityMode;
protected LazyJsonParser(XmlPathConfig config, CompatibilityMode compatibilityMode) {
this.config = config;
this.compatibilityMode = compatibilityMode;
}
public LazyJsonParser changeCompatibilityMode(CompatibilityMode mode) {
this.compatibilityMode = mode;
return this;
}
public LazyJsonParser changeConfig(XmlPathConfig config) {
this.config = config;
return this;
}
private GPathResult input;
private boolean isInputParsed;
public synchronized GPathResult invoke() {
if (isInputParsed) {
return input;
}
isInputParsed = true;
try {
final XmlSlurper slurper;
if (compatibilityMode == XML) {
slurper = new XmlSlurper();
} else {
XMLReader p = new org.ccil.cowan.tagsoup.Parser();
slurper = new XmlSlurper(p);
}
// Apply features
Map<String, Boolean> features = config.features();
for (Entry<String, Boolean> feature : features.entrySet()) {
slurper.setFeature(feature.getKey(), feature.getValue());
}
input = method(slurper);
return input;
} catch (Exception e) {
throw new XmlPathException("Failed to parse the XML document", e);
}
}
}
public static enum CompatibilityMode {
XML, HTML
}
/**
* Resets static XmlPath configuration to default values
*/
public static void reset() {
XmlPath.config = null;
}
} | Changed name of inner class
| xml-path/src/main/java/com/jayway/restassured/path/xml/XmlPath.java | Changed name of inner class |
|
Java | apache-2.0 | 500ddcf241640d3d703dacf12b8d84b1b2bf95f8 | 0 | springfox/springfox,springfox/springfox,springfox/springfox,springfox/springfox | /*
*
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 springfox.documentation.spring.web.scanners;
import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.classmate.TypeResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ModelBuilder;
import springfox.documentation.builders.ModelPropertyBuilder;
import springfox.documentation.schema.Model;
import springfox.documentation.schema.ModelProperty;
import springfox.documentation.schema.ModelProvider;
import springfox.documentation.schema.ModelReference;
import springfox.documentation.schema.TypeNameExtractor;
import springfox.documentation.schema.TypeNameIndexingAdapter;
import springfox.documentation.spi.schema.EnumTypeDeterminer;
import springfox.documentation.spi.schema.UniqueTypeNameAdapter;
import springfox.documentation.spi.schema.contexts.ModelContext;
import springfox.documentation.spi.service.contexts.RequestMappingContext;
import springfox.documentation.spring.web.plugins.DocumentationPluginsManager;
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.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import static springfox.documentation.schema.ResolvedTypes.*;
@Component
public class ApiModelReader {
private static final Logger LOG = LoggerFactory.getLogger(ApiModelReader.class);
private final ModelProvider modelProvider;
private final TypeResolver typeResolver;
private final DocumentationPluginsManager pluginsManager;
private final EnumTypeDeterminer enumTypeDeterminer;
private final TypeNameExtractor typeNameExtractor;
@Autowired
public ApiModelReader(
@Qualifier("cachedModels") ModelProvider modelProvider,
TypeResolver typeResolver,
DocumentationPluginsManager pluginsManager,
EnumTypeDeterminer enumTypeDeterminer,
TypeNameExtractor typeNameExtractor) {
this.modelProvider = modelProvider;
this.typeResolver = typeResolver;
this.pluginsManager = pluginsManager;
this.enumTypeDeterminer = enumTypeDeterminer;
this.typeNameExtractor = typeNameExtractor;
}
@SuppressWarnings("rawtypes")
public Map<String, Set<Model>> read(RequestMappingContext context) {
Map<String, Set<Model>> mergedModelMap = new TreeMap<>();
Map<String, Model> uniqueModels = new HashMap<>();
Map<String, String> parameterModelMap = new HashMap<>();
final UniqueTypeNameAdapter adapter = new TypeNameIndexingAdapter();
Set<Class> ignorableTypes = context.getIgnorableParameterTypes();
Set<ModelContext> modelContexts = pluginsManager.modelContexts(context);
for (Map.Entry<String, Set<Model>> entry : context.getModelMap().entrySet()) {
entry.getValue()
.stream()
.peek(model -> adapter.registerType(model.getName(), model.getId()))
.filter(model -> !uniqueModels.containsKey(model.getName()))
.forEach(model -> {
uniqueModels.put(model.getName(), model);
parameterModelMap.put(model.getId(), entry.getKey());
});
}
for (ModelContext rootContext : modelContexts) {
Map<String, Model> modelBranch = new HashMap<>();
final Map<String, ModelContext> contextMap = new HashMap<>();
markIgnorablesAsHasSeen(typeResolver, ignorableTypes, rootContext);
Optional<Model> pModel = modelProvider.modelFor(rootContext);
List<String> branchRoots = new ArrayList<>();
if (pModel.isPresent()) {
LOG.debug("Generated parameter model id: {}, name: {}",
// TODO: resolve this, schema: {} models",
pModel.get().getId(),
pModel.get().getName());
modelBranch.put(pModel.get().getId(), pModel.get());
contextMap.put(pModel.get().getId(), rootContext);
branchRoots.add(rootContext.getTypeId());
} else {
branchRoots = findBranchRoots(rootContext);
LOG.debug("Did not find any parameter models for {}", rootContext.getType());
}
Map<ResolvedType, Model> dependencies = modelProvider.dependencies(rootContext);
for (ResolvedType type : dependencies.keySet()) {
ModelContext childContext = ModelContext.fromParent(rootContext, type);
modelBranch.put(dependencies.get(type).getId(), dependencies.get(type));
contextMap.put(dependencies.get(type).getId(), childContext);
}
if (modelBranch.isEmpty()) {
continue;
}
final MergingContext mergingContext = createMergingContext(
Collections.unmodifiableMap(uniqueModels),
Collections.unmodifiableMap(parameterModelMap),
Collections.unmodifiableMap(modelBranch),
Collections.unmodifiableMap(contextMap));
branchRoots.stream().filter(rootId -> modelBranch.containsKey(rootId)).forEach(
rootId -> mergeModelBranch(adapter, mergingContext.toRootId(rootId)));
Set<Model> updatedModels = updateModels(modelBranch.values(), contextMap, adapter);
mergedModelMap.put(rootContext.getParameterId(), updatedModels);
updatedModels.stream().filter(model -> !uniqueModels.containsKey(model.getName())).forEach(
model -> {
uniqueModels.put(model.getName(), model);
parameterModelMap.put(model.getId(), rootContext.getParameterId());
});
}
return Collections.unmodifiableMap(mergedModelMap);
}
private Set<ComparisonCondition> mergeModelBranch(
UniqueTypeNameAdapter adapter,
final MergingContext mergingContext) {
final Set<String> nodes = collectNodes(adapter, mergingContext);
final Set<ComparisonCondition> dependencies = new HashSet<>();
final Set<String> currentDependencies = new HashSet<>();
boolean allowableToSearchTheSame = true;
final Map<String, Optional<String>> comparisonConditions = new HashMap<>();
Set<String> parametersTo = new HashSet<>();
for (final String modelId : nodes) {
if (adapter.getTypeName(modelId).isPresent()) {
continue;
}
if (!mergingContext.hasSeenBefore(modelId)) {
MergingContext childMergingContext = createChildMergingContext(modelId,
!currentDependencies.isEmpty(),
parametersTo,
dependencies,
mergingContext,
adapter);
Set<ComparisonCondition> newDependencies = childMergingContext
.getComparisonCondition(modelId)
.<Set<ComparisonCondition>>map(
reenteredCondition -> new HashSet<>(Arrays.asList(reenteredCondition)))
.orElseGet(() -> mergeModelBranch(adapter, childMergingContext));
if (newDependencies.isEmpty()) {
allowableToSearchTheSame = false;
parametersTo = new HashSet<>();
continue;
}
newDependencies.stream()
.peek(d -> checkCondition(d, false))
.filter(d -> !d.getConditions().isEmpty())
.forEach(p -> {
dependencies.add(p);
currentDependencies.addAll(p.getConditions());
});
if (!allowableToSearchTheSame) {
continue;
}
ComparisonCondition currentCondition = currentCondition(modelId, newDependencies);
if (currentCondition.getConditions().isEmpty()) {
comparisonConditions.put(modelId,
currentCondition.getModelsTo()
.stream()
.map(mergingContext::getModelParameter)
.findFirst());
continue;
}
parametersTo = modelsToParameters(currentCondition.getModelsTo(), mergingContext);
comparisonConditions.put(modelId, Optional.empty());
} else {
currentDependencies.add(modelId);
if (!allowableToSearchTheSame) {
continue;
}
Optional<Set<String>> megedParameters = mergeParameters(modelId,
parametersTo,
mergingContext);
parametersTo = megedParameters.orElseGet(() -> new HashSet<>());
allowableToSearchTheSame = megedParameters.isPresent();
comparisonConditions.put(modelId, Optional.empty());
}
}
Set<String> sameModels = new HashSet<>();
if (allowableToSearchTheSame) {
sameModels
.addAll(findSameModels(comparisonConditions, parametersTo, adapter, mergingContext));
currentDependencies.remove(mergingContext.getRootId());
}
return mergeConditions(sameModels, currentDependencies, dependencies, adapter, mergingContext);
}
private ComparisonCondition currentCondition(
final String modelId,
final Set<ComparisonCondition> newDependencies) {
List<ComparisonCondition> conditions = newDependencies.stream()
.filter(comparisonCondition -> comparisonCondition.getModelFor().equals(modelId))
.collect(Collectors.toCollection(ArrayList::new));
if (conditions.size() > 1) {
throw new IllegalStateException("Ambiguous conditions for one model.");
}
if (conditions.size() == 0) {
throw new IllegalStateException("Condition is not present.");
}
return conditions.get(0);
}
private Set<String> findSameModels(
Map<String, Optional<String>> parametersMatching,
Set<String> allowedParameters,
UniqueTypeNameAdapter adapter,
MergingContext mergingContext) {
if (allowedParameters.isEmpty()) {
allowedParameters = new HashSet<>(Arrays.asList(""));
}
Model rootModel = mergingContext.getRootModel();
ModelBuilder rootModelBuilder = new ModelBuilder(rootModel);
Set<String> sameModels = new HashSet<>();
final String modelForTypeName = rootModel.getType().getErasedType().getName();
final Set<Model> modelsToCompare = mergingContext.getSimilarTypeModels(modelForTypeName);
Iterator<String> it = allowedParameters.iterator();
while (it.hasNext()) {
String parameter = it.next();
List<ModelReference> subTypes = new ArrayList<>();
for (ModelReference modelReference : rootModel.getSubTypes()) {
Optional<String> modelId = getModelId(modelReference);
if (modelId.isPresent() && mergingContext.containsModel(modelId.get())) {
String sModelId = modelId.get();
ModelContext modelContext = Optional.ofNullable(parametersMatching.get(sModelId))
.map(op -> op.orElseGet(() -> parameter))
.map(p -> pseudoContext(p, mergingContext.getModelContext(sModelId)))
.orElseGet(() -> mergingContext.getModelContext(sModelId));
modelReference = modelRefFactory(modelContext,
enumTypeDeterminer,
typeNameExtractor,
adapter.getNames()).apply(mergingContext.getModel(sModelId).getType());
}
subTypes.add(modelReference);
}
Map<String, ModelProperty> newProperties = new HashMap<>(rootModel.getProperties());
for (String propertyName : rootModel.getProperties().keySet()) {
ModelProperty property = rootModel.getProperties().get(propertyName);
ModelReference modelReference = property.getModelRef();
Optional<String> modelId = getModelId(modelReference);
if (modelId.isPresent() && mergingContext.containsModel(modelId.get())) {
String sModelId = modelId.get();
ModelContext modelContext = Optional.ofNullable(parametersMatching.get(sModelId))
.map(op -> op.orElseGet(() -> parameter))
.map(p -> pseudoContext(p, mergingContext.getModelContext(sModelId)))
.orElseGet(() -> mergingContext.getModelContext(sModelId));
newProperties.put(propertyName,
new ModelPropertyBuilder(property).build()
.updateModelRef(modelRefFactory(modelContext,
enumTypeDeterminer,
typeNameExtractor,
adapter.getNames())));
}
}
Model modelToCompare = rootModelBuilder.properties(newProperties).subTypes(subTypes).build();
modelsToCompare.stream()
.filter(m -> StringUtils.isEmpty(parameter)
|| parameter.equals(mergingContext.getModelParameter(m.getId())))
.filter(m -> m.equalsIgnoringName(modelToCompare))
.map(m -> m.getId())
.findFirst()
.ifPresent(sameModels::add);
}
return sameModels;
}
private Set<ComparisonCondition> mergeConditions(
Set<String> sameModels,
Set<String> currentDependencies,
Set<ComparisonCondition> dependencies,
UniqueTypeNameAdapter adapter,
MergingContext mergingContext) {
if (!sameModels.isEmpty()) {
ComparisonCondition currentCondition = new ComparisonCondition(mergingContext.getRootId(),
sameModels, currentDependencies);
dependencies = filterDependencies(dependencies,
modelsToParameters(sameModels, mergingContext),
mergingContext);
dependencies.add(currentCondition);
if (currentCondition.getConditions().isEmpty()) {
for (ComparisonCondition depComparisonCondition : dependencies) {
Set<String> conditions = new HashSet<>(depComparisonCondition.getConditions());
conditions.remove(currentCondition.getModelFor());
checkCondition(
new ComparisonCondition(depComparisonCondition.getModelFor(),
depComparisonCondition.getModelsTo(), conditions),
true);
adapter.setEqualityFor(depComparisonCondition.getModelFor(),
new ArrayList<>(depComparisonCondition.getModelsTo()).get(0));
}
return new HashSet<>(Arrays.asList(currentCondition));
} else {
Set<ComparisonCondition> newDependencies = new HashSet<>();
for (ComparisonCondition depComparisonCondition : dependencies) {
Set<String> conditions = new HashSet<>(depComparisonCondition.getConditions());
conditions.remove(currentCondition.getModelFor());
conditions.addAll(currentCondition.getConditions());
newDependencies.add(new ComparisonCondition(depComparisonCondition.getModelFor(),
depComparisonCondition.getModelsTo(), conditions));
}
return newDependencies;
}
} else {
adapter.registerUniqueType(mergingContext.getRootModel().getName(),
mergingContext.getRootId());
for (ComparisonCondition depComparisonCondition : dependencies) {
String modelId = depComparisonCondition.getModelFor();
adapter.registerUniqueType(mergingContext.getModel(modelId).getName(), modelId);
}
}
return new HashSet<>();
}
private List<String> findBranchRoots(ModelContext rootContext) {
List<String> roots = new ArrayList<>();
ResolvedType resolvedType = rootContext.alternateFor(rootContext.getType());
if (resolvedType.isArray()) {
ResolvedType elementType = resolvedType.getArrayElementType();
roots.addAll(findBranchRoots(ModelContext.fromParent(rootContext, elementType)));
} else {
for (ResolvedType parameter : resolvedType.getTypeParameters()) {
roots.addAll(findBranchRoots(ModelContext.fromParent(rootContext, parameter)));
}
roots.add(ModelContext.fromParent(rootContext, resolvedType).getTypeId());
}
return roots;
}
private Set<String> collectNodes(UniqueTypeNameAdapter adapter, MergingContext mergingContext) {
Model rootModel = mergingContext.getRootModel();
final Set<String> nodes = new TreeSet<>();
for (ModelReference modelReference : rootModel.getSubTypes()) {
Optional<String> modelId = getModelId(modelReference);
if (modelId.isPresent() && mergingContext.containsModel(modelId.get())) {
nodes.add(modelId.get());
}
}
final ModelContext rootModelContext = mergingContext
.getModelContext(mergingContext.getRootId());
for (ResolvedType type : rootModel.getType().getTypeParameters()) {
String modelId = ModelContext
.fromParent(rootModelContext, rootModelContext.alternateFor(type))
.getTypeId();
if (mergingContext.containsModel(modelId)) {
nodes.add(modelId);
}
}
for (ModelProperty modelProperty : rootModel.getProperties().values()) {
Optional<String> modelId = getModelId(modelProperty.getModelRef());
if (modelId.isPresent() && mergingContext.containsModel(modelId.get())) {
nodes.add(modelId.get());
}
}
nodes.removeIf(s -> adapter.getTypeName(s).isPresent());
return nodes;
}
private Optional<Set<String>> mergeParameters(
String modelId,
Set<String> existingParameters,
MergingContext mergingContext) {
if (modelId.equals(mergingContext.getRootId())) {
return Optional.of(existingParameters);
}
Set<String> parameters = new HashSet<>(existingParameters);
for (Map.Entry<String, Set<String>> entry : mergingContext.getCircles().entrySet()) {
if (!entry.getValue().contains(modelId)) {
if (parameters.isEmpty()) {
parameters.addAll(mergingContext.getCircleParameters(entry.getKey()));
} else {
parameters.retainAll(mergingContext.getCircleParameters(entry.getKey()));
}
if (parameters.isEmpty()) {
return Optional.empty();
}
}
}
String modelForTypeName = mergingContext.getModel(modelId).getType().getErasedType().getName();
Set<Model> similarTypeModels = mergingContext.getSimilarTypeModels(modelForTypeName);
Set<String> candidateParameters = similarTypeModels.stream()
.map(model -> mergingContext.getModelParameter(model.getId()))
.collect(Collectors.toCollection(HashSet::new));
if (parameters.isEmpty()) {
parameters.addAll(candidateParameters);
} else {
parameters.retainAll(candidateParameters);
}
if (parameters.isEmpty()) {
return Optional.empty();
}
return Optional.of(parameters);
}
private Set<ComparisonCondition> filterDependencies(
Set<ComparisonCondition> dependencies,
Set<String> parameters,
MergingContext mergingContext) {
return dependencies.stream().map(condition -> {
Set<String> modelsTo = condition.getModelsTo()
.stream()
.filter(modelId -> parameters.contains(mergingContext.getModelParameter(modelId)))
.collect(Collectors.toCollection(HashSet::new));
return new ComparisonCondition(condition.getModelFor(), modelsTo, condition.getConditions());
}).collect(Collectors.toCollection(HashSet::new));
}
private Model updateModel(
Model model,
Map<String, ModelContext> contextMap,
UniqueTypeNameAdapter adapter) {
for (String propertyName : model.getProperties().keySet()) {
ModelProperty property = model.getProperties().get(propertyName);
Optional<String> modelId = getModelId(property.getModelRef());
if (modelId.isPresent() && contextMap.containsKey(modelId.get())) {
property.updateModelRef(modelRefFactory(contextMap.get(modelId.get()),
enumTypeDeterminer,
typeNameExtractor,
adapter.getNames()));
}
}
List<ModelReference> subTypes = new ArrayList<>();
for (ModelReference oldModelRef : model.getSubTypes()) {
Optional<String> modelId = getModelId(oldModelRef);
if (modelId.isPresent() && contextMap.containsKey(modelId.get())) {
ModelContext modelContext = contextMap.get(modelId.get());
subTypes.add(
modelRefFactory(modelContext, enumTypeDeterminer, typeNameExtractor, adapter.getNames())
.apply(modelContext.getType()));
} else {
subTypes.add(oldModelRef);
}
}
String name = typeNameExtractor.typeName(contextMap.get(model.getId()), adapter.getNames());
return new ModelBuilder(model).name(name).subTypes(subTypes).build();
}
private Set<Model> updateModels(
final Collection<Model> models,
final Map<String, ModelContext> contextMap,
final UniqueTypeNameAdapter adapter) {
models.forEach(model -> {
if (!adapter.getTypeName(model.getId()).isPresent()) {
adapter.registerUniqueType(model.getName(), model.getId());
}
});
return models.stream().map(model -> updateModel(model, contextMap, adapter)).collect(
Collectors.toCollection(HashSet::new));
}
private static ModelContext pseudoContext(String parameterId, ModelContext context) {
return ModelContext.inputParam(parameterId,
context.getGroupName(),
context.getType(),
Optional.empty(),
new HashSet<>(),
context.getDocumentationType(),
context.getAlternateTypeProvider(),
context.getGenericNamingStrategy(),
Collections.unmodifiableSet(new HashSet<>()));
}
private static void checkCondition(
ComparisonCondition condition,
boolean conditionalPresenceCheck) {
if (conditionalPresenceCheck && !condition.getConditions().isEmpty()) {
throw new IllegalStateException("Equality with conditions is not allowed.");
}
if (condition.getConditions().isEmpty() && condition.getModelsTo().size() > 1) {
throw new IllegalStateException("Ambiguous models equality when conditions is empty.");
}
}
private static Optional<String> getModelId(ModelReference ref) {
ModelReference refT = ref;
while (true) {
if (refT.getModelId().isPresent()) {
return refT.getModelId();
}
if (refT.itemModel().isPresent()) {
refT = refT.itemModel().get();
} else {
return Optional.empty();
}
}
}
private static Set<String> modelsToParameters(Set<String> models, MergingContext mergingContext) {
return models.stream().map(mergingContext::getModelParameter).collect(
Collectors.toCollection(HashSet::new));
}
@SuppressWarnings("rawtypes")
private void markIgnorablesAsHasSeen(
TypeResolver typeResolver,
Set<Class> ignorableParameterTypes,
ModelContext modelContext) {
for (Class ignorableParameterType : ignorableParameterTypes) {
modelContext.seen(typeResolver.resolve(ignorableParameterType));
}
}
private static MergingContext createChildMergingContext(
String modelId,
boolean isCircle,
Set<String> parameters,
Set<ComparisonCondition> dependencies,
MergingContext mergingContext,
UniqueTypeNameAdapter adapter) {
if (isCircle) {
return mergingContext.toRootId(modelId, dependencies, parameters);
} else {
return mergingContext.toRootId(modelId);
}
}
private static MergingContext createMergingContext(
Map<String, Model> uniqueModels,
Map<String, String> parameterModelMap,
Map<String, Model> currentBranch,
Map<String, ModelContext> contextMap) {
Map<String, Set<Model>> typedModelMap = new HashMap<>();
Iterator<Model> it = uniqueModels.values().iterator();
while (it.hasNext()) {
Model model = it.next();
String rawType = model.getType().getErasedType().getName();
Set<Model> models = new HashSet<>();
models.add(model);
if (typedModelMap.containsKey(rawType)) {
models.addAll(typedModelMap.get(rawType));
}
typedModelMap.put(rawType, Collections.unmodifiableSet(models));
}
return new MergingContext(typedModelMap, parameterModelMap, currentBranch, contextMap);
}
} | springfox-spring-web/src/main/java/springfox/documentation/spring/web/scanners/ApiModelReader.java | /*
*
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 springfox.documentation.spring.web.scanners;
import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.classmate.TypeResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ModelBuilder;
import springfox.documentation.builders.ModelPropertyBuilder;
import springfox.documentation.schema.Model;
import springfox.documentation.schema.ModelProperty;
import springfox.documentation.schema.ModelProvider;
import springfox.documentation.schema.ModelReference;
import springfox.documentation.schema.TypeNameExtractor;
import springfox.documentation.schema.TypeNameIndexingAdapter;
import springfox.documentation.spi.schema.EnumTypeDeterminer;
import springfox.documentation.spi.schema.UniqueTypeNameAdapter;
import springfox.documentation.spi.schema.contexts.ModelContext;
import springfox.documentation.spi.service.contexts.RequestMappingContext;
import springfox.documentation.spring.web.plugins.DocumentationPluginsManager;
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.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import static springfox.documentation.schema.ResolvedTypes.*;
@Component
public class ApiModelReader {
private static final Logger LOG = LoggerFactory.getLogger(ApiModelReader.class);
private final ModelProvider modelProvider;
private final TypeResolver typeResolver;
private final DocumentationPluginsManager pluginsManager;
private final EnumTypeDeterminer enumTypeDeterminer;
private final TypeNameExtractor typeNameExtractor;
@Autowired
public ApiModelReader(
@Qualifier("cachedModels") ModelProvider modelProvider,
TypeResolver typeResolver,
DocumentationPluginsManager pluginsManager,
EnumTypeDeterminer enumTypeDeterminer,
TypeNameExtractor typeNameExtractor) {
this.modelProvider = modelProvider;
this.typeResolver = typeResolver;
this.pluginsManager = pluginsManager;
this.enumTypeDeterminer = enumTypeDeterminer;
this.typeNameExtractor = typeNameExtractor;
}
@SuppressWarnings("rawtypes")
public Map<String, Set<Model>> read(RequestMappingContext context) {
Map<String, Set<Model>> mergedModelMap = new TreeMap<>();
Map<String, Model> uniqueModels = new HashMap<>();
Map<String, String> parameterModelMap = new HashMap<>();
final UniqueTypeNameAdapter adapter = new TypeNameIndexingAdapter();
Set<Class> ignorableTypes = context.getIgnorableParameterTypes();
Set<ModelContext> modelContexts = pluginsManager.modelContexts(context);
for (Map.Entry<String, Set<Model>> entry : context.getModelMap().entrySet()) {
entry.getValue()
.stream()
.peek(model -> adapter.registerType(model.getName(), model.getId()))
.filter(model -> !uniqueModels.containsKey(model.getName()))
.forEach(model -> {
uniqueModels.put(model.getName(), model);
parameterModelMap.put(model.getId(), entry.getKey());
});
}
for (ModelContext rootContext : modelContexts) {
Map<String, Model> modelBranch = new HashMap<>();
final Map<String, ModelContext> contextMap = new HashMap<>();
markIgnorablesAsHasSeen(typeResolver, ignorableTypes, rootContext);
Optional<Model> pModel = modelProvider.modelFor(rootContext);
List<String> branchRoots = new ArrayList<>();
if (pModel.isPresent()) {
LOG.debug("Generated parameter model id: {}, name: {}",
// TODO: resolve this, schema: {} models",
pModel.get().getId(),
pModel.get().getName());
modelBranch.put(pModel.get().getId(), pModel.get());
contextMap.put(pModel.get().getId(), rootContext);
branchRoots.add(rootContext.getTypeId());
} else {
branchRoots = findBranchRoots(rootContext);
LOG.debug("Did not find any parameter models for {}", rootContext.getType());
}
Map<ResolvedType, Model> dependencies = modelProvider.dependencies(rootContext);
for (ResolvedType type : dependencies.keySet()) {
ModelContext childContext = ModelContext.fromParent(rootContext, type);
modelBranch.put(dependencies.get(type).getId(), dependencies.get(type));
contextMap.put(dependencies.get(type).getId(), childContext);
}
if (modelBranch.isEmpty()) {
continue;
}
final MergingContext mergingContext = createMergingContext(
Collections.unmodifiableMap(uniqueModels),
Collections.unmodifiableMap(parameterModelMap),
Collections.unmodifiableMap(modelBranch),
Collections.unmodifiableMap(contextMap));
branchRoots.stream().filter(rootId -> modelBranch.containsKey(rootId)).forEach(
rootId -> mergeModelBranch(adapter, mergingContext.toRootId(rootId)));
Set<Model> updatedModels = updateModels(modelBranch.values(), contextMap, adapter);
mergedModelMap.put(rootContext.getParameterId(), updatedModels);
updatedModels.stream().filter(model -> !uniqueModels.containsKey(model.getName())).forEach(
model -> {
uniqueModels.put(model.getName(), model);
parameterModelMap.put(model.getId(), rootContext.getParameterId());
});
}
return Collections.unmodifiableMap(mergedModelMap);
}
private Set<ComparisonCondition> mergeModelBranch(
UniqueTypeNameAdapter adapter,
final MergingContext mergingContext) {
final Set<String> nodes = collectNodes(adapter, mergingContext);
final Set<ComparisonCondition> dependencies = new HashSet<>();
final Set<String> currentDependencies = new HashSet<>();
boolean allowableToSearchTheSame = true;
final Map<String, Optional<String>> comparisonConditions = new HashMap<>();
Set<String> parametersTo = new HashSet<>();
for (final String modelId : nodes) {
if (adapter.getTypeName(modelId).isPresent()) {
continue;
}
if (!mergingContext.hasSeenBefore(modelId)) {
MergingContext childMergingContext = createChildMergingContext(modelId,
!currentDependencies.isEmpty(),
parametersTo,
dependencies,
mergingContext,
adapter);
Set<ComparisonCondition> newDependencies = childMergingContext
.getComparisonCondition(modelId)
.<Set<ComparisonCondition>>map(
reenteredCondition -> new HashSet<>(Arrays.asList(reenteredCondition)))
.orElseGet(() -> mergeModelBranch(adapter, childMergingContext));
if (newDependencies.isEmpty()) {
allowableToSearchTheSame = false;
parametersTo = new HashSet<>();
continue;
}
newDependencies.stream()
.peek(d -> checkCondition(d, false))
.filter(d -> !d.getConditions().isEmpty())
.forEach(p -> {
dependencies.add(p);
currentDependencies.addAll(p.getConditions());
});
if (!allowableToSearchTheSame) {
continue;
}
ComparisonCondition currentCondition = currentCondition(modelId, newDependencies);
if (currentCondition.getConditions().isEmpty()) {
comparisonConditions.put(modelId,
currentCondition.getModelsTo()
.stream()
.map(mergingContext::getModelParameter)
.findFirst());
continue;
}
parametersTo = modelsToParameters(currentCondition.getModelsTo(), mergingContext);
comparisonConditions.put(modelId, Optional.empty());
} else {
currentDependencies.add(modelId);
if (!allowableToSearchTheSame) {
continue;
}
Optional<Set<String>> megedParameters = mergeParameters(modelId,
parametersTo,
mergingContext);
parametersTo = megedParameters.orElseGet(() -> new HashSet<>());
allowableToSearchTheSame = megedParameters.isPresent();
comparisonConditions.put(modelId, Optional.empty());
}
}
Set<String> sameModels = new HashSet<>();
if (allowableToSearchTheSame) {
sameModels
.addAll(findSameModels(comparisonConditions, parametersTo, adapter, mergingContext));
currentDependencies.remove(mergingContext.getRootId());
}
return mergeConditions(sameModels, currentDependencies, dependencies, adapter, mergingContext);
}
private ComparisonCondition currentCondition(
final String modelId,
final Set<ComparisonCondition> newDependencies) {
List<ComparisonCondition> conditions = newDependencies.stream()
.filter(comparisonCondition -> comparisonCondition.getModelFor().equals(modelId))
.collect(Collectors.toCollection(ArrayList::new));
if (conditions.size() > 1) {
throw new IllegalStateException("Ambiguous conditions for one model.");
}
if (conditions.size() == 0) {
throw new IllegalStateException("Condition is not present.");
}
return conditions.get(0);
}
private Set<String> findSameModels(
Map<String, Optional<String>> parametersMatching,
Set<String> allowedParameters,
UniqueTypeNameAdapter adapter,
MergingContext mergingContext) {
if (allowedParameters.isEmpty()) {
allowedParameters = new HashSet<>(Arrays.asList(""));
}
Model rootModel = mergingContext.getRootModel();
ModelBuilder rootModelBuilder = new ModelBuilder(rootModel);
Set<String> sameModels = new HashSet<>();
final String modelForTypeName = rootModel.getType().getErasedType().getName();
final Set<Model> modelsToCompare = mergingContext.getSimilarTypeModels(modelForTypeName);
Iterator<String> it = allowedParameters.iterator();
while (it.hasNext()) {
String parameter = it.next();
List<ModelReference> subTypes = new ArrayList<>();
for (ModelReference modelReference : rootModel.getSubTypes()) {
Optional<String> modelId = getModelId(modelReference);
if (modelId.isPresent()) {
String sModelId = modelId.get();
ModelContext modelContext = Optional.ofNullable(parametersMatching.get(sModelId))
.map(op -> op.orElseGet(() -> parameter))
.map(p -> pseudoContext(p, mergingContext.getModelContext(sModelId)))
.orElseGet(() -> mergingContext.getModelContext(sModelId));
modelReference = modelRefFactory(modelContext,
enumTypeDeterminer,
typeNameExtractor,
adapter.getNames()).apply(mergingContext.getModel(sModelId).getType());
}
subTypes.add(modelReference);
}
Map<String, ModelProperty> newProperties = new HashMap<>(rootModel.getProperties());
for (String propertyName : rootModel.getProperties().keySet()) {
ModelProperty property = rootModel.getProperties().get(propertyName);
ModelReference modelReference = property.getModelRef();
Optional<String> modelId = getModelId(modelReference);
if (modelId.isPresent()) {
String sModelId = modelId.get();
ModelContext modelContext = Optional.ofNullable(parametersMatching.get(sModelId))
.map(op -> op.orElseGet(() -> parameter))
.map(p -> pseudoContext(p, mergingContext.getModelContext(sModelId)))
.orElseGet(() -> mergingContext.getModelContext(sModelId));
newProperties.put(propertyName,
new ModelPropertyBuilder(property).build()
.updateModelRef(modelRefFactory(modelContext,
enumTypeDeterminer,
typeNameExtractor,
adapter.getNames())));
}
}
Model modelToCompare = rootModelBuilder.properties(newProperties).subTypes(subTypes).build();
modelsToCompare.stream()
.filter(m -> StringUtils.isEmpty(parameter)
|| parameter.equals(mergingContext.getModelParameter(m.getId())))
.filter(m -> m.equalsIgnoringName(modelToCompare))
.map(m -> m.getId())
.findFirst()
.ifPresent(sameModels::add);
}
return sameModels;
}
private Set<ComparisonCondition> mergeConditions(
Set<String> sameModels,
Set<String> currentDependencies,
Set<ComparisonCondition> dependencies,
UniqueTypeNameAdapter adapter,
MergingContext mergingContext) {
if (!sameModels.isEmpty()) {
ComparisonCondition currentCondition = new ComparisonCondition(mergingContext.getRootId(),
sameModels, currentDependencies);
dependencies = filterDependencies(dependencies,
modelsToParameters(sameModels, mergingContext),
mergingContext);
dependencies.add(currentCondition);
if (currentCondition.getConditions().isEmpty()) {
for (ComparisonCondition depComparisonCondition : dependencies) {
Set<String> conditions = new HashSet<>(depComparisonCondition.getConditions());
conditions.remove(currentCondition.getModelFor());
checkCondition(
new ComparisonCondition(depComparisonCondition.getModelFor(),
depComparisonCondition.getModelsTo(), conditions),
true);
adapter.setEqualityFor(depComparisonCondition.getModelFor(),
new ArrayList<>(depComparisonCondition.getModelsTo()).get(0));
}
return new HashSet<>(Arrays.asList(currentCondition));
} else {
Set<ComparisonCondition> newDependencies = new HashSet<>();
for (ComparisonCondition depComparisonCondition : dependencies) {
Set<String> conditions = new HashSet<>(depComparisonCondition.getConditions());
conditions.remove(currentCondition.getModelFor());
conditions.addAll(currentCondition.getConditions());
newDependencies.add(new ComparisonCondition(depComparisonCondition.getModelFor(),
depComparisonCondition.getModelsTo(), conditions));
}
return newDependencies;
}
} else {
adapter.registerUniqueType(mergingContext.getRootModel().getName(),
mergingContext.getRootId());
for (ComparisonCondition depComparisonCondition : dependencies) {
String modelId = depComparisonCondition.getModelFor();
adapter.registerUniqueType(mergingContext.getModel(modelId).getName(), modelId);
}
}
return new HashSet<>();
}
private List<String> findBranchRoots(ModelContext rootContext) {
List<String> roots = new ArrayList<>();
ResolvedType resolvedType = rootContext.alternateFor(rootContext.getType());
if (resolvedType.isArray()) {
ResolvedType elementType = resolvedType.getArrayElementType();
roots.addAll(findBranchRoots(ModelContext.fromParent(rootContext, elementType)));
} else {
for (ResolvedType parameter : resolvedType.getTypeParameters()) {
roots.addAll(findBranchRoots(ModelContext.fromParent(rootContext, parameter)));
}
roots.add(ModelContext.fromParent(rootContext, resolvedType).getTypeId());
}
return roots;
}
private Set<String> collectNodes(UniqueTypeNameAdapter adapter, MergingContext mergingContext) {
Model rootModel = mergingContext.getRootModel();
final Set<String> nodes = new TreeSet<>();
for (ModelReference modelReference : rootModel.getSubTypes()) {
Optional<String> modelId = getModelId(modelReference);
if (modelId.isPresent() && mergingContext.containsModel(modelId.get())) {
nodes.add(modelId.get());
}
}
final ModelContext rootModelContext = mergingContext
.getModelContext(mergingContext.getRootId());
for (ResolvedType type : rootModel.getType().getTypeParameters()) {
String modelId = ModelContext
.fromParent(rootModelContext, rootModelContext.alternateFor(type))
.getTypeId();
if (mergingContext.containsModel(modelId)) {
nodes.add(modelId);
}
}
for (ModelProperty modelProperty : rootModel.getProperties().values()) {
Optional<String> modelId = getModelId(modelProperty.getModelRef());
if (modelId.isPresent() && mergingContext.containsModel(modelId.get())) {
nodes.add(modelId.get());
}
}
nodes.removeIf(s -> adapter.getTypeName(s).isPresent());
return nodes;
}
private Optional<Set<String>> mergeParameters(
String modelId,
Set<String> existingParameters,
MergingContext mergingContext) {
if (modelId.equals(mergingContext.getRootId())) {
return Optional.of(existingParameters);
}
Set<String> parameters = new HashSet<>(existingParameters);
for (Map.Entry<String, Set<String>> entry : mergingContext.getCircles().entrySet()) {
if (!entry.getValue().contains(modelId)) {
if (parameters.isEmpty()) {
parameters.addAll(mergingContext.getCircleParameters(entry.getKey()));
} else {
parameters.retainAll(mergingContext.getCircleParameters(entry.getKey()));
}
if (parameters.isEmpty()) {
return Optional.empty();
}
}
}
String modelForTypeName = mergingContext.getModel(modelId).getType().getErasedType().getName();
Set<Model> similarTypeModels = mergingContext.getSimilarTypeModels(modelForTypeName);
Set<String> candidateParameters = similarTypeModels.stream()
.map(model -> mergingContext.getModelParameter(model.getId()))
.collect(Collectors.toCollection(HashSet::new));
if (parameters.isEmpty()) {
parameters.addAll(candidateParameters);
} else {
parameters.retainAll(candidateParameters);
}
if (parameters.isEmpty()) {
return Optional.empty();
}
return Optional.of(parameters);
}
private Set<ComparisonCondition> filterDependencies(
Set<ComparisonCondition> dependencies,
Set<String> parameters,
MergingContext mergingContext) {
return dependencies.stream().map(condition -> {
Set<String> modelsTo = condition.getModelsTo()
.stream()
.filter(modelId -> parameters.contains(mergingContext.getModelParameter(modelId)))
.collect(Collectors.toCollection(HashSet::new));
return new ComparisonCondition(condition.getModelFor(), modelsTo, condition.getConditions());
}).collect(Collectors.toCollection(HashSet::new));
}
private Model updateModel(
Model model,
Map<String, ModelContext> contextMap,
UniqueTypeNameAdapter adapter) {
for (String propertyName : model.getProperties().keySet()) {
ModelProperty property = model.getProperties().get(propertyName);
Optional<String> modelId = getModelId(property.getModelRef());
if (modelId.isPresent() && contextMap.containsKey(modelId.get())) {
property.updateModelRef(modelRefFactory(contextMap.get(modelId.get()),
enumTypeDeterminer,
typeNameExtractor,
adapter.getNames()));
}
}
List<ModelReference> subTypes = new ArrayList<>();
for (ModelReference oldModelRef : model.getSubTypes()) {
Optional<String> modelId = getModelId(oldModelRef);
if (modelId.isPresent() && contextMap.containsKey(modelId.get())) {
ModelContext modelContext = contextMap.get(modelId.get());
subTypes.add(
modelRefFactory(modelContext, enumTypeDeterminer, typeNameExtractor, adapter.getNames())
.apply(modelContext.getType()));
} else {
subTypes.add(oldModelRef);
}
}
String name = typeNameExtractor.typeName(contextMap.get(model.getId()), adapter.getNames());
return new ModelBuilder(model).name(name).subTypes(subTypes).build();
}
private Set<Model> updateModels(
final Collection<Model> models,
final Map<String, ModelContext> contextMap,
final UniqueTypeNameAdapter adapter) {
models.forEach(model -> {
if (!adapter.getTypeName(model.getId()).isPresent()) {
adapter.registerUniqueType(model.getName(), model.getId());
}
});
return models.stream().map(model -> updateModel(model, contextMap, adapter)).collect(
Collectors.toCollection(HashSet::new));
}
private static ModelContext pseudoContext(String parameterId, ModelContext context) {
return ModelContext.inputParam(parameterId,
context.getGroupName(),
context.getType(),
Optional.empty(),
new HashSet<>(),
context.getDocumentationType(),
context.getAlternateTypeProvider(),
context.getGenericNamingStrategy(),
Collections.unmodifiableSet(new HashSet<>()));
}
private static void checkCondition(
ComparisonCondition condition,
boolean conditionalPresenceCheck) {
if (conditionalPresenceCheck && !condition.getConditions().isEmpty()) {
throw new IllegalStateException("Equality with conditions is not allowed.");
}
if (condition.getConditions().isEmpty() && condition.getModelsTo().size() > 1) {
throw new IllegalStateException("Ambiguous models equality when conditions is empty.");
}
}
private static Optional<String> getModelId(ModelReference ref) {
ModelReference refT = ref;
while (true) {
if (refT.getModelId().isPresent()) {
return refT.getModelId();
}
if (refT.itemModel().isPresent()) {
refT = refT.itemModel().get();
} else {
return Optional.empty();
}
}
}
private static Set<String> modelsToParameters(Set<String> models, MergingContext mergingContext) {
return models.stream().map(mergingContext::getModelParameter).collect(
Collectors.toCollection(HashSet::new));
}
@SuppressWarnings("rawtypes")
private void markIgnorablesAsHasSeen(
TypeResolver typeResolver,
Set<Class> ignorableParameterTypes,
ModelContext modelContext) {
for (Class ignorableParameterType : ignorableParameterTypes) {
modelContext.seen(typeResolver.resolve(ignorableParameterType));
}
}
private static MergingContext createChildMergingContext(
String modelId,
boolean isCircle,
Set<String> parameters,
Set<ComparisonCondition> dependencies,
MergingContext mergingContext,
UniqueTypeNameAdapter adapter) {
if (isCircle) {
return mergingContext.toRootId(modelId, dependencies, parameters);
} else {
return mergingContext.toRootId(modelId);
}
}
private static MergingContext createMergingContext(
Map<String, Model> uniqueModels,
Map<String, String> parameterModelMap,
Map<String, Model> currentBranch,
Map<String, ModelContext> contextMap) {
Map<String, Set<Model>> typedModelMap = new HashMap<>();
Iterator<Model> it = uniqueModels.values().iterator();
while (it.hasNext()) {
Model model = it.next();
String rawType = model.getType().getErasedType().getName();
Set<Model> models = new HashSet<>();
models.add(model);
if (typedModelMap.containsKey(rawType)) {
models.addAll(typedModelMap.get(rawType));
}
typedModelMap.put(rawType, Collections.unmodifiableSet(models));
}
return new MergingContext(typedModelMap, parameterModelMap, currentBranch, contextMap);
}
} | #3303
Check if model exists in listing. A fuse to prevent NPE. | springfox-spring-web/src/main/java/springfox/documentation/spring/web/scanners/ApiModelReader.java | #3303 |
|
Java | apache-2.0 | f8482c86a0ecac7c467f062fa1ee1b5084c0e8ed | 0 | JEBailey/sling,wimsymons/sling,anchela/sling,roele/sling,mmanski/sling,mmanski/sling,tmaret/sling,ieb/sling,plutext/sling,trekawek/sling,ieb/sling,mcdan/sling,dulvac/sling,vladbailescu/sling,klcodanr/sling,tteofili/sling,awadheshv/sling,Sivaramvt/sling,vladbailescu/sling,SylvesterAbreu/sling,headwirecom/sling,mikibrv/sling,SylvesterAbreu/sling,tyge68/sling,trekawek/sling,vladbailescu/sling,sdmcraft/sling,roele/sling,nleite/sling,cleliameneghin/sling,cleliameneghin/sling,mmanski/sling,wimsymons/sling,labertasch/sling,SylvesterAbreu/sling,Nimco/sling,plutext/sling,klcodanr/sling,plutext/sling,awadheshv/sling,roele/sling,Nimco/sling,trekawek/sling,klcodanr/sling,awadheshv/sling,ffromm/sling,cleliameneghin/sling,dulvac/sling,tyge68/sling,sdmcraft/sling,JEBailey/sling,trekawek/sling,Sivaramvt/sling,mcdan/sling,labertasch/sling,dulvac/sling,Nimco/sling,tyge68/sling,mcdan/sling,wimsymons/sling,JEBailey/sling,dulvac/sling,nleite/sling,mcdan/sling,tteofili/sling,ieb/sling,ieb/sling,ffromm/sling,headwirecom/sling,tmaret/sling,gutsy/sling,cleliameneghin/sling,Sivaramvt/sling,anchela/sling,gutsy/sling,dulvac/sling,plutext/sling,klcodanr/sling,labertasch/sling,plutext/sling,mmanski/sling,dulvac/sling,tteofili/sling,cleliameneghin/sling,plutext/sling,tyge68/sling,sdmcraft/sling,anchela/sling,nleite/sling,ffromm/sling,gutsy/sling,labertasch/sling,SylvesterAbreu/sling,ffromm/sling,SylvesterAbreu/sling,mikibrv/sling,wimsymons/sling,ist-dresden/sling,tyge68/sling,ist-dresden/sling,ffromm/sling,headwirecom/sling,awadheshv/sling,ffromm/sling,wimsymons/sling,mcdan/sling,JEBailey/sling,tteofili/sling,Sivaramvt/sling,mikibrv/sling,sdmcraft/sling,mcdan/sling,tmaret/sling,sdmcraft/sling,gutsy/sling,Nimco/sling,gutsy/sling,mmanski/sling,mikibrv/sling,tteofili/sling,headwirecom/sling,vladbailescu/sling,Sivaramvt/sling,trekawek/sling,mikibrv/sling,tmaret/sling,JEBailey/sling,tyge68/sling,roele/sling,klcodanr/sling,vladbailescu/sling,ist-dresden/sling,anchela/sling,nleite/sling,gutsy/sling,tmaret/sling,Nimco/sling,nleite/sling,ist-dresden/sling,nleite/sling,ist-dresden/sling,klcodanr/sling,awadheshv/sling,Sivaramvt/sling,mikibrv/sling,wimsymons/sling,trekawek/sling,headwirecom/sling,awadheshv/sling,anchela/sling,roele/sling,SylvesterAbreu/sling,tteofili/sling,ieb/sling,labertasch/sling,ieb/sling,Nimco/sling,sdmcraft/sling,mmanski/sling | /*
* 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.sling.servlets.resolver.internal;
import static org.apache.sling.api.SlingConstants.ERROR_MESSAGE;
import static org.apache.sling.api.SlingConstants.ERROR_SERVLET_NAME;
import static org.apache.sling.api.SlingConstants.ERROR_STATUS;
import static org.apache.sling.api.SlingConstants.SLING_CURRENT_SERVLET_NAME;
import static org.apache.sling.servlets.resolver.internal.ServletResolverConstants.SLING_SERLVET_NAME;
import static org.osgi.framework.Constants.SERVICE_ID;
import static org.osgi.framework.Constants.SERVICE_PID;
import static org.osgi.service.component.ComponentConstants.COMPONENT_NAME;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.SlingException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.request.RequestProgressTracker;
import org.apache.sling.api.request.RequestUtil;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceProvider;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.SyntheticResource;
import org.apache.sling.api.scripting.SlingScript;
import org.apache.sling.api.scripting.SlingScriptResolver;
import org.apache.sling.api.servlets.OptingServlet;
import org.apache.sling.api.servlets.ServletResolver;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.engine.servlets.ErrorHandler;
import org.apache.sling.servlets.resolver.internal.defaults.DefaultErrorHandlerServlet;
import org.apache.sling.servlets.resolver.internal.defaults.DefaultServlet;
import org.apache.sling.servlets.resolver.internal.helper.AbstractResourceCollector;
import org.apache.sling.servlets.resolver.internal.helper.NamedScriptResourceCollector;
import org.apache.sling.servlets.resolver.internal.helper.ResourceCollector;
import org.apache.sling.servlets.resolver.internal.helper.SlingServletConfig;
import org.apache.sling.servlets.resolver.internal.resource.ServletResourceProvider;
import org.apache.sling.servlets.resolver.internal.resource.ServletResourceProviderFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>SlingServletResolver</code> has two functions: It resolves scripts
* by implementing the {@link SlingScriptResolver} interface and it resolves a
* servlet for a request by implementing the {@link ServletResolver} interface.
*
* The resolver uses an own session to find the scripts.
*
*/
@Component(name="org.apache.sling.servlets.resolver.SlingServletResolver", metatype=true,
label="%servletresolver.name", description="%servletresolver.description")
@Service(value={ServletResolver.class, SlingScriptResolver.class, ErrorHandler.class})
@Properties({
@Property(name="service.description", value="Sling Servlet Resolver and Error Handler"),
@Property(name="event.topics", propertyPrivate=true,
value={"org/apache/sling/api/resource/Resource/*",
"org/apache/sling/api/resource/ResourceProvider/*",
"javax/script/ScriptEngineFactory/*",
"org/apache/sling/api/adapter/AdapterFactory/*",
"org/apache/sling/scripting/core/BindingsValuesProvider/*"})
})
@Reference(name="Servlet", referenceInterface=javax.servlet.Servlet.class,
cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC)
public class SlingServletResolver
implements ServletResolver,
SlingScriptResolver,
ErrorHandler,
EventHandler {
/**
* The default servlet root is the first search path (which is usally /apps)
*/
public static final String DEFAULT_SERVLET_ROOT = "0";
/** The default cache size for the script resolution. */
public static final int DEFAULT_CACHE_SIZE = 200;
/** Servlet resolver logger */
public static final Logger LOGGER = LoggerFactory.getLogger(SlingServletResolver.class);
@Property(value=DEFAULT_SERVLET_ROOT)
public static final String PROP_SERVLET_ROOT = "servletresolver.servletRoot";
@Property
public static final String PROP_SCRIPT_USER = "servletresolver.scriptUser";
@Property(intValue=DEFAULT_CACHE_SIZE)
public static final String PROP_CACHE_SIZE = "servletresolver.cacheSize";
private static final String REF_SERVLET = "Servlet";
@Property(value="/", unbounded=PropertyUnbounded.ARRAY)
public static final String PROP_PATHS = "servletresolver.paths";
private static final String[] DEFAULT_PATHS = new String[] {"/"};
@Property(value="html", unbounded=PropertyUnbounded.ARRAY)
public static final String PROP_DEFAULT_EXTENSIONS = "servletresolver.defaultExtensions";
private static final String[] DEFAULT_DEFAULT_EXTENSIONS = new String[] {"html"};
@Reference
private ServletContext servletContext;
@Reference
private ResourceResolverFactory resourceResolverFactory;
private ResourceResolver scriptResolver;
private final Map<ServiceReference, ServletReg> servletsByReference = new HashMap<ServiceReference, ServletReg>();
private final List<ServiceReference> pendingServlets = new ArrayList<ServiceReference>();
/** The component context. */
private ComponentContext context;
private ServletResourceProviderFactory servletResourceProviderFactory;
// the default servlet if no other servlet applies for a request. This
// field is set on demand by getDefaultServlet()
private Servlet defaultServlet;
// the default error handler servlet if no other error servlet applies for
// a request. This field is set on demand by getDefaultErrorServlet()
private Servlet fallbackErrorServlet;
/** The script resolution cache. */
private Map<AbstractResourceCollector, Servlet> cache;
/** The cache size. */
private int cacheSize;
/** Flag to log warning if cache size exceed only once. */
private volatile boolean logCacheSizeWarning;
/** Registration as event handler. */
private ServiceRegistration eventHandlerReg;
/**
* The allowed execution paths.
*/
private String[] executionPaths;
/**
* The default extensions
*/
private String[] defaultExtensions;
private ServletResolverWebConsolePlugin plugin;
// ---------- ServletResolver interface -----------------------------------
/**
* @see org.apache.sling.api.servlets.ServletResolver#resolveServlet(org.apache.sling.api.SlingHttpServletRequest)
*/
public Servlet resolveServlet(final SlingHttpServletRequest request) {
final Resource resource = request.getResource();
// start tracking servlet resolution
final RequestProgressTracker tracker = request.getRequestProgressTracker();
final String timerName = "resolveServlet(" + resource + ")";
tracker.startTimer(timerName);
final String type = resource.getResourceType();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("resolveServlet called for resource {}", resource);
}
Servlet servlet = null;
if ( type != null && type.length() > 0 ) {
servlet = resolveServletInternal(request, type);
}
// last resort, use the core bundle default servlet
if (servlet == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No specific servlet found, trying default");
}
servlet = getDefaultServlet();
}
// track servlet resolution termination
if (servlet == null) {
tracker.logTimer(timerName, "Servlet resolution failed. See log for details");
} else {
tracker.logTimer(timerName, "Using servlet {0}", RequestUtil.getServletName(servlet));
}
// log the servlet found
if (LOGGER.isDebugEnabled()) {
if (servlet != null) {
LOGGER.debug("Servlet {} found for resource={}", RequestUtil.getServletName(servlet), resource);
} else {
LOGGER.debug("No servlet found for resource={}", resource);
}
}
return servlet;
}
/**
* @see org.apache.sling.api.servlets.ServletResolver#resolveServlet(org.apache.sling.api.resource.Resource, java.lang.String)
*/
public Servlet resolveServlet(final Resource resource, final String scriptName) {
if ( resource == null ) {
throw new IllegalArgumentException("Resource must not be null");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("resolveServlet called for resource {} with script name {}", resource, scriptName);
}
final Servlet servlet = resolveServletInternal(resource, scriptName);
// log the servlet found
if (LOGGER.isDebugEnabled()) {
if (servlet != null) {
LOGGER.debug("Servlet {} found for resource {} and script name {}", new Object[] {RequestUtil.getServletName(servlet), resource, scriptName});
} else {
LOGGER.debug("No servlet found for resource {} and script name {}", resource, scriptName);
}
}
return servlet;
}
/**
* @see org.apache.sling.api.servlets.ServletResolver#resolveServlet(org.apache.sling.api.resource.ResourceResolver, java.lang.String)
*/
public Servlet resolveServlet(final ResourceResolver resolver, final String scriptName) {
if ( resolver == null ) {
throw new IllegalArgumentException("Resource resolver must not be null");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("resolveServlet called for for script name {}", scriptName);
}
final Servlet servlet = resolveServletInternal((Resource)null, scriptName);
// log the servlet found
if (LOGGER.isDebugEnabled()) {
if (servlet != null) {
LOGGER.debug("Servlet {} found for script name {}", RequestUtil.getServletName(servlet), scriptName);
} else {
LOGGER.debug("No servlet found for script name {}", scriptName);
}
}
return servlet;
}
/** Internal method to resolve a servlet. */
private Servlet resolveServletInternal(
final Resource resource,
final String scriptName) {
Servlet servlet = null;
// first check whether the type of a resource is the absolute
// path of a servlet (or script)
if (scriptName.charAt(0) == '/') {
final String scriptPath = ResourceUtil.normalize(scriptName);
if ( this.isPathAllowed(scriptPath) ) {
final Resource res = this.scriptResolver.getResource(scriptPath);
if (res != null) {
servlet = res.adaptTo(Servlet.class);
}
if (servlet != null && LOGGER.isDebugEnabled()) {
LOGGER.debug("Servlet {} found using absolute resource type {}", RequestUtil.getServletName(servlet),
scriptName);
}
}
}
if ( servlet == null ) {
// the resource type is not absolute, so lets go for the deep search
final NamedScriptResourceCollector locationUtil = NamedScriptResourceCollector.create(scriptName, resource, this.executionPaths);
servlet = getServletInternal(locationUtil, null);
if (LOGGER.isDebugEnabled() && servlet != null) {
LOGGER.debug("resolveServlet returns servlet {}", RequestUtil.getServletName(servlet));
}
}
return servlet;
}
// ---------- ScriptResolver interface ------------------------------------
/**
* @see org.apache.sling.api.scripting.SlingScriptResolver#findScript(org.apache.sling.api.resource.ResourceResolver, java.lang.String)
*/
public SlingScript findScript(final ResourceResolver resourceResolver, final String name)
throws SlingException {
// is the path absolute
SlingScript script = null;
if (name.startsWith("/")) {
final String path = ResourceUtil.normalize(name);
if ( this.isPathAllowed(path) ) {
final Resource resource = resourceResolver.getResource(path);
if (resource != null) {
script = resource.adaptTo(SlingScript.class);
}
}
} else {
// relative script resolution against search path
final String[] path = resourceResolver.getSearchPath();
for (int i = 0; script == null && i < path.length; i++) {
final String scriptPath = ResourceUtil.normalize(path[i] + name);
if ( this.isPathAllowed(scriptPath) ) {
final Resource resource = resourceResolver.getResource(scriptPath);
if (resource != null) {
script = resource.adaptTo(SlingScript.class);
}
}
}
}
// some logging
if (script != null) {
LOGGER.debug("findScript: Using script {} for {}", script.getScriptResource().getPath(), name);
} else {
LOGGER.info("findScript: No script {} found in path", name);
}
// and finally return the script (null or not)
return script;
}
// ---------- ErrorHandler interface --------------------------------------
/**
* @see org.apache.sling.engine.servlets.ErrorHandler#handleError(int,
* String, SlingHttpServletRequest, SlingHttpServletResponse)
*/
public void handleError(final int status,
final String message,
final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws IOException {
// do not handle, if already handling ....
if (request.getAttribute(SlingConstants.ERROR_REQUEST_URI) != null) {
LOGGER.error("handleError: Recursive invocation. Not further handling status " + status + "(" + message + ")");
return;
}
// start tracker
RequestProgressTracker tracker = request.getRequestProgressTracker();
String timerName = "handleError:status=" + status;
tracker.startTimer(timerName);
try {
// find the error handler component
Resource resource = getErrorResource(request);
// find a servlet for the status as the method name
ResourceCollector locationUtil = new ResourceCollector(String.valueOf(status),
ServletResolverConstants.ERROR_HANDLER_PATH, resource,
this.executionPaths);
Servlet servlet = getServletInternal(locationUtil, request);
// fall back to default servlet if none
if (servlet == null) {
servlet = getDefaultErrorServlet(request, resource);
}
// set the message properties
request.setAttribute(ERROR_STATUS, new Integer(status));
request.setAttribute(ERROR_MESSAGE, message);
// the servlet name for a sendError handling is still stored
// as the request attribute
Object servletName = request.getAttribute(SLING_CURRENT_SERVLET_NAME);
if (servletName instanceof String) {
request.setAttribute(ERROR_SERVLET_NAME, servletName);
}
// log a track entry after resolution before calling the handler
tracker.logTimer(timerName, "Using handler {0}", RequestUtil.getServletName(servlet));
handleError(servlet, request, response);
} finally {
tracker.logTimer(timerName, "Error handler finished");
}
}
/**
* @see org.apache.sling.engine.servlets.ErrorHandler#handleError(java.lang.Throwable, org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
*/
public void handleError(final Throwable throwable, final SlingHttpServletRequest request, final SlingHttpServletResponse response)
throws IOException {
// do not handle, if already handling ....
if (request.getAttribute(SlingConstants.ERROR_REQUEST_URI) != null) {
LOGGER.error("handleError: Recursive invocation. Not further handling Throwable:", throwable);
return;
}
// start tracker
RequestProgressTracker tracker = request.getRequestProgressTracker();
String timerName = "handleError:throwable=" + throwable.getClass().getName();
tracker.startTimer(timerName);
try {
// find the error handler component
Servlet servlet = null;
Resource resource = getErrorResource(request);
Class<?> tClass = throwable.getClass();
while (servlet == null && tClass != Object.class) {
// find a servlet for the simple class name as the method name
ResourceCollector locationUtil = new ResourceCollector(tClass.getSimpleName(),
ServletResolverConstants.ERROR_HANDLER_PATH, resource,
this.executionPaths);
servlet = getServletInternal(locationUtil, request);
// go to the base class
tClass = tClass.getSuperclass();
}
if (servlet == null) {
servlet = getDefaultErrorServlet(request, resource);
}
// set the message properties
request.setAttribute(SlingConstants.ERROR_EXCEPTION, throwable);
request.setAttribute(SlingConstants.ERROR_EXCEPTION_TYPE, throwable.getClass());
request.setAttribute(SlingConstants.ERROR_MESSAGE, throwable.getMessage());
// log a track entry after resolution before calling the handler
tracker.logTimer(timerName, "Using handler {0}", RequestUtil.getServletName(servlet));
handleError(servlet, request, response);
} finally {
tracker.logTimer(timerName, "Error handler finished");
}
}
// ---------- internal helper ---------------------------------------------
/**
* Returns the resource of the given request to be used as the basis for
* error handling. If the resource has not yet been set in the request
* because the error occurred before the resource could be set (e.g. during
* resource resolution) a synthetic resource is returned whose type is
* {@link ServletResolverConstants#ERROR_HANDLER_PATH}.
*
* @param request The request whose resource is to be returned.
*/
private Resource getErrorResource(final SlingHttpServletRequest request) {
Resource res = request.getResource();
if (res == null) {
res = new SyntheticResource(request.getResourceResolver(), request.getPathInfo(),
ServletResolverConstants.ERROR_HANDLER_PATH);
}
return res;
}
/**
* Resolve an appropriate servlet for a given request and resource type
* using the provided ResourceResolver
*/
private Servlet resolveServletInternal(final SlingHttpServletRequest request,
final String type) {
Servlet servlet = null;
// first check whether the type of a resource is the absolute
// path of a servlet (or script)
if (type.charAt(0) == '/') {
String scriptPath = ResourceUtil.normalize(type);
if ( this.isPathAllowed(scriptPath) ) {
final Resource res = this.scriptResolver.getResource(scriptPath);
if (res != null) {
servlet = res.adaptTo(Servlet.class);
}
if (servlet != null && LOGGER.isDebugEnabled()) {
LOGGER.debug("Servlet {} found using absolute resource type {}", RequestUtil.getServletName(servlet),
type);
}
} else {
request.getRequestProgressTracker().log(
"Will not look for a servlet at {0} as it is not in the list of allowed paths",
type
);
}
}
if ( servlet == null ) {
// the resource type is not absolute, so lets go for the deep search
final ResourceCollector locationUtil = ResourceCollector.create(request, this.executionPaths, this.defaultExtensions);
servlet = getServletInternal(locationUtil, request);
if (servlet != null && LOGGER.isDebugEnabled()) {
LOGGER.debug("getServlet returns servlet {}", RequestUtil.getServletName(servlet));
}
}
return servlet;
}
/**
* Returns a servlet suitable for handling a request. The
* <code>locationUtil</code> is used find any servlets or scripts usable for
* the request. Each servlet returned is in turn asked whether it is
* actually willing to handle the request in case the servlet is an
* <code>OptingServlet</code>. The first servlet willing to handle the
* request is used.
*
* @param locationUtil The helper used to find appropriate servlets ordered
* by matching priority.
* @param request The request used to give to any <code>OptingServlet</code>
* for them to decide on whether they are willing to handle the
* request
* @param resource The <code>Resource</code> for which to find a script.
* This need not be the same as
* <code>request.getResource()</code> in case of error handling
* where the resource may not have been assigned to the request
* yet.
* @return a servlet for handling the request or <code>null</code> if no
* such servlet willing to handle the request could be found.
*/
private Servlet getServletInternal(final AbstractResourceCollector locationUtil,
final SlingHttpServletRequest request) {
final Servlet scriptServlet = (this.cache != null ? this.cache.get(locationUtil) : null);
if (scriptServlet != null) {
if ( LOGGER.isDebugEnabled() ) {
LOGGER.debug("Using cached servlet {}", RequestUtil.getServletName(scriptServlet));
}
return scriptServlet;
}
final Collection<Resource> candidates = locationUtil.getServlets(this.scriptResolver);
if (LOGGER.isDebugEnabled()) {
if (candidates.isEmpty()) {
LOGGER.debug("No servlet candidates found");
} else {
LOGGER.debug("Ordered list of servlet candidates follows");
for (Resource candidateResource : candidates) {
LOGGER.debug("Servlet candidate: {}", candidateResource.getPath());
}
}
}
boolean hasOptingServlet = false;
for (Resource candidateResource : candidates) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Checking if candidate resource {} adapts to servlet and accepts request", candidateResource
.getPath());
}
Servlet candidate = candidateResource.adaptTo(Servlet.class);
if (candidate != null) {
final boolean isOptingServlet = candidate instanceof OptingServlet;
boolean servletAcceptsRequest = !isOptingServlet || (request != null && ((OptingServlet) candidate).accepts(request));
if (servletAcceptsRequest) {
if (!hasOptingServlet && !isOptingServlet && this.cache != null) {
if ( this.cache.size() < this.cacheSize ) {
this.cache.put(locationUtil, candidate);
} else if ( this.logCacheSizeWarning ) {
this.logCacheSizeWarning = false;
LOGGER.warn("Script cache has reached its limit of {}. You might want to increase the cache size for the servlet resolver.",
this.cacheSize);
}
}
LOGGER.debug("Using servlet provided by candidate resource {}", candidateResource.getPath());
return candidate;
}
if (isOptingServlet) {
hasOptingServlet = true;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Candidate {} does not accept request, ignored", candidateResource.getPath());
}
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Candidate {} does not adapt to a servlet, ignored", candidateResource.getPath());
}
}
}
// exhausted all candidates, we don't have a servlet
return null;
}
/**
* Returns the internal default servlet which is called in case no other
* servlet applies for handling a request. This servlet should really only
* be used if the default servlets have not been registered (yet).
*/
private Servlet getDefaultServlet() {
if (defaultServlet == null) {
try {
Servlet servlet = new DefaultServlet();
servlet.init(new SlingServletConfig(servletContext, null, "Sling Core Default Servlet"));
defaultServlet = servlet;
} catch (ServletException se) {
LOGGER.error("Failed to initialize default servlet", se);
}
}
return defaultServlet;
}
/**
* Returns the default error handler servlet, which is called in case there
* is no other - better matching - servlet registered to handle an error or
* exception.
* <p>
* The default error handler servlet is registered for the resource type
* "sling/servlet/errorhandler" and method "default". This may be
* overwritten by applications globally or according to the resource type
* hierarchy of the resource.
* <p>
* If no default error handler servlet can be found an adhoc error handler
* is used as a final fallback.
*/
private Servlet getDefaultErrorServlet(
final SlingHttpServletRequest request,
final Resource resource) {
// find a default error handler according to the resource type
// tree of the given resource
final ResourceCollector locationUtil = new ResourceCollector(
ServletResolverConstants.DEFAULT_ERROR_HANDLER_NAME,
ServletResolverConstants.ERROR_HANDLER_PATH, resource,
this.executionPaths);
final Servlet servlet = getServletInternal(locationUtil, request);
if (servlet != null) {
return servlet;
}
// if no registered default error handler could be found use
// the DefaultErrorHandlerServlet as an ad-hoc fallback
if (fallbackErrorServlet == null) {
// fall back to an adhoc instance of the DefaultErrorHandlerServlet
// if the actual service is not registered (yet ?)
try {
final Servlet defaultServlet = new DefaultErrorHandlerServlet();
defaultServlet.init(new SlingServletConfig(servletContext,
null, "Sling (Ad Hoc) Default Error Handler Servlet"));
fallbackErrorServlet = defaultServlet;
} catch (ServletException se) {
LOGGER.error("Failed to initialize error servlet", se);
}
}
return fallbackErrorServlet;
}
private void handleError(final Servlet errorHandler, final HttpServletRequest request, final HttpServletResponse response)
throws IOException {
request.setAttribute(SlingConstants.ERROR_REQUEST_URI, request.getRequestURI());
// if there is no explicitly known error causing servlet, use
// the name of the error handler servlet
if (request.getAttribute(SlingConstants.ERROR_SERVLET_NAME) == null) {
request.setAttribute(SlingConstants.ERROR_SERVLET_NAME, errorHandler.getServletConfig().getServletName());
}
try {
errorHandler.service(request, response);
// commit the response
response.flushBuffer();
// close the response (SLING-2724)
response.getWriter().close();
} catch (final IOException ioe) {
// forward the IOException
throw ioe;
} catch (final Throwable t) {
LOGGER.error("Calling the error handler resulted in an error", t);
LOGGER.error("Original error " + request.getAttribute(SlingConstants.ERROR_EXCEPTION_TYPE),
(Throwable) request.getAttribute(SlingConstants.ERROR_EXCEPTION));
}
}
private Map<String, Object> createAuthenticationInfo(final Dictionary<String, Object> props) {
final Map<String, Object> authInfo = new HashMap<String, Object>();
// if a script user is configured we use this user to read the scripts
final String scriptUser = OsgiUtil.toString(props.get(PROP_SCRIPT_USER), null);
if (scriptUser != null && scriptUser.length() > 0) {
authInfo.put(ResourceResolverFactory.USER_IMPERSONATION, scriptUser);
}
return authInfo;
}
// ---------- SCR Integration ----------------------------------------------
/**
* Activate this component.
*/
@SuppressWarnings("unchecked")
protected void activate(final ComponentContext context) throws LoginException {
// from configuration if available
final Dictionary<?, ?> properties = context.getProperties();
Object servletRoot = properties.get(PROP_SERVLET_ROOT);
if (servletRoot == null) {
servletRoot = DEFAULT_SERVLET_ROOT;
}
final Collection<ServiceReference> refs;
synchronized (this.pendingServlets) {
refs = new ArrayList<ServiceReference>(pendingServlets);
pendingServlets.clear();
this.scriptResolver =
resourceResolverFactory.getAdministrativeResourceResolver(this.createAuthenticationInfo(context.getProperties()));
servletResourceProviderFactory = new ServletResourceProviderFactory(servletRoot,
this.scriptResolver.getSearchPath());
// register servlets immediately from now on
this.context = context;
}
createAllServlets(refs);
// execution paths
this.executionPaths = OsgiUtil.toStringArray(properties.get(PROP_PATHS), DEFAULT_PATHS);
if ( this.executionPaths != null ) {
// if we find a string combination that basically allows all paths,
// we simply set the array to null
if ( this.executionPaths.length == 0 ) {
this.executionPaths = null;
} else {
boolean hasRoot = false;
for(int i = 0 ; i < this.executionPaths.length; i++) {
final String path = this.executionPaths[i];
if ( path == null || path.length() == 0 || path.equals("/") ) {
hasRoot = true;
break;
}
}
if ( hasRoot ) {
this.executionPaths = null;
}
}
}
this.defaultExtensions = OsgiUtil.toStringArray(properties.get(PROP_DEFAULT_EXTENSIONS), DEFAULT_DEFAULT_EXTENSIONS);
// create cache - if a cache size is configured
this.cacheSize = OsgiUtil.toInteger(properties.get(PROP_CACHE_SIZE), DEFAULT_CACHE_SIZE);
if (this.cacheSize > 5) {
this.cache = new ConcurrentHashMap<AbstractResourceCollector, Servlet>(cacheSize);
this.logCacheSizeWarning = true;
} else {
this.cacheSize = 0;
}
// and finally register as event listener
this.eventHandlerReg = context.getBundleContext().registerService(EventHandler.class.getName(), this,
properties);
this.plugin = new ServletResolverWebConsolePlugin(context.getBundleContext());
}
/**
* Deactivate this component.
*/
protected void deactivate(final ComponentContext context) {
// stop registering of servlets immediately
this.context = null;
if (this.plugin != null) {
this.plugin.dispose();
}
// unregister event handler
if (this.eventHandlerReg != null) {
this.eventHandlerReg.unregister();
this.eventHandlerReg = null;
}
// Copy the list of servlets first, to minimize the need for
// synchronization
final Collection<ServiceReference> refs;
synchronized (this.servletsByReference) {
refs = new ArrayList<ServiceReference>(servletsByReference.keySet());
}
// destroy all servlets
destroyAllServlets(refs);
// sanity check: clear array (it should be empty now anyway)
synchronized ( this.servletsByReference ) {
this.servletsByReference.clear();
}
// destroy the fallback error handler servlet
if (fallbackErrorServlet != null) {
try {
fallbackErrorServlet.destroy();
} catch (Throwable t) {
// ignore
} finally {
fallbackErrorServlet = null;
}
}
if (this.scriptResolver != null) {
this.scriptResolver.close();
this.scriptResolver = null;
}
this.cache = null;
this.servletResourceProviderFactory = null;
}
protected void bindServlet(final ServiceReference reference) {
boolean directCreate = true;
if (context == null) {
synchronized ( pendingServlets ) {
if (context == null) {
pendingServlets.add(reference);
directCreate = false;
}
}
}
if ( directCreate ) {
createServlet(reference);
}
}
protected void unbindServlet(final ServiceReference reference) {
synchronized ( pendingServlets ) {
pendingServlets.remove(reference);
}
destroyServlet(reference);
}
// ---------- Servlet Management -------------------------------------------
private void createAllServlets(final Collection<ServiceReference> pendingServlets) {
for (final ServiceReference serviceReference : pendingServlets) {
createServlet(serviceReference);
}
}
private boolean createServlet(final ServiceReference reference) {
// check for a name, this is required
final String name = getName(reference);
if (name == null) {
LOGGER.error("bindServlet: Cannot register servlet {} without a servlet name", reference);
return false;
}
// check for Sling properties in the service registration
ServletResourceProvider provider = servletResourceProviderFactory.create(reference);
if (provider == null) {
// this is expected if the servlet is not destined for Sling
return false;
}
// only now try to access the servlet service, this may still fail
Servlet servlet = null;
try {
servlet = (Servlet) context.locateService(REF_SERVLET, reference);
} catch (Throwable t) {
LOGGER.warn("bindServlet: Failed getting the service for reference " + reference, t);
}
if (servlet == null) {
LOGGER.error("bindServlet: Servlet service not available from reference {}", reference);
return false;
}
// assign the servlet to the provider
provider.setServlet(servlet);
// initialize now
try {
servlet.init(new SlingServletConfig(servletContext, reference, name));
LOGGER.debug("bindServlet: Servlet {} added", name);
} catch (ServletException ce) {
LOGGER.error("bindServlet: Component " + name + " failed to initialize", ce);
return false;
} catch (Throwable t) {
LOGGER.error("bindServlet: Unexpected problem initializing component " + name, t);
return false;
}
final Dictionary<String, Object> params = new Hashtable<String, Object>();
params.put(ResourceProvider.ROOTS, provider.getServletPaths());
params.put(Constants.SERVICE_DESCRIPTION, "ServletResourceProvider for Servlets at "
+ Arrays.asList(provider.getServletPaths()));
final ServiceRegistration reg = context.getBundleContext()
.registerService(ResourceProvider.SERVICE_NAME, provider, params);
LOGGER.info("Registered {}", provider.toString());
synchronized (this.servletsByReference) {
servletsByReference.put(reference, new ServletReg(servlet, reg));
}
return true;
}
private void destroyAllServlets(final Collection<ServiceReference> refs) {
for (ServiceReference serviceReference : refs) {
destroyServlet(serviceReference);
}
}
private void destroyServlet(final ServiceReference reference) {
ServletReg registration;
synchronized (this.servletsByReference) {
registration = servletsByReference.remove(reference);
}
if (registration != null) {
registration.registration.unregister();
final String name = RequestUtil.getServletName(registration.servlet);
LOGGER.debug("unbindServlet: Servlet {} removed", name);
try {
registration.servlet.destroy();
} catch (Throwable t) {
LOGGER.error("unbindServlet: Unexpected problem destroying servlet " + name, t);
}
}
}
/**
* @see org.osgi.service.event.EventHandler#handleEvent(org.osgi.service.event.Event)
*/
public void handleEvent(final Event event) {
if (this.cache != null) {
boolean flushCache = false;
// we may receive different events
final String topic = event.getTopic();
if (topic.startsWith("javax/script/ScriptEngineFactory/")) {
// script engine factory added or removed: we always flush
flushCache = true;
} else if (topic.startsWith("org/apache/sling/api/adapter/AdapterFactory/")) {
// adapter factory added or removed: we always flush
// as adapting might be transitive
flushCache = true;
} else if (topic.startsWith("org/apache/sling/scripting/core/BindingsValuesProvider/")) {
// bindings values provide factory added or removed: we always flush
flushCache = true;
} else {
// this is a resource event
// if the path of the event is a sub path of a search path
// we flush the whole cache
String path = (String) event.getProperty(SlingConstants.PROPERTY_PATH);
if (path.contains(":")) {
path = path.substring(path.indexOf(":") + 1);
}
final String[] searchPaths = this.scriptResolver.getSearchPath();
int index = 0;
while (!flushCache && index < searchPaths.length) {
if (path.startsWith(searchPaths[index])) {
flushCache = true;
}
index++;
}
}
if (flushCache) {
this.cache.clear();
this.logCacheSizeWarning = true;
}
}
}
/** The list of property names checked by {@link #getName(ServiceReference)} */
private static final String[] NAME_PROPERTIES = { SLING_SERLVET_NAME,
COMPONENT_NAME, SERVICE_PID, SERVICE_ID };
/**
* Looks for a name value in the service reference properties. See the
* class comment at the top for the list of properties checked by this
* method.
*/
private static String getName(final ServiceReference reference) {
String servletName = null;
for (int i = 0; i < NAME_PROPERTIES.length
&& (servletName == null || servletName.length() == 0); i++) {
Object prop = reference.getProperty(NAME_PROPERTIES[i]);
if (prop != null) {
servletName = String.valueOf(prop);
}
}
return servletName;
}
private boolean isPathAllowed(final String path) {
return AbstractResourceCollector.isPathAllowed(path, this.executionPaths);
}
private static final class ServletReg {
public final Servlet servlet;
public final ServiceRegistration registration;
public ServletReg(final Servlet s, final ServiceRegistration sr) {
this.servlet = s;
this.registration = sr;
}
}
@SuppressWarnings("serial")
class ServletResolverWebConsolePlugin extends HttpServlet {
private static final String PARAMETER_URL = "url";
private static final String PARAMETER_METHOD = "method";
private ServiceRegistration service;
public ServletResolverWebConsolePlugin(final BundleContext context) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_DESCRIPTION,
"Sling Servlet Resolver Web Console Plugin");
props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
props.put(Constants.SERVICE_PID, getClass().getName());
props.put("felix.webconsole.label", "servletresolver");
props.put("felix.webconsole.title", "Sling Servlet Resolver");
props.put("felix.webconsole.css", "/servletresolver/res/ui/styles.css");
props.put("felix.webconsole.category", "Sling");
service = context.registerService(
new String[] { "javax.servlet.Servlet" }, this, props);
}
public void dispose() {
if (service != null) {
service.unregister();
service = null;
}
}
@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
final String url = request.getParameter(PARAMETER_URL);
final RequestPathInfo requestPathInfo = new DecomposedURL(url).getRequestPathInfo();
String method = request.getParameter(PARAMETER_METHOD);
if (StringUtils.isBlank(method)) {
method = "GET";
}
final String CONSOLE_PATH_WARNING =
"<em>"
+ "Note that in a real Sling request, the path might vary depending on the existence of"
+ " resources that partially match it."
+ "<br/>This utility does not take this into account and uses the first dot to split"
+ " between path and selectors/extension."
+ "<br/>As a workaround, you can replace dots with underline characters, for example, when testing such an URL."
+ "</em>";
ResourceResolver resourceResolver = null;
try {
resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
final PrintWriter pw = response.getWriter();
pw.print("<form method='get'>");
pw.println("<table class='content' cellpadding='0' cellspacing='0' width='100%'>");
titleHtml(
pw,
"Servlet Resolver Test",
"To check which servlet is responsible for rendering a response, enter a request path into " +
"the field and click 'Resolve' to resolve it.");
tr(pw);
tdLabel(pw, "URL");
tdContent(pw);
pw.println("<input type='text' name='" + PARAMETER_URL + "' value='" +
(url != null ? url : "") + "' class='input' size='50'>");
closeTd(pw);
closeTr(pw);
closeTr(pw);
tr(pw);
tdLabel(pw, "Method");
tdContent(pw);
pw.println("<select name='" + PARAMETER_METHOD + "'>");
pw.println("<option value='GET'>GET</option>");
pw.println("<option value='POST'>POST</option>");
pw.println("</select>");
pw.println(" <input type='submit'" +
"' value='Resolve' class='submit'>");
closeTd(pw);
closeTr(pw);
if (StringUtils.isNotBlank(url)) {
tr(pw);
tdLabel(pw, "Decomposed URL");
tdContent(pw);
pw.println("<dl>");
pw.println("<dt>Path</dt>");
pw.println("<dd>" + requestPathInfo.getResourcePath() + "<br/>" + CONSOLE_PATH_WARNING + "</dd>");
pw.println("<dt>Selectors</dt>");
pw.print("<dd>");
if (requestPathInfo.getSelectors().length == 0) {
pw.print("<none>");
} else {
pw.print("[");
pw.print(StringUtils.join(requestPathInfo.getSelectors(), ", "));
pw.print("]");
}
pw.println("</dd>");
pw.println("<dt>Extension</dt>");
pw.println("<dd>" + requestPathInfo.getExtension() + "</dd>");
pw.println("</dl>");
pw.println("</dd>");
pw.println("<dt>Suffix</dt>");
pw.println("<dd>" + requestPathInfo.getSuffix() + "</dd>");
pw.println("</dl>");
closeTd(pw);
closeTr(pw);
}
if (StringUtils.isNotBlank(requestPathInfo.getResourcePath())) {
final Collection<Resource> servlets;
Resource resource = resourceResolver.resolve(requestPathInfo.getResourcePath());
if (resource.adaptTo(Servlet.class) != null) {
servlets = Collections.singleton(resource);
} else {
final ResourceCollector locationUtil = ResourceCollector.create(
resource,
requestPathInfo.getExtension(),
executionPaths,
defaultExtensions,
method,
requestPathInfo.getSelectors());
servlets = locationUtil.getServlets(resourceResolver);
}
tr(pw);
tdLabel(pw, " ");
tdContent(pw);
if (servlets == null || servlets.isEmpty()) {
pw.println("Could not find a suitable servlet for this request!");
} else {
pw.println("Candidate servlets and scripts in order of preference for method " + method + ":<br/>");
pw.println("<ol class='servlets'>");
Iterator<Resource> iterator = servlets.iterator();
outputServlets(pw, iterator);
pw.println("</ol>");
}
pw.println("</td>");
closeTr(pw);
}
pw.println("</table>");
pw.print("</form>");
} catch (LoginException e) {
throw new ServletException(e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
private void tdContent(final PrintWriter pw) {
pw.print("<td class='content' colspan='2'>");
}
private void closeTd(final PrintWriter pw) {
pw.print("</td>");
}
@SuppressWarnings("unused")
private URL getResource(final String path) {
if (path.startsWith("/servletresolver/res/ui")) {
return this.getClass().getResource(path.substring(16));
} else {
return null;
}
}
private void closeTr(final PrintWriter pw) {
pw.println("</tr>");
}
private void tdLabel(final PrintWriter pw, final String label) {
pw.println("<td class='content'>" + label + "</td>");
}
private void tr(final PrintWriter pw) {
pw.println("<tr class='content'>");
}
private void outputServlets(final PrintWriter pw, final Iterator<Resource> iterator) {
while (iterator.hasNext()) {
Resource candidateResource = iterator.next();
Servlet candidate = candidateResource.adaptTo(Servlet.class);
if (candidate != null) {
boolean isOptingServlet = false;
if (candidate instanceof SlingScript) {
pw.println("<li>" + candidateResource.getPath() + "</li>");
} else {
if (candidate instanceof OptingServlet) {
isOptingServlet = true;
}
pw.println("<li>" + candidate.getClass().getName() + (isOptingServlet ? " (OptingServlet)" : "") + "</li>");
}
}
}
}
private void titleHtml(final PrintWriter pw, final String title, final String description) {
tr(pw);
pw.println("<th colspan='3' class='content container'>" + title +
"</th>");
closeTr(pw);
if (description != null) {
tr(pw);
pw.println("<td colspan='3' class='content'>" + description +
"</th>");
closeTr(pw);
}
}
}
}
| bundles/servlets/resolver/src/main/java/org/apache/sling/servlets/resolver/internal/SlingServletResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.servlets.resolver.internal;
import static org.apache.sling.api.SlingConstants.ERROR_MESSAGE;
import static org.apache.sling.api.SlingConstants.ERROR_SERVLET_NAME;
import static org.apache.sling.api.SlingConstants.ERROR_STATUS;
import static org.apache.sling.api.SlingConstants.SLING_CURRENT_SERVLET_NAME;
import static org.apache.sling.servlets.resolver.internal.ServletResolverConstants.SLING_SERLVET_NAME;
import static org.osgi.framework.Constants.SERVICE_ID;
import static org.osgi.framework.Constants.SERVICE_PID;
import static org.osgi.service.component.ComponentConstants.COMPONENT_NAME;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.SlingException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.request.RequestProgressTracker;
import org.apache.sling.api.request.RequestUtil;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceProvider;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.SyntheticResource;
import org.apache.sling.api.scripting.SlingScript;
import org.apache.sling.api.scripting.SlingScriptResolver;
import org.apache.sling.api.servlets.OptingServlet;
import org.apache.sling.api.servlets.ServletResolver;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.engine.servlets.ErrorHandler;
import org.apache.sling.servlets.resolver.internal.defaults.DefaultErrorHandlerServlet;
import org.apache.sling.servlets.resolver.internal.defaults.DefaultServlet;
import org.apache.sling.servlets.resolver.internal.helper.AbstractResourceCollector;
import org.apache.sling.servlets.resolver.internal.helper.NamedScriptResourceCollector;
import org.apache.sling.servlets.resolver.internal.helper.ResourceCollector;
import org.apache.sling.servlets.resolver.internal.helper.SlingServletConfig;
import org.apache.sling.servlets.resolver.internal.resource.ServletResourceProvider;
import org.apache.sling.servlets.resolver.internal.resource.ServletResourceProviderFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>SlingServletResolver</code> has two functions: It resolves scripts
* by implementing the {@link SlingScriptResolver} interface and it resolves a
* servlet for a request by implementing the {@link ServletResolver} interface.
*
* The resolver uses an own session to find the scripts.
*
*/
@Component(name="org.apache.sling.servlets.resolver.SlingServletResolver", metatype=true,
label="%servletresolver.name", description="%servletresolver.description")
@Service(value={ServletResolver.class, SlingScriptResolver.class, ErrorHandler.class})
@Properties({
@Property(name="service.description", value="Sling Servlet Resolver and Error Handler"),
@Property(name="event.topics", propertyPrivate=true,
value={"org/apache/sling/api/resource/Resource/*",
"org/apache/sling/api/resource/ResourceProvider/*",
"javax/script/ScriptEngineFactory/*",
"org/apache/sling/api/adapter/AdapterFactory/*",
"org/apache/sling/scripting/core/BindingsValuesProvider/*"})
})
@Reference(name="Servlet", referenceInterface=javax.servlet.Servlet.class,
cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC)
public class SlingServletResolver
implements ServletResolver,
SlingScriptResolver,
ErrorHandler,
EventHandler {
/**
* The default servlet root is the first search path (which is usally /apps)
*/
public static final String DEFAULT_SERVLET_ROOT = "0";
/** The default cache size for the script resolution. */
public static final int DEFAULT_CACHE_SIZE = 200;
/** Servlet resolver logger */
public static final Logger LOGGER = LoggerFactory.getLogger(SlingServletResolver.class);
@Property(value=DEFAULT_SERVLET_ROOT)
public static final String PROP_SERVLET_ROOT = "servletresolver.servletRoot";
@Property
public static final String PROP_SCRIPT_USER = "servletresolver.scriptUser";
@Property(intValue=DEFAULT_CACHE_SIZE)
public static final String PROP_CACHE_SIZE = "servletresolver.cacheSize";
private static final String REF_SERVLET = "Servlet";
@Property(value="/", unbounded=PropertyUnbounded.ARRAY)
public static final String PROP_PATHS = "servletresolver.paths";
private static final String[] DEFAULT_PATHS = new String[] {"/"};
@Property(value="html", unbounded=PropertyUnbounded.ARRAY)
public static final String PROP_DEFAULT_EXTENSIONS = "servletresolver.defaultExtensions";
private static final String[] DEFAULT_DEFAULT_EXTENSIONS = new String[] {"html"};
@Reference
private ServletContext servletContext;
@Reference
private ResourceResolverFactory resourceResolverFactory;
private ResourceResolver scriptResolver;
private final Map<ServiceReference, ServletReg> servletsByReference = new HashMap<ServiceReference, ServletReg>();
private final List<ServiceReference> pendingServlets = new ArrayList<ServiceReference>();
/** The component context. */
private ComponentContext context;
private ServletResourceProviderFactory servletResourceProviderFactory;
// the default servlet if no other servlet applies for a request. This
// field is set on demand by getDefaultServlet()
private Servlet defaultServlet;
// the default error handler servlet if no other error servlet applies for
// a request. This field is set on demand by getDefaultErrorServlet()
private Servlet fallbackErrorServlet;
/** The script resolution cache. */
private Map<AbstractResourceCollector, Servlet> cache;
/** The cache size. */
private int cacheSize;
/** Flag to log warning if cache size exceed only once. */
private volatile boolean logCacheSizeWarning;
/** Registration as event handler. */
private ServiceRegistration eventHandlerReg;
/**
* The allowed execution paths.
*/
private String[] executionPaths;
/**
* The default extensions
*/
private String[] defaultExtensions;
private ServletResolverWebConsolePlugin plugin;
// ---------- ServletResolver interface -----------------------------------
/**
* @see org.apache.sling.api.servlets.ServletResolver#resolveServlet(org.apache.sling.api.SlingHttpServletRequest)
*/
public Servlet resolveServlet(final SlingHttpServletRequest request) {
final Resource resource = request.getResource();
// start tracking servlet resolution
final RequestProgressTracker tracker = request.getRequestProgressTracker();
final String timerName = "resolveServlet(" + resource + ")";
tracker.startTimer(timerName);
final String type = resource.getResourceType();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("resolveServlet called for resource {}", resource);
}
Servlet servlet = null;
if ( type != null && type.length() > 0 ) {
servlet = resolveServlet(request, type, scriptResolver);
}
// last resort, use the core bundle default servlet
if (servlet == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No specific servlet found, trying default");
}
servlet = getDefaultServlet();
}
// track servlet resolution termination
if (servlet == null) {
tracker.logTimer(timerName, "Servlet resolution failed. See log for details");
} else {
tracker.logTimer(timerName, "Using servlet {0}", RequestUtil.getServletName(servlet));
}
// log the servlet found
if (LOGGER.isDebugEnabled()) {
if (servlet != null) {
LOGGER.debug("Servlet {} found for resource={}", RequestUtil.getServletName(servlet), resource);
} else {
LOGGER.debug("No servlet found for resource={}", resource);
}
}
return servlet;
}
/**
* @see org.apache.sling.api.servlets.ServletResolver#resolveServlet(org.apache.sling.api.resource.Resource, java.lang.String)
*/
public Servlet resolveServlet(final Resource resource, final String scriptName) {
if ( resource == null ) {
throw new IllegalArgumentException("Resource must not be null");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("resolveServlet called for resource {} with script name {}", resource, scriptName);
}
final Servlet servlet = resolveServlet(scriptResolver, resource, scriptName);
// log the servlet found
if (LOGGER.isDebugEnabled()) {
if (servlet != null) {
LOGGER.debug("Servlet {} found for resource {} and script name {}", new Object[] {RequestUtil.getServletName(servlet), resource, scriptName});
} else {
LOGGER.debug("No servlet found for resource {} and script name {}", resource, scriptName);
}
}
return servlet;
}
/**
* @see org.apache.sling.api.servlets.ServletResolver#resolveServlet(org.apache.sling.api.resource.ResourceResolver, java.lang.String)
*/
public Servlet resolveServlet(final ResourceResolver resolver, final String scriptName) {
if ( resolver == null ) {
throw new IllegalArgumentException("Resource resolver must not be null");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("resolveServlet called for for script name {}", scriptName);
}
final Servlet servlet = resolveServlet(scriptResolver, null, scriptName);
// log the servlet found
if (LOGGER.isDebugEnabled()) {
if (servlet != null) {
LOGGER.debug("Servlet {} found for script name {}", RequestUtil.getServletName(servlet), scriptName);
} else {
LOGGER.debug("No servlet found for script name {}", scriptName);
}
}
return servlet;
}
/** Internal method to resolve a servlet. */
private Servlet resolveServlet(final ResourceResolver resolver,
final Resource resource,
final String scriptName) {
Servlet servlet = null;
// first check whether the type of a resource is the absolute
// path of a servlet (or script)
if (scriptName.charAt(0) == '/') {
final String scriptPath = ResourceUtil.normalize(scriptName);
if ( this.isPathAllowed(scriptPath) ) {
final Resource res = resolver.getResource(scriptPath);
if (res != null) {
servlet = res.adaptTo(Servlet.class);
}
if (servlet != null && LOGGER.isDebugEnabled()) {
LOGGER.debug("Servlet {} found using absolute resource type {}", RequestUtil.getServletName(servlet),
scriptName);
}
}
}
if ( servlet == null ) {
// the resource type is not absolute, so lets go for the deep search
final NamedScriptResourceCollector locationUtil = NamedScriptResourceCollector.create(scriptName, resource, this.executionPaths);
servlet = getServlet(locationUtil, null, resolver);
if (LOGGER.isDebugEnabled() && servlet != null) {
LOGGER.debug("resolveServlet returns servlet {}", RequestUtil.getServletName(servlet));
}
}
return servlet;
}
// ---------- ScriptResolver interface ------------------------------------
/**
* @see org.apache.sling.api.scripting.SlingScriptResolver#findScript(org.apache.sling.api.resource.ResourceResolver, java.lang.String)
*/
public SlingScript findScript(final ResourceResolver resourceResolver, final String name)
throws SlingException {
// is the path absolute
SlingScript script = null;
if (name.startsWith("/")) {
final String path = ResourceUtil.normalize(name);
if ( this.isPathAllowed(path) ) {
final Resource resource = resourceResolver.getResource(path);
if (resource != null) {
script = resource.adaptTo(SlingScript.class);
}
}
} else {
// relative script resolution against search path
final String[] path = resourceResolver.getSearchPath();
for (int i = 0; script == null && i < path.length; i++) {
final String scriptPath = ResourceUtil.normalize(path[i] + name);
if ( this.isPathAllowed(scriptPath) ) {
final Resource resource = resourceResolver.getResource(scriptPath);
if (resource != null) {
script = resource.adaptTo(SlingScript.class);
}
}
}
}
// some logging
if (script != null) {
LOGGER.debug("findScript: Using script {} for {}", script.getScriptResource().getPath(), name);
} else {
LOGGER.info("findScript: No script {} found in path", name);
}
// and finally return the script (null or not)
return script;
}
// ---------- ErrorHandler interface --------------------------------------
/**
* @see org.apache.sling.engine.servlets.ErrorHandler#handleError(int,
* String, SlingHttpServletRequest, SlingHttpServletResponse)
*/
public void handleError(int status, String message, SlingHttpServletRequest request,
SlingHttpServletResponse response) throws IOException {
// do not handle, if already handling ....
if (request.getAttribute(SlingConstants.ERROR_REQUEST_URI) != null) {
LOGGER.error("handleError: Recursive invocation. Not further handling status " + status + "(" + message + ")");
return;
}
// start tracker
RequestProgressTracker tracker = request.getRequestProgressTracker();
String timerName = "handleError:status=" + status;
tracker.startTimer(timerName);
try {
// find the error handler component
Resource resource = getErrorResource(request);
// find a servlet for the status as the method name
ResourceCollector locationUtil = new ResourceCollector(String.valueOf(status),
ServletResolverConstants.ERROR_HANDLER_PATH, resource,
this.executionPaths);
Servlet servlet = getServlet(locationUtil, request, scriptResolver);
// fall back to default servlet if none
if (servlet == null) {
servlet = getDefaultErrorServlet(request, scriptResolver,
resource);
}
// set the message properties
request.setAttribute(ERROR_STATUS, new Integer(status));
request.setAttribute(ERROR_MESSAGE, message);
// the servlet name for a sendError handling is still stored
// as the request attribute
Object servletName = request.getAttribute(SLING_CURRENT_SERVLET_NAME);
if (servletName instanceof String) {
request.setAttribute(ERROR_SERVLET_NAME, servletName);
}
// log a track entry after resolution before calling the handler
tracker.logTimer(timerName, "Using handler {0}", RequestUtil.getServletName(servlet));
handleError(servlet, request, response);
} finally {
tracker.logTimer(timerName, "Error handler finished");
}
}
/**
* @see org.apache.sling.engine.servlets.ErrorHandler#handleError(java.lang.Throwable, org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
*/
public void handleError(Throwable throwable, SlingHttpServletRequest request, SlingHttpServletResponse response)
throws IOException {
// do not handle, if already handling ....
if (request.getAttribute(SlingConstants.ERROR_REQUEST_URI) != null) {
LOGGER.error("handleError: Recursive invocation. Not further handling Throwable:", throwable);
return;
}
// start tracker
RequestProgressTracker tracker = request.getRequestProgressTracker();
String timerName = "handleError:throwable=" + throwable.getClass().getName();
tracker.startTimer(timerName);
try {
// find the error handler component
Servlet servlet = null;
Resource resource = getErrorResource(request);
Class<?> tClass = throwable.getClass();
while (servlet == null && tClass != Object.class) {
// find a servlet for the simple class name as the method name
ResourceCollector locationUtil = new ResourceCollector(tClass.getSimpleName(),
ServletResolverConstants.ERROR_HANDLER_PATH, resource,
this.executionPaths);
servlet = getServlet(locationUtil, request, scriptResolver);
// go to the base class
tClass = tClass.getSuperclass();
}
if (servlet == null) {
servlet = getDefaultErrorServlet(request, scriptResolver,
resource);
}
// set the message properties
request.setAttribute(SlingConstants.ERROR_EXCEPTION, throwable);
request.setAttribute(SlingConstants.ERROR_EXCEPTION_TYPE, throwable.getClass());
request.setAttribute(SlingConstants.ERROR_MESSAGE, throwable.getMessage());
// log a track entry after resolution before calling the handler
tracker.logTimer(timerName, "Using handler {0}", RequestUtil.getServletName(servlet));
handleError(servlet, request, response);
} finally {
tracker.logTimer(timerName, "Error handler finished");
}
}
// ---------- internal helper ---------------------------------------------
/**
* Returns the resource of the given request to be used as the basis for
* error handling. If the resource has not yet been set in the request
* because the error occurred before the resource could be set (e.g. during
* resource resolution) a synthetic resource is returned whose type is
* {@link ServletResolverConstants#ERROR_HANDLER_PATH}.
*
* @param request The request whose resource is to be returned.
*/
private Resource getErrorResource(SlingHttpServletRequest request) {
Resource res = request.getResource();
if (res == null) {
res = new SyntheticResource(request.getResourceResolver(), request.getPathInfo(),
ServletResolverConstants.ERROR_HANDLER_PATH);
}
return res;
}
/**
* Resolve an appropriate servlet for a given request and resource type
* using the provided ResourceResolver
*/
private Servlet resolveServlet(final SlingHttpServletRequest request,
final String type,
final ResourceResolver resolver) {
Servlet servlet = null;
// first check whether the type of a resource is the absolute
// path of a servlet (or script)
if (type.charAt(0) == '/') {
String scriptPath = ResourceUtil.normalize(type);
if ( this.isPathAllowed(scriptPath) ) {
final Resource res = resolver.getResource(scriptPath);
if (res != null) {
servlet = res.adaptTo(Servlet.class);
}
if (servlet != null && LOGGER.isDebugEnabled()) {
LOGGER.debug("Servlet {} found using absolute resource type {}", RequestUtil.getServletName(servlet),
type);
}
} else {
request.getRequestProgressTracker().log(
"Will not look for a servlet at {0} as it is not in the list of allowed paths",
type
);
}
}
if ( servlet == null ) {
// the resource type is not absolute, so lets go for the deep search
final ResourceCollector locationUtil = ResourceCollector.create(request, this.executionPaths, this.defaultExtensions);
servlet = getServlet(locationUtil, request, resolver);
if (servlet != null && LOGGER.isDebugEnabled()) {
LOGGER.debug("getServlet returns servlet {}", RequestUtil.getServletName(servlet));
}
}
return servlet;
}
/**
* Returns a servlet suitable for handling a request. The
* <code>locationUtil</code> is used find any servlets or scripts usable for
* the request. Each servlet returned is in turn asked whether it is
* actually willing to handle the request in case the servlet is an
* <code>OptingServlet</code>. The first servlet willing to handle the
* request is used.
*
* @param locationUtil The helper used to find appropriate servlets ordered
* by matching priority.
* @param request The request used to give to any <code>OptingServlet</code>
* for them to decide on whether they are willing to handle the
* request
* @param resource The <code>Resource</code> for which to find a script.
* This need not be the same as
* <code>request.getResource()</code> in case of error handling
* where the resource may not have been assigned to the request
* yet.
* @return a servlet for handling the request or <code>null</code> if no
* such servlet willing to handle the request could be found.
*/
private Servlet getServlet(final AbstractResourceCollector locationUtil,
final SlingHttpServletRequest request,
final ResourceResolver scriptResolver) {
final Servlet scriptServlet = (this.cache != null ? this.cache.get(locationUtil) : null);
if (scriptServlet != null) {
if ( LOGGER.isDebugEnabled() ) {
LOGGER.debug("Using cached servlet {}", RequestUtil.getServletName(scriptServlet));
}
return scriptServlet;
}
final Collection<Resource> candidates = locationUtil.getServlets(scriptResolver);
if (LOGGER.isDebugEnabled()) {
if (candidates.isEmpty()) {
LOGGER.debug("No servlet candidates found");
} else {
LOGGER.debug("Ordered list of servlet candidates follows");
for (Resource candidateResource : candidates) {
LOGGER.debug("Servlet candidate: {}", candidateResource.getPath());
}
}
}
boolean hasOptingServlet = false;
for (Resource candidateResource : candidates) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Checking if candidate resource {} adapts to servlet and accepts request", candidateResource
.getPath());
}
Servlet candidate = candidateResource.adaptTo(Servlet.class);
if (candidate != null) {
final boolean isOptingServlet = candidate instanceof OptingServlet;
boolean servletAcceptsRequest = !isOptingServlet || (request != null && ((OptingServlet) candidate).accepts(request));
if (servletAcceptsRequest) {
if (!hasOptingServlet && !isOptingServlet && this.cache != null) {
if ( this.cache.size() < this.cacheSize ) {
this.cache.put(locationUtil, candidate);
} else if ( this.logCacheSizeWarning ) {
this.logCacheSizeWarning = false;
LOGGER.warn("Script cache has reached its limit of {}. You might want to increase the cache size for the servlet resolver.",
this.cacheSize);
}
}
LOGGER.debug("Using servlet provided by candidate resource {}", candidateResource.getPath());
return candidate;
}
if (isOptingServlet) {
hasOptingServlet = true;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Candidate {} does not accept request, ignored", candidateResource.getPath());
}
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Candidate {} does not adapt to a servlet, ignored", candidateResource.getPath());
}
}
}
// exhausted all candidates, we don't have a servlet
return null;
}
/**
* Returns the internal default servlet which is called in case no other
* servlet applies for handling a request. This servlet should really only
* be used if the default servlets have not been registered (yet).
*/
private Servlet getDefaultServlet() {
if (defaultServlet == null) {
try {
Servlet servlet = new DefaultServlet();
servlet.init(new SlingServletConfig(servletContext, null, "Sling Core Default Servlet"));
defaultServlet = servlet;
} catch (ServletException se) {
LOGGER.error("Failed to initialize default servlet", se);
}
}
return defaultServlet;
}
/**
* Returns the default error handler servlet, which is called in case there
* is no other - better matching - servlet registered to handle an error or
* exception.
* <p>
* The default error handler servlet is registered for the resource type
* "sling/servlet/errorhandler" and method "default". This may be
* overwritten by applications globally or according to the resource type
* hierarchy of the resource.
* <p>
* If no default error handler servlet can be found an adhoc error handler
* is used as a final fallback.
*/
private Servlet getDefaultErrorServlet(
final SlingHttpServletRequest request,
final ResourceResolver scriptResolver,
final Resource resource) {
// find a default error handler according to the resource type
// tree of the given resource
final ResourceCollector locationUtil = new ResourceCollector(
ServletResolverConstants.DEFAULT_ERROR_HANDLER_NAME,
ServletResolverConstants.ERROR_HANDLER_PATH, resource,
this.executionPaths);
final Servlet servlet = getServlet(locationUtil, request,
scriptResolver);
if (servlet != null) {
return servlet;
}
// if no registered default error handler could be found use
// the DefaultErrorHandlerServlet as an ad-hoc fallback
if (fallbackErrorServlet == null) {
// fall back to an adhoc instance of the DefaultErrorHandlerServlet
// if the actual service is not registered (yet ?)
try {
final Servlet defaultServlet = new DefaultErrorHandlerServlet();
defaultServlet.init(new SlingServletConfig(servletContext,
null, "Sling (Ad Hoc) Default Error Handler Servlet"));
fallbackErrorServlet = defaultServlet;
} catch (ServletException se) {
LOGGER.error("Failed to initialize error servlet", se);
}
}
return fallbackErrorServlet;
}
private void handleError(final Servlet errorHandler, final HttpServletRequest request, final HttpServletResponse response)
throws IOException {
request.setAttribute(SlingConstants.ERROR_REQUEST_URI, request.getRequestURI());
// if there is no explicitly known error causing servlet, use
// the name of the error handler servlet
if (request.getAttribute(SlingConstants.ERROR_SERVLET_NAME) == null) {
request.setAttribute(SlingConstants.ERROR_SERVLET_NAME, errorHandler.getServletConfig().getServletName());
}
try {
errorHandler.service(request, response);
// commit the response
response.flushBuffer();
// close the response (SLING-2724)
response.getWriter().close();
} catch (final IOException ioe) {
// forward the IOException
throw ioe;
} catch (final Throwable t) {
LOGGER.error("Calling the error handler resulted in an error", t);
LOGGER.error("Original error " + request.getAttribute(SlingConstants.ERROR_EXCEPTION_TYPE),
(Throwable) request.getAttribute(SlingConstants.ERROR_EXCEPTION));
}
}
private Map<String, Object> createAuthenticationInfo(final Dictionary<String, Object> props) {
final Map<String, Object> authInfo = new HashMap<String, Object>();
// if a script user is configured we use this user to read the scripts
final String scriptUser = OsgiUtil.toString(props.get(PROP_SCRIPT_USER), null);
if (scriptUser != null && scriptUser.length() > 0) {
authInfo.put(ResourceResolverFactory.USER_IMPERSONATION, scriptUser);
}
return authInfo;
}
// ---------- SCR Integration ----------------------------------------------
/**
* Activate this component.
*/
@SuppressWarnings("unchecked")
protected void activate(final ComponentContext context) throws LoginException {
// from configuration if available
final Dictionary<?, ?> properties = context.getProperties();
Object servletRoot = properties.get(PROP_SERVLET_ROOT);
if (servletRoot == null) {
servletRoot = DEFAULT_SERVLET_ROOT;
}
final Collection<ServiceReference> refs;
synchronized (this.pendingServlets) {
refs = new ArrayList<ServiceReference>(pendingServlets);
pendingServlets.clear();
this.scriptResolver =
resourceResolverFactory.getAdministrativeResourceResolver(this.createAuthenticationInfo(context.getProperties()));
servletResourceProviderFactory = new ServletResourceProviderFactory(servletRoot,
this.scriptResolver.getSearchPath());
// register servlets immediately from now on
this.context = context;
}
createAllServlets(refs);
// execution paths
this.executionPaths = OsgiUtil.toStringArray(properties.get(PROP_PATHS), DEFAULT_PATHS);
if ( this.executionPaths != null ) {
// if we find a string combination that basically allows all paths,
// we simply set the array to null
if ( this.executionPaths.length == 0 ) {
this.executionPaths = null;
} else {
boolean hasRoot = false;
for(int i = 0 ; i < this.executionPaths.length; i++) {
final String path = this.executionPaths[i];
if ( path == null || path.length() == 0 || path.equals("/") ) {
hasRoot = true;
break;
}
}
if ( hasRoot ) {
this.executionPaths = null;
}
}
}
this.defaultExtensions = OsgiUtil.toStringArray(properties.get(PROP_DEFAULT_EXTENSIONS), DEFAULT_DEFAULT_EXTENSIONS);
// create cache - if a cache size is configured
this.cacheSize = OsgiUtil.toInteger(properties.get(PROP_CACHE_SIZE), DEFAULT_CACHE_SIZE);
if (this.cacheSize > 5) {
this.cache = new ConcurrentHashMap<AbstractResourceCollector, Servlet>(cacheSize);
this.logCacheSizeWarning = true;
} else {
this.cacheSize = 0;
}
// and finally register as event listener
this.eventHandlerReg = context.getBundleContext().registerService(EventHandler.class.getName(), this,
properties);
this.plugin = new ServletResolverWebConsolePlugin(context.getBundleContext());
}
/**
* Deactivate this component.
*/
protected void deactivate(final ComponentContext context) {
// stop registering of servlets immediately
this.context = null;
if (this.plugin != null) {
this.plugin.dispose();
}
// unregister event handler
if (this.eventHandlerReg != null) {
this.eventHandlerReg.unregister();
this.eventHandlerReg = null;
}
// Copy the list of servlets first, to minimize the need for
// synchronization
final Collection<ServiceReference> refs;
synchronized (this.servletsByReference) {
refs = new ArrayList<ServiceReference>(servletsByReference.keySet());
}
// destroy all servlets
destroyAllServlets(refs);
// sanity check: clear array (it should be empty now anyway)
synchronized ( this.servletsByReference ) {
this.servletsByReference.clear();
}
// destroy the fallback error handler servlet
if (fallbackErrorServlet != null) {
try {
fallbackErrorServlet.destroy();
} catch (Throwable t) {
// ignore
} finally {
fallbackErrorServlet = null;
}
}
if (this.scriptResolver != null) {
this.scriptResolver.close();
this.scriptResolver = null;
}
this.cache = null;
this.servletResourceProviderFactory = null;
}
protected void bindServlet(ServiceReference reference) {
boolean directCreate = true;
if (context == null) {
synchronized ( pendingServlets ) {
if (context == null) {
pendingServlets.add(reference);
directCreate = false;
}
}
}
if ( directCreate ) {
createServlet(reference);
}
}
protected void unbindServlet(ServiceReference reference) {
synchronized ( pendingServlets ) {
pendingServlets.remove(reference);
}
destroyServlet(reference);
}
// ---------- Servlet Management -------------------------------------------
private void createAllServlets(final Collection<ServiceReference> pendingServlets) {
for (final ServiceReference serviceReference : pendingServlets) {
createServlet(serviceReference);
}
}
private boolean createServlet(final ServiceReference reference) {
// check for a name, this is required
final String name = getName(reference);
if (name == null) {
LOGGER.error("bindServlet: Cannot register servlet {} without a servlet name", reference);
return false;
}
// check for Sling properties in the service registration
ServletResourceProvider provider = servletResourceProviderFactory.create(reference);
if (provider == null) {
// this is expected if the servlet is not destined for Sling
return false;
}
// only now try to access the servlet service, this may still fail
Servlet servlet = null;
try {
servlet = (Servlet) context.locateService(REF_SERVLET, reference);
} catch (Throwable t) {
LOGGER.warn("bindServlet: Failed getting the service for reference " + reference, t);
}
if (servlet == null) {
LOGGER.error("bindServlet: Servlet service not available from reference {}", reference);
return false;
}
// assign the servlet to the provider
provider.setServlet(servlet);
// initialize now
try {
servlet.init(new SlingServletConfig(servletContext, reference, name));
LOGGER.debug("bindServlet: Servlet {} added", name);
} catch (ServletException ce) {
LOGGER.error("bindServlet: Component " + name + " failed to initialize", ce);
return false;
} catch (Throwable t) {
LOGGER.error("bindServlet: Unexpected problem initializing component " + name, t);
return false;
}
final Dictionary<String, Object> params = new Hashtable<String, Object>();
params.put(ResourceProvider.ROOTS, provider.getServletPaths());
params.put(Constants.SERVICE_DESCRIPTION, "ServletResourceProvider for Servlets at "
+ Arrays.asList(provider.getServletPaths()));
final ServiceRegistration reg = context.getBundleContext()
.registerService(ResourceProvider.SERVICE_NAME, provider, params);
LOGGER.info("Registered {}", provider.toString());
synchronized (this.servletsByReference) {
servletsByReference.put(reference, new ServletReg(servlet, reg));
}
return true;
}
private void destroyAllServlets(Collection<ServiceReference> refs) {
for (ServiceReference serviceReference : refs) {
destroyServlet(serviceReference);
}
}
private void destroyServlet(ServiceReference reference) {
ServletReg registration;
synchronized (this.servletsByReference) {
registration = servletsByReference.remove(reference);
}
if (registration != null) {
registration.registration.unregister();
final String name = RequestUtil.getServletName(registration.servlet);
LOGGER.debug("unbindServlet: Servlet {} removed", name);
try {
registration.servlet.destroy();
} catch (Throwable t) {
LOGGER.error("unbindServlet: Unexpected problem destroying servlet " + name, t);
}
}
}
/**
* @see org.osgi.service.event.EventHandler#handleEvent(org.osgi.service.event.Event)
*/
public void handleEvent(Event event) {
if (this.cache != null) {
boolean flushCache = false;
// we may receive different events
final String topic = event.getTopic();
if (topic.startsWith("javax/script/ScriptEngineFactory/")) {
// script engine factory added or removed: we always flush
flushCache = true;
} else if (topic.startsWith("org/apache/sling/api/adapter/AdapterFactory/")) {
// adapter factory added or removed: we always flush
// as adapting might be transitive
flushCache = true;
} else if (topic.startsWith("org/apache/sling/scripting/core/BindingsValuesProvider/")) {
// bindings values provide factory added or removed: we always flush
flushCache = true;
} else {
// this is a resource event
// if the path of the event is a sub path of a search path
// we flush the whole cache
String path = (String) event.getProperty(SlingConstants.PROPERTY_PATH);
if (path.contains(":")) {
path = path.substring(path.indexOf(":") + 1);
}
final String[] searchPaths = this.scriptResolver.getSearchPath();
int index = 0;
while (!flushCache && index < searchPaths.length) {
if (path.startsWith(searchPaths[index])) {
flushCache = true;
}
index++;
}
}
if (flushCache) {
this.cache.clear();
this.logCacheSizeWarning = true;
}
}
}
/** The list of property names checked by {@link #getName(ServiceReference)} */
private static final String[] NAME_PROPERTIES = { SLING_SERLVET_NAME,
COMPONENT_NAME, SERVICE_PID, SERVICE_ID };
/**
* Looks for a name value in the service reference properties. See the
* class comment at the top for the list of properties checked by this
* method.
*/
private static String getName(ServiceReference reference) {
String servletName = null;
for (int i = 0; i < NAME_PROPERTIES.length
&& (servletName == null || servletName.length() == 0); i++) {
Object prop = reference.getProperty(NAME_PROPERTIES[i]);
if (prop != null) {
servletName = String.valueOf(prop);
}
}
return servletName;
}
private boolean isPathAllowed(final String path) {
return AbstractResourceCollector.isPathAllowed(path, this.executionPaths);
}
private static final class ServletReg {
public final Servlet servlet;
public final ServiceRegistration registration;
public ServletReg(final Servlet s, final ServiceRegistration sr) {
this.servlet = s;
this.registration = sr;
}
}
@SuppressWarnings("serial")
class ServletResolverWebConsolePlugin extends HttpServlet {
private static final String PARAMETER_URL = "url";
private static final String PARAMETER_METHOD = "method";
private ServiceRegistration service;
public ServletResolverWebConsolePlugin(BundleContext context) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_DESCRIPTION,
"Sling Servlet Resolver Web Console Plugin");
props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
props.put(Constants.SERVICE_PID, getClass().getName());
props.put("felix.webconsole.label", "servletresolver");
props.put("felix.webconsole.title", "Sling Servlet Resolver");
props.put("felix.webconsole.css", "/servletresolver/res/ui/styles.css");
props.put("felix.webconsole.category", "Sling");
service = context.registerService(
new String[] { "javax.servlet.Servlet" }, this, props);
}
public void dispose() {
if (service != null) {
service.unregister();
service = null;
}
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String url = request.getParameter(PARAMETER_URL);
final RequestPathInfo requestPathInfo = new DecomposedURL(url).getRequestPathInfo();
String method = request.getParameter(PARAMETER_METHOD);
if (StringUtils.isBlank(method)) {
method = "GET";
}
final String CONSOLE_PATH_WARNING =
"<em>"
+ "Note that in a real Sling request, the path might vary depending on the existence of"
+ " resources that partially match it."
+ "<br/>This utility does not take this into account and uses the first dot to split"
+ " between path and selectors/extension."
+ "<br/>As a workaround, you can replace dots with underline characters, for example, when testing such an URL."
+ "</em>";
ResourceResolver resourceResolver = null;
try {
resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
final PrintWriter pw = response.getWriter();
pw.print("<form method='get'>");
pw.println("<table class='content' cellpadding='0' cellspacing='0' width='100%'>");
titleHtml(
pw,
"Servlet Resolver Test",
"To check which servlet is responsible for rendering a response, enter a request path into " +
"the field and click 'Resolve' to resolve it.");
tr(pw);
tdLabel(pw, "URL");
tdContent(pw);
pw.println("<input type='text' name='" + PARAMETER_URL + "' value='" +
(url != null ? url : "") + "' class='input' size='50'>");
closeTd(pw);
closeTr(pw);
closeTr(pw);
tr(pw);
tdLabel(pw, "Method");
tdContent(pw);
pw.println("<select name='" + PARAMETER_METHOD + "'>");
pw.println("<option value='GET'>GET</option>");
pw.println("<option value='POST'>POST</option>");
pw.println("</select>");
pw.println(" <input type='submit'" +
"' value='Resolve' class='submit'>");
closeTd(pw);
closeTr(pw);
if (StringUtils.isNotBlank(url)) {
tr(pw);
tdLabel(pw, "Decomposed URL");
tdContent(pw);
pw.println("<dl>");
pw.println("<dt>Path</dt>");
pw.println("<dd>" + requestPathInfo.getResourcePath() + "<br/>" + CONSOLE_PATH_WARNING + "</dd>");
pw.println("<dt>Selectors</dt>");
pw.print("<dd>");
if (requestPathInfo.getSelectors().length == 0) {
pw.print("<none>");
} else {
pw.print("[");
pw.print(StringUtils.join(requestPathInfo.getSelectors(), ", "));
pw.print("]");
}
pw.println("</dd>");
pw.println("<dt>Extension</dt>");
pw.println("<dd>" + requestPathInfo.getExtension() + "</dd>");
pw.println("</dl>");
pw.println("</dd>");
pw.println("<dt>Suffix</dt>");
pw.println("<dd>" + requestPathInfo.getSuffix() + "</dd>");
pw.println("</dl>");
closeTd(pw);
closeTr(pw);
}
if (StringUtils.isNotBlank(requestPathInfo.getResourcePath())) {
final Collection<Resource> servlets;
Resource resource = resourceResolver.resolve(requestPathInfo.getResourcePath());
if (resource.adaptTo(Servlet.class) != null) {
servlets = Collections.singleton(resource);
} else {
final ResourceCollector locationUtil = ResourceCollector.create(
resource,
requestPathInfo.getExtension(),
executionPaths,
defaultExtensions,
method,
requestPathInfo.getSelectors());
servlets = locationUtil.getServlets(resourceResolver);
}
tr(pw);
tdLabel(pw, " ");
tdContent(pw);
if (servlets == null || servlets.isEmpty()) {
pw.println("Could not find a suitable servlet for this request!");
} else {
pw.println("Candidate servlets and scripts in order of preference for method " + method + ":<br/>");
pw.println("<ol class='servlets'>");
Iterator<Resource> iterator = servlets.iterator();
outputServlets(pw, iterator);
pw.println("</ol>");
}
pw.println("</td>");
closeTr(pw);
}
pw.println("</table>");
pw.print("</form>");
} catch (LoginException e) {
throw new ServletException(e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
private void tdContent(final PrintWriter pw) {
pw.print("<td class='content' colspan='2'>");
}
private void closeTd(final PrintWriter pw) {
pw.print("</td>");
}
@SuppressWarnings("unused")
private URL getResource(final String path) {
if (path.startsWith("/servletresolver/res/ui")) {
return this.getClass().getResource(path.substring(16));
} else {
return null;
}
}
private void closeTr(final PrintWriter pw) {
pw.println("</tr>");
}
private void tdLabel(final PrintWriter pw, final String label) {
pw.println("<td class='content'>" + label + "</td>");
}
private void tr(final PrintWriter pw) {
pw.println("<tr class='content'>");
}
private void outputServlets(PrintWriter pw, Iterator<Resource> iterator) {
while (iterator.hasNext()) {
Resource candidateResource = iterator.next();
Servlet candidate = candidateResource.adaptTo(Servlet.class);
if (candidate != null) {
boolean isOptingServlet = false;
if (candidate instanceof SlingScript) {
pw.println("<li>" + candidateResource.getPath() + "</li>");
} else {
if (candidate instanceof OptingServlet) {
isOptingServlet = true;
}
pw.println("<li>" + candidate.getClass().getName() + (isOptingServlet ? " (OptingServlet)" : "") + "</li>");
}
}
}
}
private void titleHtml(PrintWriter pw, String title, String description) {
tr(pw);
pw.println("<th colspan='3' class='content container'>" + title +
"</th>");
closeTr(pw);
if (description != null) {
tr(pw);
pw.println("<td colspan='3' class='content'>" + description +
"</th>");
closeTr(pw);
}
}
}
}
| Clean up code: add final to parameters, rename some methods to *Internal and avoid passing around instance variables as parameters
git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1573483 13f79535-47bb-0310-9956-ffa450edef68
| bundles/servlets/resolver/src/main/java/org/apache/sling/servlets/resolver/internal/SlingServletResolver.java | Clean up code: add final to parameters, rename some methods to *Internal and avoid passing around instance variables as parameters |
|
Java | apache-2.0 | 7034150aa3c48fb9bb463b1d5e2cbdc85454a1ff | 0 | OpenHFT/Chronicle-Queue,OpenHFT/Chronicle-Queue | package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.io.AbstractReferenceCounted;
import net.openhft.chronicle.core.io.IOTools;
import net.openhft.chronicle.core.onoes.ExceptionKey;
import net.openhft.chronicle.core.onoes.LogLevel;
import net.openhft.chronicle.core.threads.ThreadDump;
import net.openhft.chronicle.core.time.SetTimeProvider;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.RollingChronicleQueue;
import net.openhft.chronicle.threads.NamedThreadFactory;
import net.openhft.chronicle.wire.DocumentContext;
import net.openhft.chronicle.wire.ValueIn;
import net.openhft.chronicle.wire.ValueOut;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static net.openhft.chronicle.core.io.Closeable.closeQuietly;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class RollCycleMultiThreadStressTest {
static {
Jvm.disableDebugHandler();
}
final long SLEEP_PER_WRITE_NANOS;
final int TEST_TIME;
final int ROLL_EVERY_MS;
final int DELAY_READER_RANDOM_MS;
final int DELAY_WRITER_RANDOM_MS;
final int WRITE_ONE_THEN_WAIT_MS;
final int CORES;
final Random random;
final int NUMBER_OF_INTS;
final boolean PRETOUCH;
final boolean READERS_READ_ONLY;
final boolean DUMP_QUEUE;
final boolean SHARED_WRITE_QUEUE;
final boolean DOUBLE_BUFFER;
private ThreadDump threadDump;
private Map<ExceptionKey, Integer> exceptionKeyIntegerMap;
final Logger LOG = LoggerFactory.getLogger(getClass());
final SetTimeProvider timeProvider = new SetTimeProvider();
private ChronicleQueue sharedWriterQueue;
public RollCycleMultiThreadStressTest() {
SLEEP_PER_WRITE_NANOS = Long.getLong("writeLatency", 30_000);
TEST_TIME = Integer.getInteger("testTime", 2);
ROLL_EVERY_MS = Integer.getInteger("rollEvery", 300);
DELAY_READER_RANDOM_MS = Integer.getInteger("delayReader", 1);
DELAY_WRITER_RANDOM_MS = Integer.getInteger("delayWriter", 1);
WRITE_ONE_THEN_WAIT_MS = Integer.getInteger("writeOneThenWait", 0);
CORES = Integer.getInteger("cores", Runtime.getRuntime().availableProcessors());
random = new Random(99);
NUMBER_OF_INTS = Integer.getInteger("numberInts", 18);//1060 / 4;
PRETOUCH = Jvm.getBoolean("pretouch");
READERS_READ_ONLY = Jvm.getBoolean("read_only");
DUMP_QUEUE = Jvm.getBoolean("dump_queue");
SHARED_WRITE_QUEUE = Jvm.getBoolean("sharedWriteQ");
DOUBLE_BUFFER = Jvm.getBoolean("double_buffer");
if (TEST_TIME > 2) {
AbstractReferenceCounted.disableReferenceTracing();
if (Jvm.isResourceTracing()) {
throw new IllegalStateException("This test will run out of memory - change your system properties");
}
}
}
static boolean areAllReadersComplete(final int expectedNumberOfMessages, final List<Reader> readers) {
boolean allReadersComplete = true;
int count = 0;
for (Reader reader : readers) {
++count;
if (reader.lastRead < expectedNumberOfMessages - 1) {
allReadersComplete = false;
// System.out.printf("Reader #%d last read: %d%n", count, reader.lastRead);
}
}
return allReadersComplete;
}
@Test
public void stress() throws InterruptedException, IOException {
assert warnIfAssertsAreOn();
File file = DirectoryUtils.tempDir("stress");
// System.out.printf("Queue dir: %s at %s%n", file.getAbsolutePath(), Instant.now());
final int numThreads = CORES;
final int numWriters = numThreads / 4 + 1;
final ExecutorService executorServicePretouch = Executors.newSingleThreadExecutor(
new NamedThreadFactory("pretouch"));
final ExecutorService executorServiceWrite = Executors.newFixedThreadPool(numWriters,
new NamedThreadFactory("writer"));
final ExecutorService executorServiceRead = Executors.newFixedThreadPool(numThreads - numWriters,
new NamedThreadFactory("reader"));
final AtomicInteger wrote = new AtomicInteger();
final int expectedNumberOfMessages = (int) (TEST_TIME * 1e9 / SLEEP_PER_WRITE_NANOS) * Math.max(1, numWriters / 2);
// System.out.printf("Running test with %d writers and %d readers, sleep %dns%n",
// numWriters, numThreads - numWriters, SLEEP_PER_WRITE_NANOS);
// System.out.printf("Writing %d messages with %dns interval%n", expectedNumberOfMessages,
// SLEEP_PER_WRITE_NANOS);
// System.out.printf("Should take ~%dms%n",
// TimeUnit.NANOSECONDS.toMillis(expectedNumberOfMessages * SLEEP_PER_WRITE_NANOS) / (numWriters / 2));
final List<Future<Throwable>> results = new ArrayList<>();
final List<Reader> readers = new ArrayList<>();
final List<Writer> writers = new ArrayList<>();
if (READERS_READ_ONLY)
try (ChronicleQueue roq = createQueue(file)) {
}
if (SHARED_WRITE_QUEUE)
sharedWriterQueue = createQueue(file);
PretoucherThread pretoucherThread = null;
if (PRETOUCH) {
pretoucherThread = new PretoucherThread(file);
executorServicePretouch.submit(pretoucherThread);
}
if (WRITE_ONE_THEN_WAIT_MS > 0) {
final Writer tempWriter = new Writer(file, wrote, expectedNumberOfMessages);
try (ChronicleQueue queue = writerQueue(file)) {
tempWriter.write(queue.acquireAppender());
}
}
for (int i = 0; i < numThreads - numWriters; i++) {
final Reader reader = new Reader(file, expectedNumberOfMessages);
readers.add(reader);
results.add(executorServiceRead.submit(reader));
}
if (WRITE_ONE_THEN_WAIT_MS > 0) {
LOG.warn("Wrote one now waiting for {}ms", WRITE_ONE_THEN_WAIT_MS);
Jvm.pause(WRITE_ONE_THEN_WAIT_MS);
}
for (int i = 0; i < numWriters; i++) {
final Writer writer = new Writer(file, wrote, expectedNumberOfMessages);
writers.add(writer);
results.add(executorServiceWrite.submit(writer));
}
final long maxWritingTime = TimeUnit.SECONDS.toMillis(TEST_TIME + 5) + queueBuilder(file).timeoutMS();
long startTime = System.currentTimeMillis();
final long giveUpWritingAt = startTime + maxWritingTime;
long nextRollTime = System.currentTimeMillis() + ROLL_EVERY_MS, nextCheckTime = System.currentTimeMillis() + 5_000;
int i = 0;
long now;
while ((now = System.currentTimeMillis()) < giveUpWritingAt) {
if (wrote.get() >= expectedNumberOfMessages)
break;
if (now > nextRollTime) {
timeProvider.advanceMillis(1000);
nextRollTime += ROLL_EVERY_MS;
}
if (now > nextCheckTime) {
String readersLastRead = readers.stream().map(reader -> Integer.toString(reader.lastRead)).collect(Collectors.joining(","));
// System.out.printf("Writer has written %d of %d messages after %dms. Readers at %s. Waiting...%n",
// wrote.get() + 1, expectedNumberOfMessages,
// i * 10, readersLastRead);
readers.stream().filter(r -> !r.isMakingProgress()).findAny().ifPresent(reader -> {
if (reader.exception != null) {
throw new AssertionError("Reader encountered exception, so stopped reading messages",
reader.exception);
}
throw new AssertionError("Reader is stuck");
});
if (pretoucherThread != null && pretoucherThread.exception != null)
throw new AssertionError("Preloader encountered exception", pretoucherThread.exception);
nextCheckTime = System.currentTimeMillis() + 10_000L;
}
i++;
Jvm.pause(5);
}
double timeToWriteSecs = (System.currentTimeMillis() - startTime) / 1000d;
final StringBuilder writerExceptions = new StringBuilder();
writers.stream().filter(w -> w.exception != null).forEach(w -> {
writerExceptions.append("Writer failed due to: ").append(w.exception.getMessage()).append("\n");
});
assertTrue("Wrote " + wrote.get() + " which is less than " + expectedNumberOfMessages + " within timeout. " + writerExceptions,
wrote.get() >= expectedNumberOfMessages);
readers.stream().filter(r -> r.exception != null).findAny().ifPresent(reader -> {
throw new AssertionError("Reader encountered exception, so stopped reading messages",
reader.exception);
});
/*
System.out.println(String.format("All messages written in %,.0fsecs at rate of %,.0f/sec %,.0f/sec per writer (actual writeLatency %,.0fns)",
timeToWriteSecs, expectedNumberOfMessages / timeToWriteSecs, (expectedNumberOfMessages / timeToWriteSecs) / numWriters,
1_000_000_000 / ((expectedNumberOfMessages / timeToWriteSecs) / numWriters)));
*/
final long giveUpReadingAt = System.currentTimeMillis() + 20_000L;
final long dumpThreadsAt = giveUpReadingAt - 5_000L;
try {
while (System.currentTimeMillis() < giveUpReadingAt) {
results.forEach(f -> {
try {
if (f.isDone()) {
final Throwable exception = f.get();
if (exception != null) {
throw Jvm.rethrow(exception);
}
}
} catch (InterruptedException e) {
// ignored
} catch (ExecutionException e) {
throw Jvm.rethrow(e);
}
});
boolean allReadersComplete = areAllReadersComplete(expectedNumberOfMessages, readers);
if (allReadersComplete) {
break;
}
// System.out.printf("Not all readers are complete. Waiting...%n");
Jvm.pause(2000);
}
assertTrue("Readers did not catch up",
areAllReadersComplete(expectedNumberOfMessages, readers));
} finally {
executorServiceRead.shutdown();
executorServiceWrite.shutdown();
executorServicePretouch.shutdown();
if (!executorServiceRead.awaitTermination(1, TimeUnit.SECONDS))
executorServiceRead.shutdownNow();
if (!executorServiceWrite.awaitTermination(1, TimeUnit.SECONDS))
executorServiceWrite.shutdownNow();
if (!executorServicePretouch.awaitTermination(1, TimeUnit.SECONDS))
executorServicePretouch.shutdownNow();
closeQuietly(sharedWriterQueue);
results.forEach(f -> {
try {
final Throwable exception = f.get(100, TimeUnit.MILLISECONDS);
if (exception != null) {
exception.printStackTrace();
}
} catch (InterruptedException | TimeoutException e) {
// ignored
} catch (ExecutionException e) {
throw Jvm.rethrow(e);
}
});
}
IOTools.deleteDirWithFiles("stress");
// System.out.println("Test complete");
}
private boolean warnIfAssertsAreOn() {
Jvm.warn().on(getClass(), "Reminder: asserts are on");
return true;
}
@NotNull
SingleChronicleQueueBuilder queueBuilder(File path) {
return SingleChronicleQueueBuilder.binary(path)
.testBlockSize()
.timeProvider(timeProvider)
.doubleBuffer(DOUBLE_BUFFER)
.rollCycle(RollCycles.TEST_SECONDLY);
}
@NotNull
private ChronicleQueue createQueue(File path) {
return queueBuilder(path).build();
}
@NotNull
private ChronicleQueue writerQueue(File path) {
return sharedWriterQueue != null ? sharedWriterQueue : createQueue(path);
}
@Before
public void multiCPU() {
Assume.assumeTrue(Runtime.getRuntime().availableProcessors() > 1);
}
@Before
public void before() {
threadDump = new ThreadDump();
exceptionKeyIntegerMap = Jvm.recordExceptions();
}
@After
public void after() {
threadDump.assertNoNewThreads();
// warnings are often expected
exceptionKeyIntegerMap.entrySet().removeIf(entry -> entry.getKey().level.equals(LogLevel.WARN));
if (Jvm.hasException(exceptionKeyIntegerMap)) {
Jvm.dumpException(exceptionKeyIntegerMap);
fail();
}
Jvm.resetExceptionHandlers();
AbstractReferenceCounted.assertReferencesReleased();
}
final class Reader implements Callable<Throwable> {
final File path;
final int expectedNumberOfMessages;
volatile int lastRead = -1;
volatile Throwable exception;
int readSequenceAtLastProgressCheck = -1;
Reader(final File path, final int expectedNumberOfMessages) {
this.path = path;
this.expectedNumberOfMessages = expectedNumberOfMessages;
}
boolean isMakingProgress() {
if (readSequenceAtLastProgressCheck == -1) {
return true;
}
final boolean makingProgress = lastRead > readSequenceAtLastProgressCheck;
readSequenceAtLastProgressCheck = lastRead;
return makingProgress;
}
@Override
public Throwable call() {
SingleChronicleQueueBuilder builder = queueBuilder(path);
if (READERS_READ_ONLY)
builder.readOnly(true);
long last = System.currentTimeMillis();
try (RollingChronicleQueue queue = builder.build();
ExcerptTailer tailer = queue.createTailer()) {
int lastTailerCycle = -1;
int lastQueueCycle = -1;
Jvm.pause(random.nextInt(DELAY_READER_RANDOM_MS));
while (lastRead != expectedNumberOfMessages - 1) {
try (DocumentContext dc = tailer.readingDocument()) {
if (!dc.isPresent()) {
long now = System.currentTimeMillis();
if (now > last + 2000) {
if (lastRead < 0)
throw new AssertionError("read nothing after 2 seconds");
// System.out.println(Thread.currentThread() + " - Last read: " + lastRead);
last = now;
}
continue;
}
int v = -1;
final ValueIn valueIn = dc.wire().getValueIn();
final long documentAcquireTimestamp = valueIn.int64();
if (documentAcquireTimestamp == 0L) {
throw new AssertionError("No timestamp");
}
for (int i = 0; i < NUMBER_OF_INTS; i++) {
v = valueIn.int32();
if (lastRead + 1 != v) {
// System.out.println(dc.wire());
String failureMessage = "Expected: " + (lastRead + 1) +
", actual: " + v + ", pos: " + i + ", index: " + Long
.toHexString(dc.index()) +
", cycle: " + tailer.cycle();
if (lastTailerCycle != -1) {
failureMessage += ". Tailer cycle at last read: " + lastTailerCycle +
" (current: " + (tailer.cycle()) +
"), queue cycle at last read: " + lastQueueCycle +
" (current: " + queue.cycle() + ")";
}
if (DUMP_QUEUE)
DumpQueueMain.dump(queue.file(), System.out, Long.MAX_VALUE);
throw new AssertionError(failureMessage);
}
}
lastRead = v;
lastTailerCycle = tailer.cycle();
lastQueueCycle = queue.cycle();
}
}
} catch (Throwable e) {
exception = e;
LOG.info("Finished reader", e);
return e;
}
LOG.info("Finished reader OK");
return null;
}
}
final class Writer implements Callable<Throwable> {
final File path;
final AtomicInteger wrote;
final int expectedNumberOfMessages;
volatile Throwable exception;
Writer(final File path, final AtomicInteger wrote,
final int expectedNumberOfMessages) {
this.path = path;
this.wrote = wrote;
this.expectedNumberOfMessages = expectedNumberOfMessages;
}
@Override
public Throwable call() {
ChronicleQueue queue = writerQueue(path);
try (final ExcerptAppender appender = queue.acquireAppender()) {
Jvm.pause(random.nextInt(DELAY_WRITER_RANDOM_MS));
final long startTime = System.nanoTime();
int loopIteration = 0;
while (true) {
final int value = write(appender);
while (System.nanoTime() < (startTime + (loopIteration * SLEEP_PER_WRITE_NANOS))) {
// spin
}
loopIteration++;
if (value >= expectedNumberOfMessages) {
LOG.info("Finished writer");
return null;
}
}
} catch (Throwable e) {
LOG.info("Finished writer", e);
exception = e;
return e;
} finally {
if (queue != sharedWriterQueue)
queue.close();
}
}
private int write(ExcerptAppender appender) {
int value;
try (DocumentContext writingDocument = appender.writingDocument()) {
final long documentAcquireTimestamp = System.nanoTime();
value = wrote.getAndIncrement();
ValueOut valueOut = writingDocument.wire().getValueOut();
// make the message longer
valueOut.int64(documentAcquireTimestamp);
for (int i = 0; i < NUMBER_OF_INTS; i++) {
valueOut.int32(value);
}
writingDocument.wire().padToCacheAlign();
}
return value;
}
}
class PretoucherThread implements Callable<Throwable> {
final File path;
volatile Throwable exception;
PretoucherThread(File path) {
this.path = path;
}
@SuppressWarnings("resource")
@Override
public Throwable call() {
ChronicleQueue queue0 = null;
try (ChronicleQueue queue = queueBuilder(path).build()) {
queue0 = queue;
ExcerptAppender appender = queue.acquireAppender();
// System.out.println("Starting pretoucher");
while (!Thread.currentThread().isInterrupted() && !queue.isClosed()) {
Jvm.pause(50);
appender.pretouch();
}
} catch (Throwable e) {
if (queue0 != null && queue0.isClosed())
return null;
exception = e;
return e;
}
return null;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
new RollCycleMultiThreadStressTest().stress();
}
} | src/test/java/net/openhft/chronicle/queue/impl/single/RollCycleMultiThreadStressTest.java | package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.io.AbstractReferenceCounted;
import net.openhft.chronicle.core.io.IOTools;
import net.openhft.chronicle.core.onoes.ExceptionKey;
import net.openhft.chronicle.core.onoes.LogLevel;
import net.openhft.chronicle.core.threads.ThreadDump;
import net.openhft.chronicle.core.time.SetTimeProvider;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.RollingChronicleQueue;
import net.openhft.chronicle.threads.NamedThreadFactory;
import net.openhft.chronicle.wire.DocumentContext;
import net.openhft.chronicle.wire.ValueIn;
import net.openhft.chronicle.wire.ValueOut;
import org.jetbrains.annotations.NotNull;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static net.openhft.chronicle.core.io.Closeable.closeQuietly;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class RollCycleMultiThreadStressTest {
static {
Jvm.disableDebugHandler();
}
final long SLEEP_PER_WRITE_NANOS;
final int TEST_TIME;
final int ROLL_EVERY_MS;
final int DELAY_READER_RANDOM_MS;
final int DELAY_WRITER_RANDOM_MS;
final int WRITE_ONE_THEN_WAIT_MS;
final int CORES;
final Random random;
final int NUMBER_OF_INTS;
final boolean PRETOUCH;
final boolean READERS_READ_ONLY;
final boolean DUMP_QUEUE;
final boolean SHARED_WRITE_QUEUE;
final boolean DOUBLE_BUFFER;
private ThreadDump threadDump;
private Map<ExceptionKey, Integer> exceptionKeyIntegerMap;
final Logger LOG = LoggerFactory.getLogger(getClass());
final SetTimeProvider timeProvider = new SetTimeProvider();
private ChronicleQueue sharedWriterQueue;
public RollCycleMultiThreadStressTest() {
SLEEP_PER_WRITE_NANOS = Long.getLong("writeLatency", 30_000);
TEST_TIME = Integer.getInteger("testTime", 2);
ROLL_EVERY_MS = Integer.getInteger("rollEvery", 300);
DELAY_READER_RANDOM_MS = Integer.getInteger("delayReader", 1);
DELAY_WRITER_RANDOM_MS = Integer.getInteger("delayWriter", 1);
WRITE_ONE_THEN_WAIT_MS = Integer.getInteger("writeOneThenWait", 0);
CORES = Integer.getInteger("cores", Runtime.getRuntime().availableProcessors());
random = new Random(99);
NUMBER_OF_INTS = Integer.getInteger("numberInts", 18);//1060 / 4;
PRETOUCH = Jvm.getBoolean("pretouch");
READERS_READ_ONLY = Jvm.getBoolean("read_only");
DUMP_QUEUE = Jvm.getBoolean("dump_queue");
SHARED_WRITE_QUEUE = Jvm.getBoolean("sharedWriteQ");
DOUBLE_BUFFER = Jvm.getBoolean("double_buffer");
if (TEST_TIME > 2) {
AbstractReferenceCounted.disableReferenceTracing();
if (Jvm.isResourceTracing()) {
throw new IllegalStateException("This test will run out of memory - change your system properties");
}
}
}
static boolean areAllReadersComplete(final int expectedNumberOfMessages, final List<Reader> readers) {
boolean allReadersComplete = true;
int count = 0;
for (Reader reader : readers) {
++count;
if (reader.lastRead < expectedNumberOfMessages - 1) {
allReadersComplete = false;
// System.out.printf("Reader #%d last read: %d%n", count, reader.lastRead);
}
}
return allReadersComplete;
}
@Test
public void stress() throws InterruptedException, IOException {
assert warnIfAssertsAreOn();
File file = DirectoryUtils.tempDir("stress");
// System.out.printf("Queue dir: %s at %s%n", file.getAbsolutePath(), Instant.now());
final int numThreads = CORES;
final int numWriters = numThreads / 4 + 1;
final ExecutorService executorServicePretouch = Executors.newSingleThreadExecutor(
new NamedThreadFactory("pretouch"));
final ExecutorService executorServiceWrite = Executors.newFixedThreadPool(numWriters,
new NamedThreadFactory("writer"));
final ExecutorService executorServiceRead = Executors.newFixedThreadPool(numThreads - numWriters,
new NamedThreadFactory("reader"));
final AtomicInteger wrote = new AtomicInteger();
final int expectedNumberOfMessages = (int) (TEST_TIME * 1e9 / SLEEP_PER_WRITE_NANOS) * Math.max(1, numWriters / 2);
// System.out.printf("Running test with %d writers and %d readers, sleep %dns%n",
// numWriters, numThreads - numWriters, SLEEP_PER_WRITE_NANOS);
// System.out.printf("Writing %d messages with %dns interval%n", expectedNumberOfMessages,
// SLEEP_PER_WRITE_NANOS);
// System.out.printf("Should take ~%dms%n",
// TimeUnit.NANOSECONDS.toMillis(expectedNumberOfMessages * SLEEP_PER_WRITE_NANOS) / (numWriters / 2));
final List<Future<Throwable>> results = new ArrayList<>();
final List<Reader> readers = new ArrayList<>();
final List<Writer> writers = new ArrayList<>();
if (READERS_READ_ONLY)
createQueue(file);
if (SHARED_WRITE_QUEUE)
sharedWriterQueue = createQueue(file);
PretoucherThread pretoucherThread = null;
if (PRETOUCH) {
pretoucherThread = new PretoucherThread(file);
executorServicePretouch.submit(pretoucherThread);
}
if (WRITE_ONE_THEN_WAIT_MS > 0) {
final Writer tempWriter = new Writer(file, wrote, expectedNumberOfMessages);
try (ChronicleQueue queue = writerQueue(file)) {
tempWriter.write(queue.acquireAppender());
}
}
for (int i = 0; i < numThreads - numWriters; i++) {
final Reader reader = new Reader(file, expectedNumberOfMessages);
readers.add(reader);
results.add(executorServiceRead.submit(reader));
}
if (WRITE_ONE_THEN_WAIT_MS > 0) {
LOG.warn("Wrote one now waiting for {}ms", WRITE_ONE_THEN_WAIT_MS);
Jvm.pause(WRITE_ONE_THEN_WAIT_MS);
}
for (int i = 0; i < numWriters; i++) {
final Writer writer = new Writer(file, wrote, expectedNumberOfMessages);
writers.add(writer);
results.add(executorServiceWrite.submit(writer));
}
final long maxWritingTime = TimeUnit.SECONDS.toMillis(TEST_TIME + 5) + queueBuilder(file).timeoutMS();
long startTime = System.currentTimeMillis();
final long giveUpWritingAt = startTime + maxWritingTime;
long nextRollTime = System.currentTimeMillis() + ROLL_EVERY_MS, nextCheckTime = System.currentTimeMillis() + 5_000;
int i = 0;
long now;
while ((now = System.currentTimeMillis()) < giveUpWritingAt) {
if (wrote.get() >= expectedNumberOfMessages)
break;
if (now > nextRollTime) {
timeProvider.advanceMillis(1000);
nextRollTime += ROLL_EVERY_MS;
}
if (now > nextCheckTime) {
String readersLastRead = readers.stream().map(reader -> Integer.toString(reader.lastRead)).collect(Collectors.joining(","));
// System.out.printf("Writer has written %d of %d messages after %dms. Readers at %s. Waiting...%n",
// wrote.get() + 1, expectedNumberOfMessages,
// i * 10, readersLastRead);
readers.stream().filter(r -> !r.isMakingProgress()).findAny().ifPresent(reader -> {
if (reader.exception != null) {
throw new AssertionError("Reader encountered exception, so stopped reading messages",
reader.exception);
}
throw new AssertionError("Reader is stuck");
});
if (pretoucherThread != null && pretoucherThread.exception != null)
throw new AssertionError("Preloader encountered exception", pretoucherThread.exception);
nextCheckTime = System.currentTimeMillis() + 10_000L;
}
i++;
Jvm.pause(5);
}
double timeToWriteSecs = (System.currentTimeMillis() - startTime) / 1000d;
final StringBuilder writerExceptions = new StringBuilder();
writers.stream().filter(w -> w.exception != null).forEach(w -> {
writerExceptions.append("Writer failed due to: ").append(w.exception.getMessage()).append("\n");
});
assertTrue("Wrote " + wrote.get() + " which is less than " + expectedNumberOfMessages + " within timeout. " + writerExceptions,
wrote.get() >= expectedNumberOfMessages);
readers.stream().filter(r -> r.exception != null).findAny().ifPresent(reader -> {
throw new AssertionError("Reader encountered exception, so stopped reading messages",
reader.exception);
});
/*
System.out.println(String.format("All messages written in %,.0fsecs at rate of %,.0f/sec %,.0f/sec per writer (actual writeLatency %,.0fns)",
timeToWriteSecs, expectedNumberOfMessages / timeToWriteSecs, (expectedNumberOfMessages / timeToWriteSecs) / numWriters,
1_000_000_000 / ((expectedNumberOfMessages / timeToWriteSecs) / numWriters)));
*/
final long giveUpReadingAt = System.currentTimeMillis() + 20_000L;
final long dumpThreadsAt = giveUpReadingAt - 5_000L;
try {
while (System.currentTimeMillis() < giveUpReadingAt) {
results.forEach(f -> {
try {
if (f.isDone()) {
final Throwable exception = f.get();
if (exception != null) {
throw Jvm.rethrow(exception);
}
}
} catch (InterruptedException e) {
// ignored
} catch (ExecutionException e) {
throw Jvm.rethrow(e);
}
});
boolean allReadersComplete = areAllReadersComplete(expectedNumberOfMessages, readers);
if (allReadersComplete) {
break;
}
// System.out.printf("Not all readers are complete. Waiting...%n");
Jvm.pause(2000);
}
assertTrue("Readers did not catch up",
areAllReadersComplete(expectedNumberOfMessages, readers));
} finally {
executorServiceRead.shutdown();
executorServiceWrite.shutdown();
executorServicePretouch.shutdown();
if (!executorServiceRead.awaitTermination(1, TimeUnit.SECONDS))
executorServiceRead.shutdownNow();
if (!executorServiceWrite.awaitTermination(1, TimeUnit.SECONDS))
executorServiceWrite.shutdownNow();
if (!executorServicePretouch.awaitTermination(1, TimeUnit.SECONDS))
executorServicePretouch.shutdownNow();
closeQuietly(sharedWriterQueue);
results.forEach(f -> {
try {
final Throwable exception = f.get(100, TimeUnit.MILLISECONDS);
if (exception != null) {
exception.printStackTrace();
}
} catch (InterruptedException | TimeoutException e) {
// ignored
} catch (ExecutionException e) {
throw Jvm.rethrow(e);
}
});
}
IOTools.deleteDirWithFiles("stress");
// System.out.println("Test complete");
}
private boolean warnIfAssertsAreOn() {
Jvm.warn().on(getClass(), "Reminder: asserts are on");
return true;
}
@NotNull
SingleChronicleQueueBuilder queueBuilder(File path) {
return SingleChronicleQueueBuilder.binary(path)
.testBlockSize()
.timeProvider(timeProvider)
.doubleBuffer(DOUBLE_BUFFER)
.rollCycle(RollCycles.TEST_SECONDLY);
}
@NotNull
private ChronicleQueue createQueue(File path) {
return queueBuilder(path).build();
}
@NotNull
private ChronicleQueue writerQueue(File path) {
return sharedWriterQueue != null ? sharedWriterQueue : createQueue(path);
}
@Before
public void multiCPU() {
Assume.assumeTrue(Runtime.getRuntime().availableProcessors() > 1);
}
@Before
public void before() {
threadDump = new ThreadDump();
exceptionKeyIntegerMap = Jvm.recordExceptions();
}
@After
public void after() {
threadDump.assertNoNewThreads();
// warnings are often expected
exceptionKeyIntegerMap.entrySet().removeIf(entry -> entry.getKey().level.equals(LogLevel.WARN));
if (Jvm.hasException(exceptionKeyIntegerMap)) {
Jvm.dumpException(exceptionKeyIntegerMap);
fail();
}
Jvm.resetExceptionHandlers();
AbstractReferenceCounted.assertReferencesReleased();
}
final class Reader implements Callable<Throwable> {
final File path;
final int expectedNumberOfMessages;
volatile int lastRead = -1;
volatile Throwable exception;
int readSequenceAtLastProgressCheck = -1;
Reader(final File path, final int expectedNumberOfMessages) {
this.path = path;
this.expectedNumberOfMessages = expectedNumberOfMessages;
}
boolean isMakingProgress() {
if (readSequenceAtLastProgressCheck == -1) {
return true;
}
final boolean makingProgress = lastRead > readSequenceAtLastProgressCheck;
readSequenceAtLastProgressCheck = lastRead;
return makingProgress;
}
@Override
public Throwable call() {
SingleChronicleQueueBuilder builder = queueBuilder(path);
if (READERS_READ_ONLY)
builder.readOnly(true);
long last = System.currentTimeMillis();
try (RollingChronicleQueue queue = builder.build();
ExcerptTailer tailer = queue.createTailer()) {
int lastTailerCycle = -1;
int lastQueueCycle = -1;
Jvm.pause(random.nextInt(DELAY_READER_RANDOM_MS));
while (lastRead != expectedNumberOfMessages - 1) {
try (DocumentContext dc = tailer.readingDocument()) {
if (!dc.isPresent()) {
long now = System.currentTimeMillis();
if (now > last + 2000) {
if (lastRead < 0)
throw new AssertionError("read nothing after 2 seconds");
// System.out.println(Thread.currentThread() + " - Last read: " + lastRead);
last = now;
}
continue;
}
int v = -1;
final ValueIn valueIn = dc.wire().getValueIn();
final long documentAcquireTimestamp = valueIn.int64();
if (documentAcquireTimestamp == 0L) {
throw new AssertionError("No timestamp");
}
for (int i = 0; i < NUMBER_OF_INTS; i++) {
v = valueIn.int32();
if (lastRead + 1 != v) {
// System.out.println(dc.wire());
String failureMessage = "Expected: " + (lastRead + 1) +
", actual: " + v + ", pos: " + i + ", index: " + Long
.toHexString(dc.index()) +
", cycle: " + tailer.cycle();
if (lastTailerCycle != -1) {
failureMessage += ". Tailer cycle at last read: " + lastTailerCycle +
" (current: " + (tailer.cycle()) +
"), queue cycle at last read: " + lastQueueCycle +
" (current: " + queue.cycle() + ")";
}
if (DUMP_QUEUE)
DumpQueueMain.dump(queue.file(), System.out, Long.MAX_VALUE);
throw new AssertionError(failureMessage);
}
}
lastRead = v;
lastTailerCycle = tailer.cycle();
lastQueueCycle = queue.cycle();
}
}
} catch (Throwable e) {
exception = e;
LOG.info("Finished reader", e);
return e;
}
LOG.info("Finished reader OK");
return null;
}
}
final class Writer implements Callable<Throwable> {
final File path;
final AtomicInteger wrote;
final int expectedNumberOfMessages;
volatile Throwable exception;
Writer(final File path, final AtomicInteger wrote,
final int expectedNumberOfMessages) {
this.path = path;
this.wrote = wrote;
this.expectedNumberOfMessages = expectedNumberOfMessages;
}
@Override
public Throwable call() {
ChronicleQueue queue = writerQueue(path);
try (final ExcerptAppender appender = queue.acquireAppender()) {
Jvm.pause(random.nextInt(DELAY_WRITER_RANDOM_MS));
final long startTime = System.nanoTime();
int loopIteration = 0;
while (true) {
final int value = write(appender);
while (System.nanoTime() < (startTime + (loopIteration * SLEEP_PER_WRITE_NANOS))) {
// spin
}
loopIteration++;
if (value >= expectedNumberOfMessages) {
LOG.info("Finished writer");
return null;
}
}
} catch (Throwable e) {
LOG.info("Finished writer", e);
exception = e;
return e;
} finally {
if (queue != sharedWriterQueue)
queue.close();
}
}
private int write(ExcerptAppender appender) {
int value;
try (DocumentContext writingDocument = appender.writingDocument()) {
final long documentAcquireTimestamp = System.nanoTime();
value = wrote.getAndIncrement();
ValueOut valueOut = writingDocument.wire().getValueOut();
// make the message longer
valueOut.int64(documentAcquireTimestamp);
for (int i = 0; i < NUMBER_OF_INTS; i++) {
valueOut.int32(value);
}
writingDocument.wire().padToCacheAlign();
}
return value;
}
}
class PretoucherThread implements Callable<Throwable> {
final File path;
volatile Throwable exception;
PretoucherThread(File path) {
this.path = path;
}
@SuppressWarnings("resource")
@Override
public Throwable call() {
ChronicleQueue queue0 = null;
try (ChronicleQueue queue = queueBuilder(path).build()) {
queue0 = queue;
ExcerptAppender appender = queue.acquireAppender();
// System.out.println("Starting pretoucher");
while (!Thread.currentThread().isInterrupted() && !queue.isClosed()) {
Jvm.pause(50);
appender.pretouch();
}
} catch (Throwable e) {
if (queue0 != null && queue0.isClosed())
return null;
exception = e;
return e;
}
return null;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
new RollCycleMultiThreadStressTest().stress();
}
} | Close readonly queue when not needed.
| src/test/java/net/openhft/chronicle/queue/impl/single/RollCycleMultiThreadStressTest.java | Close readonly queue when not needed. |
|
Java | apache-2.0 | fb0a2876352d3a25b2efef7a02f94978f55b905d | 0 | EvilMcJerkface/Aeron,mikeb01/Aeron,real-logic/Aeron,real-logic/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron | /*
* Copyright 2014-2020 Real Logic Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.aeron.agent;
import io.aeron.Aeron;
import io.aeron.Publication;
import io.aeron.Subscription;
import io.aeron.driver.MediaDriver;
import io.aeron.logbuffer.FragmentHandler;
import org.agrona.IoUtil;
import org.agrona.MutableDirectBuffer;
import org.agrona.collections.MutableInteger;
import org.agrona.concurrent.Agent;
import org.agrona.concurrent.MessageHandler;
import org.agrona.concurrent.UnsafeBuffer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.io.File;
import java.nio.file.Paths;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static io.aeron.agent.DriverEventCode.*;
import static io.aeron.agent.EventConfiguration.EVENT_READER_FRAME_LIMIT;
import static io.aeron.agent.EventConfiguration.EVENT_RING_BUFFER;
import static java.time.Duration.ofSeconds;
import static java.util.Collections.synchronizedSet;
import static java.util.stream.Collectors.toSet;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.params.provider.EnumSource.Mode.INCLUDE;
public class DriverLoggingAgentTest
{
private static final String NETWORK_CHANNEL = "aeron:udp?endpoint=localhost:54325";
private static final int STREAM_ID = 1777;
private static final Set<Integer> LOGGED_EVENTS = synchronizedSet(new HashSet<>());
private static final Set<Integer> WAIT_LIST = synchronizedSet(new HashSet<>());
private static CountDownLatch latch;
private File testDir;
@AfterEach
public void after()
{
Common.afterAgent();
LOGGED_EVENTS.clear();
WAIT_LIST.clear();
if (testDir != null && testDir.exists())
{
IoUtil.delete(testDir, false);
}
}
@Test
public void logAll()
{
testLogMediaDriverEvents("all", EnumSet.of(
FRAME_IN,
FRAME_OUT,
CMD_IN_ADD_PUBLICATION,
CMD_IN_REMOVE_PUBLICATION,
CMD_IN_ADD_SUBSCRIPTION,
CMD_IN_REMOVE_SUBSCRIPTION,
CMD_OUT_PUBLICATION_READY,
CMD_OUT_AVAILABLE_IMAGE,
CMD_OUT_ON_OPERATION_SUCCESS,
REMOVE_PUBLICATION_CLEANUP,
REMOVE_IMAGE_CLEANUP,
SEND_CHANNEL_CREATION,
RECEIVE_CHANNEL_CREATION,
SEND_CHANNEL_CLOSE,
RECEIVE_CHANNEL_CLOSE,
CMD_OUT_SUBSCRIPTION_READY,
CMD_IN_CLIENT_CLOSE));
}
@ParameterizedTest
@EnumSource(value = DriverEventCode.class, mode = INCLUDE, names = {
"REMOVE_IMAGE_CLEANUP",
"REMOVE_PUBLICATION_CLEANUP",
"SEND_CHANNEL_CREATION",
"SEND_CHANNEL_CLOSE",
"RECEIVE_CHANNEL_CREATION",
"RECEIVE_CHANNEL_CLOSE",
"FRAME_IN",
"FRAME_OUT",
"CMD_IN_ADD_SUBSCRIPTION",
"CMD_OUT_AVAILABLE_IMAGE"
})
public void logIndividualEvents(final DriverEventCode eventCode)
{
try
{
testLogMediaDriverEvents(eventCode.name(), EnumSet.of(eventCode));
}
finally
{
after();
}
}
private void testLogMediaDriverEvents(final String enabledEvents, final EnumSet<DriverEventCode> expectedEvents)
{
before(enabledEvents, expectedEvents);
assertTimeoutPreemptively(ofSeconds(20), () ->
{
final String aeronDirectoryName = testDir.toPath().resolve("media").toString();
final MediaDriver.Context driverCtx = new MediaDriver.Context()
.errorHandler(Throwable::printStackTrace)
.publicationLingerTimeoutNs(0)
.timerIntervalNs(TimeUnit.MILLISECONDS.toNanos(1))
.aeronDirectoryName(aeronDirectoryName);
try (MediaDriver ignore = MediaDriver.launchEmbedded(driverCtx))
{
final Aeron.Context clientCtx = new Aeron.Context()
.aeronDirectoryName(driverCtx.aeronDirectoryName());
try (Aeron aeron = Aeron.connect(clientCtx);
Subscription subscription = aeron.addSubscription(NETWORK_CHANNEL, STREAM_ID);
Publication publication = aeron.addPublication(NETWORK_CHANNEL, STREAM_ID))
{
final UnsafeBuffer offerBuffer = new UnsafeBuffer(new byte[32]);
while (publication.offer(offerBuffer) < 0)
{
Thread.yield();
Common.checkInterruptedStatus();
}
final MutableInteger counter = new MutableInteger();
final FragmentHandler handler = (buffer, offset, length, header) -> counter.value++;
while (0 == subscription.poll(handler, 1))
{
Thread.yield();
Common.checkInterruptedStatus();
}
assertEquals(counter.get(), 1);
}
latch.await();
}
assertEquals(expectedEvents.stream().map(DriverEventCode::id).collect(toSet()), LOGGED_EVENTS);
});
}
private void before(final String enabledEvents, final EnumSet<DriverEventCode> expectedEvents)
{
System.setProperty(EventLogAgent.READER_CLASSNAME_PROP_NAME, StubEventLogReaderAgent.class.getName());
System.setProperty(EventConfiguration.ENABLED_EVENT_CODES_PROP_NAME, enabledEvents);
Common.beforeAgent();
latch = new CountDownLatch(expectedEvents.size());
WAIT_LIST.addAll(expectedEvents.stream().map(DriverEventCode::id).collect(toSet()));
testDir = Paths.get(IoUtil.tmpDirName(), "driver-test").toFile();
if (testDir.exists())
{
IoUtil.delete(testDir, false);
}
}
static class StubEventLogReaderAgent implements Agent, MessageHandler
{
public String roleName()
{
return "event-log-reader";
}
public int doWork()
{
return EVENT_RING_BUFFER.read(this, EVENT_READER_FRAME_LIMIT);
}
public void onMessage(final int msgTypeId, final MutableDirectBuffer buffer, final int index, final int length)
{
LOGGED_EVENTS.add(msgTypeId);
if (WAIT_LIST.contains(msgTypeId) && WAIT_LIST.remove(msgTypeId))
{
latch.countDown();
}
}
}
}
| aeron-agent/src/test/java/io/aeron/agent/DriverLoggingAgentTest.java | /*
* Copyright 2014-2020 Real Logic Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.aeron.agent;
import io.aeron.Aeron;
import io.aeron.Publication;
import io.aeron.Subscription;
import io.aeron.driver.MediaDriver;
import io.aeron.logbuffer.FragmentHandler;
import org.agrona.IoUtil;
import org.agrona.MutableDirectBuffer;
import org.agrona.collections.MutableInteger;
import org.agrona.concurrent.Agent;
import org.agrona.concurrent.MessageHandler;
import org.agrona.concurrent.UnsafeBuffer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.io.File;
import java.nio.file.Paths;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import static io.aeron.agent.DriverEventCode.*;
import static io.aeron.agent.EventConfiguration.EVENT_READER_FRAME_LIMIT;
import static io.aeron.agent.EventConfiguration.EVENT_RING_BUFFER;
import static java.time.Duration.ofSeconds;
import static java.util.Collections.synchronizedSet;
import static java.util.stream.Collectors.toSet;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.params.provider.EnumSource.Mode.INCLUDE;
public class DriverLoggingAgentTest
{
private static final String NETWORK_CHANNEL = "aeron:udp?endpoint=localhost:54325";
private static final int STREAM_ID = 1777;
private static final Set<Integer> LOGGED_EVENTS = synchronizedSet(new HashSet<>());
private static final Set<Integer> WAIT_LIST = synchronizedSet(new HashSet<>());
private static CountDownLatch latch;
private File testDir;
@AfterEach
public void after()
{
Common.afterAgent();
LOGGED_EVENTS.clear();
WAIT_LIST.clear();
if (testDir != null && testDir.exists())
{
IoUtil.delete(testDir, false);
}
}
@Test
public void logAll()
{
testLogMediaDriverEvents("all", EnumSet.of(
FRAME_IN,
FRAME_OUT,
CMD_IN_ADD_PUBLICATION,
CMD_IN_REMOVE_PUBLICATION,
CMD_IN_ADD_SUBSCRIPTION,
CMD_IN_REMOVE_SUBSCRIPTION,
CMD_OUT_PUBLICATION_READY,
CMD_OUT_AVAILABLE_IMAGE,
CMD_OUT_ON_OPERATION_SUCCESS,
REMOVE_PUBLICATION_CLEANUP,
REMOVE_IMAGE_CLEANUP,
SEND_CHANNEL_CREATION,
RECEIVE_CHANNEL_CREATION,
SEND_CHANNEL_CLOSE,
RECEIVE_CHANNEL_CLOSE,
CMD_OUT_SUBSCRIPTION_READY,
CMD_IN_CLIENT_CLOSE));
}
@ParameterizedTest
@EnumSource(value = DriverEventCode.class, mode = INCLUDE, names = {
"REMOVE_IMAGE_CLEANUP",
"REMOVE_PUBLICATION_CLEANUP",
"SEND_CHANNEL_CREATION",
"SEND_CHANNEL_CLOSE",
"RECEIVE_CHANNEL_CREATION",
"RECEIVE_CHANNEL_CLOSE",
"FRAME_IN",
"FRAME_OUT",
"CMD_IN_ADD_SUBSCRIPTION",
"CMD_OUT_AVAILABLE_IMAGE"
})
public void logIndividualEvents(final DriverEventCode eventCode)
{
try
{
testLogMediaDriverEvents(eventCode.name(), EnumSet.of(eventCode));
}
finally
{
after();
}
}
private void testLogMediaDriverEvents(final String enabledEvents, final EnumSet<DriverEventCode> expectedEvents)
{
before(enabledEvents, expectedEvents);
assertTimeoutPreemptively(ofSeconds(20), () ->
{
final String aeronDirectoryName = testDir.toPath().resolve("media").toString();
final MediaDriver.Context driverCtx = new MediaDriver.Context()
.errorHandler(Throwable::printStackTrace)
.aeronDirectoryName(aeronDirectoryName);
try (MediaDriver ignore = MediaDriver.launchEmbedded(driverCtx))
{
final Aeron.Context clientCtx = new Aeron.Context()
.aeronDirectoryName(driverCtx.aeronDirectoryName());
try (Aeron aeron = Aeron.connect(clientCtx);
Subscription subscription = aeron.addSubscription(NETWORK_CHANNEL, STREAM_ID);
Publication publication = aeron.addPublication(NETWORK_CHANNEL, STREAM_ID))
{
final UnsafeBuffer offerBuffer = new UnsafeBuffer(new byte[32]);
while (publication.offer(offerBuffer) < 0)
{
Thread.yield();
Common.checkInterruptedStatus();
}
final MutableInteger counter = new MutableInteger();
final FragmentHandler handler = (buffer, offset, length, header) -> counter.value++;
while (0 == subscription.poll(handler, 1))
{
Thread.yield();
Common.checkInterruptedStatus();
}
assertEquals(counter.get(), 1);
}
latch.await();
}
assertEquals(expectedEvents.stream().map(DriverEventCode::id).collect(toSet()), LOGGED_EVENTS);
});
}
private void before(final String enabledEvents, final EnumSet<DriverEventCode> expectedEvents)
{
System.setProperty(EventLogAgent.READER_CLASSNAME_PROP_NAME, StubEventLogReaderAgent.class.getName());
System.setProperty(EventConfiguration.ENABLED_EVENT_CODES_PROP_NAME, enabledEvents);
Common.beforeAgent();
latch = new CountDownLatch(expectedEvents.size());
WAIT_LIST.addAll(expectedEvents.stream().map(DriverEventCode::id).collect(toSet()));
testDir = Paths.get(IoUtil.tmpDirName(), "driver-test").toFile();
if (testDir.exists())
{
IoUtil.delete(testDir, false);
}
}
static class StubEventLogReaderAgent implements Agent, MessageHandler
{
public String roleName()
{
return "event-log-reader";
}
public int doWork()
{
return EVENT_RING_BUFFER.read(this, EVENT_READER_FRAME_LIMIT);
}
public void onMessage(final int msgTypeId, final MutableDirectBuffer buffer, final int index, final int length)
{
LOGGED_EVENTS.add(msgTypeId);
if (WAIT_LIST.contains(msgTypeId) && WAIT_LIST.remove(msgTypeId))
{
latch.countDown();
}
}
}
}
| [Java] Speed up DriverLoggingAgentTest.
| aeron-agent/src/test/java/io/aeron/agent/DriverLoggingAgentTest.java | [Java] Speed up DriverLoggingAgentTest. |
|
Java | apache-2.0 | e53789ea896bcd72957efc2350946fa5b6dbb0b1 | 0 | apigee/astyanax,DavidHerzogTU-Berlin/astyanax,maxtomassi/ds-astyanax,maxtomassi/ds-astyanax,gorcz/astyanax,fengshao0907/astyanax,bazaarvoice/astyanax,Netflix/astyanax,DavidHerzogTU-Berlin/astyanax,DavidHerzogTU-Berlin/astyanax,Netflix/astyanax,Netflix/astyanax,apigee/astyanax,fengshao0907/astyanax,gorcz/astyanax,bazaarvoice/astyanax | /*******************************************************************************
* Copyright 2011 Netflix
*
* 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.netflix.astyanax.thrift;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.Cassandra.Client;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.CounterSuperColumn;
import org.apache.cassandra.thrift.KeyRange;
import org.apache.cassandra.thrift.Mutation;
import org.apache.cassandra.thrift.SuperColumn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.netflix.astyanax.CassandraOperationType;
import com.netflix.astyanax.KeyspaceTracerFactory;
import com.netflix.astyanax.RowCopier;
import com.netflix.astyanax.connectionpool.ConnectionPool;
import com.netflix.astyanax.connectionpool.ConnectionContext;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.model.Rows;
import com.netflix.astyanax.query.AllRowsQuery;
import com.netflix.astyanax.query.ColumnCountQuery;
import com.netflix.astyanax.query.ColumnFamilyQuery;
import com.netflix.astyanax.query.ColumnQuery;
import com.netflix.astyanax.query.CqlQuery;
import com.netflix.astyanax.query.IndexQuery;
import com.netflix.astyanax.query.RowQuery;
import com.netflix.astyanax.query.RowSliceColumnCountQuery;
import com.netflix.astyanax.query.RowSliceQuery;
import com.netflix.astyanax.retry.RetryPolicy;
import com.netflix.astyanax.shallows.EmptyColumnList;
import com.netflix.astyanax.shallows.EmptyRowsImpl;
import com.netflix.astyanax.thrift.model.*;
/**
* Implementation of all column family queries using the thrift API.
*
* @author elandau
*
* @param <K>
* @param <C>
*/
public class ThriftColumnFamilyQueryImpl<K, C> implements ColumnFamilyQuery<K, C> {
private final static Logger LOG = LoggerFactory.getLogger(ThriftColumnFamilyQueryImpl.class);
final ConnectionPool<Cassandra.Client> connectionPool;
final ColumnFamily<K, C> columnFamily;
final KeyspaceTracerFactory tracerFactory;
final ThriftKeyspaceImpl keyspace;
ConsistencyLevel consistencyLevel;
final ListeningExecutorService executor;
Host pinnedHost;
RetryPolicy retry;
public ThriftColumnFamilyQueryImpl(ExecutorService executor, KeyspaceTracerFactory tracerFactory,
ThriftKeyspaceImpl keyspace, ConnectionPool<Cassandra.Client> cp, ColumnFamily<K, C> columnFamily,
ConsistencyLevel consistencyLevel, RetryPolicy retry) {
this.keyspace = keyspace;
this.connectionPool = cp;
this.consistencyLevel = consistencyLevel;
this.columnFamily = columnFamily;
this.tracerFactory = tracerFactory;
this.executor = MoreExecutors.listeningDecorator(executor);
this.retry = retry;
}
// Single ROW query
@Override
public RowQuery<K, C> getKey(final K rowKey) {
return new AbstractRowQueryImpl<K, C>(columnFamily.getColumnSerializer()) {
private boolean firstPage = true;
@Override
public ColumnQuery<C> getColumn(final C column) {
return new ColumnQuery<C>() {
@Override
public OperationResult<Column<C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(new AbstractKeyspaceOperationImpl<Column<C>>(
tracerFactory.newTracer(CassandraOperationType.GET_COLUMN, columnFamily), pinnedHost,
keyspace.getKeyspaceName()) {
@Override
public Column<C> internalExecute(Client client, ConnectionContext context) throws Exception {
ColumnOrSuperColumn cosc = client.get(
columnFamily.getKeySerializer().toByteBuffer(rowKey),
new org.apache.cassandra.thrift.ColumnPath().setColumn_family(
columnFamily.getName()).setColumn(
columnFamily.getColumnSerializer().toByteBuffer(column)),
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
if (cosc.isSetColumn()) {
org.apache.cassandra.thrift.Column c = cosc.getColumn();
return new ThriftColumnImpl<C>(columnFamily.getColumnSerializer().fromBytes(
c.getName()), c);
}
else if (cosc.isSetSuper_column()) {
// TODO: Super columns
// should be deprecated
SuperColumn sc = cosc.getSuper_column();
return new ThriftSuperColumnImpl<C>(columnFamily.getColumnSerializer().fromBytes(
sc.getName()), sc);
}
else if (cosc.isSetCounter_column()) {
org.apache.cassandra.thrift.CounterColumn c = cosc.getCounter_column();
return new ThriftCounterColumnImpl<C>(columnFamily.getColumnSerializer().fromBytes(
c.getName()), c);
}
else if (cosc.isSetCounter_super_column()) {
// TODO: Super columns
// should be deprecated
CounterSuperColumn sc = cosc.getCounter_super_column();
return new ThriftCounterSuperColumnImpl<C>(columnFamily.getColumnSerializer()
.fromBytes(sc.getName()), sc);
}
else {
throw new RuntimeException("Unknown column type in response");
}
}
@Override
public ByteBuffer getRowKey() {
return columnFamily.getKeySerializer().toByteBuffer(rowKey);
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Column<C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Column<C>>>() {
@Override
public OperationResult<Column<C>> call() throws Exception {
return execute();
}
});
}
};
}
@Override
public OperationResult<ColumnList<C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<ColumnList<C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROW, columnFamily), pinnedHost, keyspace.getKeyspaceName()) {
@Override
public ColumnList<C> execute(Client client, ConnectionContext context) throws ConnectionException {
if (isPaginating && paginateNoMore) {
return new EmptyColumnList<C>();
}
return super.execute(client, context);
}
@Override
public ColumnList<C> internalExecute(Client client, ConnectionContext context) throws Exception {
List<ColumnOrSuperColumn> columnList = client.get_slice(columnFamily.getKeySerializer()
.toByteBuffer(rowKey), new ColumnParent().setColumn_family(columnFamily
.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
// Special handling for pagination
if (isPaginating && predicate.isSetSlice_range()) {
// Did we reach the end of the query.
if (columnList.size() != predicate.getSlice_range().getCount()) {
paginateNoMore = true;
}
// If this is the first page then adjust the
// count so we fetch one extra column
// that will later be dropped
if (firstPage) {
firstPage = false;
if (predicate.getSlice_range().getCount() != Integer.MAX_VALUE)
predicate.getSlice_range().setCount(predicate.getSlice_range().getCount() + 1);
}
else {
if (!columnList.isEmpty())
columnList.remove(0);
}
// Set the start column for the next page to
// the last column of this page.
// We will discard this column later.
if (!columnList.isEmpty()) {
ColumnOrSuperColumn last = Iterables.getLast(columnList);
if (last.isSetColumn()) {
predicate.getSlice_range().setStart(last.getColumn().getName());
} else if (last.isSetCounter_column()) {
predicate.getSlice_range().setStart(last.getCounter_column().getName());
} else if (last.isSetSuper_column()) {
// TODO: Super columns
// should be deprecated
predicate.getSlice_range().setStart(last.getSuper_column().getName());
} else if (last.isSetCounter_super_column()) {
// TODO: Super columns
// should be deprecated
predicate.getSlice_range().setStart(last.getCounter_super_column().getName());
}
}
}
ColumnList<C> result = new ThriftColumnOrSuperColumnListImpl<C>(columnList,
columnFamily.getColumnSerializer());
return result;
}
@Override
public ByteBuffer getRowKey() {
return columnFamily.getKeySerializer().toByteBuffer(rowKey);
}
}, retry);
}
@Override
public ColumnCountQuery getCount() {
return new ColumnCountQuery() {
@Override
public OperationResult<Integer> execute() throws ConnectionException {
return connectionPool.executeWithFailover(new AbstractKeyspaceOperationImpl<Integer>(
tracerFactory.newTracer(CassandraOperationType.GET_COLUMN_COUNT, columnFamily),
pinnedHost, keyspace.getKeyspaceName()) {
@Override
public Integer internalExecute(Client client, ConnectionContext context) throws Exception {
return client.get_count(columnFamily.getKeySerializer().toByteBuffer(rowKey),
new ColumnParent().setColumn_family(columnFamily.getName()), predicate,
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
}
@Override
public ByteBuffer getRowKey() {
return columnFamily.getKeySerializer().toByteBuffer(rowKey);
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Integer>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Integer>>() {
@Override
public OperationResult<Integer> call() throws Exception {
return execute();
}
});
}
};
}
@Override
public ListenableFuture<OperationResult<ColumnList<C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<ColumnList<C>>>() {
@Override
public OperationResult<ColumnList<C>> call() throws Exception {
return execute();
}
});
}
@Override
public RowCopier<K, C> copyTo(final ColumnFamily<K, C> otherColumnFamily, final K otherRowKey) {
return new RowCopier<K, C>() {
private boolean useOriginalTimestamp = true;
@Override
public OperationResult<Void> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Void>(tracerFactory.newTracer(
CassandraOperationType.COPY_TO, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Void internalExecute(Client client, ConnectionContext context) throws Exception {
long currentTime = keyspace.getConfig().getClock().getCurrentTime();
List<ColumnOrSuperColumn> columnList = client.get_slice(columnFamily
.getKeySerializer().toByteBuffer(rowKey), new ColumnParent()
.setColumn_family(columnFamily.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
// Create mutation list from columns in
// the response
List<Mutation> mutationList = new ArrayList<Mutation>();
for (ColumnOrSuperColumn sosc : columnList) {
ColumnOrSuperColumn cosc;
if (sosc.isSetColumn()) {
cosc = new ColumnOrSuperColumn().setColumn(sosc.getColumn());
if (!useOriginalTimestamp)
cosc.getColumn().setTimestamp(currentTime);
}
else if (sosc.isSetSuper_column()) {
cosc = new ColumnOrSuperColumn().setSuper_column(sosc.getSuper_column());
if (!useOriginalTimestamp) {
for (org.apache.cassandra.thrift.Column subColumn : sosc.getSuper_column().getColumns()) {
subColumn.setTimestamp(currentTime);
subColumn.setTimestamp(currentTime);
}
}
}
else if (sosc.isSetCounter_column()) {
cosc = new ColumnOrSuperColumn().setCounter_column(sosc.getCounter_column());
}
else if (sosc.isSetCounter_super_column()) {
cosc = new ColumnOrSuperColumn().setCounter_super_column(sosc.getCounter_super_column());
}
else {
continue;
}
mutationList.add(new Mutation().setColumn_or_supercolumn(cosc));
}
// Create mutation map
Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
HashMap<String, List<Mutation>> cfmap = new HashMap<String, List<Mutation>>();
cfmap.put(otherColumnFamily.getName(), mutationList);
mutationMap.put(columnFamily.getKeySerializer().toByteBuffer(otherRowKey),
cfmap);
// Execute the mutation
client.batch_mutate(mutationMap,
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
return null;
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Void>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Void>>() {
@Override
public OperationResult<Void> call() throws Exception {
return execute();
}
});
}
@Override
public RowCopier<K, C> withOriginalTimestamp(boolean useOriginalTimestamp) {
this.useOriginalTimestamp = useOriginalTimestamp;
return this;
}
};
}
};
}
@Override
public RowSliceQuery<K, C> getKeyRange(final K startKey, final K endKey, final String startToken,
final String endToken, final int count) {
return new AbstractRowSliceQueryImpl<K, C>(columnFamily.getColumnSerializer()) {
@Override
public OperationResult<Rows<K, C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Rows<K, C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_RANGE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Rows<K, C> internalExecute(Client client, ConnectionContext context) throws Exception {
// This is a sorted list
// Same call for standard and super columns via
// the ColumnParent
KeyRange range = new KeyRange();
if (startKey != null)
range.setStart_key(columnFamily.getKeySerializer().toByteBuffer(startKey));
if (endKey != null)
range.setEnd_key(columnFamily.getKeySerializer().toByteBuffer(endKey));
range.setCount(count).setStart_token(startToken).setEnd_token(endToken);
List<org.apache.cassandra.thrift.KeySlice> keySlices = client.get_range_slices(
new ColumnParent().setColumn_family(columnFamily.getName()), predicate, range,
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
if (keySlices == null || keySlices.isEmpty()) {
return new EmptyRowsImpl<K, C>();
}
else {
return new ThriftRowsSliceImpl<K, C>(keySlices, columnFamily.getKeySerializer(),
columnFamily.getColumnSerializer());
}
}
@Override
public ByteBuffer getRowKey() {
if (startKey != null)
return columnFamily.getKeySerializer().toByteBuffer(startKey);
return null;
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Rows<K, C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Rows<K, C>>>() {
@Override
public OperationResult<Rows<K, C>> call() throws Exception {
return execute();
}
});
}
@Override
public RowSliceColumnCountQuery<K> getColumnCounts() {
throw new RuntimeException("Not supported yet");
}
};
}
@Override
public RowSliceQuery<K, C> getKeySlice(final Iterable<K> keys) {
return new AbstractRowSliceQueryImpl<K, C>(columnFamily.getColumnSerializer()) {
@Override
public OperationResult<Rows<K, C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Rows<K, C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_SLICE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Rows<K, C> internalExecute(Client client, ConnectionContext context) throws Exception {
Map<ByteBuffer, List<ColumnOrSuperColumn>> cfmap = client.multiget_slice(columnFamily
.getKeySerializer().toBytesList(keys), new ColumnParent()
.setColumn_family(columnFamily.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null || cfmap.isEmpty()) {
return new EmptyRowsImpl<K, C>();
}
else {
return new ThriftRowsListImpl<K, C>(cfmap, columnFamily.getKeySerializer(),
columnFamily.getColumnSerializer());
}
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Rows<K, C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Rows<K, C>>>() {
@Override
public OperationResult<Rows<K, C>> call() throws Exception {
return execute();
}
});
}
@Override
public RowSliceColumnCountQuery<K> getColumnCounts() {
return new RowSliceColumnCountQuery<K>() {
@Override
public OperationResult<Map<K, Integer>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Map<K, Integer>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_SLICE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Map<K, Integer> internalExecute(Client client, ConnectionContext context) throws Exception {
Map<ByteBuffer, Integer> cfmap = client.multiget_count(
columnFamily.getKeySerializer().toBytesList(keys),
new ColumnParent().setColumn_family(columnFamily.getName()),
predicate,
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null || cfmap.isEmpty()) {
return Maps.newHashMap();
}
else {
return columnFamily.getKeySerializer().fromBytesMap(cfmap);
}
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Map<K, Integer>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Map<K, Integer>>>() {
@Override
public OperationResult<Map<K, Integer>> call() throws Exception {
return execute();
}
});
}
};
}
};
}
@Override
public RowSliceQuery<K, C> getKeySlice(final K keys[]) {
return getKeySlice(Arrays.asList(keys));
}
@Override
public RowSliceQuery<K, C> getKeySlice(final Collection<K> keys) {
return new AbstractRowSliceQueryImpl<K, C>(columnFamily.getColumnSerializer()) {
@Override
public OperationResult<Rows<K, C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Rows<K, C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_SLICE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Rows<K, C> internalExecute(Client client, ConnectionContext context) throws Exception {
Map<ByteBuffer, List<ColumnOrSuperColumn>> cfmap = client.multiget_slice(columnFamily
.getKeySerializer().toBytesList(keys), new ColumnParent()
.setColumn_family(columnFamily.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null || cfmap.isEmpty()) {
return new EmptyRowsImpl<K, C>();
}
else {
return new ThriftRowsListImpl<K, C>(cfmap, columnFamily.getKeySerializer(),
columnFamily.getColumnSerializer());
}
}
@Override
public ByteBuffer getRowKey() {
// / return
// partitioner.getToken(columnFamily.getKeySerializer().toByteBuffer(keys.iterator().next())).token;
return null;
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Rows<K, C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Rows<K, C>>>() {
@Override
public OperationResult<Rows<K, C>> call() throws Exception {
return execute();
}
});
}
@Override
public RowSliceColumnCountQuery<K> getColumnCounts() {
return new RowSliceColumnCountQuery<K>() {
@Override
public OperationResult<Map<K, Integer>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Map<K, Integer>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_SLICE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Map<K, Integer> internalExecute(Client client, ConnectionContext context) throws Exception {
Map<ByteBuffer, Integer> cfmap = client.multiget_count(columnFamily
.getKeySerializer().toBytesList(keys), new ColumnParent()
.setColumn_family(columnFamily.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null || cfmap.isEmpty()) {
return Maps.newHashMap();
}
else {
return columnFamily.getKeySerializer().fromBytesMap(cfmap);
}
}
@Override
public ByteBuffer getRowKey() {
// / return
// partitioner.getToken(columnFamily.getKeySerializer().toByteBuffer(keys.iterator().next())).token;
return null;
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Map<K, Integer>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Map<K, Integer>>>() {
@Override
public OperationResult<Map<K, Integer>> call() throws Exception {
return execute();
}
});
}
};
}
};
}
@Override
public ColumnFamilyQuery<K, C> setConsistencyLevel(ConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return this;
}
@Override
public IndexQuery<K, C> searchWithIndex() {
return new AbstractIndexQueryImpl<K, C>(columnFamily) {
@Override
public OperationResult<Rows<K, C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Rows<K, C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_BY_INDEX, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Rows<K, C> execute(Client client, ConnectionContext context) throws ConnectionException {
if (isPaginating && paginateNoMore) {
return new EmptyRowsImpl<K, C>();
}
return super.execute(client, context);
}
@Override
public Rows<K, C> internalExecute(Client client, ConnectionContext context) throws Exception {
List<org.apache.cassandra.thrift.KeySlice> cfmap;
cfmap = client.get_indexed_slices(
new ColumnParent().setColumn_family(columnFamily.getName()), indexClause,
predicate, ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null) {
return new EmptyRowsImpl<K, C>();
}
else {
if (isPaginating) {
if (!firstPage && !cfmap.isEmpty() &&
cfmap.get(0).bufferForKey().equals(indexClause.bufferForStart_key())) {
cfmap.remove(0);
}
try {
if (!cfmap.isEmpty()) {
setNextStartKey(ByteBuffer.wrap(Iterables.getLast(cfmap).getKey()));
}
else {
paginateNoMore = true;
}
}
catch (ArithmeticException e) {
paginateNoMore = true;
}
}
return new ThriftRowsSliceImpl<K, C>(cfmap, columnFamily.getKeySerializer(),
columnFamily.getColumnSerializer());
}
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Rows<K, C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Rows<K, C>>>() {
@Override
public OperationResult<Rows<K, C>> call() throws Exception {
return execute();
}
});
}
};
}
@Override
public CqlQuery<K, C> withCql(final String cql) {
return keyspace.cqlStatementFactory.createCqlQuery(this, cql);
}
@Override
public AllRowsQuery<K, C> getAllRows() {
return new ThriftAllRowsQueryImpl<K, C>(this);
}
@Override
public ColumnFamilyQuery<K, C> pinToHost(Host host) {
this.pinnedHost = host;
return this;
}
@Override
public ColumnFamilyQuery<K, C> withRetryPolicy(RetryPolicy retry) {
this.retry = retry;
return this;
}
@Override
public RowQuery<K, C> getRow(K rowKey) {
return getKey(rowKey);
}
@Override
public RowSliceQuery<K, C> getRowRange(K startKey, K endKey, String startToken, String endToken, int count) {
return getKeyRange(startKey, endKey, startToken, endToken, count);
}
@Override
public RowSliceQuery<K, C> getRowSlice(K... keys) {
return getKeySlice(keys);
}
@Override
public RowSliceQuery<K, C> getRowSlice(Collection<K> keys) {
return getKeySlice(keys);
}
@Override
public RowSliceQuery<K, C> getRowSlice(Iterable<K> keys) {
return getKeySlice(keys);
}
}
| astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftColumnFamilyQueryImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* 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.netflix.astyanax.thrift;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.Cassandra.Client;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.CounterSuperColumn;
import org.apache.cassandra.thrift.KeyRange;
import org.apache.cassandra.thrift.Mutation;
import org.apache.cassandra.thrift.SuperColumn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.netflix.astyanax.CassandraOperationType;
import com.netflix.astyanax.KeyspaceTracerFactory;
import com.netflix.astyanax.RowCopier;
import com.netflix.astyanax.connectionpool.ConnectionPool;
import com.netflix.astyanax.connectionpool.ConnectionContext;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.model.Rows;
import com.netflix.astyanax.query.AllRowsQuery;
import com.netflix.astyanax.query.ColumnCountQuery;
import com.netflix.astyanax.query.ColumnFamilyQuery;
import com.netflix.astyanax.query.ColumnQuery;
import com.netflix.astyanax.query.CqlQuery;
import com.netflix.astyanax.query.IndexQuery;
import com.netflix.astyanax.query.RowQuery;
import com.netflix.astyanax.query.RowSliceColumnCountQuery;
import com.netflix.astyanax.query.RowSliceQuery;
import com.netflix.astyanax.retry.RetryPolicy;
import com.netflix.astyanax.shallows.EmptyColumnList;
import com.netflix.astyanax.shallows.EmptyRowsImpl;
import com.netflix.astyanax.thrift.model.*;
/**
* Implementation of all column family queries using the thrift API.
*
* @author elandau
*
* @param <K>
* @param <C>
*/
public class ThriftColumnFamilyQueryImpl<K, C> implements ColumnFamilyQuery<K, C> {
private final static Logger LOG = LoggerFactory.getLogger(ThriftColumnFamilyQueryImpl.class);
final ConnectionPool<Cassandra.Client> connectionPool;
final ColumnFamily<K, C> columnFamily;
final KeyspaceTracerFactory tracerFactory;
final ThriftKeyspaceImpl keyspace;
ConsistencyLevel consistencyLevel;
final ListeningExecutorService executor;
Host pinnedHost;
RetryPolicy retry;
public ThriftColumnFamilyQueryImpl(ExecutorService executor, KeyspaceTracerFactory tracerFactory,
ThriftKeyspaceImpl keyspace, ConnectionPool<Cassandra.Client> cp, ColumnFamily<K, C> columnFamily,
ConsistencyLevel consistencyLevel, RetryPolicy retry) {
this.keyspace = keyspace;
this.connectionPool = cp;
this.consistencyLevel = consistencyLevel;
this.columnFamily = columnFamily;
this.tracerFactory = tracerFactory;
this.executor = MoreExecutors.listeningDecorator(executor);
this.retry = retry;
}
// Single ROW query
@Override
public RowQuery<K, C> getKey(final K rowKey) {
return new AbstractRowQueryImpl<K, C>(columnFamily.getColumnSerializer()) {
private boolean firstPage = true;
@Override
public ColumnQuery<C> getColumn(final C column) {
return new ColumnQuery<C>() {
@Override
public OperationResult<Column<C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(new AbstractKeyspaceOperationImpl<Column<C>>(
tracerFactory.newTracer(CassandraOperationType.GET_COLUMN, columnFamily), pinnedHost,
keyspace.getKeyspaceName()) {
@Override
public Column<C> internalExecute(Client client, ConnectionContext context) throws Exception {
ColumnOrSuperColumn cosc = client.get(
columnFamily.getKeySerializer().toByteBuffer(rowKey),
new org.apache.cassandra.thrift.ColumnPath().setColumn_family(
columnFamily.getName()).setColumn(
columnFamily.getColumnSerializer().toByteBuffer(column)),
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
if (cosc.isSetColumn()) {
org.apache.cassandra.thrift.Column c = cosc.getColumn();
return new ThriftColumnImpl<C>(columnFamily.getColumnSerializer().fromBytes(
c.getName()), c);
}
else if (cosc.isSetSuper_column()) {
// TODO: Super columns
// should be deprecated
SuperColumn sc = cosc.getSuper_column();
return new ThriftSuperColumnImpl<C>(columnFamily.getColumnSerializer().fromBytes(
sc.getName()), sc);
}
else if (cosc.isSetCounter_column()) {
org.apache.cassandra.thrift.CounterColumn c = cosc.getCounter_column();
return new ThriftCounterColumnImpl<C>(columnFamily.getColumnSerializer().fromBytes(
c.getName()), c);
}
else if (cosc.isSetCounter_super_column()) {
// TODO: Super columns
// should be deprecated
CounterSuperColumn sc = cosc.getCounter_super_column();
return new ThriftCounterSuperColumnImpl<C>(columnFamily.getColumnSerializer()
.fromBytes(sc.getName()), sc);
}
else {
throw new RuntimeException("Unknown column type in response");
}
}
@Override
public ByteBuffer getRowKey() {
return columnFamily.getKeySerializer().toByteBuffer(rowKey);
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Column<C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Column<C>>>() {
@Override
public OperationResult<Column<C>> call() throws Exception {
return execute();
}
});
}
};
}
@Override
public OperationResult<ColumnList<C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<ColumnList<C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROW, columnFamily), pinnedHost, keyspace.getKeyspaceName()) {
@Override
public ColumnList<C> execute(Client client, ConnectionContext context) throws ConnectionException {
if (isPaginating && paginateNoMore) {
return new EmptyColumnList<C>();
}
return super.execute(client, context);
}
@Override
public ColumnList<C> internalExecute(Client client, ConnectionContext context) throws Exception {
List<ColumnOrSuperColumn> columnList = client.get_slice(columnFamily.getKeySerializer()
.toByteBuffer(rowKey), new ColumnParent().setColumn_family(columnFamily
.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
// Special handling for pagination
if (isPaginating && predicate.isSetSlice_range()) {
// Did we reach the end of the query.
if (columnList.size() != predicate.getSlice_range().getCount()) {
paginateNoMore = true;
}
// If this is the first page then adjust the
// count so we fetch one extra column
// that will later be dropped
if (firstPage) {
firstPage = false;
if (predicate.getSlice_range().getCount() != Integer.MAX_VALUE)
predicate.getSlice_range().setCount(predicate.getSlice_range().getCount() + 1);
}
else {
if (!columnList.isEmpty())
columnList.remove(0);
}
// Set the start column for the next page to
// the last column of this page.
// We will discard this column later.
if (!columnList.isEmpty()) {
ColumnOrSuperColumn last = Iterables.getLast(columnList);
if (last.isSetColumn()) {
predicate.getSlice_range().setStart(last.getColumn().getName());
} else if (last.isSetCounter_column()) {
predicate.getSlice_range().setStart(last.getCounter_column().getName());
}
}
}
ColumnList<C> result = new ThriftColumnOrSuperColumnListImpl<C>(columnList,
columnFamily.getColumnSerializer());
return result;
}
@Override
public ByteBuffer getRowKey() {
return columnFamily.getKeySerializer().toByteBuffer(rowKey);
}
}, retry);
}
@Override
public ColumnCountQuery getCount() {
return new ColumnCountQuery() {
@Override
public OperationResult<Integer> execute() throws ConnectionException {
return connectionPool.executeWithFailover(new AbstractKeyspaceOperationImpl<Integer>(
tracerFactory.newTracer(CassandraOperationType.GET_COLUMN_COUNT, columnFamily),
pinnedHost, keyspace.getKeyspaceName()) {
@Override
public Integer internalExecute(Client client, ConnectionContext context) throws Exception {
return client.get_count(columnFamily.getKeySerializer().toByteBuffer(rowKey),
new ColumnParent().setColumn_family(columnFamily.getName()), predicate,
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
}
@Override
public ByteBuffer getRowKey() {
return columnFamily.getKeySerializer().toByteBuffer(rowKey);
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Integer>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Integer>>() {
@Override
public OperationResult<Integer> call() throws Exception {
return execute();
}
});
}
};
}
@Override
public ListenableFuture<OperationResult<ColumnList<C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<ColumnList<C>>>() {
@Override
public OperationResult<ColumnList<C>> call() throws Exception {
return execute();
}
});
}
@Override
public RowCopier<K, C> copyTo(final ColumnFamily<K, C> otherColumnFamily, final K otherRowKey) {
return new RowCopier<K, C>() {
private boolean useOriginalTimestamp = true;
@Override
public OperationResult<Void> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Void>(tracerFactory.newTracer(
CassandraOperationType.COPY_TO, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Void internalExecute(Client client, ConnectionContext context) throws Exception {
long currentTime = keyspace.getConfig().getClock().getCurrentTime();
List<ColumnOrSuperColumn> columnList = client.get_slice(columnFamily
.getKeySerializer().toByteBuffer(rowKey), new ColumnParent()
.setColumn_family(columnFamily.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
// Create mutation list from columns in
// the response
List<Mutation> mutationList = new ArrayList<Mutation>();
for (ColumnOrSuperColumn sosc : columnList) {
ColumnOrSuperColumn cosc;
if (sosc.isSetColumn()) {
cosc = new ColumnOrSuperColumn().setColumn(sosc.getColumn());
if (!useOriginalTimestamp)
cosc.getColumn().setTimestamp(currentTime);
}
else if (sosc.isSetSuper_column()) {
cosc = new ColumnOrSuperColumn().setSuper_column(sosc.getSuper_column());
if (!useOriginalTimestamp) {
for (org.apache.cassandra.thrift.Column subColumn : sosc.getSuper_column().getColumns()) {
subColumn.setTimestamp(currentTime);
subColumn.setTimestamp(currentTime);
}
}
}
else if (sosc.isSetCounter_column()) {
cosc = new ColumnOrSuperColumn().setCounter_column(sosc.getCounter_column());
}
else if (sosc.isSetCounter_super_column()) {
cosc = new ColumnOrSuperColumn().setCounter_super_column(sosc.getCounter_super_column());
}
else {
continue;
}
mutationList.add(new Mutation().setColumn_or_supercolumn(cosc));
}
// Create mutation map
Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
HashMap<String, List<Mutation>> cfmap = new HashMap<String, List<Mutation>>();
cfmap.put(otherColumnFamily.getName(), mutationList);
mutationMap.put(columnFamily.getKeySerializer().toByteBuffer(otherRowKey),
cfmap);
// Execute the mutation
client.batch_mutate(mutationMap,
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
return null;
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Void>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Void>>() {
@Override
public OperationResult<Void> call() throws Exception {
return execute();
}
});
}
@Override
public RowCopier<K, C> withOriginalTimestamp(boolean useOriginalTimestamp) {
this.useOriginalTimestamp = useOriginalTimestamp;
return this;
}
};
}
};
}
@Override
public RowSliceQuery<K, C> getKeyRange(final K startKey, final K endKey, final String startToken,
final String endToken, final int count) {
return new AbstractRowSliceQueryImpl<K, C>(columnFamily.getColumnSerializer()) {
@Override
public OperationResult<Rows<K, C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Rows<K, C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_RANGE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Rows<K, C> internalExecute(Client client, ConnectionContext context) throws Exception {
// This is a sorted list
// Same call for standard and super columns via
// the ColumnParent
KeyRange range = new KeyRange();
if (startKey != null)
range.setStart_key(columnFamily.getKeySerializer().toByteBuffer(startKey));
if (endKey != null)
range.setEnd_key(columnFamily.getKeySerializer().toByteBuffer(endKey));
range.setCount(count).setStart_token(startToken).setEnd_token(endToken);
List<org.apache.cassandra.thrift.KeySlice> keySlices = client.get_range_slices(
new ColumnParent().setColumn_family(columnFamily.getName()), predicate, range,
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
if (keySlices == null || keySlices.isEmpty()) {
return new EmptyRowsImpl<K, C>();
}
else {
return new ThriftRowsSliceImpl<K, C>(keySlices, columnFamily.getKeySerializer(),
columnFamily.getColumnSerializer());
}
}
@Override
public ByteBuffer getRowKey() {
if (startKey != null)
return columnFamily.getKeySerializer().toByteBuffer(startKey);
return null;
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Rows<K, C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Rows<K, C>>>() {
@Override
public OperationResult<Rows<K, C>> call() throws Exception {
return execute();
}
});
}
@Override
public RowSliceColumnCountQuery<K> getColumnCounts() {
throw new RuntimeException("Not supported yet");
}
};
}
@Override
public RowSliceQuery<K, C> getKeySlice(final Iterable<K> keys) {
return new AbstractRowSliceQueryImpl<K, C>(columnFamily.getColumnSerializer()) {
@Override
public OperationResult<Rows<K, C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Rows<K, C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_SLICE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Rows<K, C> internalExecute(Client client, ConnectionContext context) throws Exception {
Map<ByteBuffer, List<ColumnOrSuperColumn>> cfmap = client.multiget_slice(columnFamily
.getKeySerializer().toBytesList(keys), new ColumnParent()
.setColumn_family(columnFamily.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null || cfmap.isEmpty()) {
return new EmptyRowsImpl<K, C>();
}
else {
return new ThriftRowsListImpl<K, C>(cfmap, columnFamily.getKeySerializer(),
columnFamily.getColumnSerializer());
}
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Rows<K, C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Rows<K, C>>>() {
@Override
public OperationResult<Rows<K, C>> call() throws Exception {
return execute();
}
});
}
@Override
public RowSliceColumnCountQuery<K> getColumnCounts() {
return new RowSliceColumnCountQuery<K>() {
@Override
public OperationResult<Map<K, Integer>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Map<K, Integer>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_SLICE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Map<K, Integer> internalExecute(Client client, ConnectionContext context) throws Exception {
Map<ByteBuffer, Integer> cfmap = client.multiget_count(
columnFamily.getKeySerializer().toBytesList(keys),
new ColumnParent().setColumn_family(columnFamily.getName()),
predicate,
ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null || cfmap.isEmpty()) {
return Maps.newHashMap();
}
else {
return columnFamily.getKeySerializer().fromBytesMap(cfmap);
}
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Map<K, Integer>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Map<K, Integer>>>() {
@Override
public OperationResult<Map<K, Integer>> call() throws Exception {
return execute();
}
});
}
};
}
};
}
@Override
public RowSliceQuery<K, C> getKeySlice(final K keys[]) {
return getKeySlice(Arrays.asList(keys));
}
@Override
public RowSliceQuery<K, C> getKeySlice(final Collection<K> keys) {
return new AbstractRowSliceQueryImpl<K, C>(columnFamily.getColumnSerializer()) {
@Override
public OperationResult<Rows<K, C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Rows<K, C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_SLICE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Rows<K, C> internalExecute(Client client, ConnectionContext context) throws Exception {
Map<ByteBuffer, List<ColumnOrSuperColumn>> cfmap = client.multiget_slice(columnFamily
.getKeySerializer().toBytesList(keys), new ColumnParent()
.setColumn_family(columnFamily.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null || cfmap.isEmpty()) {
return new EmptyRowsImpl<K, C>();
}
else {
return new ThriftRowsListImpl<K, C>(cfmap, columnFamily.getKeySerializer(),
columnFamily.getColumnSerializer());
}
}
@Override
public ByteBuffer getRowKey() {
// / return
// partitioner.getToken(columnFamily.getKeySerializer().toByteBuffer(keys.iterator().next())).token;
return null;
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Rows<K, C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Rows<K, C>>>() {
@Override
public OperationResult<Rows<K, C>> call() throws Exception {
return execute();
}
});
}
@Override
public RowSliceColumnCountQuery<K> getColumnCounts() {
return new RowSliceColumnCountQuery<K>() {
@Override
public OperationResult<Map<K, Integer>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Map<K, Integer>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_SLICE, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Map<K, Integer> internalExecute(Client client, ConnectionContext context) throws Exception {
Map<ByteBuffer, Integer> cfmap = client.multiget_count(columnFamily
.getKeySerializer().toBytesList(keys), new ColumnParent()
.setColumn_family(columnFamily.getName()), predicate, ThriftConverter
.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null || cfmap.isEmpty()) {
return Maps.newHashMap();
}
else {
return columnFamily.getKeySerializer().fromBytesMap(cfmap);
}
}
@Override
public ByteBuffer getRowKey() {
// / return
// partitioner.getToken(columnFamily.getKeySerializer().toByteBuffer(keys.iterator().next())).token;
return null;
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Map<K, Integer>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Map<K, Integer>>>() {
@Override
public OperationResult<Map<K, Integer>> call() throws Exception {
return execute();
}
});
}
};
}
};
}
@Override
public ColumnFamilyQuery<K, C> setConsistencyLevel(ConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return this;
}
@Override
public IndexQuery<K, C> searchWithIndex() {
return new AbstractIndexQueryImpl<K, C>(columnFamily) {
@Override
public OperationResult<Rows<K, C>> execute() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Rows<K, C>>(tracerFactory.newTracer(
CassandraOperationType.GET_ROWS_BY_INDEX, columnFamily), pinnedHost, keyspace
.getKeyspaceName()) {
@Override
public Rows<K, C> execute(Client client, ConnectionContext context) throws ConnectionException {
if (isPaginating && paginateNoMore) {
return new EmptyRowsImpl<K, C>();
}
return super.execute(client, context);
}
@Override
public Rows<K, C> internalExecute(Client client, ConnectionContext context) throws Exception {
List<org.apache.cassandra.thrift.KeySlice> cfmap;
cfmap = client.get_indexed_slices(
new ColumnParent().setColumn_family(columnFamily.getName()), indexClause,
predicate, ThriftConverter.ToThriftConsistencyLevel(consistencyLevel));
if (cfmap == null) {
return new EmptyRowsImpl<K, C>();
}
else {
if (isPaginating) {
if (!firstPage && !cfmap.isEmpty() &&
cfmap.get(0).bufferForKey().equals(indexClause.bufferForStart_key())) {
cfmap.remove(0);
}
try {
if (!cfmap.isEmpty()) {
setNextStartKey(ByteBuffer.wrap(Iterables.getLast(cfmap).getKey()));
}
else {
paginateNoMore = true;
}
}
catch (ArithmeticException e) {
paginateNoMore = true;
}
}
return new ThriftRowsSliceImpl<K, C>(cfmap, columnFamily.getKeySerializer(),
columnFamily.getColumnSerializer());
}
}
}, retry);
}
@Override
public ListenableFuture<OperationResult<Rows<K, C>>> executeAsync() throws ConnectionException {
return executor.submit(new Callable<OperationResult<Rows<K, C>>>() {
@Override
public OperationResult<Rows<K, C>> call() throws Exception {
return execute();
}
});
}
};
}
@Override
public CqlQuery<K, C> withCql(final String cql) {
return keyspace.cqlStatementFactory.createCqlQuery(this, cql);
}
@Override
public AllRowsQuery<K, C> getAllRows() {
return new ThriftAllRowsQueryImpl<K, C>(this);
}
@Override
public ColumnFamilyQuery<K, C> pinToHost(Host host) {
this.pinnedHost = host;
return this;
}
@Override
public ColumnFamilyQuery<K, C> withRetryPolicy(RetryPolicy retry) {
this.retry = retry;
return this;
}
@Override
public RowQuery<K, C> getRow(K rowKey) {
return getKey(rowKey);
}
@Override
public RowSliceQuery<K, C> getRowRange(K startKey, K endKey, String startToken, String endToken, int count) {
return getKeyRange(startKey, endKey, startToken, endToken, count);
}
@Override
public RowSliceQuery<K, C> getRowSlice(K... keys) {
return getKeySlice(keys);
}
@Override
public RowSliceQuery<K, C> getRowSlice(Collection<K> keys) {
return getKeySlice(keys);
}
@Override
public RowSliceQuery<K, C> getRowSlice(Iterable<K> keys) {
return getKeySlice(keys);
}
}
| Support super columns for auto pagination
Although deprecated for consistency auto pagination for super columns can be supported | astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftColumnFamilyQueryImpl.java | Support super columns for auto pagination |
|
Java | apache-2.0 | 8e712dd3253026cbf422a74acc7331952e2c9ae4 | 0 | cash1981/civilization-boardgame-rest | package no.asgari.civilization.server.resource;
import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.action.GameAction;
import no.asgari.civilization.server.application.CivCache;
import no.asgari.civilization.server.dto.CreateNewGameDTO;
import no.asgari.civilization.server.dto.PbfDTO;
import no.asgari.civilization.server.model.Draw;
import no.asgari.civilization.server.model.PBF;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.Undo;
import org.mongojack.JacksonDBCollection;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.List;
@Path("/game")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Log4j
public class GameResource {
@Context
private UriInfo uriInfo;
private final JacksonDBCollection<Draw, String> drawCollection;
private final JacksonDBCollection<PBF, String> pbfCollection;
private final JacksonDBCollection<Player, String> playerCollection;
private final JacksonDBCollection<Undo, String> undoActionCollection;
public GameResource(JacksonDBCollection<PBF, String> pbfCollection, JacksonDBCollection<Player, String> playerCollection,
JacksonDBCollection<Draw, String> drawCollection, JacksonDBCollection<Undo, String> undoActionCollection) {
this.playerCollection = playerCollection;
this.pbfCollection = pbfCollection;
this.drawCollection = drawCollection;
this.undoActionCollection = undoActionCollection;
}
/**
* This is the default method for this resource.
* It will return all active games
* @return
*/
@GET
@Timed
@Produces(MediaType.APPLICATION_JSON)
public Response getAllGames() {
GameAction gameAction = new GameAction(pbfCollection, playerCollection);
List<PbfDTO> games = gameAction.getAllActiveGames(pbfCollection);
return Response.ok()
.entity(games)
.build();
}
@POST
@Timed
//TODO @Valid
public Response createGame(CreateNewGameDTO dto, @CookieParam("username") String username, @CookieParam("token") String token) {
Preconditions.checkNotNull(dto);
if(!hasCookies(username, token)) {
return Response.temporaryRedirect(
uriInfo.getBaseUriBuilder().path("/login").build())
.build();
}
boolean isLoggedIn = CivCache.getInstance().findUser(username, token);
if(!isLoggedIn) {
return Response.status(Response.Status.FORBIDDEN)
.location(uriInfo.getBaseUriBuilder().path("/login").build())
.build();
}
log.info("Creating game " + dto);
GameAction gameAction = new GameAction(pbfCollection, playerCollection);
String id = gameAction.createNewGame(dto);
return Response.status(Response.Status.CREATED)
.location(uriInfo.getAbsolutePathBuilder().path(id).build())
.build();
}
@PUT
@Timed
@Path("{pbfId}")
//TODO Implement Auth. For now its done manually with cookies and token
public Response joinGame(@PathParam("pbfId") String pbfId, @CookieParam("username") String username, @CookieParam("token") String token) {
if(!hasCookies(username, token)) {
return Response.temporaryRedirect(
uriInfo.getBaseUriBuilder().path("/login").build())
.build();
}
boolean isLoggedIn = CivCache.getInstance().findUser(username, token);
if(!isLoggedIn) {
return Response.status(Response.Status.FORBIDDEN)
.location(uriInfo.getBaseUriBuilder().path("/login").build())
.build();
}
GameAction gameAction = new GameAction(pbfCollection, playerCollection);
gameAction.joinGame(pbfId, username);
return Response.ok()
.location(uriInfo.getAbsolutePath())
.build();
}
private boolean hasCookies(String username, String token) {
return !(Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(token));
}
}
| civilization-server/src/main/java/no/asgari/civilization/server/resource/GameResource.java | package no.asgari.civilization.server.resource;
import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.action.GameAction;
import no.asgari.civilization.server.application.CivCache;
import no.asgari.civilization.server.dto.CreateNewGameDTO;
import no.asgari.civilization.server.dto.PbfDTO;
import no.asgari.civilization.server.model.Draw;
import no.asgari.civilization.server.model.PBF;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.Undo;
import org.mongojack.JacksonDBCollection;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.List;
@Path("/game")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Log4j
public class GameResource {
@Context
private UriInfo uriInfo;
private final JacksonDBCollection<Draw, String> drawCollection;
private final JacksonDBCollection<PBF, String> pbfCollection;
private final JacksonDBCollection<Player, String> playerCollection;
private final JacksonDBCollection<Undo, String> undoActionCollection;
public GameResource(JacksonDBCollection<PBF, String> pbfCollection, JacksonDBCollection<Player, String> playerCollection,
JacksonDBCollection<Draw, String> drawCollection, JacksonDBCollection<Undo, String> undoActionCollection) {
this.playerCollection = playerCollection;
this.pbfCollection = pbfCollection;
this.drawCollection = drawCollection;
this.undoActionCollection = undoActionCollection;
}
/**
* This is the default method for this resource.
* It will return all active games
* @return
*/
@GET
@Timed
@Produces(MediaType.APPLICATION_JSON)
public Response getAllGames() {
GameAction gameAction = new GameAction(pbfCollection, playerCollection);
List<PbfDTO> games = gameAction.getAllActiveGames(pbfCollection);
return Response.ok()
.entity(games)
.build();
}
@POST
@Timed
//TODO @Valid
public Response createGame(CreateNewGameDTO dto, @CookieParam("username") String username, @CookieParam("token") String token) {
Preconditions.checkNotNull(dto);
if(!hasCookies(username, token)) {
return Response.temporaryRedirect(
uriInfo.getBaseUriBuilder().path("/login").build())
.build();
}
boolean isLoggedIn = CivCache.getInstance().findUser(username, token);
if(!isLoggedIn) {
return Response.status(Response.Status.FORBIDDEN)
.location(uriInfo.getBaseUriBuilder().path("/login").build())
.build();
}
log.info("Creating game " + dto);
GameAction gameAction = new GameAction(pbfCollection, playerCollection);
String id = gameAction.createNewGame(dto);
return Response.status(Response.Status.CREATED)
.location(uriInfo.getAbsolutePathBuilder().path(id).build())
.build();
}
@PUT
@Timed
@Path("{pbfId}")
//TODO Implement Auth. For now its done manually with cookies and token
public Response joinGame(@PathParam("pbfId") String pbfId, @CookieParam("username") String username, @CookieParam("token") String token) {
if(hasCookies(username, token)) {
return Response.temporaryRedirect(
uriInfo.getBaseUriBuilder().path("/login").build())
.build();
}
boolean isLoggedIn = CivCache.getInstance().findUser(username, token);
if(!isLoggedIn) {
return Response.status(Response.Status.FORBIDDEN)
.location(uriInfo.getBaseUriBuilder().path("/login").build())
.build();
}
GameAction gameAction = new GameAction(pbfCollection, playerCollection);
gameAction.joinGame(pbfId, username);
return Response.ok()
.location(uriInfo.getAbsolutePath())
.build();
}
private boolean hasCookies(String username, String token) {
return !(Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(token));
}
}
| Fixed a small bug
| civilization-server/src/main/java/no/asgari/civilization/server/resource/GameResource.java | Fixed a small bug |
|
Java | bsd-2-clause | 1bdfe4b0fd129d3dfc99e5e6b54f619d9100fcca | 0 | runelite/runelite,runelite/runelite,runelite/runelite | /*
* Copyright (c) 2019, Twiglet1022 <https://github.com/Twiglet1022>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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 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 net.runelite.client.plugins.cluescrolls.clues;
import com.google.common.collect.ImmutableList;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.List;
import javax.annotation.Nonnull;
import lombok.Getter;
import net.runelite.api.Item;
import net.runelite.api.NPC;
import net.runelite.api.coords.WorldPoint;
import static net.runelite.api.ItemID.*;
import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR;
import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET;
import net.runelite.client.plugins.cluescrolls.clues.item.AnyRequirementCollection;
import net.runelite.client.plugins.cluescrolls.clues.item.ItemRequirement;
import net.runelite.client.plugins.cluescrolls.clues.item.RangeItemRequirement;
import net.runelite.client.plugins.cluescrolls.clues.item.SingleItemRequirement;
import net.runelite.client.ui.FontManager;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.components.LineComponent;
import net.runelite.client.ui.overlay.components.PanelComponent;
import net.runelite.client.ui.overlay.components.TitleComponent;
@Getter
public class FaloTheBardClue extends ClueScroll implements TextClueScroll, NpcClueScroll
{
private static final List<FaloTheBardClue> CLUES = ImmutableList.of(
new FaloTheBardClue("A blood red weapon, a strong curved sword, found on the island of primate lords.", any("Dragon scimitar", item(DRAGON_SCIMITAR), item(DRAGON_SCIMITAR_OR))),
new FaloTheBardClue("A book that preaches of some great figure, lending strength, might and vigour.", any("Any god book (must be complete)", item(HOLY_BOOK), item(BOOK_OF_BALANCE), item(UNHOLY_BOOK), item(BOOK_OF_LAW), item(BOOK_OF_WAR), item(BOOK_OF_DARKNESS))),
new FaloTheBardClue("A bow of elven craft was made, it shimmers bright, but will soon fade.", any("Crystal Bow", item(CRYSTAL_BOW), item(CRYSTAL_BOW_24123))),
new FaloTheBardClue("A fiery axe of great inferno, when you use it, you'll wonder where the logs go.", any("Infernal axe", item(INFERNAL_AXE), item(INFERNAL_AXE_OR))),
new FaloTheBardClue("A mark used to increase one's grace, found atop a seer's place.", item(MARK_OF_GRACE)),
new FaloTheBardClue("A molten beast with fiery breath, you acquire these with its death.", item(LAVA_DRAGON_BONES)),
new FaloTheBardClue("A shiny helmet of flight, to obtain this with melee, struggle you might.", item(ARMADYL_HELMET)),
new FaloTheBardClue("A sword held in the other hand, red its colour, Cyclops strength you must withstand.", any("Dragon or Avernic Defender", item(DRAGON_DEFENDER), item(DRAGON_DEFENDER_T), item(DRAGON_DEFENDER_L), item(AVERNIC_DEFENDER), item(AVERNIC_DEFENDER_L))),
new FaloTheBardClue("A token used to kill mythical beasts, in hopes of a blade or just for an xp feast.", item(WARRIOR_GUILD_TOKEN)),
new FaloTheBardClue("Green is my favourite, mature ale I do love, this takes your herblore above.", item(GREENMANS_ALEM)),
new FaloTheBardClue("It can hold down a boat or crush a goat, this object, you see, is quite heavy.", item(BARRELCHEST_ANCHOR)),
new FaloTheBardClue("It comes from the ground, underneath the snowy plain. Trolls aplenty, with what looks like a mane.", item(BASALT)),
new FaloTheBardClue("No attack to wield, only strength is required, made of obsidian, but with no room for a shield.", any("Tzhaar-ket-om", item(TZHAARKETOM), item(TZHAARKETOM_T))),
new FaloTheBardClue("Penance healers runners and more, obtaining this body often gives much deplore.", any("Fighter Torso", item(FIGHTER_TORSO), item(FIGHTER_TORSO_L))),
new FaloTheBardClue("Strangely found in a chest, many believe these gloves are the best.", item(BARROWS_GLOVES)),
new FaloTheBardClue("These gloves of white won't help you fight, but aid in cooking, they just might.", item(COOKING_GAUNTLETS)),
new FaloTheBardClue("They come from some time ago, from a land unto the east. Fossilised they have become, this small and gentle beast.", item(NUMULITE)),
new FaloTheBardClue("To slay a dragon you must first do, before this chest piece can be put on you.", item(RUNE_PLATEBODY)),
new FaloTheBardClue("Vampyres are agile opponents, damaged best with a weapon of many components.", any("Rod of Ivandis or Ivandis/Blisterwood flail", range(ROD_OF_IVANDIS_10, ROD_OF_IVANDIS_1), item(IVANDIS_FLAIL), item(BLISTERWOOD_FLAIL)))
);
private static final WorldPoint LOCATION = new WorldPoint(2689, 3550, 0);
private static final String FALO_THE_BARD = "Falo the Bard";
private static SingleItemRequirement item(int itemId)
{
return new SingleItemRequirement(itemId);
}
private static AnyRequirementCollection any(String name, ItemRequirement... requirements)
{
return new AnyRequirementCollection(name, requirements);
}
private static RangeItemRequirement range(int startItemId, int endItemId)
{
return range(null, startItemId, endItemId);
}
private static RangeItemRequirement range(String name, int startItemId, int endItemId)
{
return new RangeItemRequirement(name, startItemId, endItemId);
}
private final String text;
@Nonnull
private final ItemRequirement[] itemRequirements;
private FaloTheBardClue(String text, @Nonnull ItemRequirement... itemRequirements)
{
this.text = text;
this.itemRequirements = itemRequirements;
}
@Override
public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin)
{
panelComponent.getChildren().add(TitleComponent.builder().text("Falo the Bard Clue").build());
panelComponent.getChildren().add(LineComponent.builder().left("NPC:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(FALO_THE_BARD)
.leftColor(TITLED_CONTENT_COLOR)
.build());
panelComponent.getChildren().add(LineComponent.builder().left("Item:").build());
Item[] inventory = plugin.getInventoryItems();
// If inventory is null, the player has nothing in their inventory
if (inventory == null)
{
inventory = new Item[0];
}
for (ItemRequirement requirement : itemRequirements)
{
boolean inventoryFulfilled = requirement.fulfilledBy(inventory);
panelComponent.getChildren().add(LineComponent.builder()
.left(requirement.getCollectiveName(plugin.getClient()))
.leftColor(TITLED_CONTENT_COLOR)
.right(inventoryFulfilled ? "\u2713" : "\u2717")
.rightFont(FontManager.getDefaultFont())
.rightColor(inventoryFulfilled ? Color.GREEN : Color.RED)
.build());
}
}
@Override
public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin)
{
if (!LOCATION.isInScene(plugin.getClient()))
{
return;
}
for (NPC npc : plugin.getNpcsToMark())
{
OverlayUtil.renderActorOverlayImage(graphics, npc, plugin.getClueScrollImage(), Color.ORANGE, IMAGE_Z_OFFSET);
}
}
@Override
public String[] getNpcs()
{
return new String[] {FALO_THE_BARD};
}
public static FaloTheBardClue forText(String text)
{
for (FaloTheBardClue clue : CLUES)
{
if (clue.text.equalsIgnoreCase(text))
{
return clue;
}
}
return null;
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/cluescrolls/clues/FaloTheBardClue.java | /*
* Copyright (c) 2019, Twiglet1022 <https://github.com/Twiglet1022>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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 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 net.runelite.client.plugins.cluescrolls.clues;
import com.google.common.collect.ImmutableList;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.List;
import javax.annotation.Nonnull;
import lombok.Getter;
import net.runelite.api.Item;
import net.runelite.api.NPC;
import net.runelite.api.coords.WorldPoint;
import static net.runelite.api.ItemID.*;
import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR;
import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET;
import net.runelite.client.plugins.cluescrolls.clues.item.AnyRequirementCollection;
import net.runelite.client.plugins.cluescrolls.clues.item.ItemRequirement;
import net.runelite.client.plugins.cluescrolls.clues.item.RangeItemRequirement;
import net.runelite.client.plugins.cluescrolls.clues.item.SingleItemRequirement;
import net.runelite.client.ui.FontManager;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.components.LineComponent;
import net.runelite.client.ui.overlay.components.PanelComponent;
import net.runelite.client.ui.overlay.components.TitleComponent;
@Getter
public class FaloTheBardClue extends ClueScroll implements TextClueScroll, NpcClueScroll
{
private static final List<FaloTheBardClue> CLUES = ImmutableList.of(
new FaloTheBardClue("A blood red weapon, a strong curved sword, found on the island of primate lords.", any("Dragon scimitar", item(DRAGON_SCIMITAR), item(DRAGON_SCIMITAR_OR))),
new FaloTheBardClue("A book that preaches of some great figure, lending strength, might and vigour.", any("Any god book (must be complete)", item(HOLY_BOOK), item(BOOK_OF_BALANCE), item(UNHOLY_BOOK), item(BOOK_OF_LAW), item(BOOK_OF_WAR), item(BOOK_OF_DARKNESS))),
new FaloTheBardClue("A bow of elven craft was made, it shimmers bright, but will soon fade.", any("Crystal Bow", item(CRYSTAL_BOW), item(CRYSTAL_BOW_24123))),
new FaloTheBardClue("A fiery axe of great inferno, when you use it, you'll wonder where the logs go.", any("Infernal axe", item(INFERNAL_AXE), item(INFERNAL_AXE_OR))),
new FaloTheBardClue("A mark used to increase one's grace, found atop a seer's place.", item(MARK_OF_GRACE)),
new FaloTheBardClue("A molten beast with fiery breath, you acquire these with its death.", item(LAVA_DRAGON_BONES)),
new FaloTheBardClue("A shiny helmet of flight, to obtain this with melee, struggle you might.", item(ARMADYL_HELMET)),
// The wiki doesn't specify whether the trimmed dragon defender will work so I've assumed that it doesn't
new FaloTheBardClue("A sword held in the other hand, red its colour, Cyclops strength you must withstand.", any("Dragon or Avernic Defender", item(DRAGON_DEFENDER), item(DRAGON_DEFENDER_L), item(AVERNIC_DEFENDER), item(AVERNIC_DEFENDER_L))),
new FaloTheBardClue("A token used to kill mythical beasts, in hopes of a blade or just for an xp feast.", item(WARRIOR_GUILD_TOKEN)),
new FaloTheBardClue("Green is my favourite, mature ale I do love, this takes your herblore above.", item(GREENMANS_ALEM)),
new FaloTheBardClue("It can hold down a boat or crush a goat, this object, you see, is quite heavy.", item(BARRELCHEST_ANCHOR)),
new FaloTheBardClue("It comes from the ground, underneath the snowy plain. Trolls aplenty, with what looks like a mane.", item(BASALT)),
new FaloTheBardClue("No attack to wield, only strength is required, made of obsidian, but with no room for a shield.", item(TZHAARKETOM)),
new FaloTheBardClue("Penance healers runners and more, obtaining this body often gives much deplore.", any("Fighter Torso", item(FIGHTER_TORSO), item(FIGHTER_TORSO_L))),
new FaloTheBardClue("Strangely found in a chest, many believe these gloves are the best.", item(BARROWS_GLOVES)),
new FaloTheBardClue("These gloves of white won't help you fight, but aid in cooking, they just might.", item(COOKING_GAUNTLETS)),
new FaloTheBardClue("They come from some time ago, from a land unto the east. Fossilised they have become, this small and gentle beast.", item(NUMULITE)),
new FaloTheBardClue("To slay a dragon you must first do, before this chest piece can be put on you.", item(RUNE_PLATEBODY)),
new FaloTheBardClue("Vampyres are agile opponents, damaged best with a weapon of many components.", any("Rod of Ivandis or Ivandis/Blisterwood flail", range(ROD_OF_IVANDIS_10, ROD_OF_IVANDIS_1), item(IVANDIS_FLAIL), item(BLISTERWOOD_FLAIL)))
);
private static final WorldPoint LOCATION = new WorldPoint(2689, 3550, 0);
private static final String FALO_THE_BARD = "Falo the Bard";
private static SingleItemRequirement item(int itemId)
{
return new SingleItemRequirement(itemId);
}
private static AnyRequirementCollection any(String name, ItemRequirement... requirements)
{
return new AnyRequirementCollection(name, requirements);
}
private static RangeItemRequirement range(int startItemId, int endItemId)
{
return range(null, startItemId, endItemId);
}
private static RangeItemRequirement range(String name, int startItemId, int endItemId)
{
return new RangeItemRequirement(name, startItemId, endItemId);
}
private final String text;
@Nonnull
private final ItemRequirement[] itemRequirements;
private FaloTheBardClue(String text, @Nonnull ItemRequirement... itemRequirements)
{
this.text = text;
this.itemRequirements = itemRequirements;
}
@Override
public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin)
{
panelComponent.getChildren().add(TitleComponent.builder().text("Falo the Bard Clue").build());
panelComponent.getChildren().add(LineComponent.builder().left("NPC:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(FALO_THE_BARD)
.leftColor(TITLED_CONTENT_COLOR)
.build());
panelComponent.getChildren().add(LineComponent.builder().left("Item:").build());
Item[] inventory = plugin.getInventoryItems();
// If inventory is null, the player has nothing in their inventory
if (inventory == null)
{
inventory = new Item[0];
}
for (ItemRequirement requirement : itemRequirements)
{
boolean inventoryFulfilled = requirement.fulfilledBy(inventory);
panelComponent.getChildren().add(LineComponent.builder()
.left(requirement.getCollectiveName(plugin.getClient()))
.leftColor(TITLED_CONTENT_COLOR)
.right(inventoryFulfilled ? "\u2713" : "\u2717")
.rightFont(FontManager.getDefaultFont())
.rightColor(inventoryFulfilled ? Color.GREEN : Color.RED)
.build());
}
}
@Override
public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin)
{
if (!LOCATION.isInScene(plugin.getClient()))
{
return;
}
for (NPC npc : plugin.getNpcsToMark())
{
OverlayUtil.renderActorOverlayImage(graphics, npc, plugin.getClueScrollImage(), Color.ORANGE, IMAGE_Z_OFFSET);
}
}
@Override
public String[] getNpcs()
{
return new String[] {FALO_THE_BARD};
}
public static FaloTheBardClue forText(String text)
{
for (FaloTheBardClue clue : CLUES)
{
if (clue.text.equalsIgnoreCase(text))
{
return clue;
}
}
return null;
}
}
| FaloTheBardClue: Accept trimmed Dragon defender and Tzhaar-ket-om (#13317)
| runelite-client/src/main/java/net/runelite/client/plugins/cluescrolls/clues/FaloTheBardClue.java | FaloTheBardClue: Accept trimmed Dragon defender and Tzhaar-ket-om (#13317) |
|
Java | bsd-3-clause | 020612f920fb2e96aa1d7e175783dca8a90e6c01 | 0 | msf-oca-his/dhis2-core,msf-oca-his/dhis2-core,dhis2/dhis2-core,hispindia/dhis2-Core,hispindia/dhis2-Core,msf-oca-his/dhis2-core,vietnguyen/dhis2-core,vietnguyen/dhis2-core,msf-oca-his/dhis-core,msf-oca-his/dhis-core,vietnguyen/dhis2-core,vietnguyen/dhis2-core,hispindia/dhis2-Core,vietnguyen/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,dhis2/dhis2-core,hispindia/dhis2-Core,msf-oca-his/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis-core,msf-oca-his/dhis-core,hispindia/dhis2-Core | package org.hisp.dhis.dxf2.datavalueset;
/*
* 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 com.google.common.collect.Sets;
import org.hisp.dhis.DhisTest;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dataset.DataSetService;
import org.hisp.dhis.datavalue.DataValueService;
import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.importsummary.ImportStatus;
import org.hisp.dhis.dxf2.importsummary.ImportSummary;
import org.hisp.dhis.importexport.ImportStrategy;
import org.hisp.dhis.mock.MockCurrentUserService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.MonthlyPeriodType;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodService;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.User;
import org.hisp.dhis.user.UserService;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import java.io.InputStream;
import static org.junit.Assert.assertEquals;
/**
* @author Lars Helge Overland
*/
@Ignore // TOOD fix, ignore for now
public class DataValueSetServiceIntegrationTest
extends DhisTest
{
@Autowired
private IdentifiableObjectManager idObjectManager;
@Autowired
private DataSetService dataSetService;
@Autowired
private PeriodService periodService;
@Autowired
private DataValueSetService dataValueSetService;
@Autowired
private DataValueService dataValueService;
@Autowired
private UserService _userService;
private DataElement deA;
private DataElement deB;
private DataElement deC;
private PeriodType ptA;
private DataSet dsA;
private Period peA;
private Period peB;
private Period peC;
private OrganisationUnit ouA;
private OrganisationUnit ouB;
private OrganisationUnit ouC;
private User user;
private InputStream in;
@Override
public void setUpTest()
{
userService = _userService;
deA = createDataElement( 'A' );
deB = createDataElement( 'B' );
deC = createDataElement( 'C' );
deA.setUid( "f7n9E0hX8qk" );
deB.setUid( "Ix2HsbDMLea" );
deC.setUid( "eY5ehpbEsB7" );
idObjectManager.save( deA );
idObjectManager.save( deB );
idObjectManager.save( deC );
ptA = new MonthlyPeriodType();
dsA = createDataSet( 'A', ptA );
dsA.setUid( "pBOMPrpg1QX" );
dataSetService.addDataSet( dsA );
peA = createPeriod( PeriodType.getByNameIgnoreCase( MonthlyPeriodType.NAME ), getDate( 2012, 1, 1 ), getDate( 2012, 1, 31 ) );
peB = createPeriod( PeriodType.getByNameIgnoreCase( MonthlyPeriodType.NAME ), getDate( 2012, 2, 1 ), getDate( 2012, 2, 29 ) );
peC = createPeriod( PeriodType.getByNameIgnoreCase( MonthlyPeriodType.NAME ), getDate( 2012, 3, 1 ), getDate( 2012, 3, 31 ) );
periodService.addPeriod( peA );
periodService.addPeriod( peB );
periodService.addPeriod( peC );
ouA = createOrganisationUnit( 'A' );
ouB = createOrganisationUnit( 'B' );
ouC = createOrganisationUnit( 'C' );
ouA.setUid( "DiszpKrYNg8" );
ouB.setUid( "BdfsJfj87js" );
ouC.setUid( "j7Hg26FpoIa" );
idObjectManager.save( ouA );
idObjectManager.save( ouB );
idObjectManager.save( ouC );
user = createAndInjectAdminUser();
user.setOrganisationUnits( Sets.newHashSet( ouA, ouB, ouC ) );
CurrentUserService currentUserService = new MockCurrentUserService( user );
setDependency( dataValueSetService, "currentUserService", currentUserService );
}
@Override
public boolean emptyDatabaseAfterTest()
{
return true;
}
// -------------------------------------------------------------------------
// Tests
// -------------------------------------------------------------------------
/**
* Import 3 data values, then delete 3 data values.
*/
@Test
public void testImportDeleteValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetA.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 3, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 3, dataValueService.getAllDataValues().size() );
// Delete values
in = new ClassPathResource( "datavalueset/dataValueSetADeleted.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 0, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 3, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 0, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values.
*/
@Test
public void testImportValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values. Then import 6 data values, where 4 are updates.
*/
@Test
public void testImportUpdateValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
// Update
in = new ClassPathResource( "datavalueset/dataValueSetBUpdate.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 2, summary.getImportCount().getImported() );
assertEquals( 4, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 14, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values where 4 are marked as deleted. Deleted values should
* count as imports when there are no existing non-deleted matching values.
*/
@Test
public void testImportDeletedValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetBDeleted.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 8, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values where 4 are marked as deleted. Then import 12 data
* values which reverse deletion of the 4 values and update the other 8
* values.
*/
@Test
public void testImportReverseDeletedValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetBDeleted.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 8, dataValueService.getAllDataValues().size() );
// Reverse deletion and update
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 4, summary.getImportCount().getImported() );
assertEquals( 8, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values where 4 are marked as deleted. Then import 12 data
* values which reverse deletion of the 4 values, update 4 values and add 4
* values.
*/
@Test
public void testImportAddAndReverseDeletedValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetBDeleted.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 8, dataValueService.getAllDataValues().size() );
// Reverse deletion and update
in = new ClassPathResource( "datavalueset/dataValueSetBNew.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 8, summary.getImportCount().getImported() );
assertEquals( 4, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 16, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values. Then import 12 values where 4 are marked as
* deleted.
*/
@Test
public void testDeleteValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
// Delete 4 values
in = new ClassPathResource( "datavalueset/dataValueSetBDeleted.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 0, summary.getImportCount().getImported() );
assertEquals( 8, summary.getImportCount().getUpdated() );
assertEquals( 4, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 8, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values. Then import 12 values where 4 are marked as
* deleted, 6 are updates and 2 are new.
*/
@Test
public void testImportAndDeleteValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
// Delete 4 values, add 2 values
in = new ClassPathResource( "datavalueset/dataValueSetBNewDeleted.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 2, summary.getImportCount().getImported() );
assertEquals( 6, summary.getImportCount().getUpdated() );
assertEquals( 4, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 10, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values. Then import the same 12 data values with import
* strategy delete.
*/
@Test
public void testImportValuesDeleteStrategyXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
// Import with delete strategy
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportOptions options = new ImportOptions()
.setStrategy( ImportStrategy.DELETE );
summary = dataValueSetService.saveDataValueSet( in, options );
assertEquals( 0, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 12, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 0, dataValueService.getAllDataValues().size() );
}
}
| dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/datavalueset/DataValueSetServiceIntegrationTest.java | package org.hisp.dhis.dxf2.datavalueset;
/*
* 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 com.google.common.collect.Sets;
import org.hisp.dhis.DhisTest;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dataset.DataSetService;
import org.hisp.dhis.datavalue.DataValueService;
import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.importsummary.ImportStatus;
import org.hisp.dhis.dxf2.importsummary.ImportSummary;
import org.hisp.dhis.importexport.ImportStrategy;
import org.hisp.dhis.mock.MockCurrentUserService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.MonthlyPeriodType;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodService;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.User;
import org.hisp.dhis.user.UserService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import java.io.InputStream;
import static org.junit.Assert.assertEquals;
/**
* @author Lars Helge Overland
*/
public class DataValueSetServiceIntegrationTest
extends DhisTest
{
@Autowired
private IdentifiableObjectManager idObjectManager;
@Autowired
private DataSetService dataSetService;
@Autowired
private PeriodService periodService;
@Autowired
private DataValueSetService dataValueSetService;
@Autowired
private DataValueService dataValueService;
@Autowired
private UserService _userService;
private DataElement deA;
private DataElement deB;
private DataElement deC;
private PeriodType ptA;
private DataSet dsA;
private Period peA;
private Period peB;
private Period peC;
private OrganisationUnit ouA;
private OrganisationUnit ouB;
private OrganisationUnit ouC;
private User user;
private InputStream in;
@Override
public void setUpTest()
{
userService = _userService;
deA = createDataElement( 'A' );
deB = createDataElement( 'B' );
deC = createDataElement( 'C' );
deA.setUid( "f7n9E0hX8qk" );
deB.setUid( "Ix2HsbDMLea" );
deC.setUid( "eY5ehpbEsB7" );
idObjectManager.save( deA );
idObjectManager.save( deB );
idObjectManager.save( deC );
ptA = new MonthlyPeriodType();
dsA = createDataSet( 'A', ptA );
dsA.setUid( "pBOMPrpg1QX" );
dataSetService.addDataSet( dsA );
peA = createPeriod( PeriodType.getByNameIgnoreCase( MonthlyPeriodType.NAME ), getDate( 2012, 1, 1 ), getDate( 2012, 1, 31 ) );
peB = createPeriod( PeriodType.getByNameIgnoreCase( MonthlyPeriodType.NAME ), getDate( 2012, 2, 1 ), getDate( 2012, 2, 29 ) );
peC = createPeriod( PeriodType.getByNameIgnoreCase( MonthlyPeriodType.NAME ), getDate( 2012, 3, 1 ), getDate( 2012, 3, 31 ) );
periodService.addPeriod( peA );
periodService.addPeriod( peB );
periodService.addPeriod( peC );
ouA = createOrganisationUnit( 'A' );
ouB = createOrganisationUnit( 'B' );
ouC = createOrganisationUnit( 'C' );
ouA.setUid( "DiszpKrYNg8" );
ouB.setUid( "BdfsJfj87js" );
ouC.setUid( "j7Hg26FpoIa" );
idObjectManager.save( ouA );
idObjectManager.save( ouB );
idObjectManager.save( ouC );
user = createAndInjectAdminUser();
user.setOrganisationUnits( Sets.newHashSet( ouA, ouB, ouC ) );
CurrentUserService currentUserService = new MockCurrentUserService( user );
setDependency( dataValueSetService, "currentUserService", currentUserService );
}
@Override
public boolean emptyDatabaseAfterTest()
{
return true;
}
// -------------------------------------------------------------------------
// Tests
// -------------------------------------------------------------------------
/**
* Import 3 data values, then delete 3 data values.
*/
@Test
public void testImportDeleteValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetA.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 3, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 3, dataValueService.getAllDataValues().size() );
// Delete values
in = new ClassPathResource( "datavalueset/dataValueSetADeleted.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 0, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 3, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 0, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values.
*/
@Test
public void testImportValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values. Then import 6 data values, where 4 are updates.
*/
@Test
public void testImportUpdateValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
// Update
in = new ClassPathResource( "datavalueset/dataValueSetBUpdate.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 2, summary.getImportCount().getImported() );
assertEquals( 4, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 14, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values where 4 are marked as deleted. Deleted values should
* count as imports when there are no existing non-deleted matching values.
*/
@Test
public void testImportDeletedValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetBDeleted.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 8, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values where 4 are marked as deleted. Then import 12 data
* values which reverse deletion of the 4 values and update the other 8
* values.
*/
@Test
public void testImportReverseDeletedValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetBDeleted.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 8, dataValueService.getAllDataValues().size() );
// Reverse deletion and update
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 4, summary.getImportCount().getImported() );
assertEquals( 8, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values where 4 are marked as deleted. Then import 12 data
* values which reverse deletion of the 4 values, update 4 values and add 4
* values.
*/
@Test
public void testImportAddAndReverseDeletedValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetBDeleted.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 8, dataValueService.getAllDataValues().size() );
// Reverse deletion and update
in = new ClassPathResource( "datavalueset/dataValueSetBNew.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 8, summary.getImportCount().getImported() );
assertEquals( 4, summary.getImportCount().getUpdated() );
assertEquals( 0, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 16, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values. Then import 12 values where 4 are marked as
* deleted.
*/
@Test
public void testDeleteValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
// Delete 4 values
in = new ClassPathResource( "datavalueset/dataValueSetBDeleted.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 0, summary.getImportCount().getImported() );
assertEquals( 8, summary.getImportCount().getUpdated() );
assertEquals( 4, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 8, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values. Then import 12 values where 4 are marked as
* deleted, 6 are updates and 2 are new.
*/
@Test
public void testImportAndDeleteValuesXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
// Delete 4 values, add 2 values
in = new ClassPathResource( "datavalueset/dataValueSetBNewDeleted.xml" ).getInputStream();
summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 2, summary.getImportCount().getImported() );
assertEquals( 6, summary.getImportCount().getUpdated() );
assertEquals( 4, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 10, dataValueService.getAllDataValues().size() );
}
/**
* Import 12 data values. Then import the same 12 data values with import
* strategy delete.
*/
@Test
public void testImportValuesDeleteStrategyXml()
throws Exception
{
assertEquals( 0, dataValueService.getAllDataValues().size() );
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportSummary summary = dataValueSetService.saveDataValueSet( in );
assertEquals( 12, summary.getImportCount().getImported() );
assertEquals( 12, dataValueService.getAllDataValues().size() );
// Import with delete strategy
in = new ClassPathResource( "datavalueset/dataValueSetB.xml" ).getInputStream();
ImportOptions options = new ImportOptions()
.setStrategy( ImportStrategy.DELETE );
summary = dataValueSetService.saveDataValueSet( in, options );
assertEquals( 0, summary.getImportCount().getImported() );
assertEquals( 0, summary.getImportCount().getUpdated() );
assertEquals( 12, summary.getImportCount().getDeleted() );
assertEquals( summary.getConflicts().toString(), 0, summary.getConflicts().size() );
assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
assertEquals( 0, dataValueService.getAllDataValues().size() );
}
}
| Ignoring DataValueSetServiceIntegrationTest for now (#2372)
| dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/datavalueset/DataValueSetServiceIntegrationTest.java | Ignoring DataValueSetServiceIntegrationTest for now (#2372) |
|
Java | bsd-3-clause | 67ad5f554b379bc4840026dc3a6b5974f5fd5f7e | 0 | synergynet/synergynet3.1,synergynet/synergynet3.1 | package synergynet3.activitypack2.table.flickandscreenshotmysteries;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.UUID;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import multiplicity3.appsystem.MultiplicityClient;
import multiplicity3.csys.factory.ContentTypeNotBoundException;
import multiplicity3.csys.items.image.IImage;
import multiplicity3.csys.items.item.IItem;
import multiplicity3.input.MultiTouchEventAdapter;
import multiplicity3.input.events.MultiTouchCursorEvent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import synergynet3.SynergyNetApp;
import synergynet3.additionalUtils.AdditionalSynergyNetUtilities;
import synergynet3.additionalitems.interfaces.ITextbox;
import synergynet3.behaviours.networkflick.NetworkFlickBehaviour;
import synergynet3.feedbacksystem.FeedbackSystem;
import synergynet3.fonts.FontColour;
import synergynet3.mediadetection.mediasearchtypes.XMLSearchType;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Vector2f;
/**
* The Class TestVideoApp.
*/
public class FlickAndScreenShotMysteriesApp extends SynergyNetApp
{
/** The screenshot menu icon. */
private static final String SCREENSHOT_ICON = "synergynet3/activitypack2/table/flickandscreenshotmysteries/screenshotIcon.png";
/** The Constant TEXT_WIDTH_LIMIT. */
private static final float TEXT_WIDTH_LIMIT = 500;
/** The Constant TITLE_WIDTH_LIMIT. */
private static final float TITLE_WIDTH_LIMIT = 800;
/** The Constant XML_CHECK. */
private static final XMLSearchType XML_CHECK = new XMLSearchType();
/** The media source folder. */
private static String mediaSource = "";
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args)
{
if (args.length == 1)
{
mediaSource = args[0];
MultiplicityClient client = MultiplicityClient.get();
client.start();
FlickAndScreenShotMysteriesApp app = new FlickAndScreenShotMysteriesApp();
client.setCurrentApp(app);
}
else
{
AdditionalSynergyNetUtilities.logInfo("One mysteries location expected.");
}
}
/*
* (non-Javadoc)
* @see synergynet3.projector.SynergyNetProjector#getFriendlyAppName()
*/
@Override
public String getFriendlyAppName()
{
return "Flick and Screenshot Mysteries";
}
/**
* Adds the content from directory.
*
* @param f
* the File
*/
private void addContentFromDirectory(File f)
{
ArrayList<IItem> items = new ArrayList<IItem>();
File[] files = f.listFiles();
for (File file : files)
{
try
{
if (XML_CHECK.isFileOfSearchType(file))
{
items.addAll(parseXmlFile(file));
}
else
{
IItem item = AdditionalSynergyNetUtilities.generateItemFromFile(file, stage, -1, 250f, ColorRGBA.White);
if (item != null)
{
items.add(item);
// Make flickable
NetworkFlickBehaviour nf = stage.getBehaviourMaker().addBehaviour(item, NetworkFlickBehaviour.class);
nf.setMaxDimension(250f);
nf.setItemActingOn(item);
nf.setDeceleration(deceleration);
}
}
}
catch (ContentTypeNotBoundException ex)
{
}
}
Collections.shuffle(items);
for (IItem item : items)
{
stage.getZOrderManager().bringToTop(item);
item.setRelativeScale(FastMath.nextRandomInt(60, 90) / 100f);
}
IItem[] itemArray = new IItem[items.size()];
items.toArray(itemArray);
AdditionalSynergyNetUtilities.pile(itemArray, 0, 0, 20, 0);
}
/**
* Gets the text item.
*
* @param el
* the el
* @return the text item
* @throws ContentTypeNotBoundException
* the content type not bound exception
*/
private IItem getTextItem(Element el) throws ContentTypeNotBoundException
{
String text = getTextValue(el, "contents");
ITextbox textItem = stage.getContentFactory().create(ITextbox.class, text, UUID.randomUUID());
textItem.setMovable(true);
textItem.setScaleLimits(0.5f, 1.5f);
textItem.setColours(ColorRGBA.White, ColorRGBA.Gray, FontColour.Black);
textItem.setWidth(TEXT_WIDTH_LIMIT);
textItem.setHeight(60f);
textItem.setText(text, stage);
FeedbackSystem.registerAsFeedbackEligible(textItem, TEXT_WIDTH_LIMIT, textItem.getHeight(), stage);
// Make flickable
NetworkFlickBehaviour nf = stage.getBehaviourMaker().addBehaviour(textItem.getListenBlock(), NetworkFlickBehaviour.class);
nf.setMaxDimension(TEXT_WIDTH_LIMIT);
nf.setItemActingOn(textItem);
nf.setDeceleration(deceleration);
stage.addItem(textItem);
return textItem;
}
/**
* Gets the text value.
*
* @param ele
* the ele
* @param tagName
* the tag name
* @return the text value
*/
private String getTextValue(Element ele, String tagName)
{
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if ((nl != null) && (nl.getLength() > 0))
{
Element el = (Element) nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
/**
* Gets the title item.
*
* @param el
* the el
* @return the title item
* @throws ContentTypeNotBoundException
* the content type not bound exception
*/
private void getTitleItem(Element el) throws ContentTypeNotBoundException
{
String text = getTextValue(el, "contents");
ITextbox textItem = stage.getContentFactory().create(ITextbox.class, text, UUID.randomUUID());
textItem.setMovable(false);
textItem.setScaleLimits(0.5f, 1.5f);
textItem.setColours(ColorRGBA.Black, ColorRGBA.Green, FontColour.Green);
textItem.setWidth(TITLE_WIDTH_LIMIT);
textItem.setText(text, stage);
textItem.setRelativeLocation(new Vector2f(0, (stage.getDisplayHeight() / 2) - textItem.getHeight()));
stage.addItem(textItem);
}
/**
* Parses the xml file.
*
* @param file
* the file
* @return the array list
* @throws ContentTypeNotBoundException
* the content type not bound exception
*/
private ArrayList<IItem> parseXmlFile(File file) throws ContentTypeNotBoundException
{
ArrayList<IItem> items = new ArrayList<IItem>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(file);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("Text");
if ((nl != null) && (nl.getLength() > 0))
{
for (int i = 0; i < nl.getLength(); i++)
{
Element el = (Element) nl.item(i);
String type = el.getAttribute("type");
if (type.equalsIgnoreCase("title"))
{
getTitleItem(el);
}
else
{
items.add(getTextItem(el));
}
}
}
}
catch (ParserConfigurationException pce)
{
pce.printStackTrace();
}
catch (SAXException se)
{
se.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return items;
}
/*
* (non-Javadoc)
* @see synergynet3.SynergyNetApp#loadDefaultContent()
*/
@Override
protected void loadDefaultContent() throws IOException, ContentTypeNotBoundException
{
// ProjectorTransferUtilities.get().setDecelerationOnArrival(-1);
// feedbackTypes.add(SimpleTrafficLightFeedback.class);
// feedbackTypes.add(AudioFeedback.class);
// feedbackTypes.add(SmilieFeedback.class);
// feedbackTypes.add(YesOrNoFeedback.class);
this.enableNetworkFlick();
// Add button which takes screenshots.
IImage screenshotImage = stage.getContentFactory().create(IImage.class, "screenshot", UUID.randomUUID());
screenshotImage.setImage(SCREENSHOT_ICON);
screenshotImage.setSize(75, 75);
screenshotImage.getZOrderManager().setBringToTopPropagatesUp(false);
screenshotImage.getZOrderManager().setAutoBringToTop(false);
screenshotImage.setRelativeLocation(new Vector2f((-stage.getDisplayWidth() / 2) + 75, (stage.getDisplayHeight() / 2) - 75));
screenshotImage.getMultiTouchDispatcher().addListener(new MultiTouchEventAdapter()
{
@Override
public void cursorClicked(MultiTouchCursorEvent event)
{
if (tableBorder != null)
{
tableBorder.setVisible(true);
}
createScreenShotItem(new Vector2f(), 0);
}
});
stage.addItem(screenshotImage);
try
{
// Load content from mysteries folder
File mysteriesDir = new File(mediaSource);
addContentFromDirectory(mysteriesDir);
}
catch (Exception ex)
{
AdditionalSynergyNetUtilities.log(Level.SEVERE, "Unable to open the folder provided in the arguments.", ex);
}
}
/**
* Creates a manipulable screenshot item using an image file and adds it to
* the environment. The screenshot item is registered as feedback eligible
* and made capable of being network flicked when created.
*
* @param screenShotFile
* Image file to create the screenshot item from.
* @param loc
* Location at which the screenshot created should appear.
* @param rot
* Rotation at which the screenshot created should appear.
**/
@Override
public void utiliseScreenshot(File screenShotFile, Vector2f loc, float rot)
{
if (tableBorder != null)
{
tableBorder.setVisible(false);
}
super.utiliseScreenshot(screenShotFile, loc, rot);
}
}
| synergynet3.1-parent/synergynet3-activitypack2-table/src/main/java/synergynet3/activitypack2/table/flickandscreenshotmysteries/FlickAndScreenShotMysteriesApp.java | package synergynet3.activitypack2.table.flickandscreenshotmysteries;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.UUID;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import multiplicity3.appsystem.MultiplicityClient;
import multiplicity3.csys.factory.ContentTypeNotBoundException;
import multiplicity3.csys.items.image.IImage;
import multiplicity3.csys.items.item.IItem;
import multiplicity3.input.MultiTouchEventAdapter;
import multiplicity3.input.events.MultiTouchCursorEvent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import synergynet3.SynergyNetApp;
import synergynet3.additionalUtils.AdditionalSynergyNetUtilities;
import synergynet3.additionalitems.interfaces.ITextbox;
import synergynet3.behaviours.networkflick.NetworkFlickBehaviour;
import synergynet3.feedbacksystem.FeedbackSystem;
import synergynet3.fonts.FontColour;
import synergynet3.mediadetection.mediasearchtypes.XMLSearchType;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Vector2f;
/**
* The Class TestVideoApp.
*/
public class FlickAndScreenShotMysteriesApp extends SynergyNetApp
{
/** The screenshot menu icon. */
private static final String SCREENSHOT_ICON = "synergynet3/activitypack2/table/flickandscreenshotmysteries/screenshotIcon.png";
/** The Constant TEXT_WIDTH_LIMIT. */
private static final float TEXT_WIDTH_LIMIT = 500;
/** The Constant TITLE_WIDTH_LIMIT. */
private static final float TITLE_WIDTH_LIMIT = 800;
/** The Constant XML_CHECK. */
private static final XMLSearchType XML_CHECK = new XMLSearchType();
/** The media source folder. */
private static String mediaSource = "";
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args)
{
if (args.length == 1)
{
mediaSource = args[0];
MultiplicityClient client = MultiplicityClient.get();
client.start();
FlickAndScreenShotMysteriesApp app = new FlickAndScreenShotMysteriesApp();
client.setCurrentApp(app);
}
else
{
AdditionalSynergyNetUtilities.logInfo("One mysteries location expected.");
}
}
/*
* (non-Javadoc)
* @see synergynet3.projector.SynergyNetProjector#getFriendlyAppName()
*/
@Override
public String getFriendlyAppName()
{
return "Flick and Screenshot Mysteries";
}
/**
* Adds the content from directory.
*
* @param f
* the File
*/
private void addContentFromDirectory(File f)
{
ArrayList<IItem> items = new ArrayList<IItem>();
File[] files = f.listFiles();
for (File file : files)
{
try
{
if (XML_CHECK.isFileOfSearchType(file))
{
items.addAll(parseXmlFile(file));
}
else
{
IItem item = AdditionalSynergyNetUtilities.generateItemFromFile(file, stage, -1, 250f, ColorRGBA.White);
if (item != null)
{
items.add(item);
// Make flickable
NetworkFlickBehaviour nf = stage.getBehaviourMaker().addBehaviour(item, NetworkFlickBehaviour.class);
nf.setMaxDimension(250f);
nf.setItemActingOn(item);
nf.setDeceleration(deceleration);
}
}
}
catch (ContentTypeNotBoundException ex)
{
}
}
Collections.shuffle(items);
for (IItem item : items)
{
stage.getZOrderManager().bringToTop(item);
item.setRelativeScale(FastMath.nextRandomInt(60, 90) / 100f);
}
IItem[] itemArray = new IItem[items.size()];
items.toArray(itemArray);
AdditionalSynergyNetUtilities.pile(itemArray, 0, 0, 20, 0);
}
/**
* Gets the text item.
*
* @param el
* the el
* @return the text item
* @throws ContentTypeNotBoundException
* the content type not bound exception
*/
private IItem getTextItem(Element el) throws ContentTypeNotBoundException
{
String text = getTextValue(el, "contents");
ITextbox textItem = stage.getContentFactory().create(ITextbox.class, text, UUID.randomUUID());
textItem.setMovable(true);
textItem.setScaleLimits(0.5f, 1.5f);
textItem.setColours(ColorRGBA.White, ColorRGBA.Gray, FontColour.Black);
textItem.setWidth(TEXT_WIDTH_LIMIT);
textItem.setHeight(60f);
textItem.setText(text, stage);
FeedbackSystem.registerAsFeedbackEligible(textItem, TEXT_WIDTH_LIMIT, textItem.getHeight(), stage);
// Make flickable
NetworkFlickBehaviour nf = stage.getBehaviourMaker().addBehaviour(textItem.getListenBlock(), NetworkFlickBehaviour.class);
nf.setMaxDimension(TEXT_WIDTH_LIMIT);
nf.setItemActingOn(textItem);
nf.setDeceleration(deceleration);
stage.addItem(textItem);
return textItem;
}
/**
* Gets the text value.
*
* @param ele
* the ele
* @param tagName
* the tag name
* @return the text value
*/
private String getTextValue(Element ele, String tagName)
{
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if ((nl != null) && (nl.getLength() > 0))
{
Element el = (Element) nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
/**
* Gets the title item.
*
* @param el
* the el
* @return the title item
* @throws ContentTypeNotBoundException
* the content type not bound exception
*/
private void getTitleItem(Element el) throws ContentTypeNotBoundException
{
String text = getTextValue(el, "contents");
ITextbox textItem = stage.getContentFactory().create(ITextbox.class, text, UUID.randomUUID());
textItem.setMovable(false);
textItem.setScaleLimits(0.5f, 1.5f);
textItem.setColours(ColorRGBA.Black, ColorRGBA.Green, FontColour.Green);
textItem.setWidth(TITLE_WIDTH_LIMIT);
textItem.setText(text, stage);
textItem.setRelativeLocation(new Vector2f(0, (stage.getDisplayHeight() / 2) - textItem.getHeight()));
stage.addItem(textItem);
}
/**
* Parses the xml file.
*
* @param file
* the file
* @return the array list
* @throws ContentTypeNotBoundException
* the content type not bound exception
*/
private ArrayList<IItem> parseXmlFile(File file) throws ContentTypeNotBoundException
{
ArrayList<IItem> items = new ArrayList<IItem>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(file);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("Text");
if ((nl != null) && (nl.getLength() > 0))
{
for (int i = 0; i < nl.getLength(); i++)
{
Element el = (Element) nl.item(i);
String type = el.getAttribute("type");
if (type.equalsIgnoreCase("title"))
{
getTitleItem(el);
}
else
{
items.add(getTextItem(el));
}
}
}
}
catch (ParserConfigurationException pce)
{
pce.printStackTrace();
}
catch (SAXException se)
{
se.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return items;
}
/*
* (non-Javadoc)
* @see synergynet3.SynergyNetApp#loadDefaultContent()
*/
@Override
protected void loadDefaultContent() throws IOException, ContentTypeNotBoundException
{
// ProjectorTransferUtilities.get().setDecelerationOnArrival(-1);
// feedbackTypes.add(SimpleTrafficLightFeedback.class);
// feedbackTypes.add(AudioFeedback.class);
// feedbackTypes.add(SmilieFeedback.class);
// feedbackTypes.add(YesOrNoFeedback.class);
this.enableNetworkFlick();
// Add button which takes screenshots.
IImage screenshotImage = stage.getContentFactory().create(IImage.class, "screenshot", UUID.randomUUID());
screenshotImage.setImage(SCREENSHOT_ICON);
screenshotImage.setWorldLocation(new Vector2f(75, 75));
screenshotImage.setSize(75, 75);
screenshotImage.getMultiTouchDispatcher().addListener(new MultiTouchEventAdapter()
{
@Override
public void cursorClicked(MultiTouchCursorEvent event)
{
createScreenShotItem(new Vector2f(), 0);
}
});
stage.addItem(screenshotImage);
try
{
// Load content from mysteries folder
File mysteriesDir = new File(mediaSource);
addContentFromDirectory(mysteriesDir);
}
catch (Exception ex)
{
AdditionalSynergyNetUtilities.log(Level.SEVERE, "Unable to open the folder provided in the arguments.", ex);
}
}
}
| Move button to top left
Also show table colour. | synergynet3.1-parent/synergynet3-activitypack2-table/src/main/java/synergynet3/activitypack2/table/flickandscreenshotmysteries/FlickAndScreenShotMysteriesApp.java | Move button to top left |
|
Java | mit | 2a955bcd215545b4ab594fc029ad21c88be54459 | 0 | CruGlobal/android-gto-support,GlobalTechnology/android-gto-support,CruGlobal/android-gto-support | package org.ccci.gto.android.common.recyclerview.adapter;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;
public abstract class CursorAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
@Nullable
protected Cursor mCursor;
private int mIdColumn = -1;
public CursorAdapter() {
// default to stable ids for CursorAdapters
setHasStableIds(true);
}
@UiThread
@Nullable
public Cursor swapCursor(@Nullable final Cursor cursor) {
final Cursor old = mCursor;
// update Cursor
mCursor = cursor;
mIdColumn = mCursor != null ? mCursor.getColumnIndex(BaseColumns._ID) : -1;
// notify that data has changed
notifyDataSetChanged();
// return the old cursor
return old;
}
@UiThread
protected Cursor scrollCursor(@Nullable final Cursor cursor, final int position) {
if (cursor != null) {
cursor.moveToPosition(position);
}
return cursor;
}
@UiThread
@Override
public long getItemId(final int position) {
// return the item id if we have a cursor and id column
if (mIdColumn >= 0) {
final Cursor c = scrollCursor(mCursor, position);
if (c != null) {
return c.getLong(mIdColumn);
}
}
// default to NO_ID
return RecyclerView.NO_ID;
}
@UiThread
@Override
public int getItemCount() {
return mCursor != null ? mCursor.getCount() : 0;
}
@UiThread
@Override
public final void onBindViewHolder(@NonNull final VH holder, final int position) {
onBindViewHolder(holder, scrollCursor(mCursor, position), position);
}
@UiThread
protected abstract void onBindViewHolder(@NonNull VH holder, @Nullable Cursor cursor, int position);
}
| gto-support-recyclerview/src/main/java/org/ccci/gto/android/common/recyclerview/adapter/CursorAdapter.java | package org.ccci.gto.android.common.recyclerview.adapter;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;
public abstract class CursorAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
@Nullable
protected Cursor mCursor;
private int mIdColumn = -1;
public CursorAdapter() {
// default to stable ids for CursorAdapters
setHasStableIds(true);
}
/**
* @deprecated Since v1.0.0, letting a ViewAdapter close a Cursor for you has been discouraged since at least
* Gingerbread. We shouldn't implement a discouraged pattern in our own support adapters.
*/
@Deprecated
public void changeCursor(@Nullable final Cursor cursor) {
final Cursor old = swapCursor(cursor);
// close old Cursor if it differs from the new Cursor
if (old != null && old != cursor) {
old.close();
}
}
@UiThread
@Nullable
public Cursor swapCursor(@Nullable final Cursor cursor) {
final Cursor old = mCursor;
// update Cursor
mCursor = cursor;
mIdColumn = mCursor != null ? mCursor.getColumnIndex(BaseColumns._ID) : -1;
// notify that data has changed
notifyDataSetChanged();
// return the old cursor
return old;
}
@UiThread
protected Cursor scrollCursor(@Nullable final Cursor cursor, final int position) {
if (cursor != null) {
cursor.moveToPosition(position);
}
return cursor;
}
@UiThread
@Override
public long getItemId(final int position) {
// return the item id if we have a cursor and id column
if (mIdColumn >= 0) {
final Cursor c = scrollCursor(mCursor, position);
if (c != null) {
return c.getLong(mIdColumn);
}
}
// default to NO_ID
return RecyclerView.NO_ID;
}
@UiThread
@Override
public int getItemCount() {
return mCursor != null ? mCursor.getCount() : 0;
}
@UiThread
@Override
public final void onBindViewHolder(@NonNull final VH holder, final int position) {
onBindViewHolder(holder, scrollCursor(mCursor, position), position);
}
@UiThread
protected abstract void onBindViewHolder(@NonNull VH holder, @Nullable Cursor cursor, int position);
}
| remove an unsupport deprecated method
| gto-support-recyclerview/src/main/java/org/ccci/gto/android/common/recyclerview/adapter/CursorAdapter.java | remove an unsupport deprecated method |
|
Java | mit | 8e6c9cb3157070e092bfeefcbb285d1f96aed7c6 | 0 | archimatetool/archi,archimatetool/archi,archimatetool/archi | /*******************************************************************************
* Copyright (c) 2010 Bolton University, UK.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*******************************************************************************/
package uk.ac.bolton.archimate.editor.diagram.editparts.diagram;
import java.util.List;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.SnapToHelper;
import org.eclipse.gef.editpolicies.SnapFeedbackPolicy;
import org.eclipse.gef.requests.LocationRequest;
import org.eclipse.gef.tools.DirectEditManager;
import uk.ac.bolton.archimate.editor.diagram.directedit.LabelCellEditorLocator;
import uk.ac.bolton.archimate.editor.diagram.directedit.LabelDirectEditManager;
import uk.ac.bolton.archimate.editor.diagram.editparts.AbstractBaseEditPart;
import uk.ac.bolton.archimate.editor.diagram.editparts.IColoredEditPart;
import uk.ac.bolton.archimate.editor.diagram.editparts.ITextEditPart;
import uk.ac.bolton.archimate.editor.diagram.editparts.SnapEditPartAdapter;
import uk.ac.bolton.archimate.editor.diagram.figures.IContainerFigure;
import uk.ac.bolton.archimate.editor.diagram.figures.IDiagramModelObjectFigure;
import uk.ac.bolton.archimate.editor.diagram.figures.IEditableLabelFigure;
import uk.ac.bolton.archimate.editor.diagram.figures.diagram.GroupFigure;
import uk.ac.bolton.archimate.editor.diagram.policies.ContainerHighlightEditPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.DiagramLayoutPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.GroupContainerComponentEditPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.BasicContainerEditPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.PartDirectEditTitlePolicy;
import uk.ac.bolton.archimate.editor.ui.ViewManager;
import uk.ac.bolton.archimate.model.IArchimatePackage;
import uk.ac.bolton.archimate.model.IDiagramModelContainer;
import uk.ac.bolton.archimate.model.IDiagramModelObject;
/**
* Group Edit Part
*
* This is not a Connected EditPart because:
* 1. A connection anchor point looks ugly if it enters at the top-right missing section of the figure
* 2. The Magic Connector snaps to the edge of the figure rather than clicking in space
*
* @author Phillip Beauvoir
*/
public class GroupEditPart extends AbstractBaseEditPart
implements IColoredEditPart, ITextEditPart {
private DirectEditManager fManager;
private Adapter adapter = new AdapterImpl() {
@Override
public void notifyChanged(Notification msg) {
switch(msg.getEventType()) {
// Children added or removed
case Notification.ADD:
case Notification.ADD_MANY:
case Notification.REMOVE:
case Notification.REMOVE_MANY:
// Move notification sent from Z-Order changes in model
case Notification.MOVE:
refreshChildren();
break;
case Notification.SET:
Object feature = msg.getFeature();
if(feature == IArchimatePackage.Literals.DIAGRAM_MODEL_OBJECT__BOUNDS) {
refreshBounds();
}
else {
refreshFigure();
}
break;
default:
break;
}
}
};
@Override
protected List<?> getModelChildren() {
return ((IDiagramModelContainer)getModel()).getChildren();
}
@Override
protected Adapter getECoreAdapter() {
return adapter;
}
@Override
protected void createEditPolicies() {
// Add a policy to handle directly editing the Parts (for example, directly renaming a part)
installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE, new PartDirectEditTitlePolicy());
// Add a policy to handle editing the Parts (for example, deleting a part)
installEditPolicy(EditPolicy.COMPONENT_ROLE, new GroupContainerComponentEditPolicy());
// Install a custom layout policy that handles dragging things around and creating new objects
installEditPolicy(EditPolicy.LAYOUT_ROLE, new DiagramLayoutPolicy());
// Orphaning
installEditPolicy(EditPolicy.CONTAINER_ROLE, new BasicContainerEditPolicy());
// Snap to Geometry feedback
installEditPolicy("Snap Feedback", new SnapFeedbackPolicy()); //$NON-NLS-1$
// Selection Feedback
installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE, new ContainerHighlightEditPolicy());
}
@Override
protected IFigure createFigure() {
GroupFigure figure = new GroupFigure((IDiagramModelObject)getModel());
return figure;
}
@Override
public IFigure getContentPane() {
return ((IContainerFigure)getFigure()).getContentPane();
}
@Override
protected void refreshFigure() {
// Refresh the figure if necessary
((IDiagramModelObjectFigure)getFigure()).refreshVisuals();
}
/**
* Edit Requests are handled here
*/
@Override
public void performRequest(Request request) {
if(request.getType() == RequestConstants.REQ_DIRECT_EDIT || request.getType() == RequestConstants.REQ_OPEN) {
// Edit the label if we clicked on it
if(((IEditableLabelFigure)getFigure()).didClickLabel(((LocationRequest)request).getLocation().getCopy())) {
if(fManager == null) {
Label label = ((IEditableLabelFigure)getFigure()).getLabel();
fManager = new LabelDirectEditManager(this, new LabelCellEditorLocator(label), label);
}
fManager.show();
}
// Open Properties view
else if(request.getType() == RequestConstants.REQ_OPEN) {
ViewManager.showViewPart(ViewManager.PROPERTIES_VIEW, true);
}
}
}
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class adapter) {
if(adapter == SnapToHelper.class) {
return new SnapEditPartAdapter(this).getSnapToHelper();
}
return super.getAdapter(adapter);
}
}
| uk.ac.bolton.archimate.editor/src/uk/ac/bolton/archimate/editor/diagram/editparts/diagram/GroupEditPart.java | /*******************************************************************************
* Copyright (c) 2010 Bolton University, UK.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*******************************************************************************/
package uk.ac.bolton.archimate.editor.diagram.editparts.diagram;
import java.util.List;
import org.eclipse.draw2d.ChopboxAnchor;
import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.SnapToHelper;
import org.eclipse.gef.editpolicies.SnapFeedbackPolicy;
import org.eclipse.gef.requests.LocationRequest;
import org.eclipse.gef.tools.DirectEditManager;
import uk.ac.bolton.archimate.editor.diagram.directedit.LabelCellEditorLocator;
import uk.ac.bolton.archimate.editor.diagram.directedit.LabelDirectEditManager;
import uk.ac.bolton.archimate.editor.diagram.editparts.AbstractConnectedEditPart;
import uk.ac.bolton.archimate.editor.diagram.editparts.IColoredEditPart;
import uk.ac.bolton.archimate.editor.diagram.editparts.ITextEditPart;
import uk.ac.bolton.archimate.editor.diagram.editparts.SnapEditPartAdapter;
import uk.ac.bolton.archimate.editor.diagram.figures.IContainerFigure;
import uk.ac.bolton.archimate.editor.diagram.figures.IDiagramModelObjectFigure;
import uk.ac.bolton.archimate.editor.diagram.figures.IEditableLabelFigure;
import uk.ac.bolton.archimate.editor.diagram.figures.diagram.GroupFigure;
import uk.ac.bolton.archimate.editor.diagram.policies.BasicContainerEditPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.ContainerHighlightEditPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.DiagramConnectionPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.DiagramLayoutPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.GroupContainerComponentEditPolicy;
import uk.ac.bolton.archimate.editor.diagram.policies.PartDirectEditTitlePolicy;
import uk.ac.bolton.archimate.editor.ui.ViewManager;
import uk.ac.bolton.archimate.model.IDiagramModelContainer;
import uk.ac.bolton.archimate.model.IDiagramModelObject;
/**
* Group Edit Part
*
* @author Phillip Beauvoir
*/
public class GroupEditPart extends AbstractConnectedEditPart
implements IColoredEditPart, ITextEditPart {
private ConnectionAnchor fAnchor;
private DirectEditManager fManager;
@Override
protected List<?> getModelChildren() {
return ((IDiagramModelContainer)getModel()).getChildren();
}
@Override
protected void createEditPolicies() {
// Allow parts to be connected
installEditPolicy(EditPolicy.GRAPHICAL_NODE_ROLE, new DiagramConnectionPolicy());
// Add a policy to handle directly editing the Parts (for example, directly renaming a part)
installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE, new PartDirectEditTitlePolicy());
// Add a policy to handle editing the Parts (for example, deleting a part)
installEditPolicy(EditPolicy.COMPONENT_ROLE, new GroupContainerComponentEditPolicy());
// Install a custom layout policy that handles dragging things around and creating new objects
installEditPolicy(EditPolicy.LAYOUT_ROLE, new DiagramLayoutPolicy());
// Orphaning
installEditPolicy(EditPolicy.CONTAINER_ROLE, new BasicContainerEditPolicy());
// Snap to Geometry feedback
installEditPolicy("Snap Feedback", new SnapFeedbackPolicy()); //$NON-NLS-1$
// Selection Feedback
installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE, new ContainerHighlightEditPolicy());
}
@Override
protected IFigure createFigure() {
GroupFigure figure = new GroupFigure((IDiagramModelObject)getModel());
return figure;
}
@Override
public IFigure getContentPane() {
return ((IContainerFigure)getFigure()).getContentPane();
}
@Override
protected void refreshFigure() {
// Refresh the figure if necessary
((IDiagramModelObjectFigure)getFigure()).refreshVisuals();
}
/**
* Edit Requests are handled here
*/
@Override
public void performRequest(Request request) {
if(request.getType() == RequestConstants.REQ_DIRECT_EDIT || request.getType() == RequestConstants.REQ_OPEN) {
// Edit the label if we clicked on it
if(((IEditableLabelFigure)getFigure()).didClickLabel(((LocationRequest)request).getLocation().getCopy())) {
if(fManager == null) {
Label label = ((IEditableLabelFigure)getFigure()).getLabel();
fManager = new LabelDirectEditManager(this, new LabelCellEditorLocator(label), label);
}
fManager.show();
}
// Open Properties view
else if(request.getType() == RequestConstants.REQ_OPEN) {
ViewManager.showViewPart(ViewManager.PROPERTIES_VIEW, true);
}
}
}
@Override
protected ConnectionAnchor getConnectionAnchor() {
if(fAnchor == null) {
fAnchor = new ChopboxAnchor(getFigure());
}
return fAnchor;
}
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class adapter) {
if(adapter == SnapToHelper.class) {
return new SnapEditPartAdapter(this).getSnapToHelper();
}
return super.getAdapter(adapter);
}
}
| Revert Connected Edit Part
This is not a Connected EditPart because:
1. A connection anchor point looks ugly if it enters at the top-right missing section of the figure
2. The Magic Connector snaps to the edge of the figure rather than clicking in space
| uk.ac.bolton.archimate.editor/src/uk/ac/bolton/archimate/editor/diagram/editparts/diagram/GroupEditPart.java | Revert Connected Edit Part |
|
Java | mit | 5db2aabf0cf315984584210e3eee3acc71c30abe | 0 | Instabug/instabug-reactnative,Instabug/instabug-reactnative,Instabug/instabug-reactnative,Instabug/instabug-reactnative,Instabug/instabug-reactnative | package com.instabug.reactlibrary;
import android.app.Application;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.bridge.Callback;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.instabug.library.Feature;
import com.instabug.library.Instabug;
import com.instabug.library.extendedbugreport.ExtendedBugReport;
import com.instabug.library.internal.module.InstabugLocale;
import com.instabug.library.invocation.InstabugInvocationEvent;
import com.instabug.library.invocation.InstabugInvocationMode;
import com.instabug.library.InstabugColorTheme;
import com.instabug.library.invocation.util.InstabugVideoRecordingButtonCorner;
import com.instabug.library.logging.InstabugLog;
import com.instabug.library.bugreporting.model.ReportCategory;
import com.instabug.library.InstabugCustomTextPlaceHolder;
import com.instabug.library.user.UserEventParam;
import com.instabug.library.OnSdkDismissedCallback;
import com.instabug.library.bugreporting.model.Bug;
import com.instabug.library.visualusersteps.State;
import com.instabug.survey.InstabugSurvey;
import com.instabug.reactlibrary.utils.ArrayUtil;
import com.instabug.reactlibrary.utils.MapUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* The type Rn instabug reactnative module.
*/
public class RNInstabugReactnativeModule extends ReactContextBaseJavaModule {
//InvocationEvents
private final String INVOCATION_EVENT_NONE = "none";
private final String INVOCATION_EVENT_SHAKE = "shake";
private final String INVOCATION_EVENT_SCREENSHOT = "screenshot";
private final String INVOCATION_EVENT_TWO_FINGERS_SWIPE = "swipe";
private final String INVOCATION_EVENT_FLOATING_BUTTON = "button";
//InvocationModes
private final String INVOCATION_MODE_NEW_BUG = "bug";
private final String INVOCATION_MODE_NEW_FEEDBACK = "feedback";
private final String INVOCATION_MODE_NEW_CHAT = "chat";
private final String INVOCATION_MODE_CHATS_LIST = "chats";
//FloatingButtonEdge
private final String FLOATING_BUTTON_EDGE_RIGHT = "right";
private final String FLOATING_BUTTON_EDGE_LEFT = "left";
//locales
private final String LOCALE_ARABIC = "arabic";
private final String LOCALE_CHINESE_SIMPLIFIED = "chinesesimplified";
private final String LOCALE_CHINESE_TRADITIONAL = "chinesetraditional";
private final String LOCALE_CZECH = "czech";
private final String LOCALE_ENGLISH = "english";
private final String LOCALE_FRENCH = "french";
private final String LOCALE_GERMAN = "german";
private final String LOCALE_KOREAN = "korean";
private final String LOCALE_ITALIAN = "italian";
private final String LOCALE_JAPANESE = "japanese";
private final String LOCALE_POLISH = "polish";
private final String LOCALE_PORTUGUESE_BRAZIL = "portuguesebrazil";
private final String LOCALE_RUSSIAN = "russian";
private final String LOCALE_SPANISH = "spanish";
private final String LOCALE_SWEDISH = "swedish";
private final String LOCALE_TURKISH = "turkish";
//Instabug Button Corner
private final String TOP_RIGHT = "topRight";
private final String TOP_LEFT = "topLeft";
private final String BOTTOM_RIGHT = "bottomRight";
private final String BOTTOM_LEFT = "bottomLeft";
//Instabug extended bug report modes
private final String EXTENDED_BUG_REPORT_REQUIRED_FIELDS = "enabledWithRequiredFields";
private final String EXTENDED_BUG_REPORT_OPTIONAL_FIELDS = "enabledWithOptionalFields";
private final String EXTENDED_BUG_REPORT_DISABLED = "disabled";
//Instabug repro step modes
private final String ENABLED_WITH_NO_SCREENSHOTS = "enabledWithNoScreenshots";
private final String ENABLED = "enabled";
private final String DISABLED = "disabled";
//Theme colors
private final String COLOR_THEME_LIGHT = "light";
private final String COLOR_THEME_DARK = "dark";
//CustomTextPlaceHolders
private final String SHAKE_HINT = "shakeHint";
private final String SWIPE_HINT = "swipeHint";
private final String INVALID_EMAIL_MESSAGE = "invalidEmailMessage";
private final String INVALID_COMMENT_MESSAGE = "invalidCommentMessage";
private final String EMAIL_FIELD_HINT = "emailFieldHint";
private final String COMMENT_FIELD_HINT_FOR_BUG_REPORT = "commentFieldHintForBugReport";
private final String COMMENT_FIELD_HINT_FOR_FEEDBACK = "commentFieldHintForFeedback";
private final String INVOCATION_HEADER = "invocationHeader";
private final String START_CHATS = "talkToUs";
private final String REPORT_BUG = "reportBug";
private final String REPORT_FEEDBACK = "reportFeedback";
private final String CONVERSATIONS_LIST_TITLE = "conversationsHeaderTitle";
private final String ADD_VOICE_MESSAGE = "addVoiceMessage";
private final String ADD_IMAGE_FROM_GALLERY = "addImageFromGallery";
private final String ADD_EXTRA_SCREENSHOT = "addExtraScreenshot";
private final String ADD_VIDEO = "addVideoMessage";
private final String AUDIO_RECORDING_PERMISSION_DENIED = "audioRecordingPermissionDeniedMessage";
private final String VOICE_MESSAGE_PRESS_AND_HOLD_TO_RECORD = "recordingMessageToHoldText";
private final String VOICE_MESSAGE_RELEASE_TO_ATTACH = "recordingMessageToReleaseText";
private final String REPORT_SUCCESSFULLY_SENT = "thankYouText";
private final String VIDEO_PLAYER_TITLE = "video";
private final String CONVERSATION_TEXT_FIELD_HINT = "conversationTextFieldHint";
private Application androidApplication;
private Instabug mInstabug;
private InstabugInvocationEvent invocationEvent;
private InstabugCustomTextPlaceHolder placeHolders;
/**
* Instantiates a new Rn instabug reactnative module.
*
* @param reactContext the react context
* @param mInstabug the m instabug
*/
public RNInstabugReactnativeModule(ReactApplicationContext reactContext, Application
androidApplication, Instabug mInstabug) {
super(reactContext);
this.androidApplication = androidApplication;
this.mInstabug = mInstabug;
//init placHolders
placeHolders = new InstabugCustomTextPlaceHolder();
}
@Override
public String getName() {
return "Instabug";
}
@ReactMethod
public void startWithToken(String androidToken, String invocationEvent) {
mInstabug = new Instabug.Builder(this.androidApplication, androidToken)
.setIntroMessageEnabled(false)
.setInvocationEvent(getInvocationEventById(invocationEvent))
.build();
//init placHolders
placeHolders = new InstabugCustomTextPlaceHolder();
}
/**
* invoke sdk manually
*/
@ReactMethod
public void invoke() {
try {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
mInstabug.invoke();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* invoke sdk manually with desire invocation mode
*
* @param invocationMode the invocation mode
*/
@ReactMethod
public void invokeWithInvocationMode(String invocationMode) {
InstabugInvocationMode mode;
if (invocationMode.equals(INVOCATION_MODE_NEW_BUG)) {
mode = InstabugInvocationMode.NEW_BUG;
} else if (invocationMode.equals(INVOCATION_MODE_NEW_FEEDBACK)) {
mode = InstabugInvocationMode.NEW_FEEDBACK;
} else if (invocationMode.equals(INVOCATION_MODE_NEW_CHAT)) {
mode = InstabugInvocationMode.NEW_CHAT;
} else if (invocationMode.equals(INVOCATION_MODE_CHATS_LIST)) {
mode = InstabugInvocationMode.CHATS_LIST;
} else {
mode = InstabugInvocationMode.PROMPT_OPTION;
}
try {
mInstabug.invoke(mode);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Dismisses all visible Instabug views
*/
@ReactMethod
public void dismiss() {
try {
mInstabug.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adds tag(s) to issues before sending them
*
* @param tags
*/
@ReactMethod
public void appendTags(ReadableArray tags) {
try {
Object[] objectArray = ArrayUtil.toArray(tags);
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
mInstabug.addTags(stringArray);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Enable/Disable screen recording
*
* @param autoScreenRecordingEnabled boolean for enable/disable
* screen recording on crash feature
*/
@ReactMethod
public void setAutoScreenRecordingEnabled(boolean autoScreenRecordingEnabled) {
try {
Instabug.setAutoScreenRecordingEnabled(autoScreenRecordingEnabled);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets auto screen recording maximum duration
*
* @param autoScreenRecordingMaxDuration maximum duration of the screen recording video
* in milliseconds
* The maximum duration is 30000 milliseconds
*/
@ReactMethod
public void setAutoScreenRecordingMaxDuration(int autoScreenRecordingMaxDuration) {
try {
int durationInMilli = autoScreenRecordingMaxDuration*1000;
Instabug.setAutoScreenRecordingMaxDuration(durationInMilli);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Change Locale of Instabug UI elements(defaults to English)
*
* @param instabugLocale
*/
@ReactMethod
public void changeLocale(String instabugLocale) {
try {
mInstabug.changeLocale(getLocaleByKey(instabugLocale));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets whether the extended bug report mode should be disabled,
* enabled with required fields, or enabled with optional fields.
*
* @param extendedBugReportMode
*/
@ReactMethod
public void setExtendedBugReportMode(String extendedBugReportMode) {
try {
switch(extendedBugReportMode) {
case EXTENDED_BUG_REPORT_REQUIRED_FIELDS:
Instabug.setExtendedBugReportState(ExtendedBugReport.State.ENABLED_WITH_REQUIRED_FIELDS);
break;
case EXTENDED_BUG_REPORT_OPTIONAL_FIELDS:
Instabug.setExtendedBugReportState(ExtendedBugReport.State.ENABLED_WITH_OPTIONAL_FIELDS);
break;
case EXTENDED_BUG_REPORT_DISABLED:
Instabug.setExtendedBugReportState(ExtendedBugReport.State.DISABLED);
break;
default:
Instabug.setExtendedBugReportState(ExtendedBugReport.State.DISABLED);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@ReactMethod
public void setViewHierarchyEnabled(boolean enabled) {
try {
if(enabled) {
Instabug.setViewHierarchyState(Feature.State.ENABLED);
} else {
Instabug.setViewHierarchyState(Feature.State.DISABLED);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets the default corner at which the video recording floating button will be shown
*
* @param corner corner to stick the video recording floating button to
*/
@ReactMethod
public void setVideoRecordingFloatingButtonPosition(String corner) {
try {
mInstabug.setVideoRecordingFloatingButtonCorner(getVideoRecordingButtonCorner(corner));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* The file at filePath will be uploaded along upcoming reports with the name
* fileNameWithExtension
*
* @param fileUri the file uri
* @param fileNameWithExtension the file name with extension
*/
@ReactMethod
public void setFileAttachment(String fileUri, String fileNameWithExtension) {
try {
Uri uri = Uri.parse(fileUri);
mInstabug.setFileAttachment(uri, fileNameWithExtension);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* If your app already acquires the user's email address and you provide it to this method,
* Instabug will pre-fill the user email in reports.
*
* @param userEmail the user email
*/
@ReactMethod
public void setUserEmail(String userEmail) {
try {
mInstabug.setUserEmail(userEmail);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets the user name that is used in the dashboard's contacts.
*
* @param username the username
*/
@ReactMethod
public void setUserName(String username) {
try {
mInstabug.setUsername(username);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adds specific user data that you need to be added to the reports
*
* @param userData
*/
@ReactMethod
public void setUserData(String userData) {
try {
mInstabug.setUserData(userData);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Call this method to display the discovery dialog explaining the shake gesture or the two
* finger swipe gesture, if you've enabled it.
* i.e: This method is automatically called on first run of the application
*/
@ReactMethod
public void showIntroMessage() {
try {
mInstabug.showIntroMessage();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set the primary color that the SDK will use to tint certain UI elements in the SDK
*
* @param primaryColor The value of the primary color ,
* whatever this color was parsed from a resource color or hex color
* or RGB color values
*/
@ReactMethod
public void setPrimaryColor(int primaryColor) {
try {
mInstabug.setPrimaryColor(primaryColor);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets whether attachments in bug reporting and in-app messaging are enabled or not.
*
* @param {boolean} screenShot A boolean to enable or disable screenshot attachments.
* @param {boolean} extraScreenShot A boolean to enable or disable extra screenshot attachments.
* @param {boolean} galleryImage A boolean to enable or disable gallery image attachments.
* @param {boolean} screenRecording A boolean to enable or disable screen recording attachments.
*/
@ReactMethod
public void setEnabledAttachmentTypes(boolean screenshot, boolean extraScreenshot, boolean
galleryImage, boolean screenRecording) {
try {
Instabug.setAttachmentTypesEnabled(screenshot, extraScreenshot, galleryImage,
screenRecording);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Appends a log message to Instabug internal log
* These logs are then sent along the next uploaded report. All log messages are timestamped
* Logs aren't cleared per single application run. If you wish to reset the logs, use
* Note: logs passed to this method are <b>NOT</b> printed to Logcat
*
* @param message log message
*/
@ReactMethod
public void IBGLog(String message) {
try {
mInstabug.log(message);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets tags.
*
* @return all tags added
* @see #resetTags()
*/
@ReactMethod
public void getTags(Callback tagsCallback) {
WritableArray tagsArray;
try {
ArrayList<String> tags = mInstabug.getTags();
tagsArray = new WritableNativeArray();
for (int i = 0; i < tags.size(); i++) {
tagsArray.pushString(tags.get(i));
}
tagsCallback.invoke(tagsArray);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set the user identity.
* Instabug will pre-fill the user email in reports.
*
* @param userName Username.
* @param userEmail User's default email
*/
@ReactMethod
public void identifyUser(String userName, String userEmail) {
try {
mInstabug.identifyUser(userName, userEmail);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Reset ALL tags added
*/
@ReactMethod
public void resetTags() {
try {
mInstabug.resetTags();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Is enabled boolean.
*
* @return {@code true} if Instabug is enabled, {@code false} if it's disabled
* @see #enable()
* @see #disable()
*/
@ReactMethod
public boolean isEnabled() {
boolean isEnabled = false;
try {
isEnabled = mInstabug.isEnabled();
} catch (Exception e) {
e.printStackTrace();
}
return isEnabled;
}
/**
* Enables all Instabug functionality
*/
@ReactMethod
public void enable() {
try {
mInstabug.enable();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Disables all Instabug functionality
*/
@ReactMethod
public void disable() {
try {
mInstabug.disable();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return application token
*/
@ReactMethod
public String getAppToken() {
String appToken = "";
try {
appToken = mInstabug.getAppToken();
} catch (Exception e) {
e.printStackTrace();
}
return appToken;
}
/**
* Get current unread count of messages for this user
*
* @return number of messages that are unread for this user
*/
@ReactMethod
public void getUnreadMessagesCount(Callback messageCountCallback) {
int unreadMessages = 0;
try {
unreadMessages = mInstabug.getUnreadMessagesCount();
} catch (Exception e) {
e.printStackTrace();
}
messageCountCallback.invoke(unreadMessages);
}
/**
* Sets the event used to invoke Instabug SDK
*
* @param invocationEventValue the invocation event value
* @see InstabugInvocationEvent
*/
@ReactMethod
public void setInvocationEvent(String invocationEventValue) {
try {
mInstabug.changeInvocationEvent(getInvocationEventById(invocationEventValue));
} catch (Exception e) {
e.printStackTrace();
}
}
private InstabugInvocationEvent getInvocationEventById(String invocationEventValue) {
InstabugInvocationEvent invocationEvent = InstabugInvocationEvent.SHAKE;
try {
if (invocationEventValue.equals(INVOCATION_EVENT_FLOATING_BUTTON)) {
invocationEvent = InstabugInvocationEvent.FLOATING_BUTTON;
} else if (invocationEventValue.equals(INVOCATION_EVENT_TWO_FINGERS_SWIPE)) {
invocationEvent = InstabugInvocationEvent.TWO_FINGER_SWIPE_LEFT;
} else if (invocationEventValue.equals(INVOCATION_EVENT_SHAKE)) {
invocationEvent = InstabugInvocationEvent.SHAKE;
} else if (invocationEventValue.equals(INVOCATION_EVENT_SCREENSHOT)) {
invocationEvent = InstabugInvocationEvent.SCREENSHOT_GESTURE;
} else if (invocationEventValue.equals(INVOCATION_EVENT_NONE)) {
invocationEvent = InstabugInvocationEvent.NONE;
}
} catch (Exception e) {
e.printStackTrace();
}
return invocationEvent;
}
/**
* Enabled/disable chat notification
*
* @param isChatNotificationEnable whether chat notification is reburied or not
*/
@ReactMethod
public void setChatNotificationEnabled(boolean isChatNotificationEnable) {
try {
mInstabug.setChatNotificationEnabled(isChatNotificationEnable);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Enable/Disable debug logs from Instabug SDK
* Default state: disabled
*
* @param isDebugEnabled whether debug logs should be printed or not into LogCat
*/
@ReactMethod
public void setDebugEnabled(boolean isDebugEnabled) {
try {
mInstabug.setDebugEnabled(isDebugEnabled);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Report a caught exception to Instabug dashboard
*
* @param stack the exception to be reported
* @param message the message of the exception to be reported
* @param errorIdentifier used to group issues manually reported
*/
@ReactMethod
public void reportJsException(ReadableArray stack, String message, String errorIdentifier) {
try {
int size = stack != null ? stack.size() : 0;
StackTraceElement[] stackTraceElements = new StackTraceElement[size];
for (int i = 0; i < size; i++) {
ReadableMap frame = stack.getMap(i);
String methodName = frame.getString("methodName");
String fileName = frame.getString("file");
int lineNumber = frame.getInt("lineNumber");
stackTraceElements[i] = new StackTraceElement(fileName, methodName, fileName,
lineNumber);
}
Throwable throwable = new Throwable(message);
throwable.setStackTrace(stackTraceElements);
if (errorIdentifier != null)
mInstabug.reportException(throwable);
else
mInstabug.reportException(throwable, errorIdentifier);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Appends a log message to Instabug internal log
* <p>
* These logs are then sent along the next uploaded report.
* All log messages are timestamped <br/>
* Logs aren't cleared per single application run. If you wish to reset the logs,
* use {@link #clearLogs()} ()}
* </p>
* Note: logs passed to this method are <b>NOT</b> printed to Logcat
*
* @param level the level
* @param message the message
*/
@ReactMethod
public void log(String level, String message) {
try {
switch (level) {
case "v":
InstabugLog.v(message);
break;
case "i":
InstabugLog.i(message);
break;
case "d":
InstabugLog.d(message);
break;
case "e":
InstabugLog.e(message);
break;
case "w":
InstabugLog.w(message);
break;
case "wtf":
InstabugLog.wtf(message);
break;
default:
InstabugLog.d(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Clears Instabug internal log
*/
@ReactMethod
public void clearLogs() {
try {
InstabugLog.clearLogs();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns true if the survey with a specific token was answered before.
* Will return false if the token does not exist or if the survey was not answered before.
*
* @param surveyToken the attribute key as string
* @param hasRespondedCallback A callback that gets invoked with the returned value of whether
* the user has responded to the survey or not.
* @return the desired value of whether the user has responded to the survey or not.
*/
@ReactMethod
public void hasRespondedToSurveyWithToken(String surveyToken, Callback hasRespondedCallback) {
boolean hasResponded;
try {
hasResponded = Instabug.hasRespondToSurvey(surveyToken);
hasRespondedCallback.invoke(hasResponded);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Shows survey with a specific token.
* Does nothing if there are no available surveys with that specific token.
* Answered and cancelled surveys won't show up again.
*
* @param surveyToken A String with a survey token.
*/
@ReactMethod
public void showSurveyWithToken(String surveyToken) {
try {
Instabug.showSurvey(surveyToken);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets user attribute to overwrite it's value or create a new one if it doesn't exist.
*
* @param key the attribute
* @param value the value
*/
@ReactMethod
public void setUserAttribute(String key, String value) {
try {
mInstabug.setUserAttribute(key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets specific user attribute.
*
* @param key the attribute key as string
* @return the desired user attribute
*/
@ReactMethod
public void getUserAttribute(String key, Callback userAttributeCallback) {
String userAttribute;
try {
userAttribute = mInstabug.getUserAttribute(key);
userAttributeCallback.invoke(userAttribute);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Removes user attribute if exists.
*
* @param key the attribute key as string
* @see #setUserAttribute(String, String)
*/
@ReactMethod
public void removeUserAttribute(String key) {
try {
mInstabug.removeUserAttribute(key);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets all saved user attributes.
*
* @return all user attributes as HashMap<String, String>
*/
@ReactMethod
public void getAllUserAttributes(Callback userAttributesCallback) {
WritableMap writableMap = new WritableNativeMap();
try {
HashMap<String, String> map = mInstabug.getAllUserAttributes();
for (HashMap.Entry<String, String> entry : map.entrySet()) {
writableMap.putString(entry.getKey(), entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
userAttributesCallback.invoke(writableMap);
}
/**
* Clears all user attributes if exists.
*/
@ReactMethod
public void clearAllUserAttributes() {
try {
mInstabug.clearAllUserAttributes();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets InstabugSDK theme color.
*
* @param theme which is a constant String "light" or "dark"
*/
@ReactMethod
public void setColorTheme(String theme) {
try {
if (theme.equals(COLOR_THEME_LIGHT)) {
mInstabug.setTheme(InstabugColorTheme.InstabugColorThemeLight);
} else if (theme.equals(COLOR_THEME_DARK)) {
mInstabug.setTheme(InstabugColorTheme.InstabugColorThemeDark);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Allows you to show a predefined set of categories for users to choose
* from when reporting a bug or sending feedback. Selected category
* shows up on your Instabug dashboard as a tag to make filtering
* through issues easier.
*
* @param categoriesTitles the report categories list which is a list of ReportCategory model
*/
@ReactMethod
public void setReportCategories(ReadableArray categoriesTitles) {
try {
ArrayList<ReportCategory> bugCategories = new ArrayList<>();
int size = categoriesTitles != null ? categoriesTitles.size() : 0;
if (size == 0) return;
for (int i = 0; i < size; i++) {
bugCategories.add(ReportCategory.getInstance().withLabel(categoriesTitles
.getString(i)));
}
Instabug.setReportCategories(bugCategories);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets whether users are required to enter an email address or not when
* sending reports.
* Defaults to YES.
*
* @param isEmailFieldRequired A boolean to indicate whether email
* field is required or not.
*/
@ReactMethod
public void setEmailFieldRequired(boolean isEmailFieldRequired) {
try {
mInstabug.setEmailFieldRequired(isEmailFieldRequired);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets whether users are required to enter a comment or not when sending reports.
* Defaults to NO.
*
* @param isCommentFieldRequired A boolean to indicate whether comment
* field is required or not.
*/
@ReactMethod
public void setCommentFieldRequired(boolean isCommentFieldRequired) {
try {
mInstabug.setCommentFieldRequired(isCommentFieldRequired);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Overrides any of the strings shown in the SDK with custom ones.
* Allows you to customize any of the strings shown to users in the SDK.
*
* @param string String value to override the default one.
* @param key Key of string to override.
*/
@ReactMethod
public void setString(String string, String key) {
try {
placeHolders.set(getStringToKeyConstant(key), string);
Instabug.setCustomTextPlaceHolders(placeHolders);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets the default value of the user's email to null and show email field and remove user
* name from all reports
* It also reset the chats on device and removes user attributes, user data and completed
* surveys.
*/
@ReactMethod
public void logOut() {
try {
mInstabug.logoutUser();
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Enables/disables screenshot view when reporting a bug/improvement.
* By default, screenshot view is shown when reporting a bug, but not when
* sending feedback.
*
* @param willSkipScreenshotAnnotation sets whether screenshot view is
* shown or not. Passing YES will show screenshot view for both feedback and
* bug reporting, while passing NO will disable it for both.
*/
@ReactMethod
public void setWillSkipScreenshotAnnotation(boolean willSkipScreenshotAnnotation) {
try {
mInstabug.setWillSkipScreenshotAnnotation(willSkipScreenshotAnnotation);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Logs a user event that happens through the lifecycle of the application.
* Logged user events are going to be sent with each report, as well as at the end of a session.
*
* @param name Event name.
*/
@ReactMethod
public void logUserEventWithName(String name) {
try {
mInstabug.logUserEvent(name);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Logs a user event that happens through the lifecycle of the application.
* Logged user events are going to be sent with each report, as well as at the end of a
* session.
*
* @param name Event name.
* @param params An optional ReadableMap to be associated with the event.
*/
@ReactMethod
public void logUserEventWithNameAndParams(String name, ReadableMap params) {
try {
Map<String, Object> paramsMap = MapUtil.toMap(params);
UserEventParam[] userEventParams = new UserEventParam[paramsMap.size()];
int index = 0;
UserEventParam userEventParam;
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
userEventParam = new UserEventParam().setKey(entry.getKey())
.setValue((entry.getValue()).toString());
userEventParams[index] = userEventParam;
index++;
}
mInstabug.logUserEvent(name, userEventParams);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets a block of code to be executed just before the SDK's UI is presented.
* This block is executed on the UI thread. Could be used for performing any
* UI changes before the SDK's UI is shown.
*
* @param preInvocationHandler - A callback that gets executed before
* invoking the SDK
*/
@ReactMethod
public void setPreInvocationHandler(final Callback preInvocationHandler) {
try {
Runnable preInvocationRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGpreInvocationHandler", null);
}
};
mInstabug.setPreInvocation(preInvocationRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets a block of code to be executed before sending each report.
* This block is executed in the background before sending each report. Could
* be used for attaching logs and extra data to reports.
*
* @param preSendingHandler - A callback that gets executed before
* sending each bug
* report.
*/
@ReactMethod
public void setPreSendingHandler(final Callback preSendingHandler) {
try {
Runnable preSendingRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGpreSendingHandler", null);
}
};
mInstabug.setPreSendingRunnable(preSendingRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets a block of code to be executed right after the SDK's UI is dismissed.
* This block is executed on the UI thread. Could be used for performing any
* UI changes after the SDK's UI is dismissed.
*
* @param postInvocationHandler - A callback to get executed after
* dismissing the SDK.
*/
@ReactMethod
public void setPostInvocationHandler(final Callback postInvocationHandler) {
try {
mInstabug.setOnSdkDismissedCallback(new OnSdkDismissedCallback() {
@Override
public void onSdkDismissed(DismissType issueState, Bug.Type bugType) {
WritableMap params = Arguments.createMap();
params.putString("issueState", issueState.toString());
params.putString("bugType", bugType.toString());
sendEvent(getReactApplicationContext(), "IBGpostInvocationHandler", params);
}
});
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Show any valid survey if exist
*
* @return true if a valid survey was shown otherwise false
*/
@ReactMethod
public void showSurveysIfAvailable() {
try {
mInstabug.showValidSurvey();
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Show any valid survey if exist
*
* @return true if a valid survey was shown otherwise false
*/
@ReactMethod
public void setSurveysEnabled(boolean surveysEnabled) {
try {
InstabugSurvey.setSurveysAutoShowing(surveysEnabled);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets the default value of the intro message guide that gets shown on launching the app
*
* @param enabled true to show intro message guide
*/
@ReactMethod
public void setIntroMessageEnabled(boolean enabled) {
try {
mInstabug.setIntroMessageEnabled(enabled);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets the runnable that gets executed just before showing any valid survey<br/>
* WARNING: This runs on your application's main UI thread. Please do not include
* any blocking operations to avoid ANRs.
*
* @param willShowSurveyHandler to run on the UI thread before showing any valid survey
*/
@ReactMethod
public void setWillShowSurveyHandler(final Callback willShowSurveyHandler) {
try {
Runnable willShowSurveyRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGWillShowSurvey", null);
}
};
mInstabug.setPreShowingSurveyRunnable(willShowSurveyRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets the runnable that gets executed just after showing any valid survey<br/>
* WARNING: This runs on your application's main UI thread. Please do not include
* any blocking operations to avoid ANRs.
*
* @param didDismissSurveyHandler to run on the UI thread after showing any valid survey
*/
@ReactMethod
public void setDidDismissSurveyHandler(final Callback didDismissSurveyHandler) {
try {
Runnable didDismissSurveyRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGDidDismissSurvey", null);
}
};
mInstabug.setAfterShowingSurveyRunnable(didDismissSurveyRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Enable/Disable prompt options when SDK invoked. When only a single option is enabled it
* becomes the default
* invocation option that SDK gets invoked with and prompt options screen will not show. When
* none is enabled, Bug
* reporting becomes the default invocation option.
*
* @param chat weather Talk to us is enable or not
* @param bug weather Report a Problem is enable or not
* @param feedback weather General Feedback is enable or not
*/
@ReactMethod
public void setPromptOptionsEnabled(boolean chat, boolean bug, boolean feedback) {
try {
mInstabug.setPromptOptionsEnabled(chat, bug, feedback);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Clears all Uris of the attached files.
* The URIs which added via {@link Instabug#addFileAttachment} API not the physical files.
*/
@ReactMethod
public void clearFileAttachment() {
try {
mInstabug.clearFileAttachment();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets whether user steps tracking is visual, non visual or disabled.
*
* @param reproStepsMode A string to set user steps tracking to be
* enabled, non visual or disabled.
*/
@ReactMethod
public void setReproStepsMode(String reproStepsMode) {
try {
switch(reproStepsMode) {
case ENABLED_WITH_NO_SCREENSHOTS:
Instabug.setReproStepsState(State.ENABLED_WITH_NO_SCREENSHOTS);
break;
case ENABLED:
Instabug.setReproStepsState(State.ENABLED);
break;
case DISABLED:
Instabug.setReproStepsState(State.DISABLED);
break;
default:
Instabug.setReproStepsState(State.ENABLED);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets the threshold value of the shake gesture for android devices.
* Default for android is an integer value equals 350.
* you could increase the shaking difficulty level by
* increasing the `350` value and vice versa.
*
* @param androidThreshold Threshold for android devices.
*/
@ReactMethod
public void setShakingThresholdForAndroid(int androidThreshold) {
try {
mInstabug.setShakingThreshold(androidThreshold);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets a block of code that gets executed when a new message is received.
*
* @param onNewMessageHandler - A callback that gets
* executed when a new message is received.
*/
@ReactMethod
public void setOnNewMessageHandler(final Callback onNewMessageHandler) {
try {
Runnable onNewMessageRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGonNewMessageHandler", null);
}
};
mInstabug.setNewMessageHandler(onNewMessageRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* @param enabled true to show success dialog after submitting a bug report
*
*/
@ReactMethod
public void setSuccessDialogEnabled(boolean enabled) {
try {
mInstabug.setSuccessDialogEnabled(enabled);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set after how many sessions should the dismissed survey would show again.
*
* @param sessionsCount number of sessions that the dismissed survey will be shown after.
* @param daysCount number of days that the dismissed survey will show after
*
*/
@ReactMethod
public void setThresholdForReshowingSurveyAfterDismiss(int sessionsCount, int daysCount) {
try {
Instabug.setThresholdForReshowingSurveyAfterDismiss(sessionsCount, daysCount);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set whether new in app notification received will play a small sound notification
* or not (Default is {@code false})
*
* @param shouldPlaySound desired state of conversation sounds
* @since 4.1.0
*/
@ReactMethod
public void setEnableInAppNotificationSound(boolean shouldPlaySound) {
try {
mInstabug.setEnableInAppNotificationSound(shouldPlaySound);
} catch (Exception e) {
e.printStackTrace();
}
}
private InstabugCustomTextPlaceHolder.Key getStringToKeyConstant(String key) {
switch (key) {
case SHAKE_HINT:
return InstabugCustomTextPlaceHolder.Key.SHAKE_HINT;
case SWIPE_HINT:
return InstabugCustomTextPlaceHolder.Key.SWIPE_HINT;
case INVALID_EMAIL_MESSAGE:
return InstabugCustomTextPlaceHolder.Key.INVALID_EMAIL_MESSAGE;
case INVALID_COMMENT_MESSAGE:
return InstabugCustomTextPlaceHolder.Key.INVALID_COMMENT_MESSAGE;
case EMAIL_FIELD_HINT:
return InstabugCustomTextPlaceHolder.Key.EMAIL_FIELD_HINT;
case COMMENT_FIELD_HINT_FOR_BUG_REPORT:
return InstabugCustomTextPlaceHolder.Key.COMMENT_FIELD_HINT_FOR_BUG_REPORT;
case COMMENT_FIELD_HINT_FOR_FEEDBACK:
return InstabugCustomTextPlaceHolder.Key.COMMENT_FIELD_HINT_FOR_FEEDBACK;
case INVOCATION_HEADER:
return InstabugCustomTextPlaceHolder.Key.INVOCATION_HEADER;
case START_CHATS:
return InstabugCustomTextPlaceHolder.Key.START_CHATS;
case REPORT_BUG:
return InstabugCustomTextPlaceHolder.Key.REPORT_BUG;
case REPORT_FEEDBACK:
return InstabugCustomTextPlaceHolder.Key.REPORT_FEEDBACK;
case CONVERSATIONS_LIST_TITLE:
return InstabugCustomTextPlaceHolder.Key.CONVERSATIONS_LIST_TITLE;
case ADD_VOICE_MESSAGE:
return InstabugCustomTextPlaceHolder.Key.ADD_VOICE_MESSAGE;
case ADD_IMAGE_FROM_GALLERY:
return InstabugCustomTextPlaceHolder.Key.ADD_IMAGE_FROM_GALLERY;
case ADD_EXTRA_SCREENSHOT:
return InstabugCustomTextPlaceHolder.Key.ADD_EXTRA_SCREENSHOT;
case ADD_VIDEO:
return InstabugCustomTextPlaceHolder.Key.ADD_VIDEO;
case AUDIO_RECORDING_PERMISSION_DENIED:
return InstabugCustomTextPlaceHolder.Key.AUDIO_RECORDING_PERMISSION_DENIED;
case VOICE_MESSAGE_PRESS_AND_HOLD_TO_RECORD:
return InstabugCustomTextPlaceHolder.Key.VOICE_MESSAGE_PRESS_AND_HOLD_TO_RECORD;
case VOICE_MESSAGE_RELEASE_TO_ATTACH:
return InstabugCustomTextPlaceHolder.Key.VOICE_MESSAGE_RELEASE_TO_ATTACH;
case CONVERSATION_TEXT_FIELD_HINT:
return InstabugCustomTextPlaceHolder.Key.CONVERSATION_TEXT_FIELD_HINT;
case REPORT_SUCCESSFULLY_SENT:
return InstabugCustomTextPlaceHolder.Key.REPORT_SUCCESSFULLY_SENT;
case VIDEO_PLAYER_TITLE:
return InstabugCustomTextPlaceHolder.Key.VIDEO_PLAYER_TITLE;
default:
return null;
}
}
private InstabugVideoRecordingButtonCorner getVideoRecordingButtonCorner(String cornerValue) {
InstabugVideoRecordingButtonCorner corner = InstabugVideoRecordingButtonCorner.BOTTOM_RIGHT;
try {
if (cornerValue.equals(BOTTOM_RIGHT)) {
corner = InstabugVideoRecordingButtonCorner.BOTTOM_RIGHT;
} else if (cornerValue.equals(BOTTOM_LEFT)) {
corner = InstabugVideoRecordingButtonCorner.BOTTOM_LEFT;
} else if (cornerValue.equals(TOP_LEFT)) {
corner = InstabugVideoRecordingButtonCorner.TOP_LEFT;
} else if (cornerValue.equals(TOP_RIGHT)) {
corner = InstabugVideoRecordingButtonCorner.TOP_RIGHT;
}
} catch (Exception e) {
e.printStackTrace();
}
return corner;
}
private Locale getLocaleByKey(String instabugLocale) {
String localeInLowerCase = instabugLocale.toLowerCase();
switch (localeInLowerCase) {
case LOCALE_ARABIC:
return new Locale(InstabugLocale.ARABIC.getCode(), InstabugLocale.ARABIC
.getCountry());
case LOCALE_ENGLISH:
return new Locale(InstabugLocale.ENGLISH.getCode(), InstabugLocale.ENGLISH
.getCountry());
case LOCALE_CZECH:
return new Locale(InstabugLocale.CZECH.getCode(), InstabugLocale.CZECH.getCountry
());
case LOCALE_FRENCH:
return new Locale(InstabugLocale.FRENCH.getCode(), InstabugLocale.FRENCH
.getCountry());
case LOCALE_GERMAN:
return new Locale(InstabugLocale.GERMAN.getCode(), InstabugLocale.GERMAN
.getCountry());
case LOCALE_ITALIAN:
return new Locale(InstabugLocale.ITALIAN.getCode(), InstabugLocale.ITALIAN
.getCountry());
case LOCALE_JAPANESE:
return new Locale(InstabugLocale.JAPANESE.getCode(), InstabugLocale.JAPANESE
.getCountry());
case LOCALE_POLISH:
return new Locale(InstabugLocale.POLISH.getCode(), InstabugLocale.POLISH
.getCountry());
case LOCALE_RUSSIAN:
return new Locale(InstabugLocale.RUSSIAN.getCode(), InstabugLocale.RUSSIAN
.getCountry());
case LOCALE_SPANISH:
return new Locale(InstabugLocale.SPANISH.getCode(), InstabugLocale.SPANISH
.getCountry());
case LOCALE_SWEDISH:
return new Locale(InstabugLocale.SWEDISH.getCode(), InstabugLocale.SWEDISH
.getCountry());
case LOCALE_TURKISH:
return new Locale(InstabugLocale.TURKISH.getCode(), InstabugLocale.TURKISH
.getCountry());
case LOCALE_PORTUGUESE_BRAZIL:
return new Locale(InstabugLocale.PORTUGUESE_BRAZIL.getCode(), InstabugLocale
.PORTUGUESE_BRAZIL.getCountry());
case LOCALE_CHINESE_SIMPLIFIED:
return new Locale(InstabugLocale.SIMPLIFIED_CHINESE.getCode(), InstabugLocale
.SIMPLIFIED_CHINESE.getCountry());
case LOCALE_CHINESE_TRADITIONAL:
return new Locale(InstabugLocale.TRADITIONAL_CHINESE.getCode(), InstabugLocale
.TRADITIONAL_CHINESE.getCountry());
case LOCALE_KOREAN:
return new Locale(InstabugLocale.KOREAN.getCode(), InstabugLocale.KOREAN
.getCountry());
default:
return new Locale(InstabugLocale.ENGLISH.getCode(), InstabugLocale.ENGLISH
.getCountry());
}
}
private void sendEvent(ReactApplicationContext reactContext,
String eventName,
@Nullable WritableMap params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("invocationEventNone", INVOCATION_EVENT_NONE);
constants.put("invocationEventShake", INVOCATION_EVENT_SHAKE);
constants.put("invocationEventScreenshot", INVOCATION_EVENT_SCREENSHOT);
constants.put("invocationEventTwoFingersSwipe", INVOCATION_EVENT_TWO_FINGERS_SWIPE);
constants.put("invocationEventFloatingButton", INVOCATION_EVENT_FLOATING_BUTTON);
constants.put("colorThemeLight", COLOR_THEME_LIGHT);
constants.put("colorThemeDark", COLOR_THEME_DARK);
constants.put("invocationModeNewBug", INVOCATION_MODE_NEW_BUG);
constants.put("invocationModeNewFeedback", INVOCATION_MODE_NEW_FEEDBACK);
constants.put("invocationModeNewChat", INVOCATION_MODE_NEW_CHAT);
constants.put("invocationModeChatsList", INVOCATION_MODE_CHATS_LIST);
constants.put("floatingButtonEdgeLeft",FLOATING_BUTTON_EDGE_LEFT);
constants.put("floatingButtonEdgeRight",FLOATING_BUTTON_EDGE_RIGHT);
constants.put("localeArabic", LOCALE_ARABIC);
constants.put("localeChineseSimplified", LOCALE_CHINESE_SIMPLIFIED);
constants.put("localeChineseTraditional", LOCALE_CHINESE_TRADITIONAL);
constants.put("localeCzech", LOCALE_CZECH);
constants.put("localeEnglish", LOCALE_ENGLISH);
constants.put("localeFrench", LOCALE_FRENCH);
constants.put("localeGerman", LOCALE_FRENCH);
constants.put("localeKorean", LOCALE_KOREAN);
constants.put("localeItalian", LOCALE_ITALIAN);
constants.put("localeJapanese", LOCALE_JAPANESE);
constants.put("localePolish", LOCALE_POLISH);
constants.put("localePortugueseBrazil", LOCALE_PORTUGUESE_BRAZIL);
constants.put("localeRussian", LOCALE_RUSSIAN);
constants.put("localeSpanish", LOCALE_SPANISH);
constants.put("localeSwedish", LOCALE_SWEDISH);
constants.put("localeTurkish", LOCALE_TURKISH);
constants.put("topRight", TOP_RIGHT);
constants.put("topLeft", TOP_LEFT);
constants.put("bottomRight", BOTTOM_RIGHT);
constants.put("bottomLeft", BOTTOM_LEFT);
constants.put("enabledWithRequiredFields", EXTENDED_BUG_REPORT_REQUIRED_FIELDS);
constants.put("enabledWithOptionalFields", EXTENDED_BUG_REPORT_OPTIONAL_FIELDS);
constants.put("disabled", EXTENDED_BUG_REPORT_DISABLED);
constants.put("reproStepsEnabledWithNoScreenshots", ENABLED_WITH_NO_SCREENSHOTS);
constants.put("reproStepsEnabled", ENABLED);
constants.put("reproStepsDisabled", DISABLED);
constants.put("shakeHint", SHAKE_HINT);
constants.put("swipeHint", SWIPE_HINT);
constants.put("invalidEmailMessage", INVALID_EMAIL_MESSAGE);
constants.put("invalidCommentMessage", INVALID_COMMENT_MESSAGE);
constants.put("emailFieldHint", EMAIL_FIELD_HINT);
constants.put("commentFieldHintForBugReport", COMMENT_FIELD_HINT_FOR_BUG_REPORT);
constants.put("commentFieldHintForFeedback", COMMENT_FIELD_HINT_FOR_FEEDBACK);
constants.put("invocationHeader", INVOCATION_HEADER);
constants.put("talkToUs", START_CHATS);
constants.put("reportBug", REPORT_BUG);
constants.put("reportFeedback", REPORT_FEEDBACK);
constants.put("conversationsHeaderTitle", CONVERSATIONS_LIST_TITLE);
constants.put("addVoiceMessage", ADD_VOICE_MESSAGE);
constants.put("addImageFromGallery", ADD_IMAGE_FROM_GALLERY);
constants.put("addExtraScreenshot", ADD_EXTRA_SCREENSHOT);
constants.put("addVideoMessage", ADD_VIDEO);
constants.put("audioRecordingPermissionDeniedMessage", AUDIO_RECORDING_PERMISSION_DENIED);
constants.put("recordingMessageToHoldText", VOICE_MESSAGE_PRESS_AND_HOLD_TO_RECORD);
constants.put("recordingMessageToReleaseText", VOICE_MESSAGE_RELEASE_TO_ATTACH);
constants.put("thankYouText", REPORT_SUCCESSFULLY_SENT);
constants.put("video", VIDEO_PLAYER_TITLE);
constants.put("conversationTextFieldHint", CONVERSATION_TEXT_FIELD_HINT);
return constants;
}
}
| android/src/main/java/com/instabug/reactlibrary/RNInstabugReactnativeModule.java | package com.instabug.reactlibrary;
import android.app.Application;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.bridge.Callback;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.instabug.library.Feature;
import com.instabug.library.Instabug;
import com.instabug.library.extendedbugreport.ExtendedBugReport;
import com.instabug.library.internal.module.InstabugLocale;
import com.instabug.library.invocation.InstabugInvocationEvent;
import com.instabug.library.invocation.InstabugInvocationMode;
import com.instabug.library.InstabugColorTheme;
import com.instabug.library.invocation.util.InstabugVideoRecordingButtonCorner;
import com.instabug.library.logging.InstabugLog;
import com.instabug.library.bugreporting.model.ReportCategory;
import com.instabug.library.InstabugCustomTextPlaceHolder;
import com.instabug.library.user.UserEventParam;
import com.instabug.library.OnSdkDismissedCallback;
import com.instabug.library.bugreporting.model.Bug;
import com.instabug.library.visualusersteps.State;
import com.instabug.survey.InstabugSurvey;
import com.instabug.reactlibrary.utils.ArrayUtil;
import com.instabug.reactlibrary.utils.MapUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* The type Rn instabug reactnative module.
*/
public class RNInstabugReactnativeModule extends ReactContextBaseJavaModule {
//InvocationEvents
private final String INVOCATION_EVENT_NONE = "none";
private final String INVOCATION_EVENT_SHAKE = "shake";
private final String INVOCATION_EVENT_SCREENSHOT = "screenshot";
private final String INVOCATION_EVENT_TWO_FINGERS_SWIPE = "swipe";
private final String INVOCATION_EVENT_FLOATING_BUTTON = "button";
//InvocationModes
private final String INVOCATION_MODE_NEW_BUG = "bug";
private final String INVOCATION_MODE_NEW_FEEDBACK = "feedback";
private final String INVOCATION_MODE_NEW_CHAT = "chat";
private final String INVOCATION_MODE_CHATS_LIST = "chats";
//FloatingButtonEdge
private final String FLOATING_BUTTON_EDGE_RIGHT = "right";
private final String FLOATING_BUTTON_EDGE_LEFT = "left";
//locales
private final String LOCALE_ARABIC = "arabic";
private final String LOCALE_CHINESE_SIMPLIFIED = "chinesesimplified";
private final String LOCALE_CHINESE_TRADITIONAL = "chinesetraditional";
private final String LOCALE_CZECH = "czech";
private final String LOCALE_ENGLISH = "english";
private final String LOCALE_FRENCH = "french";
private final String LOCALE_GERMAN = "german";
private final String LOCALE_KOREAN = "korean";
private final String LOCALE_ITALIAN = "italian";
private final String LOCALE_JAPANESE = "japanese";
private final String LOCALE_POLISH = "polish";
private final String LOCALE_PORTUGUESE_BRAZIL = "portuguesebrazil";
private final String LOCALE_RUSSIAN = "russian";
private final String LOCALE_SPANISH = "spanish";
private final String LOCALE_SWEDISH = "swedish";
private final String LOCALE_TURKISH = "turkish";
//Instabug Button Corner
private final String TOP_RIGHT = "topRight";
private final String TOP_LEFT = "topLeft";
private final String BOTTOM_RIGHT = "bottomRight";
private final String BOTTOM_LEFT = "bottomLeft";
//Instabug extended bug report modes
private final String EXTENDED_BUG_REPORT_REQUIRED_FIELDS = "enabledWithRequiredFields";
private final String EXTENDED_BUG_REPORT_OPTIONAL_FIELDS = "enabledWithOptionalFields";
private final String EXTENDED_BUG_REPORT_DISABLED = "disabled";
//Instabug repro step modes
private final String ENABLED_WITH_NO_SCREENSHOTS = "enabledWithNoScreenshots";
private final String ENABLED = "enabled";
private final String DISABLED = "disabled";
//Theme colors
private final String COLOR_THEME_LIGHT = "light";
private final String COLOR_THEME_DARK = "dark";
//CustomTextPlaceHolders
private final String SHAKE_HINT = "shakeHint";
private final String SWIPE_HINT = "swipeHint";
private final String INVALID_EMAIL_MESSAGE = "invalidEmailMessage";
private final String INVALID_COMMENT_MESSAGE = "invalidCommentMessage";
private final String EMAIL_FIELD_HINT = "emailFieldHint";
private final String COMMENT_FIELD_HINT_FOR_BUG_REPORT = "commentFieldHintForBugReport";
private final String COMMENT_FIELD_HINT_FOR_FEEDBACK = "commentFieldHintForFeedback";
private final String INVOCATION_HEADER = "invocationHeader";
private final String START_CHATS = "talkToUs";
private final String REPORT_BUG = "reportBug";
private final String REPORT_FEEDBACK = "reportFeedback";
private final String CONVERSATIONS_LIST_TITLE = "conversationsHeaderTitle";
private final String ADD_VOICE_MESSAGE = "addVoiceMessage";
private final String ADD_IMAGE_FROM_GALLERY = "addImageFromGallery";
private final String ADD_EXTRA_SCREENSHOT = "addExtraScreenshot";
private final String ADD_VIDEO = "addVideoMessage";
private final String AUDIO_RECORDING_PERMISSION_DENIED = "audioRecordingPermissionDeniedMessage";
private final String VOICE_MESSAGE_PRESS_AND_HOLD_TO_RECORD = "recordingMessageToHoldText";
private final String VOICE_MESSAGE_RELEASE_TO_ATTACH = "recordingMessageToReleaseText";
private final String REPORT_SUCCESSFULLY_SENT = "thankYouText";
private final String VIDEO_PLAYER_TITLE = "video";
private final String CONVERSATION_TEXT_FIELD_HINT = "conversationTextFieldHint";
private Application androidApplication;
private Instabug mInstabug;
private InstabugInvocationEvent invocationEvent;
private InstabugCustomTextPlaceHolder placeHolders;
/**
* Instantiates a new Rn instabug reactnative module.
*
* @param reactContext the react context
* @param mInstabug the m instabug
*/
public RNInstabugReactnativeModule(ReactApplicationContext reactContext, Application
androidApplication, Instabug mInstabug) {
super(reactContext);
this.androidApplication = androidApplication;
this.mInstabug = mInstabug;
//init placHolders
placeHolders = new InstabugCustomTextPlaceHolder();
}
@Override
public String getName() {
return "Instabug";
}
@ReactMethod
public void startWithToken(String androidToken, String invocationEvent) {
mInstabug = new Instabug.Builder(this.androidApplication, androidToken)
.setIntroMessageEnabled(false)
.setInvocationEvent(getInvocationEventById(invocationEvent))
.build();
//init placHolders
placeHolders = new InstabugCustomTextPlaceHolder();
}
/**
* invoke sdk manually
*/
@ReactMethod
public void invoke() {
try {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
mInstabug.invoke();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* invoke sdk manually with desire invocation mode
*
* @param invocationMode the invocation mode
*/
@ReactMethod
public void invokeWithInvocationMode(String invocationMode) {
InstabugInvocationMode mode;
if (invocationMode.equals(INVOCATION_MODE_NEW_BUG)) {
mode = InstabugInvocationMode.NEW_BUG;
} else if (invocationMode.equals(INVOCATION_MODE_NEW_FEEDBACK)) {
mode = InstabugInvocationMode.NEW_FEEDBACK;
} else if (invocationMode.equals(INVOCATION_MODE_NEW_CHAT)) {
mode = InstabugInvocationMode.NEW_CHAT;
} else if (invocationMode.equals(INVOCATION_MODE_CHATS_LIST)) {
mode = InstabugInvocationMode.CHATS_LIST;
} else {
mode = InstabugInvocationMode.PROMPT_OPTION;
}
try {
mInstabug.invoke(mode);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Dismisses all visible Instabug views
*/
@ReactMethod
public void dismiss() {
try {
mInstabug.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adds tag(s) to issues before sending them
*
* @param tags
*/
@ReactMethod
public void appendTags(ReadableArray tags) {
try {
Object[] objectArray = ArrayUtil.toArray(tags);
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
mInstabug.addTags(stringArray);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Enable/Disable screen recording
*
* @param autoScreenRecordingEnabled boolean for enable/disable
* screen recording on crash feature
*/
@ReactMethod
public void setAutoScreenRecordingEnabled(boolean autoScreenRecordingEnabled) {
try {
Instabug.setAutoScreenRecordingEnabled(autoScreenRecordingEnabled);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets auto screen recording maximum duration
*
* @param autoScreenRecordingMaxDuration maximum duration of the screen recording video
* in milliseconds
* The maximum duration is 30000 milliseconds
*/
@ReactMethod
public void setAutoScreenRecordingMaxDuration(int autoScreenRecordingMaxDuration) {
try {
int durationInMilli = autoScreenRecordingMaxDuration*1000;
Instabug.setAutoScreenRecordingMaxDuration(durationInMilli);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Change Locale of Instabug UI elements(defaults to English)
*
* @param instabugLocale
*/
@ReactMethod
public void changeLocale(String instabugLocale) {
try {
mInstabug.changeLocale(getLocaleByKey(instabugLocale));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets whether the extended bug report mode should be disabled,
* enabled with required fields, or enabled with optional fields.
*
* @param extendedBugReportMode
*/
@ReactMethod
public void setExtendedBugReportMode(String extendedBugReportMode) {
try {
switch(extendedBugReportMode) {
case EXTENDED_BUG_REPORT_REQUIRED_FIELDS:
Instabug.setExtendedBugReportState(ExtendedBugReport.State.ENABLED_WITH_REQUIRED_FIELDS);
break;
case EXTENDED_BUG_REPORT_OPTIONAL_FIELDS:
Instabug.setExtendedBugReportState(ExtendedBugReport.State.ENABLED_WITH_OPTIONAL_FIELDS);
break;
case EXTENDED_BUG_REPORT_DISABLED:
Instabug.setExtendedBugReportState(ExtendedBugReport.State.DISABLED);
break;
default:
Instabug.setExtendedBugReportState(ExtendedBugReport.State.DISABLED);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@ReactMethod
public void setViewHierarchyEnabled(boolean enabled) {
try {
if(enabled) {
Instabug.setViewHierarchyState(Feature.State.ENABLED);
} else {
Instabug.setViewHierarchyState(Feature.State.DISABLED);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets the default corner at which the video recording floating button will be shown
*
* @param corner corner to stick the video recording floating button to
*/
@ReactMethod
public void setVideoRecordingFloatingButtonPosition(String corner) {
try {
mInstabug.setVideoRecordingFloatingButtonCorner(getVideoRecordingButtonCorner(corner));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* The file at filePath will be uploaded along upcoming reports with the name
* fileNameWithExtension
*
* @param fileUri the file uri
* @param fileNameWithExtension the file name with extension
*/
@ReactMethod
public void setFileAttachment(String fileUri, String fileNameWithExtension) {
try {
Uri uri = Uri.parse(fileUri);
mInstabug.setFileAttachment(uri, fileNameWithExtension);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* If your app already acquires the user's email address and you provide it to this method,
* Instabug will pre-fill the user email in reports.
*
* @param userEmail the user email
*/
@ReactMethod
public void setUserEmail(String userEmail) {
try {
mInstabug.setUserEmail(userEmail);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets the user name that is used in the dashboard's contacts.
*
* @param username the username
*/
@ReactMethod
public void setUserName(String username) {
try {
mInstabug.setUsername(username);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adds specific user data that you need to be added to the reports
*
* @param userData
*/
@ReactMethod
public void setUserData(String userData) {
try {
mInstabug.setUserData(userData);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Call this method to display the discovery dialog explaining the shake gesture or the two
* finger swipe gesture, if you've enabled it.
* i.e: This method is automatically called on first run of the application
*/
@ReactMethod
public void showIntroMessage() {
try {
mInstabug.showIntroMessage();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set the primary color that the SDK will use to tint certain UI elements in the SDK
*
* @param primaryColor The value of the primary color ,
* whatever this color was parsed from a resource color or hex color
* or RGB color values
*/
@ReactMethod
public void setPrimaryColor(int primaryColor) {
try {
mInstabug.setPrimaryColor(primaryColor);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets whether attachments in bug reporting and in-app messaging are enabled or not.
*
* @param {boolean} screenShot A boolean to enable or disable screenshot attachments.
* @param {boolean} extraScreenShot A boolean to enable or disable extra screenshot attachments.
* @param {boolean} galleryImage A boolean to enable or disable gallery image attachments.
* @param {boolean} screenRecording A boolean to enable or disable screen recording attachments.
*/
@ReactMethod
public void setEnabledAttachmentTypes(boolean screenshot, boolean extraScreenshot, boolean
galleryImage, boolean screenRecording) {
try {
Instabug.setAttachmentTypesEnabled(screenshot, extraScreenshot, galleryImage,
screenRecording);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Appends a log message to Instabug internal log
* These logs are then sent along the next uploaded report. All log messages are timestamped
* Logs aren't cleared per single application run. If you wish to reset the logs, use
* Note: logs passed to this method are <b>NOT</b> printed to Logcat
*
* @param message log message
*/
@ReactMethod
public void IBGLog(String message) {
try {
mInstabug.log(message);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets tags.
*
* @return all tags added
* @see #resetTags()
*/
@ReactMethod
public void getTags(Callback tagsCallback) {
WritableArray tagsArray;
try {
ArrayList<String> tags = mInstabug.getTags();
tagsArray = new WritableNativeArray();
for (int i = 0; i < tags.size(); i++) {
tagsArray.pushString(tags.get(i));
}
tagsCallback.invoke(tagsArray);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set the user identity.
* Instabug will pre-fill the user email in reports.
*
* @param userName Username.
* @param userEmail User's default email
*/
@ReactMethod
public void identifyUser(String userName, String userEmail) {
try {
mInstabug.identifyUser(userName, userEmail);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Reset ALL tags added
*/
@ReactMethod
public void resetTags() {
try {
mInstabug.resetTags();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Is enabled boolean.
*
* @return {@code true} if Instabug is enabled, {@code false} if it's disabled
* @see #enable()
* @see #disable()
*/
@ReactMethod
public boolean isEnabled() {
boolean isEnabled = false;
try {
isEnabled = mInstabug.isEnabled();
} catch (Exception e) {
e.printStackTrace();
}
return isEnabled;
}
/**
* Enables all Instabug functionality
*/
@ReactMethod
public void enable() {
try {
mInstabug.enable();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Disables all Instabug functionality
*/
@ReactMethod
public void disable() {
try {
mInstabug.disable();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return application token
*/
@ReactMethod
public String getAppToken() {
String appToken = "";
try {
appToken = mInstabug.getAppToken();
} catch (Exception e) {
e.printStackTrace();
}
return appToken;
}
/**
* Get current unread count of messages for this user
*
* @return number of messages that are unread for this user
*/
@ReactMethod
public void getUnreadMessagesCount(Callback messageCountCallback) {
int unreadMessages = 0;
try {
unreadMessages = mInstabug.getUnreadMessagesCount();
} catch (Exception e) {
e.printStackTrace();
}
messageCountCallback.invoke(unreadMessages);
}
/**
* Sets the event used to invoke Instabug SDK
*
* @param invocationEventValue the invocation event value
* @see InstabugInvocationEvent
*/
@ReactMethod
public void setInvocationEvent(String invocationEventValue) {
try {
mInstabug.changeInvocationEvent(getInvocationEventById(invocationEventValue));
} catch (Exception e) {
e.printStackTrace();
}
}
private InstabugInvocationEvent getInvocationEventById(String invocationEventValue) {
InstabugInvocationEvent invocationEvent = InstabugInvocationEvent.SHAKE;
try {
if (invocationEventValue.equals(INVOCATION_EVENT_FLOATING_BUTTON)) {
invocationEvent = InstabugInvocationEvent.FLOATING_BUTTON;
} else if (invocationEventValue.equals(INVOCATION_EVENT_TWO_FINGERS_SWIPE)) {
invocationEvent = InstabugInvocationEvent.TWO_FINGER_SWIPE_LEFT;
} else if (invocationEventValue.equals(INVOCATION_EVENT_SHAKE)) {
invocationEvent = InstabugInvocationEvent.SHAKE;
} else if (invocationEventValue.equals(INVOCATION_EVENT_SCREENSHOT)) {
invocationEvent = InstabugInvocationEvent.SCREENSHOT_GESTURE;
} else if (invocationEventValue.equals(INVOCATION_EVENT_NONE)) {
invocationEvent = InstabugInvocationEvent.NONE;
}
} catch (Exception e) {
e.printStackTrace();
}
return invocationEvent;
}
/**
* Enabled/disable chat notification
*
* @param isChatNotificationEnable whether chat notification is reburied or not
*/
@ReactMethod
public void setChatNotificationEnabled(boolean isChatNotificationEnable) {
try {
mInstabug.setChatNotificationEnabled(isChatNotificationEnable);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Enable/Disable debug logs from Instabug SDK
* Default state: disabled
*
* @param isDebugEnabled whether debug logs should be printed or not into LogCat
*/
@ReactMethod
public void setDebugEnabled(boolean isDebugEnabled) {
try {
mInstabug.setDebugEnabled(isDebugEnabled);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Report a caught exception to Instabug dashboard
*
* @param stack the exception to be reported
* @param message the message of the exception to be reported
* @param errorIdentifier used to group issues manually reported
*/
@ReactMethod
public void reportJsException(ReadableArray stack, String message, String errorIdentifier) {
try {
int size = stack != null ? stack.size() : 0;
StackTraceElement[] stackTraceElements = new StackTraceElement[size];
for (int i = 0; i < size; i++) {
ReadableMap frame = stack.getMap(i);
String methodName = frame.getString("methodName");
String fileName = frame.getString("file");
int lineNumber = frame.getInt("lineNumber");
stackTraceElements[i] = new StackTraceElement(fileName, methodName, fileName,
lineNumber);
}
Throwable throwable = new Throwable(message);
throwable.setStackTrace(stackTraceElements);
if (errorIdentifier != null)
mInstabug.reportException(throwable);
else
mInstabug.reportException(throwable, errorIdentifier);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Appends a log message to Instabug internal log
* <p>
* These logs are then sent along the next uploaded report.
* All log messages are timestamped <br/>
* Logs aren't cleared per single application run. If you wish to reset the logs,
* use {@link #clearLogs()} ()}
* </p>
* Note: logs passed to this method are <b>NOT</b> printed to Logcat
*
* @param level the level
* @param message the message
*/
@ReactMethod
public void log(String level, String message) {
try {
switch (level) {
case "v":
InstabugLog.v(message);
break;
case "i":
InstabugLog.i(message);
break;
case "d":
InstabugLog.d(message);
break;
case "e":
InstabugLog.e(message);
break;
case "w":
InstabugLog.w(message);
break;
case "wtf":
InstabugLog.wtf(message);
break;
default:
InstabugLog.d(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Clears Instabug internal log
*/
@ReactMethod
public void clearLogs() {
try {
InstabugLog.clearLogs();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns true if the survey with a specific token was answered before.
* Will return false if the token does not exist or if the survey was not answered before.
*
* @param surveyToken the attribute key as string
* @param hasRespondedCallback A callback that gets invoked with the returned value of whether
* the user has responded to the survey or not.
* @return the desired value of whether the user has responded to the survey or not.
*/
@ReactMethod
public void hasRespondedToSurveyWithToken(String surveyToken, Callback hasRespondedCallback) {
boolean hasResponded;
try {
hasResponded = Instabug.hasRespondToSurvey(surveyToken);
hasRespondedCallback.invoke(hasResponded);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Shows survey with a specific token.
* Does nothing if there are no available surveys with that specific token.
* Answered and cancelled surveys won't show up again.
*
* @param surveyToken A String with a survey token.
*/
@ReactMethod
public void showSurveyWithToken(String surveyToken) {
try {
Instabug.showSurvey(surveyToken);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets user attribute to overwrite it's value or create a new one if it doesn't exist.
*
* @param key the attribute
* @param value the value
*/
@ReactMethod
public void setUserAttribute(String key, String value) {
try {
mInstabug.setUserAttribute(key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets specific user attribute.
*
* @param key the attribute key as string
* @return the desired user attribute
*/
@ReactMethod
public void getUserAttribute(String key, Callback userAttributeCallback) {
String userAttribute;
try {
userAttribute = mInstabug.getUserAttribute(key);
userAttributeCallback.invoke(userAttribute);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Removes user attribute if exists.
*
* @param key the attribute key as string
* @see #setUserAttribute(String, String)
*/
@ReactMethod
public void removeUserAttribute(String key) {
try {
mInstabug.removeUserAttribute(key);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets all saved user attributes.
*
* @return all user attributes as HashMap<String, String>
*/
@ReactMethod
public void getAllUserAttributes(Callback userAttributesCallback) {
WritableMap writableMap = new WritableNativeMap();
try {
HashMap<String, String> map = mInstabug.getAllUserAttributes();
for (HashMap.Entry<String, String> entry : map.entrySet()) {
writableMap.putString(entry.getKey(), entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
userAttributesCallback.invoke(writableMap);
}
/**
* Clears all user attributes if exists.
*/
@ReactMethod
public void clearAllUserAttributes() {
try {
mInstabug.clearAllUserAttributes();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets InstabugSDK theme color.
*
* @param theme which is a constant String "light" or "dark"
*/
@ReactMethod
public void setColorTheme(String theme) {
try {
if (theme.equals(COLOR_THEME_LIGHT)) {
mInstabug.setTheme(InstabugColorTheme.InstabugColorThemeLight);
} else if (theme.equals(COLOR_THEME_DARK)) {
mInstabug.setTheme(InstabugColorTheme.InstabugColorThemeDark);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Allows you to show a predefined set of categories for users to choose
* from when reporting a bug or sending feedback. Selected category
* shows up on your Instabug dashboard as a tag to make filtering
* through issues easier.
*
* @param categoriesTitles the report categories list which is a list of ReportCategory model
*/
@ReactMethod
public void setReportCategories(ReadableArray categoriesTitles) {
try {
ArrayList<ReportCategory> bugCategories = new ArrayList<>();
int size = categoriesTitles != null ? categoriesTitles.size() : 0;
if (size == 0) return;
for (int i = 0; i < size; i++) {
bugCategories.add(ReportCategory.getInstance().withLabel(categoriesTitles
.getString(i)));
}
Instabug.setReportCategories(bugCategories);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets whether users are required to enter an email address or not when
* sending reports.
* Defaults to YES.
*
* @param isEmailFieldRequired A boolean to indicate whether email
* field is required or not.
*/
@ReactMethod
public void setEmailFieldRequired(boolean isEmailFieldRequired) {
try {
mInstabug.setEmailFieldRequired(isEmailFieldRequired);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets whether users are required to enter a comment or not when sending reports.
* Defaults to NO.
*
* @param isCommentFieldRequired A boolean to indicate whether comment
* field is required or not.
*/
@ReactMethod
public void setCommentFieldRequired(boolean isCommentFieldRequired) {
try {
mInstabug.setCommentFieldRequired(isCommentFieldRequired);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Overrides any of the strings shown in the SDK with custom ones.
* Allows you to customize any of the strings shown to users in the SDK.
*
* @param string String value to override the default one.
* @param key Key of string to override.
*/
@ReactMethod
public void setString(String string, String key) {
try {
placeHolders.set(getStringToKeyConstant(key), string);
Instabug.setCustomTextPlaceHolders(placeHolders);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets the default value of the user's email to null and show email field and remove user
* name from all reports
* It also reset the chats on device and removes user attributes, user data and completed
* surveys.
*/
@ReactMethod
public void logOut() {
try {
mInstabug.logoutUser();
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Enables/disables screenshot view when reporting a bug/improvement.
* By default, screenshot view is shown when reporting a bug, but not when
* sending feedback.
*
* @param willSkipScreenshotAnnotation sets whether screenshot view is
* shown or not. Passing YES will show screenshot view for both feedback and
* bug reporting, while passing NO will disable it for both.
*/
@ReactMethod
public void setWillSkipScreenshotAnnotation(boolean willSkipScreenshotAnnotation) {
try {
mInstabug.setWillSkipScreenshotAnnotation(willSkipScreenshotAnnotation);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Logs a user event that happens through the lifecycle of the application.
* Logged user events are going to be sent with each report, as well as at the end of a session.
*
* @param name Event name.
*/
@ReactMethod
public void logUserEventWithName(String name) {
try {
mInstabug.logUserEvent(name);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Logs a user event that happens through the lifecycle of the application.
* Logged user events are going to be sent with each report, as well as at the end of a
* session.
*
* @param name Event name.
* @param params An optional ReadableMap to be associated with the event.
*/
@ReactMethod
public void logUserEventWithNameAndParams(String name, ReadableMap params) {
try {
Map<String, Object> paramsMap = MapUtil.toMap(params);
UserEventParam[] userEventParams = new UserEventParam[paramsMap.size()];
int index = 0;
UserEventParam userEventParam;
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
userEventParam = new UserEventParam().setKey(entry.getKey())
.setValue((entry.getValue()).toString());
userEventParams[index] = userEventParam;
index++;
}
mInstabug.logUserEvent(name, userEventParams);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets a block of code to be executed just before the SDK's UI is presented.
* This block is executed on the UI thread. Could be used for performing any
* UI changes before the SDK's UI is shown.
*
* @param preInvocationHandler - A callback that gets executed before
* invoking the SDK
*/
@ReactMethod
public void setPreInvocationHandler(final Callback preInvocationHandler) {
try {
Runnable preInvocationRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGpreInvocationHandler", null);
}
};
mInstabug.setPreInvocation(preInvocationRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets a block of code to be executed before sending each report.
* This block is executed in the background before sending each report. Could
* be used for attaching logs and extra data to reports.
*
* @param preSendingHandler - A callback that gets executed before
* sending each bug
* report.
*/
@ReactMethod
public void setPreSendingHandler(final Callback preSendingHandler) {
try {
Runnable preSendingRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGpreSendingHandler", null);
}
};
mInstabug.setPreSendingRunnable(preSendingRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets a block of code to be executed right after the SDK's UI is dismissed.
* This block is executed on the UI thread. Could be used for performing any
* UI changes after the SDK's UI is dismissed.
*
* @param postInvocationHandler - A callback to get executed after
* dismissing the SDK.
*/
@ReactMethod
public void setPostInvocationHandler(final Callback postInvocationHandler) {
try {
mInstabug.setOnSdkDismissedCallback(new OnSdkDismissedCallback() {
@Override
public void onSdkDismissed(DismissType issueState, Bug.Type bugType) {
WritableMap params = Arguments.createMap();
params.putString("issueState", issueState.toString());
params.putString("bugType", bugType.toString());
sendEvent(getReactApplicationContext(), "IBGpostInvocationHandler", params);
}
});
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Show any valid survey if exist
*
* @return true if a valid survey was shown otherwise false
*/
@ReactMethod
public void showSurveysIfAvailable() {
try {
mInstabug.showValidSurvey();
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Show any valid survey if exist
*
* @return true if a valid survey was shown otherwise false
*/
@ReactMethod
public void setSurveysEnabled(boolean surveysEnabled) {
try {
InstabugSurvey.setSurveysAutoShowing(surveysEnabled);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets the default value of the intro message guide that gets shown on launching the app
*
* @param enabled true to show intro message guide
*/
@ReactMethod
public void setIntroMessageEnabled(boolean enabled) {
try {
mInstabug.setIntroMessageEnabled(enabled);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets the runnable that gets executed just before showing any valid survey<br/>
* WARNING: This runs on your application's main UI thread. Please do not include
* any blocking operations to avoid ANRs.
*
* @param willShowSurveyHandler to run on the UI thread before showing any valid survey
*/
@ReactMethod
public void setWillShowSurveyHandler(final Callback willShowSurveyHandler) {
try {
Runnable willShowSurveyRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGWillShowSurvey", null);
}
};
mInstabug.setPreShowingSurveyRunnable(willShowSurveyRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Sets the runnable that gets executed just after showing any valid survey<br/>
* WARNING: This runs on your application's main UI thread. Please do not include
* any blocking operations to avoid ANRs.
*
* @param didDismissSurveyHandler to run on the UI thread after showing any valid survey
*/
@ReactMethod
public void setDidDismissSurveyHandler(final Callback didDismissSurveyHandler) {
try {
Runnable didDismissSurveyRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGDidDismissSurvey", null);
}
};
mInstabug.setAfterShowingSurveyRunnable(didDismissSurveyRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* Enable/Disable prompt options when SDK invoked. When only a single option is enabled it
* becomes the default
* invocation option that SDK gets invoked with and prompt options screen will not show. When
* none is enabled, Bug
* reporting becomes the default invocation option.
*
* @param chat weather Talk to us is enable or not
* @param bug weather Report a Problem is enable or not
* @param feedback weather General Feedback is enable or not
*/
@ReactMethod
public void setPromptOptionsEnabled(boolean chat, boolean bug, boolean feedback) {
try {
mInstabug.setPromptOptionsEnabled(chat, bug, feedback);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Clears all Uris of the attached files.
* The URIs which added via {@link Instabug#addFileAttachment} API not the physical files.
*/
@ReactMethod
public void clearFileAttachment() {
try {
mInstabug.clearFileAttachment();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets whether user steps tracking is visual, non visual or disabled.
*
* @param reproStepsMode A string to set user steps tracking to be
* enabled, non visual or disabled.
*/
@ReactMethod
public void setReproStepsMode(String reproStepsMode) {
try {
switch(reproStepsMode) {
case ENABLED_WITH_NO_SCREENSHOTS:
Instabug.setReproStepsState(State.ENABLED_WITH_NO_SCREENSHOTS);
break;
case ENABLED:
Instabug.setReproStepsState(State.ENABLED);
break;
case DISABLED:
Instabug.setReproStepsState(State.DISABLED);
break;
default:
Instabug.setReproStepsState(State.ENABLED);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets the threshold value of the shake gesture for android devices.
* Default for android is an integer value equals 350.
* you could increase the shaking difficulty level by
* increasing the `350` value and vice versa.
*
* @param androidThreshold Threshold for android devices.
*/
@ReactMethod
public void setShakingThresholdForAndroid(int androidThreshold) {
try {
mInstabug.setShakingThreshold(androidThreshold);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets a block of code that gets executed when a new message is received.
*
* @param onNewMessageHandler - A callback that gets
* executed when a new message is received.
*/
@ReactMethod
public void setOnNewMessageHandler(final Callback onNewMessageHandler) {
try {
Runnable onNewMessageRunnable = new Runnable() {
@Override
public void run() {
sendEvent(getReactApplicationContext(), "IBGonNewMessageHandler", null);
}
};
mInstabug.setNewMessageHandler(onNewMessageRunnable);
} catch (java.lang.Exception exception) {
exception.printStackTrace();
}
}
/**
* @param enabled true to show success dialog after submitting a bug report
*
*/
@ReactMethod
public void setSuccessDialogEnabled(boolean enabled) {
try {
mInstabug.setSuccessDialogEnabled(enabled);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set whether new in app notification received will play a small sound notification
* or not (Default is {@code false})
*
* @param shouldPlaySound desired state of conversation sounds
* @since 4.1.0
*/
@ReactMethod
public void setEnableInAppNotificationSound(boolean shouldPlaySound) {
try {
mInstabug.setEnableInAppNotificationSound(shouldPlaySound);
} catch (Exception e) {
e.printStackTrace();
}
}
private InstabugCustomTextPlaceHolder.Key getStringToKeyConstant(String key) {
switch (key) {
case SHAKE_HINT:
return InstabugCustomTextPlaceHolder.Key.SHAKE_HINT;
case SWIPE_HINT:
return InstabugCustomTextPlaceHolder.Key.SWIPE_HINT;
case INVALID_EMAIL_MESSAGE:
return InstabugCustomTextPlaceHolder.Key.INVALID_EMAIL_MESSAGE;
case INVALID_COMMENT_MESSAGE:
return InstabugCustomTextPlaceHolder.Key.INVALID_COMMENT_MESSAGE;
case EMAIL_FIELD_HINT:
return InstabugCustomTextPlaceHolder.Key.EMAIL_FIELD_HINT;
case COMMENT_FIELD_HINT_FOR_BUG_REPORT:
return InstabugCustomTextPlaceHolder.Key.COMMENT_FIELD_HINT_FOR_BUG_REPORT;
case COMMENT_FIELD_HINT_FOR_FEEDBACK:
return InstabugCustomTextPlaceHolder.Key.COMMENT_FIELD_HINT_FOR_FEEDBACK;
case INVOCATION_HEADER:
return InstabugCustomTextPlaceHolder.Key.INVOCATION_HEADER;
case START_CHATS:
return InstabugCustomTextPlaceHolder.Key.START_CHATS;
case REPORT_BUG:
return InstabugCustomTextPlaceHolder.Key.REPORT_BUG;
case REPORT_FEEDBACK:
return InstabugCustomTextPlaceHolder.Key.REPORT_FEEDBACK;
case CONVERSATIONS_LIST_TITLE:
return InstabugCustomTextPlaceHolder.Key.CONVERSATIONS_LIST_TITLE;
case ADD_VOICE_MESSAGE:
return InstabugCustomTextPlaceHolder.Key.ADD_VOICE_MESSAGE;
case ADD_IMAGE_FROM_GALLERY:
return InstabugCustomTextPlaceHolder.Key.ADD_IMAGE_FROM_GALLERY;
case ADD_EXTRA_SCREENSHOT:
return InstabugCustomTextPlaceHolder.Key.ADD_EXTRA_SCREENSHOT;
case ADD_VIDEO:
return InstabugCustomTextPlaceHolder.Key.ADD_VIDEO;
case AUDIO_RECORDING_PERMISSION_DENIED:
return InstabugCustomTextPlaceHolder.Key.AUDIO_RECORDING_PERMISSION_DENIED;
case VOICE_MESSAGE_PRESS_AND_HOLD_TO_RECORD:
return InstabugCustomTextPlaceHolder.Key.VOICE_MESSAGE_PRESS_AND_HOLD_TO_RECORD;
case VOICE_MESSAGE_RELEASE_TO_ATTACH:
return InstabugCustomTextPlaceHolder.Key.VOICE_MESSAGE_RELEASE_TO_ATTACH;
case CONVERSATION_TEXT_FIELD_HINT:
return InstabugCustomTextPlaceHolder.Key.CONVERSATION_TEXT_FIELD_HINT;
case REPORT_SUCCESSFULLY_SENT:
return InstabugCustomTextPlaceHolder.Key.REPORT_SUCCESSFULLY_SENT;
case VIDEO_PLAYER_TITLE:
return InstabugCustomTextPlaceHolder.Key.VIDEO_PLAYER_TITLE;
default:
return null;
}
}
private InstabugVideoRecordingButtonCorner getVideoRecordingButtonCorner(String cornerValue) {
InstabugVideoRecordingButtonCorner corner = InstabugVideoRecordingButtonCorner.BOTTOM_RIGHT;
try {
if (cornerValue.equals(BOTTOM_RIGHT)) {
corner = InstabugVideoRecordingButtonCorner.BOTTOM_RIGHT;
} else if (cornerValue.equals(BOTTOM_LEFT)) {
corner = InstabugVideoRecordingButtonCorner.BOTTOM_LEFT;
} else if (cornerValue.equals(TOP_LEFT)) {
corner = InstabugVideoRecordingButtonCorner.TOP_LEFT;
} else if (cornerValue.equals(TOP_RIGHT)) {
corner = InstabugVideoRecordingButtonCorner.TOP_RIGHT;
}
} catch (Exception e) {
e.printStackTrace();
}
return corner;
}
private Locale getLocaleByKey(String instabugLocale) {
String localeInLowerCase = instabugLocale.toLowerCase();
switch (localeInLowerCase) {
case LOCALE_ARABIC:
return new Locale(InstabugLocale.ARABIC.getCode(), InstabugLocale.ARABIC
.getCountry());
case LOCALE_ENGLISH:
return new Locale(InstabugLocale.ENGLISH.getCode(), InstabugLocale.ENGLISH
.getCountry());
case LOCALE_CZECH:
return new Locale(InstabugLocale.CZECH.getCode(), InstabugLocale.CZECH.getCountry
());
case LOCALE_FRENCH:
return new Locale(InstabugLocale.FRENCH.getCode(), InstabugLocale.FRENCH
.getCountry());
case LOCALE_GERMAN:
return new Locale(InstabugLocale.GERMAN.getCode(), InstabugLocale.GERMAN
.getCountry());
case LOCALE_ITALIAN:
return new Locale(InstabugLocale.ITALIAN.getCode(), InstabugLocale.ITALIAN
.getCountry());
case LOCALE_JAPANESE:
return new Locale(InstabugLocale.JAPANESE.getCode(), InstabugLocale.JAPANESE
.getCountry());
case LOCALE_POLISH:
return new Locale(InstabugLocale.POLISH.getCode(), InstabugLocale.POLISH
.getCountry());
case LOCALE_RUSSIAN:
return new Locale(InstabugLocale.RUSSIAN.getCode(), InstabugLocale.RUSSIAN
.getCountry());
case LOCALE_SPANISH:
return new Locale(InstabugLocale.SPANISH.getCode(), InstabugLocale.SPANISH
.getCountry());
case LOCALE_SWEDISH:
return new Locale(InstabugLocale.SWEDISH.getCode(), InstabugLocale.SWEDISH
.getCountry());
case LOCALE_TURKISH:
return new Locale(InstabugLocale.TURKISH.getCode(), InstabugLocale.TURKISH
.getCountry());
case LOCALE_PORTUGUESE_BRAZIL:
return new Locale(InstabugLocale.PORTUGUESE_BRAZIL.getCode(), InstabugLocale
.PORTUGUESE_BRAZIL.getCountry());
case LOCALE_CHINESE_SIMPLIFIED:
return new Locale(InstabugLocale.SIMPLIFIED_CHINESE.getCode(), InstabugLocale
.SIMPLIFIED_CHINESE.getCountry());
case LOCALE_CHINESE_TRADITIONAL:
return new Locale(InstabugLocale.TRADITIONAL_CHINESE.getCode(), InstabugLocale
.TRADITIONAL_CHINESE.getCountry());
case LOCALE_KOREAN:
return new Locale(InstabugLocale.KOREAN.getCode(), InstabugLocale.KOREAN
.getCountry());
default:
return new Locale(InstabugLocale.ENGLISH.getCode(), InstabugLocale.ENGLISH
.getCountry());
}
}
private void sendEvent(ReactApplicationContext reactContext,
String eventName,
@Nullable WritableMap params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("invocationEventNone", INVOCATION_EVENT_NONE);
constants.put("invocationEventShake", INVOCATION_EVENT_SHAKE);
constants.put("invocationEventScreenshot", INVOCATION_EVENT_SCREENSHOT);
constants.put("invocationEventTwoFingersSwipe", INVOCATION_EVENT_TWO_FINGERS_SWIPE);
constants.put("invocationEventFloatingButton", INVOCATION_EVENT_FLOATING_BUTTON);
constants.put("colorThemeLight", COLOR_THEME_LIGHT);
constants.put("colorThemeDark", COLOR_THEME_DARK);
constants.put("invocationModeNewBug", INVOCATION_MODE_NEW_BUG);
constants.put("invocationModeNewFeedback", INVOCATION_MODE_NEW_FEEDBACK);
constants.put("invocationModeNewChat", INVOCATION_MODE_NEW_CHAT);
constants.put("invocationModeChatsList", INVOCATION_MODE_CHATS_LIST);
constants.put("floatingButtonEdgeLeft",FLOATING_BUTTON_EDGE_LEFT);
constants.put("floatingButtonEdgeRight",FLOATING_BUTTON_EDGE_RIGHT);
constants.put("localeArabic", LOCALE_ARABIC);
constants.put("localeChineseSimplified", LOCALE_CHINESE_SIMPLIFIED);
constants.put("localeChineseTraditional", LOCALE_CHINESE_TRADITIONAL);
constants.put("localeCzech", LOCALE_CZECH);
constants.put("localeEnglish", LOCALE_ENGLISH);
constants.put("localeFrench", LOCALE_FRENCH);
constants.put("localeGerman", LOCALE_FRENCH);
constants.put("localeKorean", LOCALE_KOREAN);
constants.put("localeItalian", LOCALE_ITALIAN);
constants.put("localeJapanese", LOCALE_JAPANESE);
constants.put("localePolish", LOCALE_POLISH);
constants.put("localePortugueseBrazil", LOCALE_PORTUGUESE_BRAZIL);
constants.put("localeRussian", LOCALE_RUSSIAN);
constants.put("localeSpanish", LOCALE_SPANISH);
constants.put("localeSwedish", LOCALE_SWEDISH);
constants.put("localeTurkish", LOCALE_TURKISH);
constants.put("topRight", TOP_RIGHT);
constants.put("topLeft", TOP_LEFT);
constants.put("bottomRight", BOTTOM_RIGHT);
constants.put("bottomLeft", BOTTOM_LEFT);
constants.put("enabledWithRequiredFields", EXTENDED_BUG_REPORT_REQUIRED_FIELDS);
constants.put("enabledWithOptionalFields", EXTENDED_BUG_REPORT_OPTIONAL_FIELDS);
constants.put("disabled", EXTENDED_BUG_REPORT_DISABLED);
constants.put("reproStepsEnabledWithNoScreenshots", ENABLED_WITH_NO_SCREENSHOTS);
constants.put("reproStepsEnabled", ENABLED);
constants.put("reproStepsDisabled", DISABLED);
constants.put("shakeHint", SHAKE_HINT);
constants.put("swipeHint", SWIPE_HINT);
constants.put("invalidEmailMessage", INVALID_EMAIL_MESSAGE);
constants.put("invalidCommentMessage", INVALID_COMMENT_MESSAGE);
constants.put("emailFieldHint", EMAIL_FIELD_HINT);
constants.put("commentFieldHintForBugReport", COMMENT_FIELD_HINT_FOR_BUG_REPORT);
constants.put("commentFieldHintForFeedback", COMMENT_FIELD_HINT_FOR_FEEDBACK);
constants.put("invocationHeader", INVOCATION_HEADER);
constants.put("talkToUs", START_CHATS);
constants.put("reportBug", REPORT_BUG);
constants.put("reportFeedback", REPORT_FEEDBACK);
constants.put("conversationsHeaderTitle", CONVERSATIONS_LIST_TITLE);
constants.put("addVoiceMessage", ADD_VOICE_MESSAGE);
constants.put("addImageFromGallery", ADD_IMAGE_FROM_GALLERY);
constants.put("addExtraScreenshot", ADD_EXTRA_SCREENSHOT);
constants.put("addVideoMessage", ADD_VIDEO);
constants.put("audioRecordingPermissionDeniedMessage", AUDIO_RECORDING_PERMISSION_DENIED);
constants.put("recordingMessageToHoldText", VOICE_MESSAGE_PRESS_AND_HOLD_TO_RECORD);
constants.put("recordingMessageToReleaseText", VOICE_MESSAGE_RELEASE_TO_ATTACH);
constants.put("thankYouText", REPORT_SUCCESSFULLY_SENT);
constants.put("video", VIDEO_PLAYER_TITLE);
constants.put("conversationTextFieldHint", CONVERSATION_TEXT_FIELD_HINT);
return constants;
}
}
| ✨ Add setThresholdForReshowingSurveyAfterDismiss API for Android
| android/src/main/java/com/instabug/reactlibrary/RNInstabugReactnativeModule.java | ✨ Add setThresholdForReshowingSurveyAfterDismiss API for Android |
|
Java | mit | 189e725a68932cbc199519f6e4ee729c8337c6be | 0 | algoliareadmebot/algoliasearch-client-android,algolia/algoliasearch-client-android,algoliareadmebot/algoliasearch-client-android,algolia/algoliasearch-client-android,algolia/algoliasearch-client-android | /*
* Copyright (c) 2012-2016 Algolia
* http://www.algolia.com/
*
* 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.algolia.search.saas;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for the `MirroredIndex` class.
*/
public class MirroredIndexTest extends OfflineTestBase {
/** Higher timeout for online queries. */
protected static long onlineTimeout = 100;
/** The current sync listener. */
private SyncListener listener;
protected static Map<String, JSONObject> moreObjects = new HashMap<>();
static {
try {
moreObjects.put("snoopy", new JSONObject()
.put("objectID", "1")
.put("name", "Snoopy")
.put("kind", new JSONArray().put("dog").put("animal"))
.put("born", 1967)
.put("series", "Peanuts")
);
moreObjects.put("woodstock", new JSONObject()
.put("objectID", "2")
.put("name", "Woodstock")
.put("kind", new JSONArray().put("bird").put("animal"))
.put("born", 1970)
.put("series", "Peanuts")
);
moreObjects.put("charlie", new JSONObject()
.put("objectID", "3")
.put("name", "Charlie Brown")
.put("kind", new JSONArray().put("human"))
.put("born", 1950)
.put("series", "Peanuts")
);
moreObjects.put("hobbes", new JSONObject()
.put("objectID", "4")
.put("name", "Hobbes")
.put("kind", new JSONArray().put("tiger").put("animal").put("teddy"))
.put("born", 1985)
.put("series", "Calvin & Hobbes")
);
moreObjects.put("calvin", new JSONObject()
.put("objectID", "5")
.put("name", "Calvin")
.put("kind", new JSONArray().put("human"))
.put("born", 1985)
.put("series", "Calvin & Hobbes")
);
}
catch (JSONException e) {
throw new RuntimeException(e); // should never happen
}
}
interface SyncCompletionHandler {
void syncCompleted(@Nullable Throwable error);
}
private void populate(final @NonNull MirroredIndex index, final @NonNull SyncCompletionHandler completionHandler) {
// Delete the index.
client.deleteIndexAsync(index.getIndexName(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
int taskID = content.optInt("taskID", -1);
assertNotEquals(-1, taskID);
index.waitTaskAsync(Integer.toString(taskID), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
// Populate the online index.
index.addObjectsAsync(new JSONArray(moreObjects.values()), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
int taskID = content.optInt("taskID", -1);
assertNotEquals(-1, taskID);
index.waitTaskAsync(Integer.toString(taskID), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
completionHandler.syncCompleted(error);
}
});
}
});
}
});
}
});
}
private void sync(final @NonNull MirroredIndex index, final @NonNull SyncCompletionHandler completionHandler) {
populate(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
// Sync the offline mirror.
index.setMirrored(true);
Query query = new Query();
query.setNumericFilters(new JSONArray().put("born < 1980"));
index.setDataSelectionQueries(
new MirroredIndex.DataSelectionQuery(query, 10)
);
listener = new SyncListener() {
@Override
public void syncDidStart(MirroredIndex index) {
// Nothing to do.
}
@Override
public void syncDidFinish(MirroredIndex index, Throwable error, MirroredIndex.SyncStats stats) {
Log.d(MirroredIndexTest.class.getSimpleName(), "Sync finished");
index.removeSyncListener(listener);
completionHandler.syncCompleted(error);
}
};
index.addSyncListener(listener);
index.sync();
}
});
}
@Test
public void testSync() throws Exception {
final CountDownLatch signal = new CountDownLatch(1);
final long waitTimeout = 5;
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
try {
assertNull(error);
// Check that a call to `syncIfNeeded()` does *not* trigger a new sync.
listener = new SyncListener() {
@Override
public void syncDidStart(MirroredIndex index) {
fail("The sync should not have been started again");
}
@Override
public void syncDidFinish(MirroredIndex index, Throwable error, MirroredIndex.SyncStats stats) {
// Nothing to do.
}
};
final CountDownLatch signal2 = new CountDownLatch(1);
index.addSyncListener(listener);
index.syncIfNeeded();
assertFalse(signal2.await(waitTimeout, TimeUnit.SECONDS));
index.removeSyncListener(listener);
// Check that changing the data selection queries makes a new sync needed.
index.setDataSelectionQueries(new MirroredIndex.DataSelectionQuery(new Query(), 6));
listener = new SyncListener() {
@Override
public void syncDidStart(MirroredIndex index) {
// Nothing to do.
}
@Override
public void syncDidFinish(MirroredIndex index, Throwable error, MirroredIndex.SyncStats stats) {
index.removeSyncListener(listener);
assertNull(error);
signal.countDown();
}
};
index.addSyncListener(listener);
index.syncIfNeeded();
} catch (InterruptedException e) {
fail(e.getMessage());
}
}
});
}
@Test
public void testSearch() throws Exception {
final CountDownLatch signal = new CountDownLatch(2);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Query the online index explicitly.
index.searchOnlineAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(5, content.optInt("nbHits"));
assertEquals("remote", content.optString("origin"));
signal.countDown();
}
});
// Query the offline index explicitly.
index.searchOfflineAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(3, content.optInt("nbHits"));
assertEquals("local", content.optString("origin"));
signal.countDown();
}
});
}
});
}
@Test
public void testSearchFallback() throws Exception {
final CountDownLatch signal = new CountDownLatch(1);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Test offline fallback.
client.setReadHosts("unknown.algolia.com");
index.setRequestStrategy(MirroredIndex.Strategy.FALLBACK_ON_FAILURE);
index.searchAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(3, content.optInt("nbHits"));
assertEquals("local", content.optString("origin"));
signal.countDown();
}
});
}
});
}
@Test
public void testBrowse() throws Exception {
final CountDownLatch signal = new CountDownLatch(2);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Query the online index explicitly.
index.browseAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(5, content.optInt("nbHits"));
signal.countDown();
}
});
// Query the offline index explicitly.
index.browseMirrorAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(3, content.optInt("nbHits"));
signal.countDown();
}
});
}
});
}
@Test
public void testBuildOffline() {
final CountDownLatch signal = new CountDownLatch(4);
// Retrieve data files from resources.
File resourcesDir = new File(RuntimeEnvironment.application.getPackageResourcePath() + "/src/testOffline/res");
File rawDir = new File(resourcesDir, "raw");
File settingsFile = new File(rawDir, "settings.json");
File objectFile = new File(rawDir, "objects.json");
// Create the index.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
index.setMirrored(true);
// Check that no offline data exists.
assertFalse(index.hasOfflineData());
// Build the index.
index.addBuildListener(new BuildListener() {
@Override
public void buildDidStart(@NonNull MirroredIndex index) {
signal.countDown();
}
@Override
public void buildDidFinish(@NonNull MirroredIndex index, @Nullable Throwable error) {
assertNull(error);
signal.countDown();
}
});
index.buildOfflineFromFiles(settingsFile, new File[]{ objectFile }, new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
// Check that offline data exists now.
assertTrue(index.hasOfflineData());
// Search.
Query query = new Query().setQuery("peanuts").setFilters("kind:animal");
index.searchOfflineAsync(query, new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(2, content.optInt("nbHits"));
signal.countDown();
}
});
signal.countDown();
}
});
}
@Test
public void testGetObject() {
final CountDownLatch signal = new CountDownLatch(4);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Query the online index explicitly.
index.getObjectOnlineAsync("1", new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals("Snoopy", content.optString("name"));
// Test offline fallback.
client.setReadHosts("unknown.algolia.com");
index.setRequestStrategy(MirroredIndex.Strategy.FALLBACK_ON_FAILURE);
index.getObjectAsync("3", new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals("Charlie Brown", content.optString("name"));
signal.countDown();
}
});
signal.countDown();
}
});
// Query the offline index explicitly.
index.getObjectOfflineAsync("2", new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals("Woodstock", content.optString("name"));
signal.countDown();
}
});
signal.countDown();
}
});
}
@Test
public void testGetObjects() {
final CountDownLatch signal = new CountDownLatch(4);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Query the online index explicitly.
index.getObjectsOnlineAsync(Arrays.asList("1"), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertNotNull(content.optJSONArray("results"));
assertEquals(1, content.optJSONArray("results").length());
assertEquals("remote", content.optString("origin"));
// Test offline fallback.
client.setReadHosts("unknown.algolia.com");
index.setRequestStrategy(MirroredIndex.Strategy.FALLBACK_ON_FAILURE);
index.getObjectsAsync(Arrays.asList("1", "2", "3"), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertNotNull(content.optJSONArray("results"));
assertEquals(3, content.optJSONArray("results").length());
assertEquals("local", content.optString("origin"));
signal.countDown();
}
});
signal.countDown();
}
});
// Query the offline index explicitly.
index.getObjectsOfflineAsync(Arrays.asList("1", "2"), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertNotNull(content.optJSONArray("results"));
assertEquals(2, content.optJSONArray("results").length());
assertEquals("local", content.optString("origin"));
signal.countDown();
}
});
signal.countDown();
}
});
}
/**
* Test that a non-mirrored index behaves like a purely online index.
*/
@Test
public void testNotMirrored() {
final CountDownLatch signal = new CountDownLatch(5);
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
// Check that the index is *not* mirrored by default.
assertFalse(index.isMirrored());
populate(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
// Check that a non-mirrored index returns online results without origin tagging.
index.searchAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(5, content.optInt("nbHits"));
assertNull(content.opt("origin"));
signal.countDown();
}
});
index.browseAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(5, content.optInt("nbHits"));
assertNull(content.opt("origin"));
signal.countDown();
}
});
index.getObjectAsync("1", new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals("Snoopy", content.optString("name"));
assertNull(content.opt("origin"));
signal.countDown();
}
});
index.getObjectsAsync(Arrays.asList("1", "2"), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertNotNull(content.optJSONArray("results"));
assertEquals(2, content.optJSONArray("results").length());
assertNull(content.opt("origin"));
signal.countDown();
}
});
signal.countDown();
}
});
}
}
| algoliasearch/src/testOffline/java/com/algolia/search/saas/MirroredIndexTest.java | /*
* Copyright (c) 2012-2016 Algolia
* http://www.algolia.com/
*
* 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.algolia.search.saas;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for the `MirroredIndex` class.
*/
public class MirroredIndexTest extends OfflineTestBase {
/** Higher timeout for online queries. */
protected static long onlineTimeout = 100;
/** The current sync listener. */
private SyncListener listener;
protected static Map<String, JSONObject> moreObjects = new HashMap<>();
static {
try {
moreObjects.put("snoopy", new JSONObject()
.put("objectID", "1")
.put("name", "Snoopy")
.put("kind", new JSONArray().put("dog").put("animal"))
.put("born", 1967)
.put("series", "Peanuts")
);
moreObjects.put("woodstock", new JSONObject()
.put("objectID", "2")
.put("name", "Woodstock")
.put("kind", new JSONArray().put("bird").put("animal"))
.put("born", 1970)
.put("series", "Peanuts")
);
moreObjects.put("charlie", new JSONObject()
.put("objectID", "3")
.put("name", "Charlie Brown")
.put("kind", new JSONArray().put("human"))
.put("born", 1950)
.put("series", "Peanuts")
);
moreObjects.put("hobbes", new JSONObject()
.put("objectID", "4")
.put("name", "Hobbes")
.put("kind", new JSONArray().put("tiger").put("animal").put("teddy"))
.put("born", 1985)
.put("series", "Calvin & Hobbes")
);
moreObjects.put("calvin", new JSONObject()
.put("objectID", "5")
.put("name", "Calvin")
.put("kind", new JSONArray().put("human"))
.put("born", 1985)
.put("series", "Calvin & Hobbes")
);
}
catch (JSONException e) {
throw new RuntimeException(e); // should never happen
}
}
interface SyncCompletionHandler {
void syncCompleted(@Nullable Throwable error);
}
private void sync(final @NonNull MirroredIndex index, final @NonNull SyncCompletionHandler completionHandler) {
// Delete the index.
client.deleteIndexAsync(index.getIndexName(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
int taskID = content.optInt("taskID", -1);
assertNotEquals(-1, taskID);
index.waitTaskAsync(Integer.toString(taskID), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
// Populate the online index.
index.addObjectsAsync(new JSONArray(moreObjects.values()), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
int taskID = content.optInt("taskID", -1);
assertNotEquals(-1, taskID);
index.waitTaskAsync(Integer.toString(taskID), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
// Sync the offline mirror.
index.setMirrored(true);
Query query = new Query();
query.setNumericFilters(new JSONArray().put("born < 1980"));
index.setDataSelectionQueries(
new MirroredIndex.DataSelectionQuery(query, 10)
);
listener = new SyncListener() {
@Override
public void syncDidStart(MirroredIndex index) {
// Nothing to do.
}
@Override
public void syncDidFinish(MirroredIndex index, Throwable error, MirroredIndex.SyncStats stats) {
Log.d(MirroredIndexTest.class.getSimpleName(), "Sync finished");
index.removeSyncListener(listener);
completionHandler.syncCompleted(error);
}
};
index.addSyncListener(listener);
index.sync();
}
});
}
});
}
});
}
});
}
@Test
public void testSync() throws Exception {
final CountDownLatch signal = new CountDownLatch(1);
final long waitTimeout = 5;
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
try {
assertNull(error);
// Check that a call to `syncIfNeeded()` does *not* trigger a new sync.
listener = new SyncListener() {
@Override
public void syncDidStart(MirroredIndex index) {
fail("The sync should not have been started again");
}
@Override
public void syncDidFinish(MirroredIndex index, Throwable error, MirroredIndex.SyncStats stats) {
// Nothing to do.
}
};
final CountDownLatch signal2 = new CountDownLatch(1);
index.addSyncListener(listener);
index.syncIfNeeded();
assertFalse(signal2.await(waitTimeout, TimeUnit.SECONDS));
index.removeSyncListener(listener);
// Check that changing the data selection queries makes a new sync needed.
index.setDataSelectionQueries(new MirroredIndex.DataSelectionQuery(new Query(), 6));
listener = new SyncListener() {
@Override
public void syncDidStart(MirroredIndex index) {
// Nothing to do.
}
@Override
public void syncDidFinish(MirroredIndex index, Throwable error, MirroredIndex.SyncStats stats) {
index.removeSyncListener(listener);
assertNull(error);
signal.countDown();
}
};
index.addSyncListener(listener);
index.syncIfNeeded();
} catch (InterruptedException e) {
fail(e.getMessage());
}
}
});
}
@Test
public void testSearch() throws Exception {
final CountDownLatch signal = new CountDownLatch(2);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Query the online index explicitly.
index.searchOnlineAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(5, content.optInt("nbHits"));
assertEquals("remote", content.optString("origin"));
signal.countDown();
}
});
// Query the offline index explicitly.
index.searchOfflineAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(3, content.optInt("nbHits"));
assertEquals("local", content.optString("origin"));
signal.countDown();
}
});
}
});
}
@Test
public void testSearchFallback() throws Exception {
final CountDownLatch signal = new CountDownLatch(1);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Test offline fallback.
client.setReadHosts("unknown.algolia.com");
index.setRequestStrategy(MirroredIndex.Strategy.FALLBACK_ON_FAILURE);
index.searchAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(3, content.optInt("nbHits"));
assertEquals("local", content.optString("origin"));
signal.countDown();
}
});
}
});
}
@Test
public void testBrowse() throws Exception {
final CountDownLatch signal = new CountDownLatch(2);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Query the online index explicitly.
index.browseAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(5, content.optInt("nbHits"));
signal.countDown();
}
});
// Query the offline index explicitly.
index.browseMirrorAsync(new Query(), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(3, content.optInt("nbHits"));
signal.countDown();
}
});
}
});
}
@Test
public void testBuildOffline() {
final CountDownLatch signal = new CountDownLatch(4);
// Retrieve data files from resources.
File resourcesDir = new File(RuntimeEnvironment.application.getPackageResourcePath() + "/src/testOffline/res");
File rawDir = new File(resourcesDir, "raw");
File settingsFile = new File(rawDir, "settings.json");
File objectFile = new File(rawDir, "objects.json");
// Create the index.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
index.setMirrored(true);
// Check that no offline data exists.
assertFalse(index.hasOfflineData());
// Build the index.
index.addBuildListener(new BuildListener() {
@Override
public void buildDidStart(@NonNull MirroredIndex index) {
signal.countDown();
}
@Override
public void buildDidFinish(@NonNull MirroredIndex index, @Nullable Throwable error) {
assertNull(error);
signal.countDown();
}
});
index.buildOfflineFromFiles(settingsFile, new File[]{ objectFile }, new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
// Check that offline data exists now.
assertTrue(index.hasOfflineData());
// Search.
Query query = new Query().setQuery("peanuts").setFilters("kind:animal");
index.searchOfflineAsync(query, new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals(2, content.optInt("nbHits"));
signal.countDown();
}
});
signal.countDown();
}
});
}
@Test
public void testGetObject() {
final CountDownLatch signal = new CountDownLatch(4);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Query the online index explicitly.
index.getObjectOnlineAsync("1", new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals("Snoopy", content.optString("name"));
// Test offline fallback.
client.setReadHosts("unknown.algolia.com");
index.setRequestStrategy(MirroredIndex.Strategy.FALLBACK_ON_FAILURE);
index.getObjectAsync("3", new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals("Charlie Brown", content.optString("name"));
signal.countDown();
}
});
signal.countDown();
}
});
// Query the offline index explicitly.
index.getObjectOfflineAsync("2", new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertEquals("Woodstock", content.optString("name"));
signal.countDown();
}
});
signal.countDown();
}
});
}
@Test
public void testGetObjects() {
final CountDownLatch signal = new CountDownLatch(4);
// Populate the online index & sync the offline mirror.
final MirroredIndex index = client.getIndex(Helpers.safeIndexName(Helpers.getMethodName()));
sync(index, new SyncCompletionHandler() {
@Override
public void syncCompleted(@Nullable Throwable error) {
assertNull(error);
// Query the online index explicitly.
index.getObjectsOnlineAsync(Arrays.asList("1"), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertNotNull(content.optJSONArray("results"));
assertEquals(1, content.optJSONArray("results").length());
assertEquals("remote", content.optString("origin"));
// Test offline fallback.
client.setReadHosts("unknown.algolia.com");
index.setRequestStrategy(MirroredIndex.Strategy.FALLBACK_ON_FAILURE);
index.getObjectsAsync(Arrays.asList("1", "2", "3"), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertNotNull(content.optJSONArray("results"));
assertEquals(3, content.optJSONArray("results").length());
assertEquals("local", content.optString("origin"));
signal.countDown();
}
});
signal.countDown();
}
});
// Query the offline index explicitly.
index.getObjectsOfflineAsync(Arrays.asList("1", "2"), new AssertCompletionHandler() {
@Override
public void doRequestCompleted(JSONObject content, AlgoliaException error) {
assertNull(error);
assertNotNull(content.optJSONArray("results"));
assertEquals(2, content.optJSONArray("results").length());
assertEquals("local", content.optString("origin"));
signal.countDown();
}
});
signal.countDown();
}
});
}
}
| [offline][test] Test that non-mirrored indices behave as pure online indices | algoliasearch/src/testOffline/java/com/algolia/search/saas/MirroredIndexTest.java | [offline][test] Test that non-mirrored indices behave as pure online indices |
|
Java | mit | b10dfe2e512cde96e0932a3346fd56eefd940ad8 | 0 | jvm-bloggers/jvm-bloggers,jvm-bloggers/jvm-bloggers,jvm-bloggers/jvm-bloggers,alien11689/jvm-bloggers,kraluk/jvm-bloggers,kraluk/jvm-bloggers,tdziurko/jvm-bloggers,tdziurko/jvm-bloggers,szpak/jvm-bloggers,jvm-bloggers/jvm-bloggers,tdziurko/jvm-bloggers,kraluk/jvm-bloggers,sobkowiak/jvm-bloggers,tdziurko/jvm-bloggers,szpak/jvm-bloggers,sobkowiak/jvm-bloggers,alien11689/jvm-bloggers,szpak/jvm-bloggers,kraluk/jvm-bloggers,szpak/jvm-bloggers | package pl.tomaszdziurko.jvm_bloggers.mailing;
import com.google.common.base.Joiner;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import lombok.extern.slf4j.Slf4j;
import org.antlr.stringtemplate.StringTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import pl.tomaszdziurko.jvm_bloggers.blog_posts.domain.BlogPost;
import pl.tomaszdziurko.jvm_bloggers.people.domain.Person;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Component
@Slf4j
public class BlogSummaryMailGenerator {
private final Resource blogsSummaryTemplate;
@Autowired
public BlogSummaryMailGenerator(@Value("classpath:mail_templates/blog_summary.st") Resource blogsSummaryTemplate) {
this.blogsSummaryTemplate = blogsSummaryTemplate;
}
public String generateSummaryMail(List<BlogPost> posts, List<Person> blogsAddedSinceLastNewsletter, int numberOfDaysBackInThePast) {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(blogsSummaryTemplate.getInputStream(), "UTF-8"));
String templateContent = Joiner.on("\n").join(bufferedReader.lines().collect(Collectors.toList()));
StringTemplate template = new StringTemplate(templateContent);
template.setAttribute("days", numberOfDaysBackInThePast);
template.setAttribute("newPosts", posts.stream().map(BlogPostForMailItem::new).collect(Collectors.toList()));
template.setAttribute("personToBlogHomepage", getPersonToBlogHomepage(blogsAddedSinceLastNewsletter));
return template.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Map<Person, String> getPersonToBlogHomepage(List<Person> blogsAddedSinceLastNewsletter) {
SyndFeedInput syndFeedInput = new SyndFeedInput();
Map<Person, String> personToBlogHomepage = blogsAddedSinceLastNewsletter.stream().collect(Collectors.toMap(
Function.identity(),
person->getBlogHomepageFromRss(person.getRss(), syndFeedInput))
);
return personToBlogHomepage;
}
private String getBlogHomepageFromRss(String rss, SyndFeedInput syndFeedInput) {
String homePageUrl = "";
try {
SyndFeed feed = syndFeedInput.build(new XmlReader(new URL(rss)));
homePageUrl = feed.getLink();
} catch (FeedException | IOException e) {
log.error("Issue while discovering blog homepage from blog rss ='{}'", rss);
}
return homePageUrl;
}
}
| src/main/java/pl/tomaszdziurko/jvm_bloggers/mailing/BlogSummaryMailGenerator.java | package pl.tomaszdziurko.jvm_bloggers.mailing;
import com.google.common.base.Joiner;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import lombok.extern.slf4j.Slf4j;
import org.antlr.stringtemplate.StringTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import pl.tomaszdziurko.jvm_bloggers.blog_posts.domain.BlogPost;
import pl.tomaszdziurko.jvm_bloggers.people.domain.Person;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Component
@Slf4j
public class BlogSummaryMailGenerator {
private final Resource blogsSummaryTemplate;
@Autowired
public BlogSummaryMailGenerator(@Value("classpath:mail_templates/blog_summary.st") Resource blogsSummaryTemplate) {
this.blogsSummaryTemplate = blogsSummaryTemplate;
}
public String generateSummaryMail(List<BlogPost> posts, List<Person> blogsAddedSinceLastNewsletter, int numberOfDaysBackInThePast) {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(blogsSummaryTemplate.getInputStream(), "UTF-8"));
String templateContent = Joiner.on("\n").join(bufferedReader.lines().collect(Collectors.toList()));
StringTemplate template = new StringTemplate(templateContent);
template.setAttribute("days", numberOfDaysBackInThePast);
template.setAttribute("newPosts", posts.stream().map(BlogPostForMailItem::new).collect(Collectors.toList()));
template.setAttribute("personToBlogHomepage", getPersonToBlogHomepage(blogsAddedSinceLastNewsletter));
return template.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Map<Person, String> getPersonToBlogHomepage(List<Person> blogsAddedSinceLastNewsletter) {
SyndFeedInput syndFeedInput = new SyndFeedInput();
Map<Person, String> personToBlogHomepage = blogsAddedSinceLastNewsletter.stream().collect(Collectors.toMap(
Function.identity(),
person->getBlogHomepageFromRss(person.getRss(), syndFeedInput))
);
return personToBlogHomepage;
}
private String getBlogHomepageFromRss(String rss, SyndFeedInput syndFeedInput) {
String homePageUrl = "";
try {
SyndFeed feed = syndFeedInput.build(new XmlReader(new URL(rss)));
homePageUrl = feed.getLink();
} catch (FeedException | IOException e) {
e.printStackTrace();
}
return homePageUrl;
}
}
| #38 log error when could not convert rss url to blog homepage
| src/main/java/pl/tomaszdziurko/jvm_bloggers/mailing/BlogSummaryMailGenerator.java | #38 log error when could not convert rss url to blog homepage |
|
Java | epl-1.0 | 8942b892f5cba21661661e2b4e7b969c0ca3a858 | 0 | Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt | /*******************************************************************************
* Copyright (c) 2005 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.cubebuilder.dialog;
import java.util.List;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.aggregation.AggregationManager;
import org.eclipse.birt.data.engine.api.aggregation.IAggrFunction;
import org.eclipse.birt.data.engine.api.aggregation.IParameterDefn;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil;
import org.eclipse.birt.report.designer.data.ui.util.DataUtil;
import org.eclipse.birt.report.designer.internal.ui.dialogs.BaseDialog;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.util.WidgetUtil;
import org.eclipse.birt.report.designer.ui.cubebuilder.nls.Messages;
import org.eclipse.birt.report.designer.ui.cubebuilder.provider.CubeExpressionProvider;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionBuilder;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider;
import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.designer.util.FontManager;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.olap.TabularCubeHandle;
import org.eclipse.birt.report.model.api.olap.TabularMeasureHandle;
import org.eclipse.birt.report.model.elements.interfaces.IMeasureModel;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class MeasureDialog extends BaseDialog
{
private TabularMeasureHandle input;
private TabularCubeHandle cube;
private Text nameText;
private static IChoice[] dataTypes = DEUtil.getMetaDataDictionary( )
.getElement( ReportDesignConstants.MEASURE_ELEMENT )
.getProperty( IMeasureModel.DATA_TYPE_PROP )
.getAllowedChoices( )
.getChoices( );
private String[] getDataTypeNames( )
{
IChoice[] choices = dataTypes;
if ( choices == null )
return new String[0];
String[] names = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
names[i] = choices[i].getName( );
}
return names;
}
private String getDataTypeDisplayName( String name )
{
return ChoiceSetFactory.getDisplayNameFromChoiceSet( name,
DEUtil.getMetaDataDictionary( )
.getElement( ReportDesignConstants.MEASURE_ELEMENT )
.getProperty( IMeasureModel.DATA_TYPE_PROP )
.getAllowedChoices( ) );
}
private String[] getDataTypeDisplayNames( )
{
IChoice[] choices = dataTypes;
if ( choices == null )
return new String[0];
String[] displayNames = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
displayNames[i] = choices[i].getDisplayName( );
}
return displayNames;
}
private String[] getFunctionDisplayNames( )
{
IAggrFunction[] choices = getFunctions( );
if ( choices == null )
return new String[0];
String[] displayNames = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
displayNames[i] = choices[i].getDisplayName( );
}
return displayNames;
}
private IAggrFunction getFunctionByDisplayName( String displayName )
{
IAggrFunction[] choices = getFunctions( );
if ( choices == null )
return null;
for ( int i = 0; i < choices.length; i++ )
{
if ( choices[i].getDisplayName( ).equals( displayName ) )
{
return choices[i];
}
}
return null;
}
private String getFunctionDisplayName( String function )
{
try
{
return DataUtil.getAggregationManager( )
.getAggregation( function )
.getDisplayName( );
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
return null;
}
}
private IAggrFunction[] getFunctions( )
{
try
{
List aggrInfoList = DataUtil.getAggregationManager( )
.getAggregations( AggregationManager.AGGR_MEASURE );
return (IAggrFunction[]) aggrInfoList.toArray( new IAggrFunction[0] );
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
return new IAggrFunction[0];
}
}
public MeasureDialog( boolean newOrEdit )
{
super( Messages.getString( "MeasureDialog.Title" ) ); //$NON-NLS-1$
this.isEdit = !newOrEdit;
}
public void setInput( TabularCubeHandle cube, TabularMeasureHandle input )
{
this.input = input;
this.cube = cube;
}
/*
* (non-Javadoc) Method declared on Dialog.
*/
protected Control createDialogArea( Composite parent )
{
createTitleArea( parent );
UIUtil.bindHelp( parent, IHelpContextIds.MEASURE_DIALOG );
Composite contents = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.verticalSpacing = 0;
layout.marginWidth = 20;
contents.setLayout( layout );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = convertWidthInCharsToPixels( 70 );
contents.setLayoutData( data );
createMeasureArea( contents );
WidgetUtil.createGridPlaceholder( contents, 1, true );
initMeasureDialog( );
return contents;
}
private void initMeasureDialog( )
{
typeCombo.setItems( getDataTypeDisplayNames( ) );
functionCombo.setItems( getFunctionDisplayNames( ) );
if ( !isEdit )
{
if ( typeCombo.getItemCount( ) > 0 )
{
typeCombo.select( 0 );
}
if ( functionCombo.getItemCount( ) > 0 )
{
functionCombo.select( 0 );
}
}
else
{
typeCombo.setText( getDataTypeDisplayName( input.getDataType( ) ) == null ? "" //$NON-NLS-1$
: getDataTypeDisplayName( input.getDataType( ) ) );
try
{
functionCombo.setText( getFunctionDisplayName( DataAdapterUtil.adaptModelAggregationType( input.getFunction( ) ) ) == null ? "" //$NON-NLS-1$
: getFunctionDisplayName( DataAdapterUtil.adaptModelAggregationType( input.getFunction( ) ) ) );
}
catch ( AdapterException e )
{
ExceptionHandler.handle( e );
}
expressionText.setText( input.getMeasureExpression( ) == null ? "" //$NON-NLS-1$
: input.getMeasureExpression( ) );
nameText.setText( input.getName( ) == null ? "" : input.getName( ) ); //$NON-NLS-1$
}
handleFunctionSelectEvent( );
}
private Object result;
public Object getResult( )
{
return result;
}
protected void okPressed( )
{
try
{
if ( !isEdit )
{
TabularMeasureHandle measure = DesignElementFactory.getInstance( )
.newTabularMeasure( nameText.getText( ) );
measure.setFunction( getFunctions( )[functionCombo.getSelectionIndex( )].getName( ) );
measure.setDataType( getDataTypeNames( )[typeCombo.getSelectionIndex( )] );
if ( expressionText.isEnabled( ) )
measure.setMeasureExpression( expressionText.getText( ) );
result = measure;
}
else
{
input.setName( nameText.getText( ) );
input.setFunction( getFunctions( )[functionCombo.getSelectionIndex( )].getName( ) );
input.setDataType( getDataTypeNames( )[typeCombo.getSelectionIndex( )] );
if ( expressionText.isEnabled( ) )
input.setMeasureExpression( expressionText.getText( ) );
else
input.setMeasureExpression( null );
result = input;
}
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
return;
}
super.okPressed( );
}
protected void createButtonsForButtonBar( Composite parent )
{
super.createButtonsForButtonBar( parent );
checkOkButtonStatus( );
}
private Composite createMeasureArea( Composite parent )
{
Group group = new Group( parent, SWT.NONE );
GridData gd = new GridData( );
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
group.setLayoutData( gd );
GridLayout layout = new GridLayout( );
layout.numColumns = 3;
group.setLayout( layout );
Label nameLabel = new Label( group, SWT.NONE );
nameLabel.setText( Messages.getString( "MeasureDialog.Label.Name" ) ); //$NON-NLS-1$
nameText = new Text( group, SWT.BORDER );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
nameText.setLayoutData( gd );
nameText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkOkButtonStatus( );
}
} );
Label functionLabel = new Label( group, SWT.NONE );
functionLabel.setText( Messages.getString( "MeasureDialog.Label.Function" ) ); //$NON-NLS-1$
functionCombo = new Combo( group, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
functionCombo.setLayoutData( gd );
functionCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
handleFunctionSelectEvent( );
checkOkButtonStatus( );
}
} );
Label typeLabel = new Label( group, SWT.NONE );
typeLabel.setText( Messages.getString( "MeasureDialog.Label.DataType" ) ); //$NON-NLS-1$
typeCombo = new Combo( group, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
typeCombo.setLayoutData( gd );
typeCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
handleTypeSelectEvent( );
checkOkButtonStatus( );
}
} );
Label expressionLabel = new Label( group, SWT.NONE );
expressionLabel.setText( Messages.getString( "MeasureDialog.Label.Expression" ) ); //$NON-NLS-1$
expressionText = new Text( group, SWT.SINGLE | SWT.BORDER );
gd = new GridData( GridData.FILL_HORIZONTAL );
expressionText.setLayoutData( gd );
expressionText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkOkButtonStatus( );
}
} );
expressionButton = new Button( group, SWT.PUSH );
UIUtil.setExpressionButtonImage( expressionButton );
expressionButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
openExpression( );
}
} );
return group;
}
protected void handleTypeSelectEvent( )
{
IAggrFunction function = getFunctionByDisplayName( functionCombo.getText( ) );
try
{
String recommendType = getDataTypeDisplayName( DataAdapterUtil.adapterToModelDataType( DataUtil.getAggregationManager( )
.getAggregation( function.getName( ) )
.getDataType( ) ) );
if ( !typeCombo.getText( ).equals( recommendType ) )
{
if ( !MessageDialog.openQuestion( getShell( ),
Messages.getString( "MeasureDialog.MessageDialog.Title" ), //$NON-NLS-1$
Messages.getFormattedString( Messages.getString( "MeasureDialog.MessageDialog.Message" ), //$NON-NLS-1$
new Object[]{
recommendType
} ) ) )
typeCombo.setText( recommendType );
}
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
}
private void handleFunctionSelectEvent( )
{
IAggrFunction function = getFunctionByDisplayName( functionCombo.getText( ) );
try
{
typeCombo.setText( getDataTypeDisplayName( DataAdapterUtil.adapterToModelDataType( DataUtil.getAggregationManager( )
.getAggregation( function.getName( ) )
.getDataType( ) ) ) );
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
int parameterLength = function.getParameterDefn( ).length;
expressionText.setEnabled( parameterLength > 0 );
expressionButton.setEnabled( parameterLength > 0 );
}
protected void checkOkButtonStatus( )
{
if ( nameText.getText( ) == null
|| nameText.getText( ).trim( ).equals( "" ) //$NON-NLS-1$
|| functionCombo.getSelectionIndex( ) == -1
|| typeCombo.getSelectionIndex( ) == -1 )
{
if ( getOkButton( ) != null )
{
getOkButton( ).setEnabled( false );
return;
}
}
IAggrFunction function = getFunctionByDisplayName( functionCombo.getText( ) );
if ( function != null && function.getParameterDefn( ).length > 0 )
{
IParameterDefn param = function.getParameterDefn( )[0];
if ( !param.isOptional( ) )
{
if ( expressionText.getText( ) == null
|| expressionText.getText( ).trim( ).length( ) == 0 )
{
if ( getOkButton( ) != null )
{
getOkButton( ).setEnabled( false );
return;
}
}
}
}
if ( getOkButton( ) != null )
getOkButton( ).setEnabled( true );
}
private void openExpression( )
{
ExpressionBuilder expressionBuilder = new ExpressionBuilder( expressionText.getText( ) );
ExpressionProvider provider = new CubeExpressionProvider( cube );
expressionBuilder.setExpressionProvier( provider );
if ( expressionBuilder.open( ) == Window.OK )
{
expressionText.setText( expressionBuilder.getResult( ) );
}
}
private Composite createTitleArea( Composite parent )
{
Composite contents = new Composite( parent, SWT.NONE );
contents.setLayout( new GridLayout( ) );
GridData data = new GridData( GridData.FILL_HORIZONTAL );
contents.setLayoutData( data );
int heightMargins = 3;
int widthMargins = 8;
final Composite titleArea = new Composite( contents, SWT.NONE );
FormLayout layout = new FormLayout( );
layout.marginHeight = heightMargins;
layout.marginWidth = widthMargins;
titleArea.setLayout( layout );
Display display = parent.getDisplay( );
Color background = JFaceColors.getBannerBackground( display );
GridData layoutData = new GridData( GridData.FILL_HORIZONTAL );
layoutData.heightHint = 20 + ( heightMargins * 2 );
titleArea.setLayoutData( layoutData );
titleArea.setBackground( background );
titleArea.addPaintListener( new PaintListener( ) {
public void paintControl( PaintEvent e )
{
e.gc.setForeground( titleArea.getDisplay( )
.getSystemColor( SWT.COLOR_WIDGET_NORMAL_SHADOW ) );
Rectangle bounds = titleArea.getClientArea( );
bounds.height = bounds.height - 2;
bounds.width = bounds.width - 1;
e.gc.drawRectangle( bounds );
}
} );
Label label = new Label( titleArea, SWT.NONE );
label.setBackground( background );
label.setFont( FontManager.getFont( label.getFont( ).toString( ),
10,
SWT.BOLD ) );
label.setText( Messages.getString( "MeasureDialog.Title.Property" ) ); //$NON-NLS-1$
return titleArea;
}
private boolean isEdit = false;
private Combo typeCombo;
private Text expressionText;
private Combo functionCombo;
private Button expressionButton;
}
| UI/org.eclipse.birt.report.designer.ui.cubebuilder/src/org/eclipse/birt/report/designer/ui/cubebuilder/dialog/MeasureDialog.java | /*******************************************************************************
* Copyright (c) 2005 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.cubebuilder.dialog;
import java.util.List;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.aggregation.AggregationManager;
import org.eclipse.birt.data.engine.api.aggregation.IAggrFunction;
import org.eclipse.birt.data.engine.api.aggregation.IParameterDefn;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil;
import org.eclipse.birt.report.designer.data.ui.util.DataUtil;
import org.eclipse.birt.report.designer.internal.ui.dialogs.BaseDialog;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.util.WidgetUtil;
import org.eclipse.birt.report.designer.ui.cubebuilder.nls.Messages;
import org.eclipse.birt.report.designer.ui.cubebuilder.provider.CubeExpressionProvider;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionBuilder;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider;
import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.designer.util.FontManager;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.olap.TabularCubeHandle;
import org.eclipse.birt.report.model.api.olap.TabularMeasureHandle;
import org.eclipse.birt.report.model.elements.interfaces.IMeasureModel;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class MeasureDialog extends BaseDialog
{
private TabularMeasureHandle input;
private TabularCubeHandle cube;
private Text nameText;
private static IChoice[] dataTypes = DEUtil.getMetaDataDictionary( )
.getElement( ReportDesignConstants.MEASURE_ELEMENT )
.getProperty( IMeasureModel.DATA_TYPE_PROP )
.getAllowedChoices( )
.getChoices( );
private String[] getDataTypeNames( )
{
IChoice[] choices = dataTypes;
if ( choices == null )
return new String[0];
String[] names = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
names[i] = choices[i].getName( );
}
return names;
}
private String getDataTypeDisplayName( String name )
{
return ChoiceSetFactory.getDisplayNameFromChoiceSet( name,
DEUtil.getMetaDataDictionary( )
.getElement( ReportDesignConstants.MEASURE_ELEMENT )
.getProperty( IMeasureModel.DATA_TYPE_PROP )
.getAllowedChoices( ) );
}
private String[] getDataTypeDisplayNames( )
{
IChoice[] choices = dataTypes;
if ( choices == null )
return new String[0];
String[] displayNames = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
displayNames[i] = choices[i].getDisplayName( );
}
return displayNames;
}
private String[] getFunctionDisplayNames( )
{
IAggrFunction[] choices = getFunctions( );
if ( choices == null )
return new String[0];
String[] displayNames = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
displayNames[i] = choices[i].getDisplayName( );
}
return displayNames;
}
private IAggrFunction getFunctionByDisplayName( String displayName )
{
IAggrFunction[] choices = getFunctions( );
if ( choices == null )
return null;
for ( int i = 0; i < choices.length; i++ )
{
if ( choices[i].getDisplayName( ).equals( displayName ) )
{
return choices[i];
}
}
return null;
}
private String getFunctionDisplayName( String function )
{
try
{
return DataUtil.getAggregationManager( )
.getAggregation( function )
.getDisplayName( );
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
return null;
}
}
private IAggrFunction[] getFunctions( )
{
try
{
List aggrInfoList = DataUtil.getAggregationManager( )
.getAggregations( AggregationManager.AGGR_MEASURE );
return (IAggrFunction[]) aggrInfoList.toArray( new IAggrFunction[0] );
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
return new IAggrFunction[0];
}
}
public MeasureDialog( boolean newOrEdit )
{
super( Messages.getString( "MeasureDialog.Title" ) ); //$NON-NLS-1$
this.isEdit = !newOrEdit;
}
public void setInput( TabularCubeHandle cube, TabularMeasureHandle input )
{
this.input = input;
this.cube = cube;
}
/*
* (non-Javadoc) Method declared on Dialog.
*/
protected Control createDialogArea( Composite parent )
{
createTitleArea( parent );
UIUtil.bindHelp( parent, IHelpContextIds.MEASURE_DIALOG );
Composite contents = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.verticalSpacing = 0;
layout.marginWidth = 20;
contents.setLayout( layout );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = convertWidthInCharsToPixels( 70 );
contents.setLayoutData( data );
createMeasureArea( contents );
WidgetUtil.createGridPlaceholder( contents, 1, true );
initMeasureDialog( );
return contents;
}
private void initMeasureDialog( )
{
typeCombo.setItems( getDataTypeDisplayNames( ) );
functionCombo.setItems( getFunctionDisplayNames( ) );
if ( !isEdit )
{
if ( typeCombo.getItemCount( ) > 0 )
{
typeCombo.select( 0 );
}
if ( functionCombo.getItemCount( ) > 0 )
{
functionCombo.select( 0 );
}
}
else
{
typeCombo.setText( getDataTypeDisplayName( input.getDataType( ) ) == null ? "" //$NON-NLS-1$
: getDataTypeDisplayName( input.getDataType( ) ) );
try
{
functionCombo.setText( getFunctionDisplayName( DataAdapterUtil.adaptModelAggregationType( input.getFunction( ) ) ) == null ? "" //$NON-NLS-1$
: getFunctionDisplayName( DataAdapterUtil.adaptModelAggregationType( input.getFunction( ) ) ) );
}
catch ( AdapterException e )
{
ExceptionHandler.handle( e );
}
expressionText.setText( input.getMeasureExpression( ) == null ? "" //$NON-NLS-1$
: input.getMeasureExpression( ) );
nameText.setText( input.getName( ) == null ? "" : input.getName( ) ); //$NON-NLS-1$
}
handleFunctionSelectEvent( );
}
private Object result;
public Object getResult( )
{
return result;
}
protected void okPressed( )
{
try
{
if ( !isEdit )
{
TabularMeasureHandle measure = DesignElementFactory.getInstance( )
.newTabularMeasure( nameText.getText( ) );
measure.setFunction( getFunctions( )[functionCombo.getSelectionIndex( )].getName( ) );
measure.setDataType( getDataTypeNames( )[typeCombo.getSelectionIndex( )] );
if ( expressionText.isEnabled( ) )
measure.setMeasureExpression( expressionText.getText( ) );
result = measure;
}
else
{
input.setName( nameText.getText( ) );
input.setFunction( getFunctions( )[functionCombo.getSelectionIndex( )].getName( ) );
input.setDataType( getDataTypeNames( )[typeCombo.getSelectionIndex( )] );
if ( expressionText.isEnabled( ) )
input.setMeasureExpression( expressionText.getText( ) );
else
input.setMeasureExpression( null );
result = input;
}
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
return;
}
super.okPressed( );
}
protected void createButtonsForButtonBar( Composite parent )
{
super.createButtonsForButtonBar( parent );
checkOkButtonStatus( );
}
private Composite createMeasureArea( Composite parent )
{
Group group = new Group( parent, SWT.NONE );
GridData gd = new GridData( );
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
group.setLayoutData( gd );
GridLayout layout = new GridLayout( );
layout.numColumns = 3;
group.setLayout( layout );
Label nameLabel = new Label( group, SWT.NONE );
nameLabel.setText( Messages.getString( "MeasureDialog.Label.Name" ) ); //$NON-NLS-1$
nameText = new Text( group, SWT.BORDER );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
nameText.setLayoutData( gd );
nameText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkOkButtonStatus( );
}
} );
Label functionLabel = new Label( group, SWT.NONE );
functionLabel.setText( Messages.getString( "MeasureDialog.Label.Function" ) ); //$NON-NLS-1$
functionCombo = new Combo( group, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
functionCombo.setLayoutData( gd );
functionCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
handleFunctionSelectEvent( );
checkOkButtonStatus( );
}
} );
Label typeLabel = new Label( group, SWT.NONE );
typeLabel.setText( Messages.getString( "MeasureDialog.Label.DataType" ) ); //$NON-NLS-1$
typeCombo = new Combo( group, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
typeCombo.setLayoutData( gd );
typeCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
checkOkButtonStatus( );
}
} );
Label expressionLabel = new Label( group, SWT.NONE );
expressionLabel.setText( Messages.getString( "MeasureDialog.Label.Expression" ) ); //$NON-NLS-1$
expressionText = new Text( group, SWT.SINGLE | SWT.BORDER );
gd = new GridData( GridData.FILL_HORIZONTAL );
expressionText.setLayoutData( gd );
expressionText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkOkButtonStatus( );
}
} );
expressionButton = new Button( group, SWT.PUSH );
UIUtil.setExpressionButtonImage( expressionButton );
expressionButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
openExpression( );
}
} );
return group;
}
private void handleFunctionSelectEvent( )
{
IAggrFunction function = getFunctionByDisplayName( functionCombo.getText( ) );
try
{
typeCombo.setText( getDataTypeDisplayName( DataAdapterUtil.adapterToModelDataType( DataUtil.getAggregationManager( )
.getAggregation( function.getName( ) )
.getDataType( ) ) ) );
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
int parameterLength = function.getParameterDefn( ).length;
expressionText.setEnabled( parameterLength > 0 );
expressionButton.setEnabled( parameterLength > 0 );
}
protected void checkOkButtonStatus( )
{
if ( nameText.getText( ) == null
|| nameText.getText( ).trim( ).equals( "" ) //$NON-NLS-1$
|| functionCombo.getSelectionIndex( ) == -1
|| typeCombo.getSelectionIndex( ) == -1 )
{
if ( getOkButton( ) != null )
{
getOkButton( ).setEnabled( false );
return;
}
}
IAggrFunction function = getFunctionByDisplayName( functionCombo.getText( ) );
if ( function != null && function.getParameterDefn( ).length > 0 )
{
IParameterDefn param = function.getParameterDefn( )[0];
if ( !param.isOptional( ) )
{
if ( expressionText.getText( ) == null
|| expressionText.getText( ).trim( ).length( ) == 0 )
{
if ( getOkButton( ) != null )
{
getOkButton( ).setEnabled( false );
return;
}
}
}
}
if ( getOkButton( ) != null )
getOkButton( ).setEnabled( true );
}
private void openExpression( )
{
ExpressionBuilder expressionBuilder = new ExpressionBuilder( expressionText.getText( ) );
ExpressionProvider provider = new CubeExpressionProvider( cube );
expressionBuilder.setExpressionProvier( provider );
if ( expressionBuilder.open( ) == Window.OK )
{
expressionText.setText( expressionBuilder.getResult( ) );
}
}
private Composite createTitleArea( Composite parent )
{
Composite contents = new Composite( parent, SWT.NONE );
contents.setLayout( new GridLayout( ) );
GridData data = new GridData( GridData.FILL_HORIZONTAL );
contents.setLayoutData( data );
int heightMargins = 3;
int widthMargins = 8;
final Composite titleArea = new Composite( contents, SWT.NONE );
FormLayout layout = new FormLayout( );
layout.marginHeight = heightMargins;
layout.marginWidth = widthMargins;
titleArea.setLayout( layout );
Display display = parent.getDisplay( );
Color background = JFaceColors.getBannerBackground( display );
GridData layoutData = new GridData( GridData.FILL_HORIZONTAL );
layoutData.heightHint = 20 + ( heightMargins * 2 );
titleArea.setLayoutData( layoutData );
titleArea.setBackground( background );
titleArea.addPaintListener( new PaintListener( ) {
public void paintControl( PaintEvent e )
{
e.gc.setForeground( titleArea.getDisplay( )
.getSystemColor( SWT.COLOR_WIDGET_NORMAL_SHADOW ) );
Rectangle bounds = titleArea.getClientArea( );
bounds.height = bounds.height - 2;
bounds.width = bounds.width - 1;
e.gc.drawRectangle( bounds );
}
} );
Label label = new Label( titleArea, SWT.NONE );
label.setBackground( background );
label.setFont( FontManager.getFont( label.getFont( ).toString( ),
10,
SWT.BOLD ) );
label.setText( Messages.getString( "MeasureDialog.Title.Property" ) ); //$NON-NLS-1$
return titleArea;
}
private boolean isEdit = false;
private Combo typeCombo;
private Text expressionText;
private Combo functionCombo;
private Button expressionButton;
}
| - Summary: BIRT: "SUM" shouldn't be allowed in the function dropdown when creating Measures
- Bugzilla Bug (s) Resolved: 4668
- Description: Popup a message dialog to prompt user the correct data type.
- Tests Description: Manual test.
- Notes to Build Team:
- Notes to Developers:
- Notes to QA:
- Notes to Documentation:
- Files Added:
- Files Edited:
- Files Deleted:
| UI/org.eclipse.birt.report.designer.ui.cubebuilder/src/org/eclipse/birt/report/designer/ui/cubebuilder/dialog/MeasureDialog.java | - Summary: BIRT: "SUM" shouldn't be allowed in the function dropdown when creating Measures |
|
Java | epl-1.0 | e313643d33f2be8802f91f0fba637cabb32eacff | 0 | unverbraucht/kura,amitjoy/kura,MMaiero/kura,MMaiero/kura,ymai/kura,markcullen/kura_Windows,nicolatimeus/kura,markoer/kura,markoer/kura,nicolatimeus/kura,darionct/kura,ymai/kura,ymai/kura,rohitdubey12/kura,ctron/kura,cdealti/kura,MMaiero/kura,cdealti/kura,nicolatimeus/kura,markcullen/kura_Windows,ctron/kura,gavinying/kura,amitjoy/kura,MMaiero/kura,unverbraucht/kura,nicolatimeus/kura,nicolatimeus/kura,darionct/kura,gavinying/kura,ctron/kura,amitjoy/kura,ctron/kura,markoer/kura,ymai/kura,unverbraucht/kura,rohitdubey12/kura,amitjoy/kura,markcullen/kura_Windows,rohitdubey12/kura,MMaiero/kura,markcullen/kura_Windows,unverbraucht/kura,darionct/kura,ctron/kura,MMaiero/kura,cdealti/kura,unverbraucht/kura,gavinying/kura,markoer/kura,darionct/kura,amitjoy/kura,markoer/kura,ymai/kura,darionct/kura,markcullen/kura_Windows,gavinying/kura,markoer/kura,ctron/kura,rohitdubey12/kura,cdealti/kura,amitjoy/kura,darionct/kura,nicolatimeus/kura,rohitdubey12/kura,cdealti/kura,cdealti/kura,ymai/kura,gavinying/kura,gavinying/kura | /**
* Copyright (c) 2011, 2015 Eurotech and/or its affiliates
*
* 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:
* Eurotech
*/
package org.eclipse.kura.core.deployment.download.impl;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.output.CountingOutputStream;
import org.eclipse.kura.core.deployment.CloudDeploymentHandlerV2.DOWNLOAD_STATUS;
import org.eclipse.kura.core.deployment.download.DeploymentPackageDownloadOptions;
import org.eclipse.kura.core.deployment.download.DownloadOptions;
import org.eclipse.kura.core.deployment.progress.ProgressEvent;
import org.eclipse.kura.core.deployment.progress.ProgressListener;
import org.eclipse.kura.ssl.SslManagerService;
public class GenericDownloadCountingOutputStream extends CountingOutputStream {
private int propResolution;
private int propBufferSize;
private int propConnectTimeout = 5000;
private int propReadTimeout = 6000;
private int propBlockDelay = 1000;
long totalBytes;
final DeploymentPackageDownloadOptions options;
final SslManagerService m_sslManagerService;
final ProgressListener pl;
final int m_alreadyDownloaded;
final String m_downloadURL;
InputStream is = null;
private long m_currentStep = 1;
//private long previous;
private DOWNLOAD_STATUS m_downloadStatus = DOWNLOAD_STATUS.FAILED;
public GenericDownloadCountingOutputStream(DownloadOptions downloadOptions) {
super(downloadOptions.getOut());
this.options = downloadOptions.getRequestOptions();
this.m_sslManagerService = downloadOptions.getSslManagerService();
this.pl = downloadOptions.getCallback();
this.m_downloadURL = downloadOptions.getDownloadURL();
this.m_alreadyDownloaded = downloadOptions.getAlreadyDownloaded();
}
public DOWNLOAD_STATUS getDownloadTransferStatus(){
return m_downloadStatus;
}
public Long getDownloadTransferProgressPercentage(){
Long percentage= (long) Math.floor((((Long) getByteCount()).doubleValue() / ((Long) totalBytes).doubleValue()) * 100);
if(percentage < 0){
return (long)50;
}
return percentage;
}
public Long getTotalBytes(){
return totalBytes;
}
public void setTotalBytes(long totalBytes){
this.totalBytes= totalBytes;
}
@Override
protected void afterWrite(int n) throws IOException {
super.afterWrite(n);
if(propResolution == 0 && getTotalBytes() > 0) {
propResolution= Math.round((totalBytes / 100) * 5);
} else if (propResolution == 0) {
propResolution= 1024 * 256;
}
if (getByteCount() >= m_currentStep * propResolution) {
//System.out.println("Bytes read: "+ (getByteCount() - previous));
//previous = getByteCount();
m_currentStep++;
postProgressEvent(options.getClientId(), getByteCount(), totalBytes, DOWNLOAD_STATUS.IN_PROGRESS, null);
}
try {
Thread.sleep(propBlockDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void postProgressEvent(String clientId, long progress, long total, DOWNLOAD_STATUS status, String errorMessage) {
Long perc = getDownloadTransferProgressPercentage();
m_downloadStatus = status;
ProgressEvent pe= new ProgressEvent(this, options, ((Long) total).intValue(), ((Long) perc).intValue(),
getDownloadTransferStatus().getStatusString(), m_alreadyDownloaded);
if(errorMessage != null){
pe.setExceptionMessage(errorMessage);
}
pl.progressChanged(pe);
}
protected void setResolution(int resolution) {
propResolution = resolution;
}
protected void setBufferSize(int size) {
propBufferSize = size;
}
protected void setConnectTimeout(int timeout) {
propConnectTimeout = timeout;
}
protected void setReadTimeout(int timeout) {
propReadTimeout = timeout;
}
protected void setBlockDelay(int delay) {
propBlockDelay = delay;
}
protected int getResolution() {
return propResolution;
}
protected int getBufferSize() {
return propBufferSize;
}
protected int getConnectTimeout() {
return propConnectTimeout;
}
protected int getPROP_READ_TIMEOUT() {
return propReadTimeout;
}
protected int getPROP_BLOCK_DELAY() {
return propBlockDelay;
}
}
| kura/org.eclipse.kura.core.deployment/src/main/java/org/eclipse/kura/core/deployment/download/impl/GenericDownloadCountingOutputStream.java | /**
* Copyright (c) 2011, 2015 Eurotech and/or its affiliates
*
* 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:
* Eurotech
*/
package org.eclipse.kura.core.deployment.download.impl;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.output.CountingOutputStream;
import org.eclipse.kura.core.deployment.CloudDeploymentHandlerV2.DOWNLOAD_STATUS;
import org.eclipse.kura.core.deployment.download.DeploymentPackageDownloadOptions;
import org.eclipse.kura.core.deployment.download.DownloadOptions;
import org.eclipse.kura.core.deployment.progress.ProgressEvent;
import org.eclipse.kura.core.deployment.progress.ProgressListener;
import org.eclipse.kura.ssl.SslManagerService;
public class GenericDownloadCountingOutputStream extends CountingOutputStream {
private static int PROP_RESOLUTION;
private static int PROP_BUFFER_SIZE;
private static int PROP_CONNECT_TIMEOUT = 5000;
private static int PROP_READ_TIMEOUT = 6000;
private static int PROP_BLOCK_DELAY = 1000;
long totalBytes;
final DeploymentPackageDownloadOptions options;
final SslManagerService m_sslManagerService;
final ProgressListener pl;
final int m_alreadyDownloaded;
final String m_downloadURL;
InputStream is = null;
private long m_currentStep = 1;
//private long previous;
private DOWNLOAD_STATUS m_downloadStatus = DOWNLOAD_STATUS.FAILED;
public GenericDownloadCountingOutputStream(DownloadOptions downloadOptions) {
super(downloadOptions.getOut());
this.options = downloadOptions.getRequestOptions();
this.m_sslManagerService = downloadOptions.getSslManagerService();
this.pl = downloadOptions.getCallback();
this.m_downloadURL = downloadOptions.getDownloadURL();
this.m_alreadyDownloaded = downloadOptions.getAlreadyDownloaded();
}
public DOWNLOAD_STATUS getDownloadTransferStatus(){
return m_downloadStatus;
}
public Long getDownloadTransferProgressPercentage(){
Long percentage= (long) Math.floor((((Long) getByteCount()).doubleValue() / ((Long) totalBytes).doubleValue()) * 100);
if(percentage < 0){
return (long)50;
}
return percentage;
}
public Long getTotalBytes(){
return totalBytes;
}
public void setTotalBytes(long totalBytes){
this.totalBytes= totalBytes;
}
@Override
protected void afterWrite(int n) throws IOException {
super.afterWrite(n);
if(PROP_RESOLUTION == 0 && getTotalBytes() > 0) {
PROP_RESOLUTION= Math.round((totalBytes / 100) * 5);
} else if (PROP_RESOLUTION == 0) {
PROP_RESOLUTION= 1024 * 256;
}
if (getByteCount() >= m_currentStep * PROP_RESOLUTION) {
//System.out.println("Bytes read: "+ (getByteCount() - previous));
//previous = getByteCount();
m_currentStep++;
postProgressEvent(options.getClientId(), getByteCount(), totalBytes, DOWNLOAD_STATUS.IN_PROGRESS, null);
}
try {
Thread.sleep(PROP_BLOCK_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void postProgressEvent(String clientId, long progress, long total, DOWNLOAD_STATUS status, String errorMessage) {
Long perc = getDownloadTransferProgressPercentage();
m_downloadStatus = status;
ProgressEvent pe= new ProgressEvent(this, options, ((Long) total).intValue(), ((Long) perc).intValue(),
getDownloadTransferStatus().getStatusString(), m_alreadyDownloaded);
if(errorMessage != null){
pe.setExceptionMessage(errorMessage);
}
pl.progressChanged(pe);
}
protected void setResolution(int resolution) {
PROP_RESOLUTION = resolution;
}
protected void setBufferSize(int size) {
PROP_BUFFER_SIZE = size;
}
protected void setConnectTimeout(int timeout) {
PROP_CONNECT_TIMEOUT = timeout;
}
protected void setReadTimeout(int timeout) {
PROP_READ_TIMEOUT = timeout;
}
protected void setBlockDelay(int delay) {
PROP_BLOCK_DELAY = delay;
}
protected static int getResolution() {
return PROP_RESOLUTION;
}
protected static int getBufferSize() {
return PROP_BUFFER_SIZE;
}
protected static int getConnectTimeout() {
return PROP_CONNECT_TIMEOUT;
}
protected static int getPROP_READ_TIMEOUT() {
return PROP_READ_TIMEOUT;
}
protected static int getPROP_BLOCK_DELAY() {
return PROP_BLOCK_DELAY;
}
}
| Removed static variables
Signed-off-by: MMaiero <[email protected]>
| kura/org.eclipse.kura.core.deployment/src/main/java/org/eclipse/kura/core/deployment/download/impl/GenericDownloadCountingOutputStream.java | Removed static variables |
|
Java | epl-1.0 | ea27118305d6becb20186a4ca960d5bab03bb9c8 | 0 | spring-projects/eclipse-integration-tcserver,spring-projects/eclipse-integration-tcserver | /*******************************************************************************
* Copyright (c) 2012 - 2013 GoPivotal, Inc.
* 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:
* GoPivotal, Inc. - initial API and implementation
*******************************************************************************/
package com.vmware.vfabric.ide.eclipse.tcserver.internal.core;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jst.server.tomcat.core.internal.FileUtil;
import org.eclipse.jst.server.tomcat.core.internal.Messages;
import org.eclipse.jst.server.tomcat.core.internal.PingThread;
import org.eclipse.jst.server.tomcat.core.internal.ProgressUtil;
import org.eclipse.jst.server.tomcat.core.internal.TomcatServerBehaviour;
import org.eclipse.jst.server.tomcat.core.internal.Trace;
import org.eclipse.mylyn.commons.net.WebLocation;
import org.eclipse.wst.server.core.IModule;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.ServerPort;
import org.eclipse.wst.server.core.model.IModuleResource;
import org.eclipse.wst.server.core.model.IModuleResourceDelta;
import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.TcServer.Layout;
import com.vmware.vfabric.ide.eclipse.tcserver.reloading.TcServerReloadingPlugin;
/**
* @author Steffen Pingel
* @author Christian Dupuis
* @author Kris De Volder
* @author Leo Dos Santos
*/
public class TcServerBehaviour extends TomcatServerBehaviour {
private static class SslPingThread extends PingThread {
private static int DELAY = 10;
private static int INTERVAL = 250;
private final String url;
private boolean stopped;
private final TcServerBehaviour serverBehaviour;
private final int maxPings;
private int interval;
public SslPingThread(IServer server, String url, int maxPings, TcServerBehaviour behaviour) {
super(server, url, maxPings, behaviour);
this.url = url;
this.maxPings = (maxPings != -1) ? maxPings : 100;
this.serverBehaviour = behaviour;
}
@Override
protected void ping() {
interval = DELAY;
for (int i = 0; i < maxPings && !stopped; i++) {
try {
Thread.sleep(interval);
WebLocation location = new WebLocation(url);
HttpClient client = new HttpClient();
org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$
HeadMethod method = new HeadMethod(location.getUrl());
HostConfiguration hostConfiguration = org.eclipse.mylyn.commons.net.WebUtil
.createHostConfiguration(client, location, new NullProgressMonitor());
org.eclipse.mylyn.commons.net.WebUtil.execute(client, hostConfiguration, method,
new NullProgressMonitor());
// success
serverBehaviour.setServerStarted();
stop();
break;
}
catch (ConnectException e) {
// ignore
}
catch (Exception e) {
Trace.trace(Trace.SEVERE, "Failed to ping for tc Server startup.", e);
forceStop();
break;
}
interval = INTERVAL;
}
}
private void forceStop() {
stop();
serverBehaviour.stopImpl();
}
@Override
public void stop() {
super.stop();
this.stopped = true;
}
}
public static boolean mergeClasspathIfRequired(List<IRuntimeClasspathEntry> cp, IRuntimeClasspathEntry entry) {
return mergeClasspathIfRequired(cp, entry, false);
}
public static boolean mergeClasspathIfRequired(List<IRuntimeClasspathEntry> cp, IRuntimeClasspathEntry entry,
boolean prepend) {
boolean first = true;
Iterator<IRuntimeClasspathEntry> iterator = cp.iterator();
while (iterator.hasNext()) {
IRuntimeClasspathEntry entry2 = iterator.next();
if (entry2.getPath().equals(entry.getPath())) {
if (prepend && !first) {
// ensure new element is always first
iterator.remove();
}
else {
return false;
}
}
first = false;
}
if (prepend) {
cp.add(0, entry);
}
else {
cp.add(entry);
}
return true;
}
public String getDeployRoot() {
return getServerDeployDirectory().toOSString() + File.separator;
}
// make method visible to package
@Override
public IModuleResourceDelta[] getPublishedResourceDelta(IModule[] module) {
return super.getPublishedResourceDelta(module);
}
@Override
public IModuleResource[] getResources(IModule[] module) {
return super.getResources(module);
}
public IServicabilityInfo getServicabilityInfo() throws CoreException {
TcServer server = getTomcatServer();
return getTomcatConfiguration().getServicabilityInfo(server.getRuntimeBaseDirectory());
}
@Override
public TcServerConfiguration getTomcatConfiguration() throws CoreException {
return (TcServerConfiguration) super.getTomcatConfiguration();
}
@Override
public TcServerRuntime getTomcatRuntime() {
return (TcServerRuntime) super.getTomcatRuntime();
}
@Override
public TcServer getTomcatServer() {
return (TcServer) super.getTomcatServer();
}
@Override
public void setupLaunch(ILaunch launch, String launchMode, IProgressMonitor monitor) throws CoreException {
super.setupLaunch(launch, launchMode, monitor);
// transfer VM arguments to launch to make them accessible for later use
launch.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, launch.getLaunchConfiguration()
.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, (String) null));
TcServer.getCallback().setupLaunch(getTomcatServer(), launch, launchMode, monitor);
TcServerConfiguration configuration = getTomcatConfiguration();
if (configuration.getMainPort() == null && ping == null) {
ServerPort serverPort = configuration.getMainSslPort();
if (serverPort != null) {
try {
String url = "https://" + getServer().getHost() + ":" + serverPort.getPort();
ping = new SslPingThread(getServer(), url, -1, this);
}
catch (Exception e) {
Trace.trace(Trace.SEVERE, "Can't ping for tc Server startup.");
}
}
}
}
@Override
public void setupLaunchConfiguration(ILaunchConfigurationWorkingCopy workingCopy, IProgressMonitor monitor)
throws CoreException {
super.setupLaunchConfiguration(workingCopy, monitor);
TcServer.getCallback().setupLaunchConfiguration(getTomcatServer(), workingCopy, monitor);
if (getTomcatServer().isTestEnvironment()) {
setupRuntimeClasspathForTestEnvironment(workingCopy, monitor);
}
String existingVMArgs = workingCopy.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS,
(String) null);
String[] parsedVMArgs = null;
if (existingVMArgs != null) {
parsedVMArgs = DebugPlugin.parseArguments(existingVMArgs);
}
List<String> argsToAdd = new ArrayList<String>();
List<String> argsToRemove = new ArrayList<String>();
if (getTomcatServer().isAgentRedeployEnabled() && TcServerReloadingPlugin.getAgentJarPath() != null) {
argsToAdd.add("-javaagent:\"" + TcServerReloadingPlugin.getAgentJarPath() + "\"");
argsToAdd.add("-noverify");
String agentOptions = getTomcatServer().getAgentOptions();
if (StringUtils.isNotBlank(agentOptions)) {
argsToAdd.add("-Dspringloaded=\"" + agentOptions + "\"");
}
else {
argsToRemove.add("-Dspringloaded");
}
}
else {
argsToRemove.add("-javaagent:\"" + TcServerReloadingPlugin.getAgentJarPath() + "\"");
argsToRemove.add("-noverify");
argsToRemove.add("-Dspringloaded");
}
boolean grailsInstalled = Platform.getBundle("org.grails.ide.eclipse.runonserver") != null
|| Platform.getBundle("com.springsource.sts.grails.runonserver") != null;
boolean addXmx = true;
boolean addXss = true;
boolean addGrailsGspEnable = true;
boolean addMaxPermSize = true;
// check if arguments are already present
if (parsedVMArgs != null) {
for (String parsedVMArg : parsedVMArgs) {
if (parsedVMArg.startsWith("-Xmx")) {
addXmx = false;
}
else if (parsedVMArg.startsWith("-Xss")) {
addXss = false;
}
else if (parsedVMArg.startsWith("-XX:MaxPermSize=")) {
addMaxPermSize = false;
}
else if (parsedVMArg.startsWith("-Dgrails.gsp.enable.reload=")) {
addGrailsGspEnable = false;
}
}
}
if (addXmx) {
argsToAdd.add("-Xmx768m");
}
if (addXss) {
argsToAdd.add("-Xss256k");
}
if (addMaxPermSize) {
argsToAdd.add("-XX:MaxPermSize=256m");
}
if (grailsInstalled) {
if (addGrailsGspEnable) {
argsToAdd.add("-Dgrails.gsp.enable.reload=true");
}
}
argsToAdd.addAll(getTomcatServer().getAddExtraVmArgs());
argsToRemove.addAll(getTomcatServer().getRemoveExtraVmArgs());
if (argsToAdd.size() > 0 || argsToRemove.size() > 0) {
workingCopy.setAttribute(
IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS,
mergeArguments(existingVMArgs, argsToAdd.toArray(new String[0]),
argsToRemove.toArray(new String[0]), false));
}
}
/**
* In test mode webtools creates a temporary directory that is missing
* required jars for tc Server. This method copies the necessary jars from
* the instance base directory.
*/
private void setupRuntimeClasspathForTestEnvironment(ILaunchConfigurationWorkingCopy launchConfiguration,
IProgressMonitor monitor) throws CoreException {
TcServer tcServer = getTomcatServer();
IRuntimeClasspathEntry[] originalClasspath = JavaRuntime.computeUnresolvedRuntimeClasspath(launchConfiguration);
List<IRuntimeClasspathEntry> cp = new ArrayList<IRuntimeClasspathEntry>(Arrays.asList(originalClasspath));
IPath instanceBaseDirectory = tcServer.getInstanceBase(getServer().getRuntime());
if (instanceBaseDirectory != null) {
boolean changed = false;
IPath path = instanceBaseDirectory.append("bin");
changed |= addJarToClasspath(launchConfiguration, cp, path, "tomcat-juli.jar", false);
if (changed) {
List<String> list = new ArrayList<String>(cp.size());
for (IRuntimeClasspathEntry entry : cp) {
try {
list.add(entry.getMemento());
}
catch (Exception e) {
Trace.trace(Trace.SEVERE, "Could not resolve classpath entry: " + entry, e);
}
}
launchConfiguration.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, list);
}
}
}
private boolean addJarToClasspath(ILaunchConfigurationWorkingCopy launchConfiguration,
List<IRuntimeClasspathEntry> cp, IPath path, String prefix, boolean prepend) throws CoreException {
File directory = path.toFile();
String[] filenames = directory.list();
if (filenames != null) {
for (String filename : filenames) {
if (filename.startsWith(prefix) && filename.endsWith(".jar")) {
IRuntimeClasspathEntry entry = JavaRuntime.newArchiveRuntimeClasspathEntry(path.append(filename));
return TcServerBehaviour.mergeClasspathIfRequired(cp, entry, prepend);
}
}
}
return false;
}
@Override
public void stop(boolean force) {
if (!force) {
ServerPort[] ports = getTomcatServer().getServerPorts();
for (ServerPort serverPort : ports) {
if ("server".equals(serverPort.getId())) {
super.stop(force);
return;
}
}
int state = getServer().getServerState();
// If stopped or stopping, no need to run stop command again
if (state == IServer.STATE_STOPPED || state == IServer.STATE_STOPPING) {
return;
}
setServerState(IServer.STATE_STOPPING);
// fall-back to JMX command
ShutdownTcServerCommand command = new ShutdownTcServerCommand(this);
try {
command.execute();
// need to kill server unfortunately since the shutdown command
// only stops Catalina but not the Tomcat process itself
terminate();
stopImpl();
}
catch (TimeoutException e) {
// webtools will invoke this method again with and set force to
// true in case of a timeout
}
catch (CoreException e) {
// ignore, already logged in command
super.stop(true);
}
}
else {
super.stop(force);
}
}
/**
* Public for testing only.
*/
@Override
public String[] getRuntimeVMArguments() {
IPath instancePath = getRuntimeBaseDirectory();
IPath deployPath;
// If serving modules without publishing, use workspace path as the
// deploy path
if (getTomcatServer().isServeModulesWithoutPublish()) {
deployPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
}
// Else normal publishing for modules
else {
deployPath = getServerDeployDirectory();
// If deployPath is relative, convert to canonical path and hope for
// the best
if (!deployPath.isAbsolute()) {
try {
String deployLoc = (new File(deployPath.toOSString())).getCanonicalPath();
deployPath = new Path(deployLoc);
}
catch (IOException e) {
// Ignore if there is a problem
}
}
}
IPath installPath;
if (getTomcatServer().getLayout() == Layout.COMBINED) {
installPath = instancePath;
}
else {
installPath = getTomcatRuntime().getTomcatLocation();
}
// pass true to ensure that configPath is always respected
return getTomcatVersionHandler().getRuntimeVMArguments(installPath, instancePath, deployPath, true);
}
@Override
protected void publishModule(int kind, int deltaKind, IModule[] moduleTree, IProgressMonitor monitor)
throws CoreException {
super.publishModule(kind, deltaKind, moduleTree, monitor);
// reload application if enhanced redeploy is enabled
TcPublisher op = new TcPublisher(this, kind, moduleTree, deltaKind);
op.execute(monitor, null);
}
@Override
protected void publishServer(int kind, IProgressMonitor monitor) throws CoreException {
if (getServer().getRuntime() == null) {
return;
}
// set install dir to catalina.home
IPath installDir = getRuntimeBaseDirectory();
IPath confDir = null;
if (getTomcatServer().isTestEnvironment()) {
confDir = getRuntimeBaseDirectory();
IStatus status = getTomcatVersionHandler().prepareRuntimeDirectory(confDir);
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
IPath instanceBase = getTomcatServer().getInstanceBase(getServer().getRuntime());
// copy keystore file in case of ssl instance
IPath keystorePath = instanceBase.append("conf").append("tcserver.keystore");
if (keystorePath.toFile().exists()) {
IPath destPath = confDir.append("conf");
if (!destPath.toFile().exists()) {
destPath.toFile().mkdirs();
}
File file = keystorePath.toFile();
destPath = destPath.append(file.getName());
if (!destPath.toFile().exists()) {
FileUtil.copyFile(file.getAbsolutePath(), destPath.toFile().getAbsolutePath());
}
}
// copy libraries from instance base
IPath libPath = instanceBase.append("lib");
if (libPath.toFile().exists()) {
File[] files = libPath.toFile().listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().endsWith(".jar")) {
IPath destPath = confDir.append("lib");
if (!destPath.toFile().exists()) {
destPath.toFile().mkdirs();
}
destPath = destPath.append(file.getName());
if (!destPath.toFile().exists()) {
FileUtil.copyFile(file.getAbsolutePath(), destPath.toFile().getAbsolutePath());
}
}
}
}
}
}
else {
confDir = installDir;
}
IStatus status = getTomcatVersionHandler().prepareDeployDirectory(getServerDeployDirectory());
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
TcServer.getCallback().publishServer(getTomcatServer(), kind, monitor);
monitor = ProgressUtil.getMonitorFor(monitor);
monitor.beginTask(Messages.publishServerTask, 600);
status = getTomcatConfiguration().cleanupServer(confDir, installDir,
!getTomcatServer().isSaveSeparateContextFiles(), ProgressUtil.getSubMonitorFor(monitor, 100));
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
status = getTomcatConfiguration().backupAndPublish(confDir, !getTomcatServer().isTestEnvironment(),
ProgressUtil.getSubMonitorFor(monitor, 400));
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
status = getTomcatConfiguration().localizeConfiguration(confDir, getServerDeployDirectory(), getTomcatServer(),
ProgressUtil.getSubMonitorFor(monitor, 100));
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
monitor.done();
setServerPublishState(IServer.PUBLISH_STATE_NONE);
}
}
| com.vmware.vfabric.ide.eclipse.tcserver.core/src/com/vmware/vfabric/ide/eclipse/tcserver/internal/core/TcServerBehaviour.java | /*******************************************************************************
* Copyright (c) 2012 - 2013 GoPivotal, Inc.
* 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:
* GoPivotal, Inc. - initial API and implementation
*******************************************************************************/
package com.vmware.vfabric.ide.eclipse.tcserver.internal.core;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jst.server.tomcat.core.internal.FileUtil;
import org.eclipse.jst.server.tomcat.core.internal.Messages;
import org.eclipse.jst.server.tomcat.core.internal.PingThread;
import org.eclipse.jst.server.tomcat.core.internal.ProgressUtil;
import org.eclipse.jst.server.tomcat.core.internal.TomcatServerBehaviour;
import org.eclipse.jst.server.tomcat.core.internal.Trace;
import org.eclipse.mylyn.commons.net.WebLocation;
import org.eclipse.wst.server.core.IModule;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.ServerPort;
import org.eclipse.wst.server.core.model.IModuleResource;
import org.eclipse.wst.server.core.model.IModuleResourceDelta;
import com.vmware.vfabric.ide.eclipse.tcserver.internal.core.TcServer.Layout;
import com.vmware.vfabric.ide.eclipse.tcserver.reloading.TcServerReloadingPlugin;
/**
* @author Steffen Pingel
* @author Christian Dupuis
* @author Kris De Volder
* @author Leo Dos Santos
*/
public class TcServerBehaviour extends TomcatServerBehaviour {
private static class SslPingThread extends PingThread {
private static int DELAY = 10;
private static int INTERVAL = 250;
private final String url;
private boolean stopped;
private final TcServerBehaviour serverBehaviour;
private final int maxPings;
private int interval;
public SslPingThread(IServer server, String url, int maxPings, TcServerBehaviour behaviour) {
super(server, url, maxPings, behaviour);
this.url = url;
this.maxPings = (maxPings != -1) ? maxPings : 100;
this.serverBehaviour = behaviour;
}
@Override
protected void ping() {
interval = DELAY;
for (int i = 0; i < maxPings && !stopped; i++) {
try {
Thread.sleep(interval);
WebLocation location = new WebLocation(url);
HttpClient client = new HttpClient();
org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$
HeadMethod method = new HeadMethod(location.getUrl());
HostConfiguration hostConfiguration = org.eclipse.mylyn.commons.net.WebUtil
.createHostConfiguration(client, location, new NullProgressMonitor());
org.eclipse.mylyn.commons.net.WebUtil.execute(client, hostConfiguration, method,
new NullProgressMonitor());
// success
serverBehaviour.setServerStarted();
stop();
break;
}
catch (ConnectException e) {
// ignore
}
catch (Exception e) {
Trace.trace(Trace.SEVERE, "Failed to ping for tc Server startup.", e);
forceStop();
break;
}
interval = INTERVAL;
}
}
private void forceStop() {
stop();
serverBehaviour.stopImpl();
}
@Override
public void stop() {
super.stop();
this.stopped = true;
}
}
public static boolean mergeClasspathIfRequired(List<IRuntimeClasspathEntry> cp, IRuntimeClasspathEntry entry) {
return mergeClasspathIfRequired(cp, entry, false);
}
public static boolean mergeClasspathIfRequired(List<IRuntimeClasspathEntry> cp, IRuntimeClasspathEntry entry,
boolean prepend) {
boolean first = true;
Iterator<IRuntimeClasspathEntry> iterator = cp.iterator();
while (iterator.hasNext()) {
IRuntimeClasspathEntry entry2 = iterator.next();
if (entry2.getPath().equals(entry.getPath())) {
if (prepend && !first) {
// ensure new element is always first
iterator.remove();
}
else {
return false;
}
}
first = false;
}
if (prepend) {
cp.add(0, entry);
}
else {
cp.add(entry);
}
return true;
}
public String getDeployRoot() {
return getServerDeployDirectory().toOSString() + File.separator;
}
// make method visible to package
@Override
public IModuleResourceDelta[] getPublishedResourceDelta(IModule[] module) {
return super.getPublishedResourceDelta(module);
}
@Override
public IModuleResource[] getResources(IModule[] module) {
return super.getResources(module);
}
public IServicabilityInfo getServicabilityInfo() throws CoreException {
TcServer server = getTomcatServer();
return getTomcatConfiguration().getServicabilityInfo(server.getRuntimeBaseDirectory());
}
@Override
public TcServerConfiguration getTomcatConfiguration() throws CoreException {
return (TcServerConfiguration) super.getTomcatConfiguration();
}
@Override
public TcServerRuntime getTomcatRuntime() {
return (TcServerRuntime) super.getTomcatRuntime();
}
@Override
public TcServer getTomcatServer() {
return (TcServer) super.getTomcatServer();
}
@Override
public void setupLaunch(ILaunch launch, String launchMode, IProgressMonitor monitor) throws CoreException {
super.setupLaunch(launch, launchMode, monitor);
// transfer VM arguments to launch to make them accessible for later use
launch.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, launch.getLaunchConfiguration()
.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, (String) null));
TcServer.getCallback().setupLaunch(getTomcatServer(), launch, launchMode, monitor);
TcServerConfiguration configuration = getTomcatConfiguration();
if (configuration.getMainPort() == null && ping == null) {
ServerPort serverPort = configuration.getMainSslPort();
if (serverPort != null) {
try {
String url = "https://" + getServer().getHost() + ":" + serverPort.getPort();
ping = new SslPingThread(getServer(), url, -1, this);
}
catch (Exception e) {
Trace.trace(Trace.SEVERE, "Can't ping for tc Server startup.");
}
}
}
}
@Override
public void setupLaunchConfiguration(ILaunchConfigurationWorkingCopy workingCopy, IProgressMonitor monitor)
throws CoreException {
super.setupLaunchConfiguration(workingCopy, monitor);
TcServer.getCallback().setupLaunchConfiguration(getTomcatServer(), workingCopy, monitor);
if (getTomcatServer().isTestEnvironment()) {
setupRuntimeClasspathForTestEnvironment(workingCopy, monitor);
}
String existingVMArgs = workingCopy.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS,
(String) null);
String[] parsedVMArgs = null;
if (existingVMArgs != null) {
parsedVMArgs = DebugPlugin.parseArguments(existingVMArgs);
}
List<String> argsToAdd = new ArrayList<String>();
List<String> argsToRemove = new ArrayList<String>();
if (getTomcatServer().isAgentRedeployEnabled() && TcServerReloadingPlugin.getAgentJarPath() != null) {
argsToAdd.add("-javaagent:\"" + TcServerReloadingPlugin.getAgentJarPath() + "\"");
argsToAdd.add("-noverify");
String agentOptions = getTomcatServer().getAgentOptions();
if (StringUtils.isNotBlank(agentOptions)) {
argsToAdd.add("-Dspringloaded=\"" + agentOptions + "\"");
}
else {
argsToRemove.add("-Dspringloaded");
}
}
else {
argsToRemove.add("-javaagent:\"" + TcServerReloadingPlugin.getAgentJarPath() + "\"");
argsToRemove.add("-noverify");
argsToRemove.add("-Dspringloaded");
}
boolean grailsInstalled = Platform.getBundle("org.grails.ide.eclipse.runonserver") != null
|| Platform.getBundle("com.springsource.sts.grails.runonserver") != null;
boolean addXmx = true;
boolean addXss = true;
boolean addGrailsGspEnable = true;
boolean addMaxPermSize = true;
// check if arguments are already present
if (parsedVMArgs != null) {
for (String parsedVMArg : parsedVMArgs) {
if (parsedVMArg.startsWith("-Xmx")) {
addXmx = false;
}
else if (parsedVMArg.startsWith("-Xss")) {
addXss = false;
}
else if (parsedVMArg.startsWith("-XX:MaxPermSize=")) {
addMaxPermSize = false;
}
else if (parsedVMArg.startsWith("-Dgrails.gsp.enable.reload=")) {
addGrailsGspEnable = false;
}
}
}
if (addXmx) {
argsToAdd.add("-Xmx768m");
}
if (addXss) {
argsToAdd.add("-Xss192k");
}
if (addMaxPermSize) {
argsToAdd.add("-XX:MaxPermSize=256m");
}
if (grailsInstalled) {
if (addGrailsGspEnable) {
argsToAdd.add("-Dgrails.gsp.enable.reload=true");
}
}
argsToAdd.addAll(getTomcatServer().getAddExtraVmArgs());
argsToRemove.addAll(getTomcatServer().getRemoveExtraVmArgs());
if (argsToAdd.size() > 0 || argsToRemove.size() > 0) {
workingCopy.setAttribute(
IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS,
mergeArguments(existingVMArgs, argsToAdd.toArray(new String[0]),
argsToRemove.toArray(new String[0]), false));
}
}
/**
* In test mode webtools creates a temporary directory that is missing
* required jars for tc Server. This method copies the necessary jars from
* the instance base directory.
*/
private void setupRuntimeClasspathForTestEnvironment(ILaunchConfigurationWorkingCopy launchConfiguration,
IProgressMonitor monitor) throws CoreException {
TcServer tcServer = getTomcatServer();
IRuntimeClasspathEntry[] originalClasspath = JavaRuntime.computeUnresolvedRuntimeClasspath(launchConfiguration);
List<IRuntimeClasspathEntry> cp = new ArrayList<IRuntimeClasspathEntry>(Arrays.asList(originalClasspath));
IPath instanceBaseDirectory = tcServer.getInstanceBase(getServer().getRuntime());
if (instanceBaseDirectory != null) {
boolean changed = false;
IPath path = instanceBaseDirectory.append("bin");
changed |= addJarToClasspath(launchConfiguration, cp, path, "tomcat-juli.jar", false);
if (changed) {
List<String> list = new ArrayList<String>(cp.size());
for (IRuntimeClasspathEntry entry : cp) {
try {
list.add(entry.getMemento());
}
catch (Exception e) {
Trace.trace(Trace.SEVERE, "Could not resolve classpath entry: " + entry, e);
}
}
launchConfiguration.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, list);
}
}
}
private boolean addJarToClasspath(ILaunchConfigurationWorkingCopy launchConfiguration,
List<IRuntimeClasspathEntry> cp, IPath path, String prefix, boolean prepend) throws CoreException {
File directory = path.toFile();
String[] filenames = directory.list();
if (filenames != null) {
for (String filename : filenames) {
if (filename.startsWith(prefix) && filename.endsWith(".jar")) {
IRuntimeClasspathEntry entry = JavaRuntime.newArchiveRuntimeClasspathEntry(path.append(filename));
return TcServerBehaviour.mergeClasspathIfRequired(cp, entry, prepend);
}
}
}
return false;
}
@Override
public void stop(boolean force) {
if (!force) {
ServerPort[] ports = getTomcatServer().getServerPorts();
for (ServerPort serverPort : ports) {
if ("server".equals(serverPort.getId())) {
super.stop(force);
return;
}
}
int state = getServer().getServerState();
// If stopped or stopping, no need to run stop command again
if (state == IServer.STATE_STOPPED || state == IServer.STATE_STOPPING) {
return;
}
setServerState(IServer.STATE_STOPPING);
// fall-back to JMX command
ShutdownTcServerCommand command = new ShutdownTcServerCommand(this);
try {
command.execute();
// need to kill server unfortunately since the shutdown command
// only stops Catalina but not the Tomcat process itself
terminate();
stopImpl();
}
catch (TimeoutException e) {
// webtools will invoke this method again with and set force to
// true in case of a timeout
}
catch (CoreException e) {
// ignore, already logged in command
super.stop(true);
}
}
else {
super.stop(force);
}
}
/**
* Public for testing only.
*/
@Override
public String[] getRuntimeVMArguments() {
IPath instancePath = getRuntimeBaseDirectory();
IPath deployPath;
// If serving modules without publishing, use workspace path as the
// deploy path
if (getTomcatServer().isServeModulesWithoutPublish()) {
deployPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
}
// Else normal publishing for modules
else {
deployPath = getServerDeployDirectory();
// If deployPath is relative, convert to canonical path and hope for
// the best
if (!deployPath.isAbsolute()) {
try {
String deployLoc = (new File(deployPath.toOSString())).getCanonicalPath();
deployPath = new Path(deployLoc);
}
catch (IOException e) {
// Ignore if there is a problem
}
}
}
IPath installPath;
if (getTomcatServer().getLayout() == Layout.COMBINED) {
installPath = instancePath;
}
else {
installPath = getTomcatRuntime().getTomcatLocation();
}
// pass true to ensure that configPath is always respected
return getTomcatVersionHandler().getRuntimeVMArguments(installPath, instancePath, deployPath, true);
}
@Override
protected void publishModule(int kind, int deltaKind, IModule[] moduleTree, IProgressMonitor monitor)
throws CoreException {
super.publishModule(kind, deltaKind, moduleTree, monitor);
// reload application if enhanced redeploy is enabled
TcPublisher op = new TcPublisher(this, kind, moduleTree, deltaKind);
op.execute(monitor, null);
}
@Override
protected void publishServer(int kind, IProgressMonitor monitor) throws CoreException {
if (getServer().getRuntime() == null) {
return;
}
// set install dir to catalina.home
IPath installDir = getRuntimeBaseDirectory();
IPath confDir = null;
if (getTomcatServer().isTestEnvironment()) {
confDir = getRuntimeBaseDirectory();
IStatus status = getTomcatVersionHandler().prepareRuntimeDirectory(confDir);
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
IPath instanceBase = getTomcatServer().getInstanceBase(getServer().getRuntime());
// copy keystore file in case of ssl instance
IPath keystorePath = instanceBase.append("conf").append("tcserver.keystore");
if (keystorePath.toFile().exists()) {
IPath destPath = confDir.append("conf");
if (!destPath.toFile().exists()) {
destPath.toFile().mkdirs();
}
File file = keystorePath.toFile();
destPath = destPath.append(file.getName());
if (!destPath.toFile().exists()) {
FileUtil.copyFile(file.getAbsolutePath(), destPath.toFile().getAbsolutePath());
}
}
// copy libraries from instance base
IPath libPath = instanceBase.append("lib");
if (libPath.toFile().exists()) {
File[] files = libPath.toFile().listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().endsWith(".jar")) {
IPath destPath = confDir.append("lib");
if (!destPath.toFile().exists()) {
destPath.toFile().mkdirs();
}
destPath = destPath.append(file.getName());
if (!destPath.toFile().exists()) {
FileUtil.copyFile(file.getAbsolutePath(), destPath.toFile().getAbsolutePath());
}
}
}
}
}
}
else {
confDir = installDir;
}
IStatus status = getTomcatVersionHandler().prepareDeployDirectory(getServerDeployDirectory());
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
TcServer.getCallback().publishServer(getTomcatServer(), kind, monitor);
monitor = ProgressUtil.getMonitorFor(monitor);
monitor.beginTask(Messages.publishServerTask, 600);
status = getTomcatConfiguration().cleanupServer(confDir, installDir,
!getTomcatServer().isSaveSeparateContextFiles(), ProgressUtil.getSubMonitorFor(monitor, 100));
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
status = getTomcatConfiguration().backupAndPublish(confDir, !getTomcatServer().isTestEnvironment(),
ProgressUtil.getSubMonitorFor(monitor, 400));
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
status = getTomcatConfiguration().localizeConfiguration(confDir, getServerDeployDirectory(), getTomcatServer(),
ProgressUtil.getSubMonitorFor(monitor, 100));
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
monitor.done();
setServerPublishState(IServer.PUBLISH_STATE_NONE);
}
}
| STS-3578: Default tc server instance create launch config with too small
stack size | com.vmware.vfabric.ide.eclipse.tcserver.core/src/com/vmware/vfabric/ide/eclipse/tcserver/internal/core/TcServerBehaviour.java | STS-3578: Default tc server instance create launch config with too small stack size |
|
Java | mpl-2.0 | be982dea42a1e6f0d7aeaa60822dd4d64d0f86b0 | 0 | Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV | package org.helioviewer.jhv.internal_plugins.filter.SOHOLUTFilterPlugin;
import org.helioviewer.base.logging.Log;
import org.helioviewer.viewmodel.filter.Filter;
import org.helioviewer.viewmodel.metadata.HelioviewerMetaData;
import org.helioviewer.viewmodel.metadata.MetaData;
import org.helioviewer.viewmodel.view.FilterView;
import org.helioviewer.viewmodel.view.MetaDataView;
import org.helioviewer.viewmodel.view.SubimageDataView;
import org.helioviewer.viewmodel.view.jp2view.JHVJP2View;
import org.helioviewer.viewmodelplugin.filter.FilterContainer;
import org.helioviewer.viewmodelplugin.filter.FilterTab;
import org.helioviewer.viewmodelplugin.filter.FilterTabDescriptor.Type;
import org.helioviewer.viewmodelplugin.filter.FilterTabList;
import org.helioviewer.viewmodelplugin.filter.FilterTabPanelManager;
import org.helioviewer.viewmodelplugin.filter.FilterTabPanelManager.Area;
/**
* Filter plugin for applying a color table to single channel images.
*
* <p>
* This plugin provides several different color tables to improve the visual
* impression of single channel images. It manages a filter for applying the
* color table and a combobox to change it.
*
* partly rewritten
*
* @author Helge Dietert
*/
public class SOHOLUTFilterPlugin extends FilterContainer {
/**
* {@inheritDoc}
*/
@Override
public String getDescription() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Color Tables";
}
/**
* If the given meta data contain helioviewer meta data, the default color
* table for the given instrument is chosen. Otherwise, the color table is
* set to gray by default, which does not change the color at all.
*/
@Override
protected void installFilterImpl(FilterView filterView, FilterTabList tabList) {
// Only applicable for SingeChannelFormat
if (!(filterView.getAdapter(SubimageDataView.class).getSubimageData().getImageFormat().isSingleChannel()))
return;
SOHOLUTFilter filter = new SOHOLUTFilter();
FilterTabPanelManager manager = tabList.getFirstPanelManagerByType(Type.COMPACT_FILTER);
if (manager == null) {
manager = new FilterTabPanelManager();
tabList.add(new FilterTab(Type.COMPACT_FILTER, getName(), manager));
}
SOHOLUTPanel pane = new SOHOLUTPanel();
pane.setFilter(filter);
manager.add(pane, Area.CENTER);
// Set standard gray and install filter
pane.setLutByName("Gray");
filterView.setFilter(filter);
// Now need to set the initial filter
JHVJP2View jp2View = filterView.getAdapter(JHVJP2View.class);
if (jp2View != null) {
int[] builtIn = jp2View.getBuiltInLUT();
if (builtIn != null) {
LUT builtInLut = new LUT("built-in", builtIn, builtIn);
pane.addLut(builtInLut);
return;
}
}
// Standard using meta data
MetaDataView metaDataView = filterView.getAdapter(MetaDataView.class);
if (metaDataView != null) {
MetaData metaData = metaDataView.getMetaData();
if (metaData != null && metaData instanceof HelioviewerMetaData) {
HelioviewerMetaData hvMetaData = (HelioviewerMetaData) metaData;
String colorKey = DefaultTable.getSingletonInstance().getColorTable(hvMetaData);
if (colorKey != null) {
Log.debug("Try to apply color table " + colorKey);
pane.setLutByName(colorKey);
return;
}
}
}
// Otherwise gray
pane.setLutByName("Gray");
}
/**
* {@inheritDoc}
*/
@Override
public Class<? extends Filter> getFilterClass() {
return SOHOLUTFilter.class;
}
}
| src/jhv/src/org/helioviewer/jhv/internal_plugins/filter/SOHOLUTFilterPlugin/SOHOLUTFilterPlugin.java | package org.helioviewer.jhv.internal_plugins.filter.SOHOLUTFilterPlugin;
import org.helioviewer.base.logging.Log;
import org.helioviewer.viewmodel.filter.Filter;
import org.helioviewer.viewmodel.imageformat.SingleChannelImageFormat;
import org.helioviewer.viewmodel.metadata.HelioviewerMetaData;
import org.helioviewer.viewmodel.metadata.MetaData;
import org.helioviewer.viewmodel.view.FilterView;
import org.helioviewer.viewmodel.view.MetaDataView;
import org.helioviewer.viewmodel.view.SubimageDataView;
import org.helioviewer.viewmodel.view.jp2view.JHVJP2View;
import org.helioviewer.viewmodelplugin.filter.FilterContainer;
import org.helioviewer.viewmodelplugin.filter.FilterTab;
import org.helioviewer.viewmodelplugin.filter.FilterTabDescriptor.Type;
import org.helioviewer.viewmodelplugin.filter.FilterTabList;
import org.helioviewer.viewmodelplugin.filter.FilterTabPanelManager;
import org.helioviewer.viewmodelplugin.filter.FilterTabPanelManager.Area;
/**
* Filter plugin for applying a color table to single channel images.
*
* <p>
* This plugin provides several different color tables to improve the visual
* impression of single channel images. It manages a filter for applying the
* color table and a combobox to change it.
*
* partly rewritten
*
* @author Helge Dietert
*/
public class SOHOLUTFilterPlugin extends FilterContainer {
/**
* {@inheritDoc}
*/
@Override
public String getDescription() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Color Tables";
}
/**
* If the given meta data contain helioviewer meta data, the default color
* table for the given instrument is chosen. Otherwise, the color table is
* set to gray by default, which does not change the color at all.
*/
@Override
protected void installFilterImpl(FilterView filterView, FilterTabList tabList) {
// Only applicable for SingeChannelFormat
if (!(filterView.getAdapter(SubimageDataView.class).getSubimageData().getImageFormat() instanceof SingleChannelImageFormat))
return;
SOHOLUTFilter filter = new SOHOLUTFilter();
FilterTabPanelManager manager = tabList.getFirstPanelManagerByType(Type.COMPACT_FILTER);
if (manager == null) {
manager = new FilterTabPanelManager();
tabList.add(new FilterTab(Type.COMPACT_FILTER, getName(), manager));
}
SOHOLUTPanel pane = new SOHOLUTPanel();
pane.setFilter(filter);
manager.add(pane, Area.CENTER);
// Set standard gray and install filter
pane.setLutByName("Gray");
filterView.setFilter(filter);
// Now need to set the initial filter
JHVJP2View jp2View = filterView.getAdapter(JHVJP2View.class);
if (jp2View != null) {
int[] builtIn = jp2View.getBuiltInLUT();
if (builtIn != null) {
LUT builtInLut = new LUT("built-in", builtIn, builtIn);
pane.addLut(builtInLut);
return;
}
}
// Standard using meta data
MetaDataView metaDataView = filterView.getAdapter(MetaDataView.class);
if (metaDataView != null) {
MetaData metaData = metaDataView.getMetaData();
if (metaData != null && metaData instanceof HelioviewerMetaData) {
HelioviewerMetaData hvMetaData = (HelioviewerMetaData) metaData;
String colorKey = DefaultTable.getSingletonInstance().getColorTable(hvMetaData);
if (colorKey != null) {
Log.debug("Try to apply color table " + colorKey);
pane.setLutByName(colorKey);
return;
}
}
}
// Otherwise gray
pane.setLutByName("Gray");
}
/**
* {@inheritDoc}
*/
@Override
public Class<? extends Filter> getFilterClass() {
return SOHOLUTFilter.class;
}
}
| check for single channel
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@1406 b4e469a2-07ce-4b26-9273-4d7d95a670c7
| src/jhv/src/org/helioviewer/jhv/internal_plugins/filter/SOHOLUTFilterPlugin/SOHOLUTFilterPlugin.java | check for single channel |
|
Java | agpl-3.0 | 72254a00278db2f779869f31b05149403317ef92 | 0 | RestComm/restcomm-android-sdk,RestComm/restcomm-android-sdk,Mobicents/restcomm-android-sdk | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2015, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* For questions related to commercial use licensing, please contact [email protected].
*
*/
/*
* libjingle
* Copyright 2014 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.restcomm.android.sdk.MediaClient.util;
//import org.appspot.apprtc.AppRTCClient.SignalingParameters;
//import org.appspot.apprtc.util.AsyncHttpURLConnection;
//import org.appspot.apprtc.util.AsyncHttpURLConnection.AsyncHttpEvents;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restcomm.android.sdk.util.RCLogger;
import org.webrtc.PeerConnection;
import java.util.LinkedList;
// Fetches the ICE Servers asynchronously and provides callbacks for result
public class IceServerFetcher {
private static final String TAG = "IceServerFetcher";
private final IceServerFetcherEvents events;
private final String iceUrl;
private boolean turnEnabled = true;
private AsyncHttpURLConnection httpConnection;
/**
* Room parameters fetcher callbacks.
*/
public static interface IceServerFetcherEvents {
/**
* Callback fired when ICE servers are fetched
*/
public void onIceServersReady(final LinkedList<PeerConnection.IceServer> iceServers);
/**
* Callback if there's an error fetching ICE servers
*/
public void onIceServersError(final String description);
}
public IceServerFetcher(String iceUrl, boolean turnEnabled, final IceServerFetcherEvents events) {
this.iceUrl = iceUrl;
this.turnEnabled = turnEnabled;
this.events = events;
}
public void makeRequest() {
RCLogger.d(TAG, "Requesting ICE servers from: " + iceUrl);
httpConnection = new AsyncHttpURLConnection(
"GET", iceUrl,
new AsyncHttpURLConnection.AsyncHttpEvents() {
@Override
public void onHttpError(String errorMessage) {
RCLogger.e(TAG, "ICE servers request timeout: " + errorMessage);
events.onIceServersError("ICE servers request timeout");
}
@Override
public void onHttpComplete(String response) {
iceServersHttpResponseParse(response);
}
});
httpConnection.send();
}
private void iceServersHttpResponseParse(String response) {
try {
JSONObject iceServersJson = new JSONObject(response);
int result = iceServersJson.getInt("s");
RCLogger.d(TAG, "Ice Servers response status: " + result);
if (result != 200) {
events.onIceServersError("Ice Servers response error: " + iceServersJson.getString("e"));
return;
}
LinkedList<PeerConnection.IceServer> iceServers = new LinkedList<PeerConnection.IceServer>();
JSONArray iceServersArray = iceServersJson.getJSONObject("d").getJSONArray("iceServers");
for (int i = 0; i < iceServersArray.length(); ++i) {
String iceServerString = iceServersArray.getString(i);
JSONObject iceServerJson = new JSONObject(iceServerString);
String url = iceServerJson.getString("url");
if (!this.turnEnabled && url.startsWith("turn:")) {
// if turn is not enabled and the server we got back is a turn (as opposed to stun), skip it
continue;
}
// username and credentials is optional, for example in the STUN server setting
String username = "", password = "";
if (iceServerJson.has("username")) {
username = iceServerJson.getString("username");
}
if (iceServerJson.has("credential")) {
password = iceServerJson.getString("credential");
}
iceServers.add(new PeerConnection.IceServer(url, username, password));
RCLogger.d(TAG, "==== URL: " + url + ", username: " + username);
}
events.onIceServersReady(iceServers);
} catch (JSONException e) {
events.onIceServersError("ICE server JSON parsing error: " + e.toString());
}
}
// Requests & returns a TURN ICE Server based on a request URL. Must be run
// off the main thread!
/*
private LinkedList<PeerConnection.IceServer> requestTurnServers(String url)
throws IOException, JSONException {
LinkedList<PeerConnection.IceServer> turnServers =
new LinkedList<PeerConnection.IceServer>();
RCLogger.d(TAG, "Request TURN from: " + url);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(TURN_HTTP_TIMEOUT_MS);
connection.setReadTimeout(TURN_HTTP_TIMEOUT_MS);
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
throw new IOException("Non-200 response when requesting TURN server from "
+ url + " : " + connection.getHeaderField(null));
}
InputStream responseStream = connection.getInputStream();
String response = drainStream(responseStream);
connection.disconnect();
RCLogger.d(TAG, "TURN response: " + response);
JSONObject responseJSON = new JSONObject(response);
String username = responseJSON.getString("username");
String password = responseJSON.getString("password");
JSONArray turnUris = responseJSON.getJSONArray("uris");
for (int i = 0; i < turnUris.length(); i++) {
String uri = turnUris.getString(i);
turnServers.add(new PeerConnection.IceServer(uri, username, password));
}
return turnServers;
}
// Return the list of ICE servers described by a WebRTCPeerConnection
// configuration string.
private LinkedList<PeerConnection.IceServer> iceServersFromPCConfigJSON(
String pcConfig) throws JSONException {
JSONObject json = new JSONObject(pcConfig);
JSONArray servers = json.getJSONArray("iceServers");
LinkedList<PeerConnection.IceServer> ret =
new LinkedList<PeerConnection.IceServer>();
for (int i = 0; i < servers.length(); ++i) {
JSONObject server = servers.getJSONObject(i);
String url = server.getString("urls");
String credential =
server.has("credential") ? server.getString("credential") : "";
ret.add(new PeerConnection.IceServer(url, "", credential));
}
return ret;
}
// Return the contents of an InputStream as a String.
private static String drainStream(InputStream in) {
Scanner s = new Scanner(in).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
*/
}
| restcomm.android.sdk/src/main/java/org/restcomm/android/sdk/MediaClient/util/IceServerFetcher.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2015, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* For questions related to commercial use licensing, please contact [email protected].
*
*/
/*
* libjingle
* Copyright 2014 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.restcomm.android.sdk.MediaClient.util;
//import org.appspot.apprtc.AppRTCClient.SignalingParameters;
//import org.appspot.apprtc.util.AsyncHttpURLConnection;
//import org.appspot.apprtc.util.AsyncHttpURLConnection.AsyncHttpEvents;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restcomm.android.sdk.util.RCLogger;
import org.webrtc.PeerConnection;
import java.util.LinkedList;
// Fetches the ICE Servers asynchronously and provides callbacks for result
public class IceServerFetcher {
private static final String TAG = "IceServerFetcher";
private final IceServerFetcherEvents events;
private final String iceUrl;
private boolean turnEnabled = true;
private AsyncHttpURLConnection httpConnection;
/**
* Room parameters fetcher callbacks.
*/
public static interface IceServerFetcherEvents {
/**
* Callback fired when ICE servers are fetched
*/
public void onIceServersReady(final LinkedList<PeerConnection.IceServer> iceServers);
/**
* Callback if there's an error fetching ICE servers
*/
public void onIceServersError(final String description);
}
public IceServerFetcher(String iceUrl, boolean turnEnabled, final IceServerFetcherEvents events) {
this.iceUrl = iceUrl;
this.turnEnabled = turnEnabled;
this.events = events;
}
public void makeRequest() {
RCLogger.d(TAG, "Requesting ICE servers from: " + iceUrl);
httpConnection = new AsyncHttpURLConnection(
"GET", iceUrl,
new AsyncHttpURLConnection.AsyncHttpEvents() {
@Override
public void onHttpError(String errorMessage) {
RCLogger.e(TAG, "ICE servers request timeout: " + errorMessage);
events.onIceServersError(errorMessage);
}
@Override
public void onHttpComplete(String response) {
iceServersHttpResponseParse(response);
}
});
httpConnection.send();
}
private void iceServersHttpResponseParse(String response) {
try {
JSONObject iceServersJson = new JSONObject(response);
int result = iceServersJson.getInt("s");
RCLogger.d(TAG, "Ice Servers response status: " + result);
if (result != 200) {
events.onIceServersError("Ice Servers response error: " + iceServersJson.getString("e"));
return;
}
LinkedList<PeerConnection.IceServer> iceServers = new LinkedList<PeerConnection.IceServer>();
JSONArray iceServersArray = iceServersJson.getJSONObject("d").getJSONArray("iceServers");
for (int i = 0; i < iceServersArray.length(); ++i) {
String iceServerString = iceServersArray.getString(i);
JSONObject iceServerJson = new JSONObject(iceServerString);
String url = iceServerJson.getString("url");
if (!this.turnEnabled && url.startsWith("turn:")) {
// if turn is not enabled and the server we got back is a turn (as opposed to stun), skip it
continue;
}
// username and credentials is optional, for example in the STUN server setting
String username = "", password = "";
if (iceServerJson.has("username")) {
username = iceServerJson.getString("username");
}
if (iceServerJson.has("credential")) {
password = iceServerJson.getString("credential");
}
iceServers.add(new PeerConnection.IceServer(url, username, password));
RCLogger.d(TAG, "==== URL: " + url + ", username: " + username);
}
events.onIceServersReady(iceServers);
} catch (JSONException e) {
events.onIceServersError("ICE server JSON parsing error: " + e.toString());
}
}
// Requests & returns a TURN ICE Server based on a request URL. Must be run
// off the main thread!
/*
private LinkedList<PeerConnection.IceServer> requestTurnServers(String url)
throws IOException, JSONException {
LinkedList<PeerConnection.IceServer> turnServers =
new LinkedList<PeerConnection.IceServer>();
RCLogger.d(TAG, "Request TURN from: " + url);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(TURN_HTTP_TIMEOUT_MS);
connection.setReadTimeout(TURN_HTTP_TIMEOUT_MS);
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
throw new IOException("Non-200 response when requesting TURN server from "
+ url + " : " + connection.getHeaderField(null));
}
InputStream responseStream = connection.getInputStream();
String response = drainStream(responseStream);
connection.disconnect();
RCLogger.d(TAG, "TURN response: " + response);
JSONObject responseJSON = new JSONObject(response);
String username = responseJSON.getString("username");
String password = responseJSON.getString("password");
JSONArray turnUris = responseJSON.getJSONArray("uris");
for (int i = 0; i < turnUris.length(); i++) {
String uri = turnUris.getString(i);
turnServers.add(new PeerConnection.IceServer(uri, username, password));
}
return turnServers;
}
// Return the list of ICE servers described by a WebRTCPeerConnection
// configuration string.
private LinkedList<PeerConnection.IceServer> iceServersFromPCConfigJSON(
String pcConfig) throws JSONException {
JSONObject json = new JSONObject(pcConfig);
JSONArray servers = json.getJSONArray("iceServers");
LinkedList<PeerConnection.IceServer> ret =
new LinkedList<PeerConnection.IceServer>();
for (int i = 0; i < servers.length(); ++i) {
JSONObject server = servers.getJSONObject(i);
String url = server.getString("urls");
String credential =
server.has("credential") ? server.getString("credential") : "";
ret.add(new PeerConnection.IceServer(url, "", credential));
}
return ret;
}
// Return the contents of an InputStream as a String.
private static String drainStream(InputStream in) {
Scanner s = new Scanner(in).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
*/
}
| Fixed #463: Remove passwords from logs, as they sometimes end up in gists, etc
| restcomm.android.sdk/src/main/java/org/restcomm/android/sdk/MediaClient/util/IceServerFetcher.java | Fixed #463: Remove passwords from logs, as they sometimes end up in gists, etc |
|
Java | agpl-3.0 | 791b456dc5142ba33778fc4f8bd25501531e29e2 | 0 | CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine | package com.splicemachine.stats.estimate;
import com.splicemachine.stats.ColumnStatistics;
import com.splicemachine.stats.frequency.FrequencyEstimate;
import com.splicemachine.stats.frequency.FrequentElements;
import com.splicemachine.utils.ComparableComparator;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Set;
/**
* A uniform distribution of strings.
*
* <p>
* In this implementation, all strings are assumed to occur with equal probability. That is,
* if {@code p(x)} is the probability that {@code x} is equal to a specific value, then this implementation
* assumes that {@code p(x) = P}, where {@code P} is a constant. Since all elements have an equal
* probability of occurring, and {@code N} is the total number of elements in the data set,
* then we would see that each element likely occurs about {@code P*N = Ns} times. Since each distinct element
* in the data set will occur {@code Ns} times, then the total number of rows in the data set should be {@code C*Ns},
* where {@code C} is the cardinality of the data set. Therefore, we see that {@code Ns = N/C}.
* </p>
*
* <p>
* To estimate range scans, we simply estimate the number of elements which match each single row, and multiply
* that by the number of distinct elements which we expect to see within that range. To do this, we make use
* of the fact that, for any subrange, {@code N/C = Nr/Cr}, where {@code Cr} is the number of distinct elements
* in the range of interest, and {@code Nr} is the total number of elements in the range of interest. Therefore,
* if we can compute {@code Cr}, we can compute {@code Nr = Cr*N/C}, which will give us our estimate.
* </p>
*
* <p>
* In order to compute {@code Cr}, we perform a simple linear interpolation. When we are at the minimum value,
* the cardinality of the data set is 0, and when we are at the maximum value, the cardinality of the data set
* is {@code C}. Therefore, our linear interpolation says that the cardinality for any range {@code [min,x)}
*
* <pre>
* Cr(x) = C*d(min,x)/d(min,max)
* </pre>
* where {@code d(a,b)} is the number of distinct elements which can occur in the range {@code [a,b)}. Thus, for
* any range{@code [x,y)}, the number of distinct elements in that range is {@code C*d(x,y)/d(min,max) = Cr}.
* </p>
*
* <p>
* Note that, for computing range scans, we <em>must</em> have a well-constructed distance function. We do this
* by using the "position" of a string in the total ordering defined for the column. By default, this implementation
* uses a lexicographic ordering, in which the position of the string is computed using the
* {@link #computePosition(String)} method (more details about the default implementation of that is in the javadoc
* for that method). The distance is then {@code Pos(y)-Pos(x)}(assuming {@code y>x}).
* </p>
*
* @author Scott Fines
* Date: 3/5/15
*/
public class UniformStringDistribution extends BaseDistribution<String> {
protected final int strLen;
private final BigDecimal a;
private final BigDecimal b;
public UniformStringDistribution(ColumnStatistics<String> columnStats, int strLen) {
super(columnStats, ComparableComparator.<String>newComparator());
this.strLen = strLen;
if (columnStats.maxValue() == null) {
this.a = BigDecimal.valueOf(0.0);
this.b = BigDecimal.valueOf(0.0);
} else {
String maxV = columnStats.maxValue();
String minV = columnStats.minValue();
if(maxV.equals(minV)){
/*
* the start and stop values are the same, so we just assume a constant line
*/
this.a = BigDecimal.ZERO;
this.b = BigDecimal.valueOf(columnStats.nonNullCount()-columnStats.minCount());
}else{
BigDecimal maxPosition=computePosition(columnStats.maxValue());
BigDecimal at=BigDecimal.valueOf(columnStats.nonNullCount()-columnStats.minCount());
BigDecimal overallDistance=maxPosition.subtract(computePosition(columnStats.minValue()));
at=at.divide(overallDistance,MathContext.DECIMAL64);
this.a=at;
this.b=BigDecimal.valueOf(columnStats.nonNullCount()).subtract(a.multiply(maxPosition));
}
}
}
@Override
protected final long estimateRange(String start, String stop, boolean includeStart, boolean includeStop, boolean isMin) {
BigDecimal startPos = computePosition(start);
BigDecimal stopPos = computePosition(stop);
BigDecimal baseE = a.multiply(stopPos).add(b).subtract(a.multiply(startPos).add(b));
long rowsPerEntry = getPerRowCount();
/*
* This is safe, because the linear function we used has a max of maxValue on the range [minValue,maxValue),
* with a maximum value of rowCount (we built the linear function to do this). Since rowCount is a long,
* the value of baseE *MUST* fit within a long (and therefore, within a double).
*/
double baseEstimate = baseE.doubleValue();
if(!includeStart){
baseEstimate-=rowsPerEntry;
}
if(includeStop)
baseEstimate+=rowsPerEntry;
FrequentElements<String> fe = columnStats.topK();
//if we are the min value, don't include the start key in frequent elements
includeStart = includeStart &&!isMin;
Set<? extends FrequencyEstimate<String>> estimates = fe.frequentElementsBetween(start, stop, includeStart, includeStop);
baseEstimate-=rowsPerEntry*estimates.size();
for(FrequencyEstimate<String> est:estimates){
baseEstimate+=est.count()-est.error();
}
return (long)baseEstimate;
}
/**
* Compute the "position" of the specified string, relative to the total ordering of the defined string
* set.
*
* <p>
* The default algorithm uses the recurrance relation
*
* <pre>
* {@code pos(i,s) = m*pos(i-1,s) + s[i]}
* {@code pos(0,s) = s[0]}
* </pre>
*
* where {@code m = 2^32}, and {@code s[i]} is the Unicode code point for the {@code i}th character in the
* string. When the length of the string is strictly less than the maximum length, we "pad" the string with
* 0s until the length is equal. We do not physically add characters to the string, however; instead, we
* simply scale the number by {@code m^(strLen-length(s))} to represent the extra padding.
* </p>
*
* <p>
* It is acknowledged that this approach may not be ideal for many use cases (particularly ones in which
* there are only a few possible elements for each character). Thus, this method is designed to be
* subclassed, so that different methods may be used when necessary.
* </p>
* @param str the the string to compute the position for.
* @return a numeric representation of the location of the string within the total ordering of all possible
* strings.
*/
protected BigDecimal computePosition(String str) {
return unicodePosition(strLen,str);
}
/**
* Get a Distribution Factory which creates uniform distributions for strings, based on the <em>maximum</em>
* length of the string field allowed.
*
* <p>
* Note that this implementation depends heavily on there <em>being</em> a maximum string length (otherwise,
* it is unable to compute the distance between two strings effectively). If you have a situation where
* you cannot rely on that fact, you are best off subclassing this implementation and overriding
* {@link #computePosition(String)} in order to deal with your particular environment.
* </p>
* @param stringLength the maximum length of a string which is part of this distribution
* @return a DistributionFactory which creates Uniform distributions.
*/
public static DistributionFactory<String> factory(final int stringLength){
return new DistributionFactory<String>() {
@Override
public Distribution<String> newDistribution(ColumnStatistics<String> statistics) {
return new UniformStringDistribution(statistics,stringLength);
}
};
}
/* ****************************************************************************************************************/
/*private helper methods*/
private static final BigDecimal TWO_THIRTY_TWO = BigDecimal.valueOf(Integer.MAX_VALUE);
private static BigDecimal unicodePosition(int strLen,String str) {
/*
* Each UTF-8 encoded character takes up between 1 and 4 bytes, so if we represent each character
* with a single big-endian integer holding the character, then we can compute the absolute position
* in the ordering according to the rule
*
* 2^strLen*char[0]+2^(strLen-1)*char[1]+...char[strLen-1]
*/
int len = str.length();
BigDecimal pos = BigDecimal.ZERO;
for(int codePoint = 0;codePoint<len;codePoint++){
int v = str.codePointAt(codePoint);
pos = BigDecimal.valueOf(v).add(TWO_THIRTY_TWO.multiply(pos));
}
//now shift the data over to account for string padding at the end
if(strLen>len){
BigDecimal scale = TWO_THIRTY_TWO.pow(strLen-len);
pos = pos.multiply(scale);
}
return pos;
}
private long getPerRowCount() {
return getAdjustedRowCount()/columnStats.cardinality();
}
}
| src/main/java/com/splicemachine/stats/estimate/UniformStringDistribution.java | package com.splicemachine.stats.estimate;
import com.splicemachine.stats.ColumnStatistics;
import com.splicemachine.stats.frequency.FrequencyEstimate;
import com.splicemachine.stats.frequency.FrequentElements;
import com.splicemachine.utils.ComparableComparator;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Set;
/**
* A uniform distribution of strings.
*
* <p>
* In this implementation, all strings are assumed to occur with equal probability. That is,
* if {@code p(x)} is the probability that {@code x} is equal to a specific value, then this implementation
* assumes that {@code p(x) = P}, where {@code P} is a constant. Since all elements have an equal
* probability of occurring, and {@code N} is the total number of elements in the data set,
* then we would see that each element likely occurs about {@code P*N = Ns} times. Since each distinct element
* in the data set will occur {@code Ns} times, then the total number of rows in the data set should be {@code C*Ns},
* where {@code C} is the cardinality of the data set. Therefore, we see that {@code Ns = N/C}.
* </p>
*
* <p>
* To estimate range scans, we simply estimate the number of elements which match each single row, and multiply
* that by the number of distinct elements which we expect to see within that range. To do this, we make use
* of the fact that, for any subrange, {@code N/C = Nr/Cr}, where {@code Cr} is the number of distinct elements
* in the range of interest, and {@code Nr} is the total number of elements in the range of interest. Therefore,
* if we can compute {@code Cr}, we can compute {@code Nr = Cr*N/C}, which will give us our estimate.
* </p>
*
* <p>
* In order to compute {@code Cr}, we perform a simple linear interpolation. When we are at the minimum value,
* the cardinality of the data set is 0, and when we are at the maximum value, the cardinality of the data set
* is {@code C}. Therefore, our linear interpolation says that the cardinality for any range {@code [min,x)}
*
* <pre>
* Cr(x) = C*d(min,x)/d(min,max)
* </pre>
* where {@code d(a,b)} is the number of distinct elements which can occur in the range {@code [a,b)}. Thus, for
* any range{@code [x,y)}, the number of distinct elements in that range is {@code C*d(x,y)/d(min,max) = Cr}.
* </p>
*
* <p>
* Note that, for computing range scans, we <em>must</em> have a well-constructed distance function. We do this
* by using the "position" of a string in the total ordering defined for the column. By default, this implementation
* uses a lexicographic ordering, in which the position of the string is computed using the
* {@link #computePosition(String)} method (more details about the default implementation of that is in the javadoc
* for that method). The distance is then {@code Pos(y)-Pos(x)}(assuming {@code y>x}).
* </p>
*
* @author Scott Fines
* Date: 3/5/15
*/
public class UniformStringDistribution extends BaseDistribution<String> {
protected final int strLen;
private final BigDecimal a;
private final BigDecimal b;
public UniformStringDistribution(ColumnStatistics<String> columnStats, int strLen) {
super(columnStats, ComparableComparator.<String>newComparator());
this.strLen = strLen;
if (columnStats.maxValue() == null) {
this.a = BigDecimal.valueOf(0.0);
this.b = BigDecimal.valueOf(0.0);
} else {
BigDecimal at = BigDecimal.valueOf(columnStats.nonNullCount() - columnStats.minCount());
BigDecimal maxPosition = computePosition(columnStats.maxValue());
BigDecimal overallDistance = maxPosition.subtract(computePosition(columnStats.minValue()));
at = at.divide(overallDistance, MathContext.DECIMAL64);
this.a = at;
this.b = BigDecimal.valueOf(columnStats.nonNullCount()).subtract(a.multiply(maxPosition));
}
}
@Override
protected final long estimateRange(String start, String stop, boolean includeStart, boolean includeStop, boolean isMin) {
BigDecimal startPos = computePosition(start);
BigDecimal stopPos = computePosition(stop);
BigDecimal baseE = a.multiply(stopPos).add(b).subtract(a.multiply(startPos).add(b));
long rowsPerEntry = getPerRowCount();
/*
* This is safe, because the linear function we used has a max of maxValue on the range [minValue,maxValue),
* with a maximum value of rowCount (we built the linear function to do this). Since rowCount is a long,
* the value of baseE *MUST* fit within a long (and therefore, within a double).
*/
double baseEstimate = baseE.doubleValue();
if(!includeStart){
baseEstimate-=rowsPerEntry;
}
if(includeStop)
baseEstimate+=rowsPerEntry;
FrequentElements<String> fe = columnStats.topK();
//if we are the min value, don't include the start key in frequent elements
includeStart = includeStart &&!isMin;
Set<? extends FrequencyEstimate<String>> estimates = fe.frequentElementsBetween(start, stop, includeStart, includeStop);
baseEstimate-=rowsPerEntry*estimates.size();
for(FrequencyEstimate<String> est:estimates){
baseEstimate+=est.count()-est.error();
}
return (long)baseEstimate;
}
/**
* Compute the "position" of the specified string, relative to the total ordering of the defined string
* set.
*
* <p>
* The default algorithm uses the recurrance relation
*
* <pre>
* {@code pos(i,s) = m*pos(i-1,s) + s[i]}
* {@code pos(0,s) = s[0]}
* </pre>
*
* where {@code m = 2^32}, and {@code s[i]} is the Unicode code point for the {@code i}th character in the
* string. When the length of the string is strictly less than the maximum length, we "pad" the string with
* 0s until the length is equal. We do not physically add characters to the string, however; instead, we
* simply scale the number by {@code m^(strLen-length(s))} to represent the extra padding.
* </p>
*
* <p>
* It is acknowledged that this approach may not be ideal for many use cases (particularly ones in which
* there are only a few possible elements for each character). Thus, this method is designed to be
* subclassed, so that different methods may be used when necessary.
* </p>
* @param str the the string to compute the position for.
* @return a numeric representation of the location of the string within the total ordering of all possible
* strings.
*/
protected BigDecimal computePosition(String str) {
return unicodePosition(strLen,str);
}
/**
* Get a Distribution Factory which creates uniform distributions for strings, based on the <em>maximum</em>
* length of the string field allowed.
*
* <p>
* Note that this implementation depends heavily on there <em>being</em> a maximum string length (otherwise,
* it is unable to compute the distance between two strings effectively). If you have a situation where
* you cannot rely on that fact, you are best off subclassing this implementation and overriding
* {@link #computePosition(String)} in order to deal with your particular environment.
* </p>
* @param stringLength the maximum length of a string which is part of this distribution
* @return a DistributionFactory which creates Uniform distributions.
*/
public static DistributionFactory<String> factory(final int stringLength){
return new DistributionFactory<String>() {
@Override
public Distribution<String> newDistribution(ColumnStatistics<String> statistics) {
return new UniformStringDistribution(statistics,stringLength);
}
};
}
/* ****************************************************************************************************************/
/*private helper methods*/
private static final BigDecimal TWO_THIRTY_TWO = BigDecimal.valueOf(Integer.MAX_VALUE);
private static BigDecimal unicodePosition(int strLen,String str) {
/*
* Each UTF-8 encoded character takes up between 1 and 4 bytes, so if we represent each character
* with a single big-endian integer holding the character, then we can compute the absolute position
* in the ordering according to the rule
*
* 2^strLen*char[0]+2^(strLen-1)*char[1]+...char[strLen-1]
*/
int len = str.length();
BigDecimal pos = BigDecimal.ZERO;
for(int codePoint = 0;codePoint<len;codePoint++){
int v = str.codePointAt(codePoint);
pos = BigDecimal.valueOf(v).add(TWO_THIRTY_TWO.multiply(pos));
}
//now shift the data over to account for string padding at the end
if(strLen>len){
BigDecimal scale = TWO_THIRTY_TWO.pow(strLen-len);
pos = pos.multiply(scale);
}
return pos;
}
private long getPerRowCount() {
return getAdjustedRowCount()/columnStats.cardinality();
}
}
| DB-3469: Correcting arithmetic error when min==max.
When the minimum value ==the maximum value, the run=0, so we can't form
a line (since the slope will cause a divide-by-zero error). When that
happens, we need to convert back to a horizontal line.
Also added an IT to verify.
| src/main/java/com/splicemachine/stats/estimate/UniformStringDistribution.java | DB-3469: Correcting arithmetic error when min==max. |
|
Java | agpl-3.0 | 34ae7f2ae585e670208987ab580d10637bf0e232 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 8780a8e8-2e60-11e5-9284-b827eb9e62be | hello.java | 877b48bc-2e60-11e5-9284-b827eb9e62be | 8780a8e8-2e60-11e5-9284-b827eb9e62be | hello.java | 8780a8e8-2e60-11e5-9284-b827eb9e62be |
|
Java | agpl-3.0 | 7564e8b46e6349e7eb6b57eeb20675ff0cb8213d | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 6d163b60-2e62-11e5-9284-b827eb9e62be | hello.java | 6d10d51c-2e62-11e5-9284-b827eb9e62be | 6d163b60-2e62-11e5-9284-b827eb9e62be | hello.java | 6d163b60-2e62-11e5-9284-b827eb9e62be |
|
Java | agpl-3.0 | c9103f04a098cb4a1053b9ed39419f4a04a5fd43 | 0 | joshzamor/open-lmis,USAID-DELIVER-PROJECT/elmis,joshzamor/open-lmis,kelvinmbwilo/vims,vimsvarcode/elmis,OpenLMIS/open-lmis,OpenLMIS/open-lmis,kelvinmbwilo/vims,OpenLMIS/open-lmis,kelvinmbwilo/vims,vimsvarcode/elmis,vimsvarcode/elmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,joshzamor/open-lmis,USAID-DELIVER-PROJECT/elmis,kelvinmbwilo/vims,vimsvarcode/elmis,vimsvarcode/elmis,OpenLMIS/open-lmis,joshzamor/open-lmis | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.pageobjects;
import org.openlmis.UiUtils.TestWebDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;
import java.util.List;
import static com.thoughtworks.selenium.SeleneseTestBase.assertFalse;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertEquals;
import static org.openqa.selenium.support.How.ID;
import static org.openqa.selenium.support.How.XPATH;
public class UserPage extends FilterSearchPage {
@FindBy(how = ID, using = "userAddNew")
private static WebElement addNewButton = null;
@FindBy(how = ID, using = "userName")
private static WebElement userNameField = null;
@FindBy(how = ID, using = "email")
private static WebElement emailField = null;
@FindBy(how = ID, using = "firstName")
private static WebElement firstNameField = null;
@FindBy(how = ID, using = "lastName")
private static WebElement lastNameField = null;
@FindBy(how = ID, using = "userSaveButton")
private static WebElement saveButton = null;
@FindBy(how = ID, using = "userCancelButton")
private static WebElement cancelButton = null;
@FindBy(how = ID, using = "userDisableButton")
private static WebElement disableButton = null;
@FindBy(how = ID, using = "userEnableButton")
private static WebElement enableButton = null;
@FindBy(how = ID, using = "searchUser")
private static WebElement searchUserTextField = null;
@FindBy(how = ID, using = "resetPassword")
private static WebElement resetPasswordButton = null;
@FindBy(how = ID, using = "password1")
private static WebElement newPasswordField = null;
@FindBy(how = ID, using = "password2")
private static WebElement confirmPasswordField = null;
@FindBy(how = ID, using = "resetPasswordDone")
private static WebElement resetPasswordDone = null;
@FindBy(how = ID, using = "button_OK")
private static WebElement okButton = null;
@FindBy(how = ID, using = "editUserLabel")
private static WebElement editUserHeader = null;
@FindBy(how = How.XPATH, using = "//form[@id='create-user']/div/div[1]/div[8]/div/ng-switch/span")
private static WebElement verifiedLabel = null;
@FindBy(how = ID, using = "expandAll")
private static WebElement expandAllOption = null;
@FindBy(how = ID, using = "collapseAll")
private static WebElement collapseAllOption = null;
@FindBy(how = ID, using = "homeFacilityRoles")
private static WebElement homeFacilityRolesAccordion = null;
@FindBy(how = ID, using = "programSelected")
private static WebElement homeFacilityPrograms = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[15]")
private static WebElement roleInputFieldHomeFacility = null;
@FindBy(how = How.XPATH, using = "//div[@class='select2-result-label']/span")
private static WebElement rolesSelectField = null;
@FindBy(how = ID, using = "addHomeRole")
private static WebElement addHomeFacilityRolesButton = null;
@FindBy(how = ID, using = "supervisoryRoles")
private static WebElement supervisoryRolesAccordion = null;
@FindBy(how = ID, using = "programToSupervise")
private static WebElement programsToSupervise = null;
@FindBy(how = ID, using = "supervisoryNodeToSupervise")
private static WebElement supervisoryNodeToSupervise = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[17]")
private static WebElement rolesInputFieldSupervisoryRole = null;
@FindBy(how = ID, using = "addSupervisoryRole")
private static WebElement addSupervisoryRoleButton = null;
@FindBy(how = ID, using = "orderFulfillmentRoles")
private static WebElement orderFulfillmentRolesAccordion = null;
@FindBy(how = ID, using = "reportingRoles")
private static WebElement reportingRolesAccordion = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[19]")
private static WebElement rolesInputFieldWarehouse = null;
@FindBy(how = XPATH, using = "//div[@id='s2id_reportingRoles']/ul/li[@class='select2-search-field']/input")
private static WebElement rolesInputFieldReporting = null;
@FindBy(how = ID, using = "warehouseToSelect")
private static WebElement warehouseToSelect = null;
@FindBy(how = ID, using = "addFulfillmentRole")
private static WebElement addWarehouseRoleButton = null;
@FindBy(how = ID, using = "allocationRoles")
private static WebElement deliveryZonesAccordion = null;
@FindBy(how = ID, using = "deliveryZoneToSelect")
private static WebElement zoneToDelivery = null;
@FindBy(how = ID, using = "programToDelivery")
private static WebElement programToDeliver = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[21]")
private static WebElement rolesInputFieldMDeliveryZone = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[18]")
private static WebElement rolesInputFieldDeliveryZone = null;
@FindBy(how = ID, using = "addAllocationRole")
private static WebElement addDeliveryZoneRoleButton = null;
@FindBy(how = ID, using = "adminRoles")
private static WebElement adminAndGeneralOperationsRolesAccordion = null;
@FindBy(how = XPATH, using = "//*[@id='s2id_adminRoles']/ul/li[@class='select2-search-field']/input")
private static WebElement adminRolesInputField = null;
@FindBy(how = ID, using = "viewHereLink")
private static WebElement viewHereLink = null;
@FindBy(how = ID, using = "saveSuccessMsgDiv")
private static WebElement successMessage = null;
@FindBy(how = How.XPATH, using = "//input[contains(text(),'Remove')]")
private static WebElement removeButton = null;
@FindBy(how = How.XPATH, using = "//div[6]/div[2]/ng-include/div/div[1]/div[2]/div[1]/div/label[@class='ng-binding']")
private static WebElement addedDeliveryZoneLabel = null;
@FindBy(how = ID, using = "restrictLoginYes")
private static WebElement restrictLoginYesOption = null;
@FindBy(how = ID, using = "restrictLoginNo")
private static WebElement restrictLoginNoOption = null;
@FindBy(how = ID, using = "associatedFacilityField")
private static WebElement associatedFacilityField = null;
@FindBy(how = ID, using = "searchIcon")
private static WebElement searchIcon = null;
@FindBy(how = ID, using = "clearFacility")
private static WebElement clearFacility = null;
@FindBy(how = ID, using = "saveErrorMsgDiv")
private static WebElement saveErrorMsg = null;
@FindBy(how = ID, using = "oneResultMessage")
private static WebElement oneResultMessage = null;
@FindBy(how = ID, using = "noResultMessage")
private static WebElement noResultMessage = null;
@FindBy(how = ID, using = "nResultsMessage")
private static WebElement nResultsMessage = null;
@FindBy(how = ID, using = "closeButton")
private static WebElement closeButton = null;
@FindBy(how = ID, using = "nameHeader")
private static WebElement nameHeader = null;
@FindBy(how = ID, using = "userNameHeader")
private static WebElement userNameHeader = null;
@FindBy(how = ID, using = "emailHeader")
private static WebElement emailHeader = null;
@FindBy(how = ID, using = "verifiedHeader")
private static WebElement verifiedHeader = null;
@FindBy(how = ID, using = "activeHeader")
private static WebElement activeHeader = null;
@FindBy(how = ID, using = "dialogMessage")
private static WebElement dialogMessage = null;
@FindBy(how = ID, using = "searchUserLabel")
private static WebElement searchUserLabel = null;
public UserPage(TestWebDriver driver) {
super(driver);
PageFactory.initElements(new AjaxElementLocatorFactory(TestWebDriver.getDriver(), 1), this);
testWebDriver.setImplicitWait(1);
}
public void searchUser(String user) {
testWebDriver.waitForElementToAppear(searchUserTextField);
sendKeys(searchUserTextField, user);
}
public void resetPassword(String newPassword, String confirmPassword) {
testWebDriver.waitForElementToAppear(resetPasswordButton);
resetPasswordButton.click();
testWebDriver.waitForElementToAppear(newPasswordField);
sendKeys(newPasswordField, newPassword);
testWebDriver.waitForElementToAppear(confirmPasswordField);
sendKeys(confirmPasswordField, confirmPassword);
testWebDriver.waitForElementToBeEnabled(resetPasswordDone);
resetPasswordDone.click();
}
public void enterUserDetails(String userName, String email, String firstName, String lastName) {
testWebDriver.waitForElementToAppear(addNewButton);
addNewButton.click();
testWebDriver.waitForElementToAppear(userNameField);
sendKeys(userNameField, userName);
testWebDriver.waitForElementToAppear(emailField);
sendKeys(emailField, email);
testWebDriver.waitForElementToAppear(firstNameField);
sendKeys(firstNameField, firstName);
testWebDriver.waitForElementToAppear(lastNameField);
sendKeys(lastNameField, lastName);
testWebDriver.handleScroll();
clickRestrictLoginNo();
assertFalse(resetPasswordButton.isDisplayed());
assertFalse(disableButton.isDisplayed());
testWebDriver.waitForElementToAppear(saveButton);
saveButton.click();
testWebDriver.waitForElementToAppear(viewHereLink);
}
public String getSuccessMessage() {
testWebDriver.waitForElementToAppear(successMessage);
return successMessage.getText();
}
public void enterUserHomeFacility(String facilityCode) {
if (clearFacility.isDisplayed()) {
clearFacility.click();
}
testWebDriver.sleep(500);
testWebDriver.handleScrollByPixels(0, 1600);
testWebDriver.sleep(500);
associatedFacilityField.click();
searchFacility(facilityCode);
}
public void ExpandAll() {
testWebDriver.waitForElementToAppear(expandAllOption);
expandAllOption.click();
}
public void collapseAll() {
testWebDriver.waitForElementToAppear(collapseAllOption);
collapseAllOption.click();
}
public void clickRestrictLoginYes() {
testWebDriver.waitForElementToAppear(restrictLoginYesOption);
restrictLoginYesOption.click();
}
public void clickRestrictLoginNo() {
testWebDriver.waitForElementToAppear(restrictLoginNoOption);
restrictLoginNoOption.click();
}
public boolean isProgramsToSuperviseDisplayed() {
try {
testWebDriver.waitForElementToAppear(programsToSupervise);
} catch (TimeoutException e) {
return false;
} catch (NoSuchElementException e) {
return false;
}
return programsToSupervise.isDisplayed();
}
public boolean isProgramToDeliverDisplayed() {
try {
testWebDriver.waitForElementToAppear(programToDeliver);
} catch (TimeoutException e) {
return false;
} catch (NoSuchElementException e) {
return false;
}
return programToDeliver.isDisplayed();
}
public boolean isWarehouseToSelectDisplayed() {
try {
testWebDriver.waitForElementToAppear(warehouseToSelect);
} catch (TimeoutException e) {
return false;
} catch (NoSuchElementException e) {
return false;
}
return warehouseToSelect.isDisplayed();
}
public void enterMyFacilityAndMySupervisedFacilityData(String facilityCode, String program1, String node, String role, String roleType) {
assertFalse(homeFacilityRolesAccordion.isDisplayed());
if (!roleType.equals("ADMIN")) {
enterUserHomeFacility(facilityCode);
testWebDriver.waitForAjax();
selectFacility(1);
testWebDriver.waitForAjax();
testWebDriver.scrollAndClick(homeFacilityRolesAccordion);
testWebDriver.sleep(500);
testWebDriver.scrollToElement(homeFacilityPrograms);
testWebDriver.selectByVisibleText(homeFacilityPrograms, program1);
testWebDriver.waitForElementToAppear(roleInputFieldHomeFacility);
testWebDriver.scrollAndClick(roleInputFieldHomeFacility);
sendKeys(roleInputFieldHomeFacility, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
testWebDriver.scrollAndClick(rolesSelectField);
testWebDriver.scrollAndClick(addHomeFacilityRolesButton);
testWebDriver.waitForElementToAppear(supervisoryRolesAccordion);
testWebDriver.scrollAndClick(supervisoryRolesAccordion);
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(programsToSupervise);
testWebDriver.selectByVisibleText(programsToSupervise, program1);
testWebDriver.waitForElementToAppear(supervisoryNodeToSupervise);
testWebDriver.selectByVisibleText(supervisoryNodeToSupervise, node);
testWebDriver.sleep(1000);
testWebDriver.handleScroll();
testWebDriver.waitForElementToAppear(rolesInputFieldSupervisoryRole);
testWebDriver.scrollAndClick(rolesInputFieldSupervisoryRole);
sendKeys(rolesInputFieldSupervisoryRole, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
testWebDriver.scrollAndClick(rolesSelectField);
assertEquals(testWebDriver.getFirstSelectedOption(supervisoryNodeToSupervise).getText(), node);
assertEquals(testWebDriver.getFirstSelectedOption(programsToSupervise).getText(), program1);
testWebDriver.waitForElementToAppear(addSupervisoryRoleButton);
testWebDriver.scrollAndClick(addSupervisoryRoleButton);
} else {
testWebDriver.handleScroll();
testWebDriver.waitForElementToAppear(adminAndGeneralOperationsRolesAccordion);
testWebDriver.scrollAndClick(adminAndGeneralOperationsRolesAccordion);
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(adminRolesInputField);
testWebDriver.scrollAndClick(adminRolesInputField);
sendKeys(adminRolesInputField, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
testWebDriver.scrollAndClick(rolesSelectField);
}
}
public void verifyUserUpdated(String firstName, String lastName) {
testWebDriver.sleep(1000);
assertTrue("User '" + firstName + " " + lastName + "' has been successfully updated message is not getting displayed",
successMessage.isDisplayed());
}
public void assignWarehouse(String warehouse, String role) {
testWebDriver.waitForElementToAppear(orderFulfillmentRolesAccordion);
orderFulfillmentRolesAccordion.click();
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(warehouseToSelect);
testWebDriver.selectByVisibleText(warehouseToSelect, warehouse);
testWebDriver.waitForElementToAppear(rolesInputFieldWarehouse);
rolesInputFieldWarehouse.click();
rolesInputFieldWarehouse.clear();
rolesInputFieldWarehouse.sendKeys(role);
testWebDriver.waitForElementToAppear(rolesSelectField);
rolesSelectField.click();
assertEquals(testWebDriver.getFirstSelectedOption(warehouseToSelect).getText(), warehouse);
testWebDriver.waitForElementToAppear(addWarehouseRoleButton);
addWarehouseRoleButton.click();
testWebDriver.sleep(1000);
verifyWarehouseSelectedNotAvailable(warehouse);
testWebDriver.waitForElementToAppear(orderFulfillmentRolesAccordion);
orderFulfillmentRolesAccordion.click();
testWebDriver.sleep(500);
}
public void assignReportingRole(String role) {
testWebDriver.waitForElementToAppear(reportingRolesAccordion);
reportingRolesAccordion.click();
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(rolesInputFieldReporting);
rolesInputFieldReporting.click();
sendKeys(rolesInputFieldReporting, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
rolesSelectField.click();
testWebDriver.sleep(1000);
}
public void assignAdminRole(String role) {
testWebDriver.waitForElementToAppear(adminAndGeneralOperationsRolesAccordion);
testWebDriver.scrollAndClick(adminAndGeneralOperationsRolesAccordion);
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(adminRolesInputField);
testWebDriver.scrollAndClick(adminRolesInputField);
sendKeys(adminRolesInputField, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
rolesSelectField.click();
testWebDriver.sleep(1000);
}
public void verifyMessage(String message) {
testWebDriver.waitForElementToAppear(successMessage);
assertEquals(successMessage.getText(), message);
}
public void enterDeliveryZoneData(String deliveryZoneCode, String program, String role) {
testWebDriver.handleScroll();
testWebDriver.getElementByXpath("//a[contains(text(),'Delivery zones')]").click();
testWebDriver.waitForElementToAppear(zoneToDelivery);
testWebDriver.selectByVisibleText(zoneToDelivery, deliveryZoneCode);
testWebDriver.waitForElementToAppear(programToDeliver);
testWebDriver.selectByVisibleText(programToDeliver, program);
testWebDriver.waitForElementToAppear(rolesInputFieldMDeliveryZone);
rolesInputFieldMDeliveryZone.click();
rolesInputFieldMDeliveryZone.clear();
rolesInputFieldMDeliveryZone.sendKeys(role);
rolesInputFieldMDeliveryZone.sendKeys(Keys.RETURN);
addDeliveryZoneRoleButton.click();
}
public void enterDeliveryZoneDataWithoutHomeAndSupervisoryRolesAssigned(String deliveryZoneCode, String program, String role) {
testWebDriver.handleScroll();
deliveryZonesAccordion.click();
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(zoneToDelivery);
testWebDriver.selectByVisibleText(zoneToDelivery, deliveryZoneCode);
testWebDriver.waitForElementToAppear(programToDeliver);
testWebDriver.selectByVisibleText(programToDeliver, program);
testWebDriver.waitForElementToAppear(rolesInputFieldDeliveryZone);
rolesInputFieldDeliveryZone.click();
rolesInputFieldDeliveryZone.clear();
rolesInputFieldDeliveryZone.sendKeys(role);
rolesInputFieldDeliveryZone.sendKeys(Keys.RETURN);
testWebDriver.waitForElementToAppear(addDeliveryZoneRoleButton);
addDeliveryZoneRoleButton.click();
}
public void removeRole(int indexOfCancelIcon, boolean adminRole) {
int counter = 1;
List<WebElement> closeButtons = testWebDriver.getElementsByXpath("//a[@class='select2-search-choice-close']");
for (WebElement closeButton : closeButtons) {
if (counter == indexOfCancelIcon) {
closeButton.click();
if (adminRole)
clickOk();
testWebDriver.sleep(100);
counter++;
}
}
}
public void clickCancelButton() {
testWebDriver.waitForElementToAppear(cancelButton);
cancelButton.click();
}
public void clickSaveButton() {
testWebDriver.waitForElementToBeEnabled(saveButton);
saveButton.click();
}
public void disableUser(String userName) {
testWebDriver.waitForElementToBeEnabled(disableButton);
disableButton.click();
assertEquals(testWebDriver.getElementByXpath("//*[@id='disableUserDialog']/div[1]/h3").getText(), "Disable user");
assertEquals(dialogMessage.getText(), "User \"" + userName + "\" will be disabled");
clickOk();
}
public void clickEnableButton() {
testWebDriver.waitForElementToBeEnabled(enableButton);
enableButton.click();
clickOk();
}
public void verifyRolePresent(String roleName) {
testWebDriver.sleep(500);
WebElement roleElement = testWebDriver.getElementByXpath("//div[contains(text(),'" + roleName + "')]");
assertTrue(roleName + " should be displayed", roleElement.isDisplayed());
}
public void verifyRoleNotPresent(String roleName) {
boolean rolePresent;
try {
testWebDriver.sleep(500);
WebElement element = testWebDriver.getElementByXpath("//div[contains(text(),'" + roleName + "')]");
rolePresent = element.isDisplayed();
} catch (ElementNotVisibleException e) {
rolePresent = false;
} catch (NoSuchElementException e) {
rolePresent = false;
}
assertFalse(rolePresent);
}
public String getAllProgramsToSupervise() {
testWebDriver.waitForElementToAppear(programsToSupervise);
return programsToSupervise.getText();
}
public String getAllProgramsHomeFacility() {
testWebDriver.waitForElementToAppear(homeFacilityPrograms);
return homeFacilityPrograms.getText();
}
public String getAllWarehouseToSelect() {
testWebDriver.waitForElementToAppear(warehouseToSelect);
return warehouseToSelect.getText();
}
public void clickViewHere() {
testWebDriver.waitForElementToAppear(viewHereLink);
viewHereLink.click();
testWebDriver.waitForElementToAppear(editUserHeader);
}
public void clickOk() {
testWebDriver.waitForElementToAppear(okButton);
okButton.click();
}
public void verifyRemoveNotPresent() {
boolean removePresent;
try {
testWebDriver.sleep(500);
removeButton.isDisplayed();
removePresent = true;
} catch (ElementNotVisibleException e) {
removePresent = false;
} catch (NoSuchElementException e) {
removePresent = false;
}
assertFalse(removePresent);
}
public void clickRemoveButtonWithOk(int removeButtonNumber) {
testWebDriver.sleep(500);
testWebDriver.getElementByXpath("(//input[@value='Remove'])[" + removeButtonNumber + "]").click();
clickOk();
}
public String getAddedDeliveryZoneLabel() {
testWebDriver.waitForElementToAppear(addedDeliveryZoneLabel);
return addedDeliveryZoneLabel.getText();
}
public String getVerifiedLabel() {
testWebDriver.waitForElementToAppear(verifiedLabel);
return verifiedLabel.getText();
}
public void clickWarehouseRolesAccordion() {
testWebDriver.waitForElementToAppear(orderFulfillmentRolesAccordion);
orderFulfillmentRolesAccordion.click();
testWebDriver.sleep(500);
}
public void clickHomeFacilityRolesAccordion() {
testWebDriver.waitForElementToAppear(homeFacilityRolesAccordion);
homeFacilityRolesAccordion.click();
testWebDriver.sleep(500);
}
public void clickSupervisoryRolesAccordion() {
testWebDriver.waitForElementToAppear(supervisoryRolesAccordion);
supervisoryRolesAccordion.click();
testWebDriver.sleep(500);
}
public void clickDeliveryZonesAccordion() {
testWebDriver.waitForElementToAppear(deliveryZonesAccordion);
deliveryZonesAccordion.click();
testWebDriver.sleep(500);
}
private void verifyWarehouseSelectedNotAvailable(String warehouse1) {
assertFalse(getAllWarehouseToSelect().contains(warehouse1));
}
public void clickSearchIcon() {
testWebDriver.waitForElementToAppear(searchIcon);
searchIcon.click();
}
public void clickUserName(int rowNumber) {
WebElement element = testWebDriver.getElementById("name" + (rowNumber - 1));
testWebDriver.waitForElementToAppear(element);
element.click();
}
public void clickResetPasswordButton() {
testWebDriver.waitForElementToAppear(resetPasswordButton);
resetPasswordButton.click();
}
public String getSaveErrorMessage() {
testWebDriver.waitForElementToAppear(saveErrorMsg);
return saveErrorMsg.getText();
}
public String getOneResultMessage() {
testWebDriver.waitForElementToAppear(oneResultMessage);
return oneResultMessage.getText();
}
public String getNResultsMessage() {
testWebDriver.waitForElementToAppear(nResultsMessage);
return nResultsMessage.getText();
}
public String getNoResultMessage() {
testWebDriver.waitForElementToAppear(noResultMessage);
return noResultMessage.getText();
}
public String getNameHeader() {
testWebDriver.waitForElementToAppear(nameHeader);
return nameHeader.getText();
}
public String getUserNameHeader() {
testWebDriver.waitForElementToAppear(userNameHeader);
return userNameHeader.getText();
}
public String getEmailHeader() {
testWebDriver.waitForElementToAppear(emailHeader);
return emailHeader.getText();
}
public String getVerifiedHeader() {
testWebDriver.waitForElementToAppear(verifiedHeader);
return verifiedHeader.getText();
}
public String getActiveHeader() {
testWebDriver.waitForElementToAppear(activeHeader);
return activeHeader.getText();
}
public String getName(int rowNumber) {
WebElement element = testWebDriver.getElementById("name" + (rowNumber - 1));
testWebDriver.waitForElementToAppear(element);
return element.getText();
}
public String getUserName(int rowNumber) {
WebElement element = testWebDriver.getElementById("userName" + (rowNumber - 1));
testWebDriver.waitForElementToAppear(element);
return element.getText();
}
public String getEmail(int rowNumber) {
WebElement element = testWebDriver.getElementById("email" + (rowNumber - 1));
testWebDriver.waitForElementToAppear(element);
return element.getText();
}
public boolean getIsVerified(int rowNumber) {
WebElement element = testWebDriver.getElementById("verifiedIconOk" + (rowNumber - 1));
return element.isDisplayed();
}
public boolean getIsActive(int rowNumber) {
WebElement element = testWebDriver.getElementById("activeIconOk" + (rowNumber - 1));
return element.isDisplayed();
}
public void clickCrossIcon() {
testWebDriver.waitForElementToAppear(closeButton);
closeButton.click();
}
public void clickHomeFacilityField() {
testWebDriver.waitForElementToAppear(associatedFacilityField);
associatedFacilityField.click();
}
public void clearFacility() {
testWebDriver.waitForElementToAppear(clearFacility);
clearFacility.click();
okButton.click();
}
public boolean isHomeFacilityAccordionDisplayed() {
return homeFacilityRolesAccordion.isDisplayed();
}
public boolean isNameHeaderPresent() {
return nameHeader.isDisplayed();
}
public String getSearchUserLabel() {
testWebDriver.waitForElementToAppear(searchUserLabel);
return searchUserLabel.getText();
}
public String getSearchPlaceHolder() {
testWebDriver.waitForElementToAppear(searchUserTextField);
return searchUserTextField.getAttribute("placeholder");
}
} | test-modules/functional-tests/src/main/java/org/openlmis/pageobjects/UserPage.java | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.pageobjects;
import org.openlmis.UiUtils.TestWebDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;
import java.util.List;
import static com.thoughtworks.selenium.SeleneseTestBase.assertFalse;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertEquals;
import static org.openqa.selenium.support.How.ID;
import static org.openqa.selenium.support.How.XPATH;
public class UserPage extends FilterSearchPage {
@FindBy(how = ID, using = "userAddNew")
private static WebElement addNewButton = null;
@FindBy(how = ID, using = "userName")
private static WebElement userNameField = null;
@FindBy(how = ID, using = "email")
private static WebElement emailField = null;
@FindBy(how = ID, using = "firstName")
private static WebElement firstNameField = null;
@FindBy(how = ID, using = "lastName")
private static WebElement lastNameField = null;
@FindBy(how = ID, using = "userSaveButton")
private static WebElement saveButton = null;
@FindBy(how = ID, using = "userCancelButton")
private static WebElement cancelButton = null;
@FindBy(how = ID, using = "userDisableButton")
private static WebElement disableButton = null;
@FindBy(how = ID, using = "userEnableButton")
private static WebElement enableButton = null;
@FindBy(how = ID, using = "searchUser")
private static WebElement searchUserTextField = null;
@FindBy(how = ID, using = "resetPassword")
private static WebElement resetPasswordButton = null;
@FindBy(how = ID, using = "password1")
private static WebElement newPasswordField = null;
@FindBy(how = ID, using = "password2")
private static WebElement confirmPasswordField = null;
@FindBy(how = ID, using = "resetPasswordDone")
private static WebElement resetPasswordDone = null;
@FindBy(how = ID, using = "button_OK")
private static WebElement okButton = null;
@FindBy(how = ID, using = "editUserLabel")
private static WebElement editUserHeader = null;
@FindBy(how = How.XPATH, using = "//form[@id='create-user']/div/div[1]/div[8]/div/ng-switch/span")
private static WebElement verifiedLabel = null;
@FindBy(how = ID, using = "expandAll")
private static WebElement expandAllOption = null;
@FindBy(how = ID, using = "collapseAll")
private static WebElement collapseAllOption = null;
@FindBy(how = ID, using = "homeFacilityRoles")
private static WebElement homeFacilityRolesAccordion = null;
@FindBy(how = ID, using = "programSelected")
private static WebElement homeFacilityPrograms = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[15]")
private static WebElement roleInputFieldHomeFacility = null;
@FindBy(how = How.XPATH, using = "//div[@class='select2-result-label']/span")
private static WebElement rolesSelectField = null;
@FindBy(how = ID, using = "addHomeRole")
private static WebElement addHomeFacilityRolesButton = null;
@FindBy(how = ID, using = "supervisoryRoles")
private static WebElement supervisoryRolesAccordion = null;
@FindBy(how = ID, using = "programToSupervise")
private static WebElement programsToSupervise = null;
@FindBy(how = ID, using = "supervisoryNodeToSupervise")
private static WebElement supervisoryNodeToSupervise = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[17]")
private static WebElement rolesInputFieldSupervisoryRole = null;
@FindBy(how = ID, using = "addSupervisoryRole")
private static WebElement addSupervisoryRoleButton = null;
@FindBy(how = ID, using = "orderFulfillmentRoles")
private static WebElement orderFulfillmentRolesAccordion = null;
@FindBy(how = ID, using = "reportingRoles")
private static WebElement reportingRolesAccordion = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[19]")
private static WebElement rolesInputFieldWarehouse = null;
@FindBy(how = XPATH, using = "//div[@id='s2id_reportingRoles']/ul/li[@class='select2-search-field']/input")
private static WebElement rolesInputFieldReporting = null;
@FindBy(how = ID, using = "warehouseToSelect")
private static WebElement warehouseToSelect = null;
@FindBy(how = ID, using = "addFulfillmentRole")
private static WebElement addWarehouseRoleButton = null;
@FindBy(how = ID, using = "allocationRoles")
private static WebElement deliveryZonesAccordion = null;
@FindBy(how = ID, using = "deliveryZoneToSelect")
private static WebElement zoneToDelivery = null;
@FindBy(how = ID, using = "programToDelivery")
private static WebElement programToDeliver = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[21]")
private static WebElement rolesInputFieldMDeliveryZone = null;
@FindBy(how = How.XPATH, using = "(//input[@type='text'])[18]")
private static WebElement rolesInputFieldDeliveryZone = null;
@FindBy(how = ID, using = "addAllocationRole")
private static WebElement addDeliveryZoneRoleButton = null;
@FindBy(how = ID, using = "adminRoles")
private static WebElement adminAndGeneralOperationsRolesAccordion = null;
@FindBy(how = XPATH, using = "//*[@id='s2id_adminRoles']/ul/li[@class='select2-search-field']/input")
private static WebElement adminRolesInputField = null;
@FindBy(how = ID, using = "viewHereLink")
private static WebElement viewHereLink = null;
@FindBy(how = ID, using = "saveSuccessMsgDiv")
private static WebElement successMessage = null;
@FindBy(how = How.XPATH, using = "//input[contains(text(),'Remove')]")
private static WebElement removeButton = null;
@FindBy(how = How.XPATH, using = "//div[6]/div[2]/ng-include/div/div[1]/div[2]/div[1]/div/label[@class='ng-binding']")
private static WebElement addedDeliveryZoneLabel = null;
@FindBy(how = ID, using = "restrictLoginYes")
private static WebElement restrictLoginYesOption = null;
@FindBy(how = ID, using = "restrictLoginNo")
private static WebElement restrictLoginNoOption = null;
@FindBy(how = ID, using = "associatedFacilityField")
private static WebElement associatedFacilityField = null;
@FindBy(how = ID, using = "searchIcon")
private static WebElement searchIcon = null;
@FindBy(how = ID, using = "clearFacility")
private static WebElement clearFacility = null;
@FindBy(how = ID, using = "saveErrorMsgDiv")
private static WebElement saveErrorMsg = null;
@FindBy(how = ID, using = "oneResultMessage")
private static WebElement oneResultMessage = null;
@FindBy(how = ID, using = "noResultMessage")
private static WebElement noResultMessage = null;
@FindBy(how = ID, using = "nResultsMessage")
private static WebElement nResultsMessage = null;
@FindBy(how = ID, using = "closeButton")
private static WebElement closeButton = null;
@FindBy(how = ID, using = "nameHeader")
private static WebElement nameHeader = null;
@FindBy(how = ID, using = "userNameHeader")
private static WebElement userNameHeader = null;
@FindBy(how = ID, using = "emailHeader")
private static WebElement emailHeader = null;
@FindBy(how = ID, using = "verifiedHeader")
private static WebElement verifiedHeader = null;
@FindBy(how = ID, using = "activeHeader")
private static WebElement activeHeader = null;
@FindBy(how = ID, using = "dialogMessage")
private static WebElement dialogMessage = null;
@FindBy(how = ID, using = "searchUserLabel")
private static WebElement searchUserLabel = null;
public UserPage(TestWebDriver driver) {
super(driver);
PageFactory.initElements(new AjaxElementLocatorFactory(TestWebDriver.getDriver(), 1), this);
testWebDriver.setImplicitWait(1);
}
public void searchUser(String user) {
testWebDriver.waitForElementToAppear(searchUserTextField);
sendKeys(searchUserTextField, user);
}
public void resetPassword(String newPassword, String confirmPassword) {
testWebDriver.waitForElementToAppear(resetPasswordButton);
resetPasswordButton.click();
testWebDriver.waitForElementToAppear(newPasswordField);
sendKeys(newPasswordField, newPassword);
testWebDriver.waitForElementToAppear(confirmPasswordField);
sendKeys(confirmPasswordField, confirmPassword);
testWebDriver.waitForElementToBeEnabled(resetPasswordDone);
resetPasswordDone.click();
}
public void enterUserDetails(String userName, String email, String firstName, String lastName) {
testWebDriver.waitForElementToAppear(addNewButton);
addNewButton.click();
testWebDriver.waitForElementToAppear(userNameField);
sendKeys(userNameField, userName);
testWebDriver.waitForElementToAppear(emailField);
sendKeys(emailField, email);
testWebDriver.waitForElementToAppear(firstNameField);
sendKeys(firstNameField, firstName);
testWebDriver.waitForElementToAppear(lastNameField);
sendKeys(lastNameField, lastName);
testWebDriver.handleScroll();
clickRestrictLoginNo();
assertFalse(resetPasswordButton.isDisplayed());
assertFalse(disableButton.isDisplayed());
testWebDriver.waitForElementToAppear(saveButton);
saveButton.click();
testWebDriver.waitForElementToAppear(viewHereLink);
}
public String getSuccessMessage() {
testWebDriver.waitForElementToAppear(successMessage);
return successMessage.getText();
}
public void enterUserHomeFacility(String facilityCode) {
if (clearFacility.isDisplayed()) {
clearFacility.click();
}
testWebDriver.handleScrollByPixels(0, 600);
associatedFacilityField.click();
searchFacility(facilityCode);
}
public void ExpandAll() {
testWebDriver.waitForElementToAppear(expandAllOption);
expandAllOption.click();
}
public void collapseAll() {
testWebDriver.waitForElementToAppear(collapseAllOption);
collapseAllOption.click();
}
public void clickRestrictLoginYes() {
testWebDriver.waitForElementToAppear(restrictLoginYesOption);
restrictLoginYesOption.click();
}
public void clickRestrictLoginNo() {
testWebDriver.waitForElementToAppear(restrictLoginNoOption);
restrictLoginNoOption.click();
}
public boolean isProgramsToSuperviseDisplayed() {
try {
testWebDriver.waitForElementToAppear(programsToSupervise);
} catch (TimeoutException e) {
return false;
} catch (NoSuchElementException e) {
return false;
}
return programsToSupervise.isDisplayed();
}
public boolean isProgramToDeliverDisplayed() {
try {
testWebDriver.waitForElementToAppear(programToDeliver);
} catch (TimeoutException e) {
return false;
} catch (NoSuchElementException e) {
return false;
}
return programToDeliver.isDisplayed();
}
public boolean isWarehouseToSelectDisplayed() {
try {
testWebDriver.waitForElementToAppear(warehouseToSelect);
} catch (TimeoutException e) {
return false;
} catch (NoSuchElementException e) {
return false;
}
return warehouseToSelect.isDisplayed();
}
public void enterMyFacilityAndMySupervisedFacilityData(String facilityCode, String program1, String node, String role, String roleType) {
assertFalse(homeFacilityRolesAccordion.isDisplayed());
if (!roleType.equals("ADMIN")) {
enterUserHomeFacility(facilityCode);
testWebDriver.waitForAjax();
selectFacility(1);
testWebDriver.waitForAjax();
testWebDriver.scrollAndClick(homeFacilityRolesAccordion);
testWebDriver.sleep(500);
testWebDriver.scrollToElement(homeFacilityPrograms);
testWebDriver.selectByVisibleText(homeFacilityPrograms, program1);
testWebDriver.waitForElementToAppear(roleInputFieldHomeFacility);
testWebDriver.scrollAndClick(roleInputFieldHomeFacility);
sendKeys(roleInputFieldHomeFacility, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
testWebDriver.scrollAndClick(rolesSelectField);
testWebDriver.scrollAndClick(addHomeFacilityRolesButton);
testWebDriver.waitForElementToAppear(supervisoryRolesAccordion);
testWebDriver.scrollAndClick(supervisoryRolesAccordion);
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(programsToSupervise);
testWebDriver.selectByVisibleText(programsToSupervise, program1);
testWebDriver.waitForElementToAppear(supervisoryNodeToSupervise);
testWebDriver.selectByVisibleText(supervisoryNodeToSupervise, node);
testWebDriver.sleep(1000);
testWebDriver.handleScroll();
testWebDriver.waitForElementToAppear(rolesInputFieldSupervisoryRole);
testWebDriver.scrollAndClick(rolesInputFieldSupervisoryRole);
sendKeys(rolesInputFieldSupervisoryRole, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
testWebDriver.scrollAndClick(rolesSelectField);
assertEquals(testWebDriver.getFirstSelectedOption(supervisoryNodeToSupervise).getText(), node);
assertEquals(testWebDriver.getFirstSelectedOption(programsToSupervise).getText(), program1);
testWebDriver.waitForElementToAppear(addSupervisoryRoleButton);
testWebDriver.scrollAndClick(addSupervisoryRoleButton);
} else {
testWebDriver.handleScroll();
testWebDriver.waitForElementToAppear(adminAndGeneralOperationsRolesAccordion);
testWebDriver.scrollAndClick(adminAndGeneralOperationsRolesAccordion);
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(adminRolesInputField);
testWebDriver.scrollAndClick(adminRolesInputField);
sendKeys(adminRolesInputField, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
testWebDriver.scrollAndClick(rolesSelectField);
}
}
public void verifyUserUpdated(String firstName, String lastName) {
testWebDriver.sleep(1000);
assertTrue("User '" + firstName + " " + lastName + "' has been successfully updated message is not getting displayed",
successMessage.isDisplayed());
}
public void assignWarehouse(String warehouse, String role) {
testWebDriver.waitForElementToAppear(orderFulfillmentRolesAccordion);
orderFulfillmentRolesAccordion.click();
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(warehouseToSelect);
testWebDriver.selectByVisibleText(warehouseToSelect, warehouse);
testWebDriver.waitForElementToAppear(rolesInputFieldWarehouse);
rolesInputFieldWarehouse.click();
rolesInputFieldWarehouse.clear();
rolesInputFieldWarehouse.sendKeys(role);
testWebDriver.waitForElementToAppear(rolesSelectField);
rolesSelectField.click();
assertEquals(testWebDriver.getFirstSelectedOption(warehouseToSelect).getText(), warehouse);
testWebDriver.waitForElementToAppear(addWarehouseRoleButton);
addWarehouseRoleButton.click();
testWebDriver.sleep(1000);
verifyWarehouseSelectedNotAvailable(warehouse);
testWebDriver.waitForElementToAppear(orderFulfillmentRolesAccordion);
orderFulfillmentRolesAccordion.click();
testWebDriver.sleep(500);
}
public void assignReportingRole(String role) {
testWebDriver.waitForElementToAppear(reportingRolesAccordion);
reportingRolesAccordion.click();
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(rolesInputFieldReporting);
rolesInputFieldReporting.click();
sendKeys(rolesInputFieldReporting, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
rolesSelectField.click();
testWebDriver.sleep(1000);
}
public void assignAdminRole(String role) {
testWebDriver.waitForElementToAppear(adminAndGeneralOperationsRolesAccordion);
testWebDriver.scrollAndClick(adminAndGeneralOperationsRolesAccordion);
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(adminRolesInputField);
testWebDriver.scrollAndClick(adminRolesInputField);
sendKeys(adminRolesInputField, role);
testWebDriver.waitForElementToAppear(rolesSelectField);
rolesSelectField.click();
testWebDriver.sleep(1000);
}
public void verifyMessage(String message) {
testWebDriver.waitForElementToAppear(successMessage);
assertEquals(successMessage.getText(), message);
}
public void enterDeliveryZoneData(String deliveryZoneCode, String program, String role) {
testWebDriver.handleScroll();
testWebDriver.getElementByXpath("//a[contains(text(),'Delivery zones')]").click();
testWebDriver.waitForElementToAppear(zoneToDelivery);
testWebDriver.selectByVisibleText(zoneToDelivery, deliveryZoneCode);
testWebDriver.waitForElementToAppear(programToDeliver);
testWebDriver.selectByVisibleText(programToDeliver, program);
testWebDriver.waitForElementToAppear(rolesInputFieldMDeliveryZone);
rolesInputFieldMDeliveryZone.click();
rolesInputFieldMDeliveryZone.clear();
rolesInputFieldMDeliveryZone.sendKeys(role);
rolesInputFieldMDeliveryZone.sendKeys(Keys.RETURN);
addDeliveryZoneRoleButton.click();
}
public void enterDeliveryZoneDataWithoutHomeAndSupervisoryRolesAssigned(String deliveryZoneCode, String program, String role) {
testWebDriver.handleScroll();
deliveryZonesAccordion.click();
testWebDriver.sleep(500);
testWebDriver.waitForElementToAppear(zoneToDelivery);
testWebDriver.selectByVisibleText(zoneToDelivery, deliveryZoneCode);
testWebDriver.waitForElementToAppear(programToDeliver);
testWebDriver.selectByVisibleText(programToDeliver, program);
testWebDriver.waitForElementToAppear(rolesInputFieldDeliveryZone);
rolesInputFieldDeliveryZone.click();
rolesInputFieldDeliveryZone.clear();
rolesInputFieldDeliveryZone.sendKeys(role);
rolesInputFieldDeliveryZone.sendKeys(Keys.RETURN);
testWebDriver.waitForElementToAppear(addDeliveryZoneRoleButton);
addDeliveryZoneRoleButton.click();
}
public void removeRole(int indexOfCancelIcon, boolean adminRole) {
int counter = 1;
List<WebElement> closeButtons = testWebDriver.getElementsByXpath("//a[@class='select2-search-choice-close']");
for (WebElement closeButton : closeButtons) {
if (counter == indexOfCancelIcon) {
closeButton.click();
if (adminRole)
clickOk();
testWebDriver.sleep(100);
counter++;
}
}
}
public void clickCancelButton() {
testWebDriver.waitForElementToAppear(cancelButton);
cancelButton.click();
}
public void clickSaveButton() {
testWebDriver.waitForElementToBeEnabled(saveButton);
saveButton.click();
}
public void disableUser(String userName) {
testWebDriver.waitForElementToBeEnabled(disableButton);
disableButton.click();
assertEquals(testWebDriver.getElementByXpath("//*[@id='disableUserDialog']/div[1]/h3").getText(), "Disable user");
assertEquals(dialogMessage.getText(), "User \"" + userName + "\" will be disabled");
clickOk();
}
public void clickEnableButton() {
testWebDriver.waitForElementToBeEnabled(enableButton);
enableButton.click();
clickOk();
}
public void verifyRolePresent(String roleName) {
testWebDriver.sleep(500);
WebElement roleElement = testWebDriver.getElementByXpath("//div[contains(text(),'" + roleName + "')]");
assertTrue(roleName + " should be displayed", roleElement.isDisplayed());
}
public void verifyRoleNotPresent(String roleName) {
boolean rolePresent;
try {
testWebDriver.sleep(500);
WebElement element = testWebDriver.getElementByXpath("//div[contains(text(),'" + roleName + "')]");
rolePresent = element.isDisplayed();
} catch (ElementNotVisibleException e) {
rolePresent = false;
} catch (NoSuchElementException e) {
rolePresent = false;
}
assertFalse(rolePresent);
}
public String getAllProgramsToSupervise() {
testWebDriver.waitForElementToAppear(programsToSupervise);
return programsToSupervise.getText();
}
public String getAllProgramsHomeFacility() {
testWebDriver.waitForElementToAppear(homeFacilityPrograms);
return homeFacilityPrograms.getText();
}
public String getAllWarehouseToSelect() {
testWebDriver.waitForElementToAppear(warehouseToSelect);
return warehouseToSelect.getText();
}
public void clickViewHere() {
testWebDriver.waitForElementToAppear(viewHereLink);
viewHereLink.click();
testWebDriver.waitForElementToAppear(editUserHeader);
}
public void clickOk() {
testWebDriver.waitForElementToAppear(okButton);
okButton.click();
}
public void verifyRemoveNotPresent() {
boolean removePresent;
try {
testWebDriver.sleep(500);
removeButton.isDisplayed();
removePresent = true;
} catch (ElementNotVisibleException e) {
removePresent = false;
} catch (NoSuchElementException e) {
removePresent = false;
}
assertFalse(removePresent);
}
public void clickRemoveButtonWithOk(int removeButtonNumber) {
testWebDriver.sleep(500);
testWebDriver.getElementByXpath("(//input[@value='Remove'])[" + removeButtonNumber + "]").click();
clickOk();
}
public String getAddedDeliveryZoneLabel() {
testWebDriver.waitForElementToAppear(addedDeliveryZoneLabel);
return addedDeliveryZoneLabel.getText();
}
public String getVerifiedLabel() {
testWebDriver.waitForElementToAppear(verifiedLabel);
return verifiedLabel.getText();
}
public void clickWarehouseRolesAccordion() {
testWebDriver.waitForElementToAppear(orderFulfillmentRolesAccordion);
orderFulfillmentRolesAccordion.click();
testWebDriver.sleep(500);
}
public void clickHomeFacilityRolesAccordion() {
testWebDriver.waitForElementToAppear(homeFacilityRolesAccordion);
homeFacilityRolesAccordion.click();
testWebDriver.sleep(500);
}
public void clickSupervisoryRolesAccordion() {
testWebDriver.waitForElementToAppear(supervisoryRolesAccordion);
supervisoryRolesAccordion.click();
testWebDriver.sleep(500);
}
public void clickDeliveryZonesAccordion() {
testWebDriver.waitForElementToAppear(deliveryZonesAccordion);
deliveryZonesAccordion.click();
testWebDriver.sleep(500);
}
private void verifyWarehouseSelectedNotAvailable(String warehouse1) {
assertFalse(getAllWarehouseToSelect().contains(warehouse1));
}
public void clickSearchIcon() {
testWebDriver.waitForElementToAppear(searchIcon);
searchIcon.click();
}
public void clickUserName(int rowNumber) {
WebElement element = testWebDriver.getElementById("name" + (rowNumber - 1));
testWebDriver.waitForElementToAppear(element);
element.click();
}
public void clickResetPasswordButton() {
testWebDriver.waitForElementToAppear(resetPasswordButton);
resetPasswordButton.click();
}
public String getSaveErrorMessage() {
testWebDriver.waitForElementToAppear(saveErrorMsg);
return saveErrorMsg.getText();
}
public String getOneResultMessage() {
testWebDriver.waitForElementToAppear(oneResultMessage);
return oneResultMessage.getText();
}
public String getNResultsMessage() {
testWebDriver.waitForElementToAppear(nResultsMessage);
return nResultsMessage.getText();
}
public String getNoResultMessage() {
testWebDriver.waitForElementToAppear(noResultMessage);
return noResultMessage.getText();
}
public String getNameHeader() {
testWebDriver.waitForElementToAppear(nameHeader);
return nameHeader.getText();
}
public String getUserNameHeader() {
testWebDriver.waitForElementToAppear(userNameHeader);
return userNameHeader.getText();
}
public String getEmailHeader() {
testWebDriver.waitForElementToAppear(emailHeader);
return emailHeader.getText();
}
public String getVerifiedHeader() {
testWebDriver.waitForElementToAppear(verifiedHeader);
return verifiedHeader.getText();
}
public String getActiveHeader() {
testWebDriver.waitForElementToAppear(activeHeader);
return activeHeader.getText();
}
public String getName(int rowNumber) {
WebElement element = testWebDriver.getElementById("name" + (rowNumber - 1));
testWebDriver.waitForElementToAppear(element);
return element.getText();
}
public String getUserName(int rowNumber) {
WebElement element = testWebDriver.getElementById("userName" + (rowNumber - 1));
testWebDriver.waitForElementToAppear(element);
return element.getText();
}
public String getEmail(int rowNumber) {
WebElement element = testWebDriver.getElementById("email" + (rowNumber - 1));
testWebDriver.waitForElementToAppear(element);
return element.getText();
}
public boolean getIsVerified(int rowNumber) {
WebElement element = testWebDriver.getElementById("verifiedIconOk" + (rowNumber - 1));
return element.isDisplayed();
}
public boolean getIsActive(int rowNumber) {
WebElement element = testWebDriver.getElementById("activeIconOk" + (rowNumber - 1));
return element.isDisplayed();
}
public void clickCrossIcon() {
testWebDriver.waitForElementToAppear(closeButton);
closeButton.click();
}
public void clickHomeFacilityField() {
testWebDriver.waitForElementToAppear(associatedFacilityField);
associatedFacilityField.click();
}
public void clearFacility() {
testWebDriver.waitForElementToAppear(clearFacility);
clearFacility.click();
okButton.click();
}
public boolean isHomeFacilityAccordionDisplayed() {
return homeFacilityRolesAccordion.isDisplayed();
}
public boolean isNameHeaderPresent() {
return nameHeader.isDisplayed();
}
public String getSearchUserLabel() {
testWebDriver.waitForElementToAppear(searchUserLabel);
return searchUserLabel.getText();
}
public String getSearchPlaceHolder() {
testWebDriver.waitForElementToAppear(searchUserTextField);
return searchUserTextField.getAttribute("placeholder");
}
} | |#000| fixing E2E - adding wait
| test-modules/functional-tests/src/main/java/org/openlmis/pageobjects/UserPage.java | |#000| fixing E2E - adding wait |
|
Java | lgpl-2.1 | e7d95d9b1a432ba596165cf7dd75d15a26dbd5e4 | 0 | xwiki/xwiki-commons,xwiki/xwiki-commons | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.velocity.internal;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.context.Execution;
import org.xwiki.context.ExecutionContext;
import org.xwiki.logging.LoggerConfiguration;
import org.xwiki.test.LogLevel;
import org.xwiki.test.annotation.ComponentList;
import org.xwiki.test.junit5.LogCaptureExtension;
import org.xwiki.test.junit5.mockito.ComponentTest;
import org.xwiki.test.junit5.mockito.InjectMockComponents;
import org.xwiki.test.junit5.mockito.MockComponent;
import org.xwiki.velocity.XWikiVelocityContext;
import org.xwiki.velocity.XWikiVelocityException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link DefaultVelocityEngine}.
*/
@ComponentTest
@ComponentList(DefaultVelocityConfiguration.class)
public class DefaultVelocityEngineTest
{
public class TestClass
{
private Context context;
private String name = "name";
public TestClass()
{
}
public TestClass(Context context)
{
this.context = context;
}
public TestClass(Context context, String name)
{
this.context = context;
this.name = name;
}
public String getName()
{
return this.name;
}
public String evaluate(String input) throws XWikiVelocityException
{
return evaluate(input, DEFAULT_TEMPLATE_NAME);
}
public String evaluate(String input, String namespace) throws XWikiVelocityException
{
StringWriter writer = new StringWriter();
engine.evaluate(this.context, writer, namespace, input);
return writer.toString();
}
}
private static final String DEFAULT_TEMPLATE_NAME = "mytemplate";
@RegisterExtension
LogCaptureExtension logCapture = new LogCaptureExtension(LogLevel.WARN);
@MockComponent
private ComponentManager componentManager;
@MockComponent
private LoggerConfiguration loggerConfiguration;
@InjectMockComponents
private DefaultVelocityEngine engine;
@MockComponent
private Execution execution;
@MockComponent
private ConfigurationSource configurationSource;
@BeforeEach
void setUp() throws Exception
{
when(execution.getContext()).thenReturn(new ExecutionContext());
when(this.loggerConfiguration.isDeprecatedLogEnabled()).thenReturn(true);
}
private void assertEvaluate(String expected, String content) throws XWikiVelocityException
{
assertEvaluate(expected, content, DEFAULT_TEMPLATE_NAME);
}
private void assertEvaluate(String expected, String content, String template) throws XWikiVelocityException
{
assertEvaluate(expected, content, template, new XWikiVelocityContext());
}
private void assertEvaluate(String expected, String content, Context context) throws XWikiVelocityException
{
assertEvaluate(expected, content, DEFAULT_TEMPLATE_NAME, context);
}
private void assertEvaluate(String expected, String content, String template, Context context)
throws XWikiVelocityException
{
String result = evaluate(content, template, context);
assertEquals(expected, result);
}
private String evaluate(String content, String template) throws XWikiVelocityException
{
return evaluate(content, template, new XWikiVelocityContext());
}
private String evaluate(String content, String template, Context context) throws XWikiVelocityException
{
StringWriter writer = new StringWriter();
this.engine.evaluate(context, writer, template, content);
return writer.toString();
}
@Test
public void testEvaluateReader() throws Exception
{
this.engine.initialize(new Properties());
StringWriter writer = new StringWriter();
this.engine.evaluate(new XWikiVelocityContext(), writer, DEFAULT_TEMPLATE_NAME,
new StringReader("#set($foo='hello')$foo World"));
assertEquals("hello World", writer.toString());
}
@Test
public void testEvaluateString() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("hello World", "#set($foo='hello')$foo World", DEFAULT_TEMPLATE_NAME);
}
/**
* Verify that the default configuration doesn't allow calling Class.forName.
*/
@Test
public void testSecureUberspectorActiveByDefault() throws Exception
{
this.engine.initialize(new Properties());
String content = "#set($foo = 'test')#set($object = $foo.class.forName('java.util.ArrayList')"
+ ".newInstance())$object.size()";
assertEvaluate("$object.size()", content, DEFAULT_TEMPLATE_NAME);
// Verify that we log a warning and verify the message.
assertEquals(
"Cannot retrieve method forName from object of class java.lang.Class due to security restrictions.",
logCapture.getMessage(0));
}
/**
* Verify that the default configuration allows #setting existing variables to null.
*/
@Test
public void testSettingNullAllowedByDefault() throws Exception
{
this.engine.initialize(new Properties());
StringWriter writer = new StringWriter();
Context context = new XWikiVelocityContext();
context.put("null", null);
List<String> list = new ArrayList<String>();
list.add("1");
list.add(null);
list.add("3");
context.put("list", list);
this.engine.evaluate(context, writer, DEFAULT_TEMPLATE_NAME,
"#set($foo = true)${foo}#set($foo = $null)${foo}\n" + "#foreach($i in $list)${foreach.count}=$!{i} #end");
assertEquals("true${foo}\n1=1 2= 3=3 ", writer.toString());
String content =
"#set($foo = true)${foo}#set($foo = $null)${foo}\n" + "#foreach($i in $list)${foreach.count}=$!{i} #end";
assertEvaluate("true${foo}\n1=1 2= 3=3 ", content, DEFAULT_TEMPLATE_NAME, context);
}
@Test
public void testOverrideConfiguration() throws Exception
{
// For example try setting a non secure Uberspector.
Properties properties = new Properties();
properties.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME,
"org.apache.velocity.util.introspection.UberspectImpl");
this.engine.initialize(properties);
StringWriter writer = new StringWriter();
this.engine.evaluate(new XWikiVelocityContext(), writer, DEFAULT_TEMPLATE_NAME,
"#set($foo = 'test')#set($object = $foo.class.forName('java.util.ArrayList')"
+ ".newInstance())$object.size()");
assertEquals("0", writer.toString());
}
@Test
public void testMacroIsolation() throws Exception
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
this.engine.evaluate(context, new StringWriter(), "template1", "#macro(mymacro)test#end");
assertEvaluate("#mymacro", "#mymacro", "template2");
}
@Test
public void testConfigureMacrosToBeGlobal() throws Exception
{
Properties properties = new Properties();
// Force macros to be global
properties.put(RuntimeConstants.VM_PERM_INLINE_LOCAL, "false");
this.engine.initialize(properties);
Context context = new XWikiVelocityContext();
this.engine.evaluate(context, new StringWriter(), "template1", "#macro(mymacro)test#end");
assertEvaluate("test", "#mymacro", "template2");
}
@Test
public void testMacroScope() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("{}", "#macro (testMacro)$macro#end#testMacro()");
}
@Test
public void testMacroWithMissingParameter() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("$param", "#macro (testMacro $param)$param#end#testMacro()");
}
@Test
public void testMacroWithLiterralBooleanParameter() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("true", "#macro (testMacro $param)$param#end#testMacro(true)");
}
@Test
public void testMacroWithLiterralMapParameter() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("{}", "#macro (testMacro $param)$param#end#testMacro({})");
}
@Test
public void testMacroWithLiterralArrayParameter() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("[]", "#macro (testMacro $param)$param#end#testMacro([])");
}
@Test
public void testUseGlobalMacroUseLocalMacro() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
// Register a global macro
evaluate("#macro (globalMacro)#localMacro()#end", "");
// Can the global macro call local macros
assertEvaluate("locallocal", "#macro (localMacro)local#end#localMacro()#globalMacro()");
}
@Test
public void testGlobalMacroUseLocalMacroAfterInclude() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
// Register a global macro
evaluate("#macro (globalMacro)#localMacro()#end", "");
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
// Can the global macro still call the local macro after executing another script in the same namespace
assertEvaluate("locallocallocal",
"#globalMacro()#macro (localMacro)local#end$test.evaluate('')#globalMacro()#localMacro()", context);
}
@Test
public void testIncludeMacro() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
// Can the script use an included macro
assertEvaluate("included", "$test.evaluate('#macro(includedmacro)included#end')#includedmacro()", context);
}
@Test
public void testOverwriteIncludeMacro() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
// Can the script overwrite an included macro
// No because macros are registered before executing the script (TODO: fix that)
assertEvaluate("included",
"$test.evaluate('#macro(includedmacro)included#end')#macro(includedmacro)ovewritten#end#includedmacro()",
context);
}
@Test
public void testTemplateScope() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("{}", "$template");
}
/**
* Verify namespace is properly cleared when not needed anymore.
*/
@Test
public void testMacroNamespaceCleanup() throws Exception
{
this.engine.initialize(new Properties());
// Unprotected namespace
assertEvaluate("#mymacro", "#mymacro", "namespace");
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "namespace", "#macro(mymacro)test#end");
assertEvaluate("#mymacro", "#mymacro", "namespace");
// Protected namespace
// Start using namespace "namespace"
this.engine.startedUsingMacroNamespace("namespace");
// Register macro
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "namespace", "#macro(mymacro)test#end");
assertEvaluate("test", "#mymacro", "namespace");
// Mark namespace "namespace" as not used anymore
this.engine.stoppedUsingMacroNamespace("namespace");
assertEvaluate("#mymacro", "#mymacro", "namespace");
}
@Test
public void testEvaluateWithStopCommand() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("hello world", "hello world#stop", DEFAULT_TEMPLATE_NAME);
}
@Test
public void testVelocityCount() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("1true2true3true4true5false", "#foreach($nb in [1,2,3,4,5])$velocityCount$velocityHasNext#end",
DEFAULT_TEMPLATE_NAME);
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(0));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(1));
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(2));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(3));
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(4));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(5));
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(6));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(7));
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(8));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(9));
}
@Test
public void testEmptyNamespaceInheritance() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("#mymacro", "#mymacro", "namespace");
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "", "#macro(mymacro)test#end");
assertEvaluate("test", "#mymacro", "namespace");
}
@Test
public void testOverrideMacros() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("#mymacro", "#mymacro", "namespace");
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "", "#macro(mymacro)global#end");
assertEvaluate("global", "#mymacro", "namespace");
// Start using namespace "namespace"
this.engine.startedUsingMacroNamespace("namespace");
// Register macro
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "namespace", "#macro(mymacro)test1#end");
assertEvaluate("test1", "#mymacro", "namespace");
// Override macro
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "namespace", "#macro(mymacro)test2#end");
assertEvaluate("test2", "#mymacro", "namespace");
// Override in the same script
assertEvaluate("test4", "#macro(mymacro)test3#end#macro(mymacro)test4#end#mymacro", "namespace");
// Mark namespace "namespace" as not used anymore
this.engine.stoppedUsingMacroNamespace("namespace");
}
@Test
public void testMacroParameters() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("$caller", "#macro (testMacro $called)$called#end#testMacro($caller)");
assertEvaluate("$caller",
"#macro (testMacro $called)#set($called = $NULL)$called#set($called = 'value')#end#testMacro($caller)");
assertEvaluate("$caller",
"#macro (testMacro $called)#set($called = $NULL)$called#set($called = 'value')#end#set($caller = 'value')#testMacro($caller)");
assertEvaluate("$caller$caller2$caller",
"#macro(macro1 $called)$called#macro2($caller2)$called#end#macro(macro2 $called)$called#end#macro1($caller)");
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
context.put("other", new TestClass(context, "othername"));
assertEvaluate("namename", "#macro (testMacro $test $name)$name#end$test.name#testMacro($other, $test.name)",
context);
}
@Test
public void testSetSharpString() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("#", "#set($var = \"#\")$var", DEFAULT_TEMPLATE_NAME);
assertEvaluate("test#", "#set($var = \"test#\")$var", DEFAULT_TEMPLATE_NAME);
}
@Test
public void testSetDollarString() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("$", "#set($var = \"$\")$var", DEFAULT_TEMPLATE_NAME);
assertEvaluate("test$", "#set($var = \"test$\")$var", DEFAULT_TEMPLATE_NAME);
}
@Test
public void testExpressionFollowedByTwoPipes() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("$var||", "$var||");
}
@Test
public void testClassMethods() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
context.put("var", new TestClass());
assertEvaluate("org.xwiki.velocity.internal.DefaultVelocityEngineTest$TestClass name",
"$var.class.getName() $var.getName()", context);
}
@Test
public void testSubEvaluate() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
assertEvaluate("top", "#set($var = 'top')$test.evaluate('$var')", context);
assertEvaluate("sub", "$test.evaluate('#set($var = \"sub\")')$var", context);
assertEvaluate("sub", "#set($var = 'top')$test.evaluate('#set($var = \"sub\")')$var", context);
assertEvaluate("global", "#macro(mymacro $var)#if (!$var)#set($var = {})#end#end#set($var = 'global')#mymacro()$var", context);
assertEvaluate("global", "#macro(mymacro $var)$var#end#set($var = 'global')#mymacro()", context);
// TODO: update this test when a decision is taken in Velocity side regarding macro context behavior
// See
// https://mail-archives.apache.org/mod_mbox/velocity-dev/202001.mbox/%3cCAPnKnLHmL2oeYBNHvq3FHO1BmFW0DFjChk6sxXb9s+mwKhxirQ@mail.gmail.com%3e
// assertEvaluate("local",
// "#macro(mymacro)#set($var = 'local')$test.evaluate('#set($var = \"global\")')$var#end#mymacro()", context);
}
@Test
public void testSpaceGobling() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("value\nvalueline", "#macro (testMacro)value#end#testMacro\n#testMacro()\nline");
}
}
| xwiki-commons-core/xwiki-commons-velocity/src/test/java/org/xwiki/velocity/internal/DefaultVelocityEngineTest.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.velocity.internal;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.context.Execution;
import org.xwiki.context.ExecutionContext;
import org.xwiki.logging.LoggerConfiguration;
import org.xwiki.test.LogLevel;
import org.xwiki.test.annotation.ComponentList;
import org.xwiki.test.junit5.LogCaptureExtension;
import org.xwiki.test.junit5.mockito.ComponentTest;
import org.xwiki.test.junit5.mockito.InjectMockComponents;
import org.xwiki.test.junit5.mockito.MockComponent;
import org.xwiki.velocity.XWikiVelocityContext;
import org.xwiki.velocity.XWikiVelocityException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link DefaultVelocityEngine}.
*/
@ComponentTest
@ComponentList(DefaultVelocityConfiguration.class)
public class DefaultVelocityEngineTest
{
public class TestClass
{
private Context context;
private String name = "name";
public TestClass()
{
}
public TestClass(Context context)
{
this.context = context;
}
public TestClass(Context context, String name)
{
this.context = context;
this.name = name;
}
public String getName()
{
return this.name;
}
public String evaluate(String input) throws XWikiVelocityException
{
return evaluate(input, DEFAULT_TEMPLATE_NAME);
}
public String evaluate(String input, String namespace) throws XWikiVelocityException
{
StringWriter writer = new StringWriter();
engine.evaluate(this.context, writer, namespace, input);
return writer.toString();
}
}
private static final String DEFAULT_TEMPLATE_NAME = "mytemplate";
@RegisterExtension
LogCaptureExtension logCapture = new LogCaptureExtension(LogLevel.WARN);
@MockComponent
private ComponentManager componentManager;
@MockComponent
private LoggerConfiguration loggerConfiguration;
@InjectMockComponents
private DefaultVelocityEngine engine;
@MockComponent
private Execution execution;
@MockComponent
private ConfigurationSource configurationSource;
@BeforeEach
void setUp() throws Exception
{
when(execution.getContext()).thenReturn(new ExecutionContext());
when(this.loggerConfiguration.isDeprecatedLogEnabled()).thenReturn(true);
}
private void assertEvaluate(String expected, String content) throws XWikiVelocityException
{
assertEvaluate(expected, content, DEFAULT_TEMPLATE_NAME);
}
private void assertEvaluate(String expected, String content, String template) throws XWikiVelocityException
{
assertEvaluate(expected, content, template, new XWikiVelocityContext());
}
private void assertEvaluate(String expected, String content, Context context) throws XWikiVelocityException
{
assertEvaluate(expected, content, DEFAULT_TEMPLATE_NAME, context);
}
private void assertEvaluate(String expected, String content, String template, Context context)
throws XWikiVelocityException
{
String result = evaluate(content, template, context);
assertEquals(expected, result);
}
private String evaluate(String content, String template) throws XWikiVelocityException
{
return evaluate(content, template, new XWikiVelocityContext());
}
private String evaluate(String content, String template, Context context) throws XWikiVelocityException
{
StringWriter writer = new StringWriter();
this.engine.evaluate(context, writer, template, content);
return writer.toString();
}
@Test
public void testEvaluateReader() throws Exception
{
this.engine.initialize(new Properties());
StringWriter writer = new StringWriter();
this.engine.evaluate(new XWikiVelocityContext(), writer, DEFAULT_TEMPLATE_NAME,
new StringReader("#set($foo='hello')$foo World"));
assertEquals("hello World", writer.toString());
}
@Test
public void testEvaluateString() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("hello World", "#set($foo='hello')$foo World", DEFAULT_TEMPLATE_NAME);
}
/**
* Verify that the default configuration doesn't allow calling Class.forName.
*/
@Test
public void testSecureUberspectorActiveByDefault() throws Exception
{
this.engine.initialize(new Properties());
String content = "#set($foo = 'test')#set($object = $foo.class.forName('java.util.ArrayList')"
+ ".newInstance())$object.size()";
assertEvaluate("$object.size()", content, DEFAULT_TEMPLATE_NAME);
// Verify that we log a warning and verify the message.
assertEquals(
"Cannot retrieve method forName from object of class java.lang.Class due to security restrictions.",
logCapture.getMessage(0));
}
/**
* Verify that the default configuration allows #setting existing variables to null.
*/
@Test
public void testSettingNullAllowedByDefault() throws Exception
{
this.engine.initialize(new Properties());
StringWriter writer = new StringWriter();
Context context = new XWikiVelocityContext();
context.put("null", null);
List<String> list = new ArrayList<String>();
list.add("1");
list.add(null);
list.add("3");
context.put("list", list);
this.engine.evaluate(context, writer, DEFAULT_TEMPLATE_NAME,
"#set($foo = true)${foo}#set($foo = $null)${foo}\n" + "#foreach($i in $list)${foreach.count}=$!{i} #end");
assertEquals("true${foo}\n1=1 2= 3=3 ", writer.toString());
String content =
"#set($foo = true)${foo}#set($foo = $null)${foo}\n" + "#foreach($i in $list)${foreach.count}=$!{i} #end";
assertEvaluate("true${foo}\n1=1 2= 3=3 ", content, DEFAULT_TEMPLATE_NAME, context);
}
@Test
public void testOverrideConfiguration() throws Exception
{
// For example try setting a non secure Uberspector.
Properties properties = new Properties();
properties.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME,
"org.apache.velocity.util.introspection.UberspectImpl");
this.engine.initialize(properties);
StringWriter writer = new StringWriter();
this.engine.evaluate(new XWikiVelocityContext(), writer, DEFAULT_TEMPLATE_NAME,
"#set($foo = 'test')#set($object = $foo.class.forName('java.util.ArrayList')"
+ ".newInstance())$object.size()");
assertEquals("0", writer.toString());
}
@Test
public void testMacroIsolation() throws Exception
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
this.engine.evaluate(context, new StringWriter(), "template1", "#macro(mymacro)test#end");
assertEvaluate("#mymacro", "#mymacro", "template2");
}
@Test
public void testConfigureMacrosToBeGlobal() throws Exception
{
Properties properties = new Properties();
// Force macros to be global
properties.put(RuntimeConstants.VM_PERM_INLINE_LOCAL, "false");
this.engine.initialize(properties);
Context context = new XWikiVelocityContext();
this.engine.evaluate(context, new StringWriter(), "template1", "#macro(mymacro)test#end");
assertEvaluate("test", "#mymacro", "template2");
}
@Test
public void testMacroScope() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("{}", "#macro (testMacro)$macro#end#testMacro()");
}
@Test
public void testMacroWithMissingParameter() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("$param", "#macro (testMacro $param)$param#end#testMacro()");
}
@Test
public void testMacroWithLiterralBooleanParameter() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("true", "#macro (testMacro $param)$param#end#testMacro(true)");
}
@Test
public void testMacroWithLiterralMapParameter() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("{}", "#macro (testMacro $param)$param#end#testMacro({})");
}
@Test
public void testMacroWithLiterralArrayParameter() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("[]", "#macro (testMacro $param)$param#end#testMacro([])");
}
@Test
public void testUseGlobalMacroUseLocalMacro() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
// Register a global macro
evaluate("#macro (globalMacro)#localMacro()#end", "");
// Can the global macro call local macros
assertEvaluate("locallocal", "#macro (localMacro)local#end#localMacro()#globalMacro()");
}
@Test
public void testGlobalMacroUseLocalMacroAfterInclude() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
// Register a global macro
evaluate("#macro (globalMacro)#localMacro()#end", "");
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
// Can the global macro still call the local macro after executing another script in the same namespace
assertEvaluate("locallocallocal",
"#globalMacro()#macro (localMacro)local#end$test.evaluate('')#globalMacro()#localMacro()", context);
}
@Test
public void testIncludeMacro() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
// Can the script use an included macro
assertEvaluate("included", "$test.evaluate('#macro(includedmacro)included#end')#includedmacro()", context);
}
@Test
public void testOverwriteIncludeMacro() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
// Can the script overwrite an included macro
// No because macros are registered before executing the script (TODO: fix that)
assertEvaluate("included",
"$test.evaluate('#macro(includedmacro)included#end')#macro(includedmacro)ovewritten#end#includedmacro()",
context);
}
@Test
public void testTemplateScope() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("{}", "$template");
}
/**
* Verify namespace is properly cleared when not needed anymore.
*/
@Test
public void testMacroNamespaceCleanup() throws Exception
{
this.engine.initialize(new Properties());
// Unprotected namespace
assertEvaluate("#mymacro", "#mymacro", "namespace");
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "namespace", "#macro(mymacro)test#end");
assertEvaluate("#mymacro", "#mymacro", "namespace");
// Protected namespace
// Start using namespace "namespace"
this.engine.startedUsingMacroNamespace("namespace");
// Register macro
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "namespace", "#macro(mymacro)test#end");
assertEvaluate("test", "#mymacro", "namespace");
// Mark namespace "namespace" as not used anymore
this.engine.stoppedUsingMacroNamespace("namespace");
assertEvaluate("#mymacro", "#mymacro", "namespace");
}
@Test
public void testEvaluateWithStopCommand() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("hello world", "hello world#stop", DEFAULT_TEMPLATE_NAME);
}
@Test
public void testVelocityCount() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("1true2true3true4true5false", "#foreach($nb in [1,2,3,4,5])$velocityCount$velocityHasNext#end",
DEFAULT_TEMPLATE_NAME);
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(0));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(1));
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(2));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(3));
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(4));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(5));
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(6));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(7));
assertEquals("Deprecated binding [$velocityCount] used in [mytemplate]", logCapture.getMessage(8));
assertEquals("Deprecated binding [$velocityHasNext] used in [mytemplate]", logCapture.getMessage(9));
}
@Test
public void testEmptyNamespaceInheritance() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("#mymacro", "#mymacro", "namespace");
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "", "#macro(mymacro)test#end");
assertEvaluate("test", "#mymacro", "namespace");
}
@Test
public void testOverrideMacros() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("#mymacro", "#mymacro", "namespace");
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "", "#macro(mymacro)global#end");
assertEvaluate("global", "#mymacro", "namespace");
// Start using namespace "namespace"
this.engine.startedUsingMacroNamespace("namespace");
// Register macro
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "namespace", "#macro(mymacro)test1#end");
assertEvaluate("test1", "#mymacro", "namespace");
// Override macro
this.engine.evaluate(new XWikiVelocityContext(), new StringWriter(), "namespace", "#macro(mymacro)test2#end");
assertEvaluate("test2", "#mymacro", "namespace");
// Override in the same script
assertEvaluate("test4", "#macro(mymacro)test3#end#macro(mymacro)test4#end#mymacro", "namespace");
// Mark namespace "namespace" as not used anymore
this.engine.stoppedUsingMacroNamespace("namespace");
}
@Test
public void testMacroParameters() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("$caller", "#macro (testMacro $called)$called#end#testMacro($caller)");
assertEvaluate("$caller",
"#macro (testMacro $called)#set($called = $NULL)$called#set($called = 'value')#end#testMacro($caller)");
assertEvaluate("$caller",
"#macro (testMacro $called)#set($called = $NULL)$called#set($called = 'value')#end#set($caller = 'value')#testMacro($caller)");
assertEvaluate("$caller$caller2$caller",
"#macro(macro1 $called)$called#macro2($caller2)$called#end#macro(macro2 $called)$called#end#macro1($caller)");
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
context.put("other", new TestClass(context, "othername"));
assertEvaluate("namename", "#macro (testMacro $test $name)$name#end$test.name#testMacro($other, $test.name)",
context);
}
@Test
public void testSetSharpString() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("#", "#set($var = \"#\")$var", DEFAULT_TEMPLATE_NAME);
assertEvaluate("test#", "#set($var = \"test#\")$var", DEFAULT_TEMPLATE_NAME);
}
@Test
public void testSetDollarString() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("$", "#set($var = \"$\")$var", DEFAULT_TEMPLATE_NAME);
assertEvaluate("test$", "#set($var = \"test$\")$var", DEFAULT_TEMPLATE_NAME);
}
@Test
public void testExpressionFollowedByTwoPipes() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
assertEvaluate("$var||", "$var||");
}
@Test
public void testClassMethods() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
context.put("var", new TestClass());
assertEvaluate("org.xwiki.velocity.internal.DefaultVelocityEngineTest$TestClass name",
"$var.class.getName() $var.getName()", context);
}
@Test
public void testSubEvaluate() throws XWikiVelocityException
{
this.engine.initialize(new Properties());
Context context = new XWikiVelocityContext();
context.put("test", new TestClass(context));
assertEvaluate("top", "#set($var = 'top')$test.evaluate('$var')", context);
assertEvaluate("sub", "$test.evaluate('#set($var = \"sub\")')$var", context);
assertEvaluate("sub", "#set($var = 'top')$test.evaluate('#set($var = \"sub\")')$var", context);
assertEvaluate("global", "#macro(mymacro $var)#end#set($var = 'global')#mymacro()$var",
context);
assertEvaluate("global", "#macro(mymacro $var)$var#end#set($var = 'global')#mymacro()",
context);
// TODO: update this test when a decision is taken in Velocity side regarding macro context behavior
// See
// https://mail-archives.apache.org/mod_mbox/velocity-dev/202001.mbox/%3cCAPnKnLHmL2oeYBNHvq3FHO1BmFW0DFjChk6sxXb9s+mwKhxirQ@mail.gmail.com%3e
// assertEvaluate("local",
// "#macro(mymacro)#set($var = 'local')$test.evaluate('#set($var = \"global\")')$var#end#mymacro()", context);
}
@Test
public void testSpaceGobling() throws Exception
{
this.engine.initialize(new Properties());
assertEvaluate("value\nvalueline", "#macro (testMacro)value#end#testMacro\n#testMacro()\nline");
}
}
| XCOMMONS-1839: Velocity macro parameter name can break passed parameter expression
* Fix wrong test case.
| xwiki-commons-core/xwiki-commons-velocity/src/test/java/org/xwiki/velocity/internal/DefaultVelocityEngineTest.java | XCOMMONS-1839: Velocity macro parameter name can break passed parameter expression |
|
Java | lgpl-2.1 | cf49dd2dcebc67ad819fd204330a3d40d93ae73a | 0 | gytis/narayana,gytis/narayana,gytis/narayana,jbosstm/narayana,mmusgrov/narayana,mmusgrov/narayana,tomjenkinson/narayana,jbosstm/narayana,tomjenkinson/narayana,gytis/narayana,tomjenkinson/narayana,mmusgrov/narayana,jbosstm/narayana,jbosstm/narayana,mmusgrov/narayana,tomjenkinson/narayana,gytis/narayana,gytis/narayana | package com.arjuna.qa.extension;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import org.jboss.arquillian.container.spi.Container;
import org.jboss.arquillian.container.spi.ServerKillProcessor;
public class JBossAS7ServerKillProcessor implements ServerKillProcessor {
private final Logger log = Logger.getLogger(
JBossAS7ServerKillProcessor.class.getName());
private static String killSequence = "sh -x [jbossHome]/bin/jboss-cli.[suffix] --commands=connect,quit";
private static String shutdownSequence = "[jbossHome]/bin/jboss-cli.[suffix] --connect command=:shutdown";
private int checkDurableTime = 10;
private int numofCheck = 60;
@Override
public void kill(Container container) throws Exception {
log.info("waiting for byteman to kill server");
String jbossHome = System.getenv().get("JBOSS_HOME");
if(jbossHome == null) {
jbossHome = container.getContainerConfiguration().getContainerProperties().get("jbossHome");
}
killSequence = killSequence.replace("[jbossHome]", jbossHome);
shutdownSequence = shutdownSequence.replace("[jbossHome]", jbossHome);
String suffix;
String os = System.getProperty("os.name").toLowerCase();
if(os.indexOf("windows") > -1) {
suffix = "bat";
} else {
suffix = "sh";
}
killSequence = killSequence.replace("[suffix]", suffix);
shutdownSequence = shutdownSequence.replace("[suffix]", suffix);
int checkn = 0;
boolean killed = false;
do {
if(checkJBossAlive()) {
Thread.sleep(checkDurableTime * 1000);
log.info("jboss-as is alive");
} else {
killed = true;
break;
}
checkn ++;
} while(checkn < numofCheck);
if(killed) {
log.info("jboss-as killed by byteman scirpt");
} else {
String env = System.getenv().get("CLI_IPV6_OPTS");
Process p;
if (env == null)
p = Runtime.getRuntime().exec(shutdownSequence);
else
p = Runtime.getRuntime().exec(shutdownSequence,
new String[] {"JAVA_OPTS="+env});
log.info("jboss-as not killed and shutdown");
p.waitFor();
p.destroy();
// wait 5 * 60 second for jboss-as shutdown complete
int checkn_s = 0;
do {
if(checkJBossAlive()) {
Thread.sleep(5000);
} else {
log.info("jboss-as shutdown");
break;
}
checkn_s ++;
} while (checkn_s < 60);
throw new RuntimeException("jboss-as not killed and shutdown");
}
}
private void listAllJavaProcesses() {
String os = System.getProperty("os.name").toLowerCase();
if(os.indexOf("windows") == -1) {
try {
String line;
Process p = Runtime.getRuntime().exec("ps -ef |grep java");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //<-- Parse data here.
}
input.close();
} catch (Exception err) {
}
}
}
private void dumpStream(String msg, InputStream is) {
try {
BufferedReader ein = new BufferedReader(new InputStreamReader(is));
String res = ein.readLine();
is.close();
System.out.printf("%s %s\n", msg, res);
} catch (IOException e) {
log.info("Exception dumping stream: " + e.getMessage());
}
}
private boolean checkJBossAlive() throws Exception {
String env = System.getenv().get("CLI_IPV6_OPTS");
Process p;
if (env == null)
p = Runtime.getRuntime().exec(killSequence);
else
p = Runtime.getRuntime().exec(killSequence, new String[] {"JAVA_OPTS="+env});
p.waitFor();
int rc = p.exitValue();
if (rc != 0 && rc != 1) {
listAllJavaProcesses();
dumpStream("Error Stream: ", p.getErrorStream());
dumpStream("Input Stream: ", p.getInputStream());
p.destroy();
throw new RuntimeException("Kill Sequence "+ killSequence + " failed. Returned " + rc
+ " CLI_IPV6_OPTS=" + System.getenv().get("CLI_IPV6_OPTS"));
}
InputStream out = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(out));
String result= in.readLine();
out.close();
p.destroy();
return !(result != null && result.contains("The controller is not available"));
}
}
| XTS/localjunit/crash-recovery-tests/src/main/java/com/arjuna/qa/extension/JBossAS7ServerKillProcessor.java | package com.arjuna.qa.extension;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import org.jboss.arquillian.container.spi.Container;
import org.jboss.arquillian.container.spi.ServerKillProcessor;
public class JBossAS7ServerKillProcessor implements ServerKillProcessor {
private final Logger log = Logger.getLogger(
JBossAS7ServerKillProcessor.class.getName());
private static String killSequence = "sh -x [jbossHome]/bin/jboss-cli.[suffix] --commands=connect,quit";
private static String shutdownSequence = "[jbossHome]/bin/jboss-cli.[suffix] --connect command=:shutdown";
private int checkDurableTime = 10;
private int numofCheck = 60;
@Override
public void kill(Container container) throws Exception {
log.info("waiting for byteman to kill server");
String jbossHome = System.getenv().get("JBOSS_HOME");
if(jbossHome == null) {
jbossHome = container.getContainerConfiguration().getContainerProperties().get("jbossHome");
}
killSequence = killSequence.replace("[jbossHome]", jbossHome);
shutdownSequence = shutdownSequence.replace("[jbossHome]", jbossHome);
String suffix;
String os = System.getProperty("os.name").toLowerCase();
if(os.indexOf("windows") > -1) {
suffix = "bat";
} else {
suffix = "sh";
}
killSequence = killSequence.replace("[suffix]", suffix);
shutdownSequence = shutdownSequence.replace("[suffix]", suffix);
int checkn = 0;
boolean killed = false;
do {
if(checkJBossAlive()) {
Thread.sleep(checkDurableTime * 1000);
log.info("jboss-as is alive");
} else {
killed = true;
break;
}
checkn ++;
} while(checkn < numofCheck);
if(killed) {
log.info("jboss-as killed by byteman scirpt");
} else {
String env = System.getenv().get("CLI_IPV6_OPTS");
Process p;
if (env == null)
p = Runtime.getRuntime().exec(shutdownSequence);
else
p = Runtime.getRuntime().exec(shutdownSequence,
new String[] {"JAVA_OPTS="+env});
log.info("jboss-as not killed and shutdown");
p.waitFor();
p.destroy();
// wait 5 * 60 second for jboss-as shutdown complete
int checkn_s = 0;
do {
if(checkJBossAlive()) {
Thread.sleep(5000);
} else {
log.info("jboss-as shutdown");
break;
}
checkn_s ++;
} while (checkn_s < 60);
throw new RuntimeException("jboss-as not killed and shutdown");
}
}
private void listAllJavaProcesses() {
String os = System.getProperty("os.name").toLowerCase();
if(os.indexOf("windows") == -1) {
try {
String line;
Process p = Runtime.getRuntime().exec("ps -ef |grep java");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //<-- Parse data here.
}
input.close();
} catch (Exception err) {
}
}
}
private boolean checkJBossAlive() throws Exception {
String env = System.getenv().get("CLI_IPV6_OPTS");
Process p;
if (env == null)
p = Runtime.getRuntime().exec(killSequence);
else
p = Runtime.getRuntime().exec(killSequence, new String[] {"JAVA_OPTS="+env});
p.waitFor();
int rc = p.exitValue();
if (rc != 0 && rc != 1) {
listAllJavaProcesses();
p.destroy();
throw new RuntimeException("Kill Sequence "+ killSequence + " failed. Returned " + rc
+ " CLI_IPV6_OPTS=" + System.getenv().get("CLI_IPV6_OPTS"));
}
InputStream out = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(out));
String result= in.readLine();
out.close();
p.destroy();
return !(result != null && result.contains("The controller is not available"));
}
}
| JBTM-1235 Add some debug
| XTS/localjunit/crash-recovery-tests/src/main/java/com/arjuna/qa/extension/JBossAS7ServerKillProcessor.java | JBTM-1235 Add some debug |
|
Java | lgpl-2.1 | c0cfd52ffe981587b5b01b51209f2a02e6a8eefe | 0 | pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.gwt.wysiwyg.client.plugin.macro;
import java.util.Map;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* Describes a macro and its parameters.
* <p>
* NOTE: This class is a serializable, GWT-supported <em>clone</em> of the MacroDescriptor from the rendering module.
*
* @version $Id$
*/
public class MacroDescriptor implements IsSerializable
{
/**
* The macro identifier.
*/
private String id;
/**
* The human-readable name of the macro (e.g. Table of Contents for ToC macro).
*/
private String name;
/**
* The description of the macro.
*/
private String description;
/**
* The category of the macro.
*/
private String category;
/**
* A {@link Map} with descriptors for each parameter supported by the macro. The key is the parameter name.
*/
private Map<String, ParameterDescriptor> parameterDescriptorMap;
/**
* Describes the content of the macro.
*/
private ParameterDescriptor contentDescriptor;
/**
* Flag indicating if this macro supports in-line mode.
*/
private boolean supportingInlineMode;
/**
* @return the macro identifier
*/
public String getId()
{
return id;
}
/**
* Sets the identifier of the macro.
*
* @param id a macro identifier
*/
public void setId(String id)
{
this.id = id;
}
/**
* @return the human-readable name of the macro (e.g. Table of Contents for ToC macro)
*/
public String getName()
{
return name;
}
/**
* Sets the human-readable name of the macro (e.g. Table of Contents for ToC macro).
*
* @param name the macro name
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return the description of the macro
*/
public String getDescription()
{
return description;
}
/**
* Sets the macro description.
*
* @param description a {@link String} representing the macro description
*/
public void setDescription(String description)
{
this.description = description;
}
/**
* @return the category of the macro
*/
public String getCategory()
{
return category;
}
/**
* Sets the macro category.
*
* @param category the macro category
*/
public void setCategory(String category)
{
this.category = category;
}
/**
* @return a {@link Map} with parameter descriptors
*/
public Map<String, ParameterDescriptor> getParameterDescriptorMap()
{
return parameterDescriptorMap;
}
/**
* Sets the {@link Map} of parameter descriptors.
*
* @param parameterDescriptorMap a {@link Map} of parameter descriptors
*/
public void setParameterDescriptorMap(Map<String, ParameterDescriptor> parameterDescriptorMap)
{
this.parameterDescriptorMap = parameterDescriptorMap;
}
/**
* @return the content descriptor
*/
public ParameterDescriptor getContentDescriptor()
{
return contentDescriptor;
}
/**
* Sets the content descriptor.
*
* @param contentDescriptor the object describing the content of the macro
*/
public void setContentDescriptor(ParameterDescriptor contentDescriptor)
{
this.contentDescriptor = contentDescriptor;
}
/**
* @return {@code true} if this macro supports in-line mode, {@code false} otherwise
*/
public boolean isSupportingInlineMode()
{
return supportingInlineMode;
}
/**
* Sets the flag which indicates if this macro supports in-line mode.
*
* @param supportingInlineMode {@code true} if this macro is allowed in-line, {@code false} otherwise
*/
public void setSupportingInlineMode(boolean supportingInlineMode)
{
this.supportingInlineMode = supportingInlineMode;
}
}
| xwiki-platform-web/xwiki-gwt-wysiwyg-client/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/macro/MacroDescriptor.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.gwt.wysiwyg.client.plugin.macro;
import java.util.Map;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* Describes a macro and its parameters.
* <p>
* NOTE: This class is a serializable, GWT-supported <em>clone</em> of the MacroDescriptor from the rendering module.
*
* @version $Id$
*/
public class MacroDescriptor implements IsSerializable
{
/**
* The macro identifier.
*/
private String id;
/**
* The human-readable name of the macro (e.g. Table of Contents for ToC macro).
*/
private String name;
/**
* The description of the macro.
*/
private String description;
/**
* The category of the macro.
*/
private String category;
/**
* A {@link Map} with descriptors for each parameter supported by the macro. The key is the parameter name.
*/
private Map<String, ParameterDescriptor> parameterDescriptorMap;
/**
* Describes the content of the macro.
*/
private ParameterDescriptor contentDescriptor;
/**
* @return the macro identifier
*/
public String getId()
{
return id;
}
/**
* Sets the identifier of the macro.
*
* @param id a macro identifier
*/
public void setId(String id)
{
this.id = id;
}
/**
* @return the human-readable name of the macro (e.g. Table of Contents for ToC macro)
*/
public String getName()
{
return name;
}
/**
* Sets the human-readable name of the macro (e.g. Table of Contents for ToC macro).
*
* @param name the macro name
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return the description of the macro
*/
public String getDescription()
{
return description;
}
/**
* Sets the macro description.
*
* @param description a {@link String} representing the macro description
*/
public void setDescription(String description)
{
this.description = description;
}
/**
* @return the category of the macro
*/
public String getCategory()
{
return category;
}
/**
* Sets the macro category.
*
* @param category the macro category
*/
public void setCategory(String category)
{
this.category = category;
}
/**
* @return a {@link Map} with parameter descriptors
*/
public Map<String, ParameterDescriptor> getParameterDescriptorMap()
{
return parameterDescriptorMap;
}
/**
* Sets the {@link Map} of parameter descriptors.
*
* @param parameterDescriptorMap a {@link Map} of parameter descriptors
*/
public void setParameterDescriptorMap(Map<String, ParameterDescriptor> parameterDescriptorMap)
{
this.parameterDescriptorMap = parameterDescriptorMap;
}
/**
* @return the content descriptor
*/
public ParameterDescriptor getContentDescriptor()
{
return contentDescriptor;
}
/**
* Sets the content descriptor.
*
* @param contentDescriptor the object describing the content of the macro
*/
public void setContentDescriptor(ParameterDescriptor contentDescriptor)
{
this.contentDescriptor = contentDescriptor;
}
}
| Add a flag in the macro descriptor to specifiy if the macro supports in-line mode.
git-svn-id: 04343649e741710b2e0f622af6defd1ac33e5ca5@27164 f329d543-caf0-0310-9063-dda96c69346f
| xwiki-platform-web/xwiki-gwt-wysiwyg-client/src/main/java/org/xwiki/gwt/wysiwyg/client/plugin/macro/MacroDescriptor.java | Add a flag in the macro descriptor to specifiy if the macro supports in-line mode. |
|
Java | lgpl-2.1 | dc9f7c1d08e798a47b7264a67cb5a2f1142c9634 | 0 | mbenz89/soot,cfallin/soot,cfallin/soot,anddann/soot,cfallin/soot,mbenz89/soot,anddann/soot,mbenz89/soot,plast-lab/soot,plast-lab/soot,anddann/soot,xph906/SootNew,cfallin/soot,xph906/SootNew,plast-lab/soot,anddann/soot,mbenz89/soot,xph906/SootNew,xph906/SootNew | /* Soot - a J*va Optimization Framework
* Copyright (C) 1997-1999 Raja Vallee-Rai
* Copyright (C) 2004 Ondrej Lhotak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.ContextSensitiveCallGraph;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import soot.jimple.toolkits.pointer.DumbPointerAnalysis;
import soot.jimple.toolkits.pointer.SideEffectAnalysis;
import soot.options.CGOptions;
import soot.options.Options;
import soot.toolkits.exceptions.PedanticThrowAnalysis;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.exceptions.UnitThrowAnalysis;
import soot.util.ArrayNumberer;
import soot.util.Chain;
import soot.util.HashChain;
import soot.util.MapNumberer;
import soot.util.Numberer;
import soot.util.SingletonList;
import soot.util.StringNumberer;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.AXmlResourceParser;
import test.AXMLPrinter;
/** Manages the SootClasses of the application being analyzed. */
public class Scene //extends AbstractHost
{
public Scene ( Singletons.Global g )
{
setReservedNames();
// load soot.class.path system property, if defined
String scp = System.getProperty("soot.class.path");
if (scp != null)
setSootClassPath(scp);
kindNumberer.add( Kind.INVALID );
kindNumberer.add( Kind.STATIC );
kindNumberer.add( Kind.VIRTUAL );
kindNumberer.add( Kind.INTERFACE );
kindNumberer.add( Kind.SPECIAL );
kindNumberer.add( Kind.CLINIT );
kindNumberer.add( Kind.THREAD );
kindNumberer.add( Kind.FINALIZE );
kindNumberer.add( Kind.INVOKE_FINALIZE );
kindNumberer.add( Kind.PRIVILEGED );
kindNumberer.add( Kind.NEWINSTANCE );
addSootBasicClasses();
determineExcludedPackages();
}
private void determineExcludedPackages() {
excludedPackages = new LinkedList<String>();
if (Options.v().exclude() != null)
excludedPackages.addAll(Options.v().exclude());
if( !Options.v().include_all() ) {
excludedPackages.add("java.");
excludedPackages.add("sun.");
excludedPackages.add("javax.");
excludedPackages.add("com.sun.");
excludedPackages.add("com.ibm.");
excludedPackages.add("org.xml.");
excludedPackages.add("org.w3c.");
excludedPackages.add("apple.awt.");
excludedPackages.add("com.apple.");
}
}
public static Scene v() { return G.v().soot_Scene (); }
private Chain<SootClass> classes = new HashChain<SootClass>();
private Chain<SootClass> applicationClasses = new HashChain<SootClass>();
private Chain<SootClass> libraryClasses = new HashChain<SootClass>();
private Chain<SootClass> phantomClasses = new HashChain<SootClass>();
private final Map<String,Type> nameToClass = new HashMap<String,Type>();
private ArrayNumberer kindNumberer = new ArrayNumberer();
private ArrayNumberer typeNumberer = new ArrayNumberer();
private ArrayNumberer methodNumberer = new ArrayNumberer();
private Numberer unitNumberer = new MapNumberer();
private Numberer contextNumberer = null;
private ArrayNumberer fieldNumberer = new ArrayNumberer();
private ArrayNumberer classNumberer = new ArrayNumberer();
private StringNumberer subSigNumberer = new StringNumberer();
private ArrayNumberer localNumberer = new ArrayNumberer();
private Hierarchy activeHierarchy;
private FastHierarchy activeFastHierarchy;
private CallGraph activeCallGraph;
private ReachableMethods reachableMethods;
private PointsToAnalysis activePointsToAnalysis;
private SideEffectAnalysis activeSideEffectAnalysis;
private List<SootMethod> entryPoints;
boolean allowsPhantomRefs = false;
SootClass mainClass;
String sootClassPath = null;
// Two default values for constructing ExceptionalUnitGraphs:
private ThrowAnalysis defaultThrowAnalysis = null;
public void setMainClass(SootClass m)
{
mainClass = m;
if(!m.declaresMethod(getSubSigNumberer().findOrAdd( "void main(java.lang.String[])" ))) {
throw new RuntimeException("Main-class has no main method!");
}
}
Set<String> reservedNames = new HashSet<String>();
/**
Returns a set of tokens which are reserved. Any field, class, method, or local variable with such a name will be quoted.
*/
public Set<String> getReservedNames()
{
return reservedNames;
}
/**
If this name is in the set of reserved names, then return a quoted version of it. Else pass it through.
*/
public String quotedNameOf(String s)
{
if(reservedNames.contains(s))
return "\'" + s + "\'";
else
return s;
}
public boolean hasMainClass() {
if(mainClass == null) {
setMainClassFromOptions();
}
return mainClass!=null;
}
public SootClass getMainClass()
{
if(!hasMainClass())
throw new RuntimeException("There is no main class set!");
return mainClass;
}
public SootMethod getMainMethod() {
if(mainClass==null) {
throw new RuntimeException("There is no main class set!");
}
if (!mainClass.declaresMethod ("main", new SingletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v())) {
throw new RuntimeException("Main class declares no main method!");
}
return mainClass.getMethod ("main", new SingletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v());
}
public void setSootClassPath(String p)
{
sootClassPath = p;
SourceLocator.v().invalidateClassPath();
}
public String getSootClassPath()
{
if( sootClassPath == null ) {
String optionscp = Options.v().soot_classpath();
if( optionscp.length() > 0 )
sootClassPath = optionscp;
String defaultSootClassPath = defaultClassPath();
//if no classpath is given on the command line, take the default
if( sootClassPath == null ) {
sootClassPath = defaultSootClassPath;
} else {
//if one is given...
if(Options.v().prepend_classpath()) {
//if the prepend flag is set, append the default classpath
sootClassPath += File.pathSeparator + defaultSootClassPath;
}
//else, leave it as it is
}
//add process-dirs
List<String> process_dir = Options.v().process_dir();
StringBuffer pds = new StringBuffer();
for (String path : process_dir) {
if(!sootClassPath.contains(path)) {
pds.append(path);
pds.append(File.pathSeparator);
}
}
sootClassPath = pds + sootClassPath;
}
return sootClassPath;
}
public String getAndroidJarPath(String jars, String apk) {
File jarsF = new File(jars);
File apkF = new File(apk);
int APIVersion = -1;
String jarPath = "";
if (!jarsF.exists())
throw new RuntimeException("file '" + jars + "' does not exist!");
if (!apkF.exists())
throw new RuntimeException("file '" + apk + "' does not exist!");
// get AndroidManifest
InputStream manifestIS = null;
try {
ZipFile archive = new ZipFile(apkF);
for (@SuppressWarnings("rawtypes") Enumeration entries = archive.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String entryName = entry.getName();
// We are dealing with the Android manifest
if (entryName.equals("AndroidManifest.xml")) {
manifestIS = archive.getInputStream(entry);
break;
}
}
} catch (Exception e) {
throw new RuntimeException("Error when looking for manifest in apk: " + e);
}
final int defaultSdkVersion = 15;
if (manifestIS == null) {
G.v().out.println("Could not find sdk version in Android manifest! Using default: "+defaultSdkVersion);
APIVersion = defaultSdkVersion;
} else {
// process AndroidManifest.xml
int sdkTargetVersion = -1;
int minSdkVersion = -1;
try {
AXmlResourceParser parser = new AXmlResourceParser();
parser.open(manifestIS);
int depth = 0;
while (true) {
int type = parser.next();
if (type == XmlPullParser.END_DOCUMENT) {
// throw new RuntimeException
// ("target sdk version not found in Android manifest ("+
// apkF +")");
break;
}
switch (type) {
case XmlPullParser.START_DOCUMENT: {
break;
}
case XmlPullParser.START_TAG: {
depth++;
String tagName = parser.getName();
if (depth == 2 && tagName.equals("uses-sdk")) {
for (int i = 0; i != parser.getAttributeCount(); ++i) {
String attributeName = parser.getAttributeName(i);
String attributeValue = AXMLPrinter.getAttributeValue(parser, i);
if (attributeName.equals("targetSdkVersion")) {
sdkTargetVersion = Integer.parseInt(attributeValue);
} else if (attributeName.equals("minSdkVersion")) {
minSdkVersion = Integer.parseInt(attributeValue);
}
}
}
break;
}
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.TEXT:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (sdkTargetVersion != -1) {
APIVersion = sdkTargetVersion;
} else if (minSdkVersion != -1) {
APIVersion = minSdkVersion;
} else {
G.v().out.println("Could not find sdk version in Android manifest! Using default: "+defaultSdkVersion);
APIVersion = defaultSdkVersion;
}
if (APIVersion <= 2)
APIVersion = 3;
}
// get path to appropriate android.jar
jarPath = jars + File.separator + "android-" + APIVersion + File.separator + "android.jar";
return jarPath;
}
public String defaultClassPath() {
StringBuffer sb = new StringBuffer();
if(System.getProperty("os.name").equals("Mac OS X")) {
//in older Mac OS X versions, rt.jar was split into classes.jar and ui.jar
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("..");
sb.append(File.separator);
sb.append("Classes");
sb.append(File.separator);
sb.append("classes.jar");
sb.append(File.pathSeparator);
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("..");
sb.append(File.separator);
sb.append("Classes");
sb.append(File.separator);
sb.append("ui.jar");
sb.append(File.pathSeparator);
}
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("lib");
sb.append(File.separator);
sb.append("rt.jar");
if(Options.v().whole_program() || Options.v().output_format()==Options.output_format_dava) {
//add jce.jar, which is necessary for whole program mode
//(java.security.Signature from rt.jar import javax.crypto.Cipher from jce.jar
sb.append(File.pathSeparator+
System.getProperty("java.home")+File.separator+"lib"+File.separator+"jce.jar");
}
String defaultClassPath = sb.toString();
if (Options.v().src_prec() == Options.src_prec_apk) {
// check that android.jar is not in classpath
if (!defaultClassPath.contains ("android.jar")) {
String androidJars = Options.v().android_jars();
String forceAndroidJar = Options.v().force_android_jar();
if (androidJars.equals("") && forceAndroidJar.equals("")) {
throw new RuntimeException("You are analyzing an Android application but did not define android.jar. Options -android-jars or -force-android-jar should be used.");
}
String jarPath = "";
if (!forceAndroidJar.equals("")) {
jarPath = forceAndroidJar;
} else if (!androidJars.equals("")) {
List<String> classPathEntries = new LinkedList<String>(Arrays.asList(Options.v().soot_classpath().split(File.pathSeparator)));
classPathEntries.addAll(Options.v().process_dir());
Set<String> targetApks = new HashSet<String>();
for (String entry : classPathEntries) {
if(entry.endsWith(".apk"))
targetApks.add(entry);
}
if (targetApks.size() == 0)
throw new RuntimeException("no apk file given");
else if (targetApks.size() > 1)
throw new RuntimeException("only one Android application can be analyzed when using option -android-jars.");
jarPath = getAndroidJarPath (androidJars, (String)targetApks.toArray()[0]);
}
if (jarPath.equals(""))
throw new RuntimeException("android.jar not found.");
File f = new File (jarPath);
if (!f.exists())
throw new RuntimeException("file '"+ jarPath +"' does not exist!");
else
G.v().out.println("Using '"+ jarPath +"' as android.jar");
defaultClassPath = jarPath + File.pathSeparator + defaultClassPath;
} else {
G.v().out.println("warning: defaultClassPath contains android.jar! Options -android-jars and -force-android-jar are ignored!");
}
}
return defaultClassPath;
}
private int stateCount;
public int getState() { return this.stateCount; }
private void modifyHierarchy() {
stateCount++;
activeHierarchy = null;
activeFastHierarchy = null;
activeSideEffectAnalysis = null;
activePointsToAnalysis = null;
}
public void addClass(SootClass c)
{
if(c.isInScene())
throw new RuntimeException("already managed: "+c.getName());
if(containsClass(c.getName()))
throw new RuntimeException("duplicate class: "+c.getName());
classes.add(c);
c.setLibraryClass();
nameToClass.put(c.getName(), c.getType());
c.getType().setSootClass(c);
c.setInScene(true);
modifyHierarchy();
}
public void removeClass(SootClass c)
{
if(!c.isInScene())
throw new RuntimeException();
classes.remove(c);
if(c.isLibraryClass()) {
libraryClasses.remove(c);
} else if(c.isPhantomClass()) {
phantomClasses.remove(c);
} else if(c.isApplicationClass()) {
applicationClasses.remove(c);
}
c.getType().setSootClass(null);
c.setInScene(false);
modifyHierarchy();
}
public boolean containsClass(String className)
{
RefType type = (RefType) nameToClass.get(className);
if( type == null ) return false;
if( !type.hasSootClass() ) return false;
SootClass c = type.getSootClass();
return c.isInScene();
}
public boolean containsType(String className)
{
return nameToClass.containsKey(className);
}
public String signatureToClass(String sig) {
if( sig.charAt(0) != '<' ) throw new RuntimeException("oops "+sig);
if( sig.charAt(sig.length()-1) != '>' ) throw new RuntimeException("oops "+sig);
int index = sig.indexOf( ":" );
if( index < 0 ) throw new RuntimeException("oops "+sig);
return sig.substring(1,index);
}
public String signatureToSubsignature(String sig) {
if( sig.charAt(0) != '<' ) throw new RuntimeException("oops "+sig);
if( sig.charAt(sig.length()-1) != '>' ) throw new RuntimeException("oops "+sig);
int index = sig.indexOf( ":" );
if( index < 0 ) throw new RuntimeException("oops "+sig);
return sig.substring(index+2,sig.length()-1);
}
private SootField grabField(String fieldSignature)
{
String cname = signatureToClass( fieldSignature );
String fname = signatureToSubsignature( fieldSignature );
if( !containsClass(cname) ) return null;
SootClass c = getSootClass(cname);
if( !c.declaresField( fname ) ) return null;
return c.getField( fname );
}
public boolean containsField(String fieldSignature)
{
return grabField(fieldSignature) != null;
}
private SootMethod grabMethod(String methodSignature)
{
String cname = signatureToClass( methodSignature );
String mname = signatureToSubsignature( methodSignature );
if( !containsClass(cname) ) return null;
SootClass c = getSootClass(cname);
if( !c.declaresMethod( mname ) ) return null;
return c.getMethod( mname );
}
public boolean containsMethod(String methodSignature)
{
return grabMethod(methodSignature) != null;
}
public SootField getField(String fieldSignature)
{
SootField f = grabField( fieldSignature );
if (f != null)
return f;
throw new RuntimeException("tried to get nonexistent field "+fieldSignature);
}
public SootMethod getMethod(String methodSignature)
{
SootMethod m = grabMethod( methodSignature );
if (m != null)
return m;
throw new RuntimeException("tried to get nonexistent method "+methodSignature);
}
/**
* Attempts to load the given class and all of the required support classes.
* Returns the original class if it was loaded, or null otherwise.
*/
public SootClass tryLoadClass(String className, int desiredLevel)
{
/*
if(Options.v().time())
Main.v().resolveTimer.start();
*/
setPhantomRefs(true);
//SootResolver resolver = new SootResolver();
if( !getPhantomRefs()
&& SourceLocator.v().getClassSource(className) == null ) {
setPhantomRefs(false);
return null;
}
SootResolver resolver = SootResolver.v();
SootClass toReturn = resolver.resolveClass(className, desiredLevel);
setPhantomRefs(false);
return toReturn;
/*
if(Options.v().time())
Main.v().resolveTimer.end(); */
}
/**
* Loads the given class and all of the required support classes. Returns the first class.
*/
public SootClass loadClassAndSupport(String className)
{
SootClass ret = loadClass(className, SootClass.SIGNATURES);
if( !ret.isPhantom() ) ret = loadClass(className, SootClass.BODIES);
return ret;
}
public SootClass loadClass(String className, int desiredLevel)
{
/*
if(Options.v().time())
Main.v().resolveTimer.start();
*/
setPhantomRefs(true);
//SootResolver resolver = new SootResolver();
SootResolver resolver = SootResolver.v();
SootClass toReturn = resolver.resolveClass(className, desiredLevel);
setPhantomRefs(false);
return toReturn;
/*
if(Options.v().time())
Main.v().resolveTimer.end(); */
}
/**
* Returns the RefType with the given className.
* @throws IllegalStateException if the RefType for this class cannot be found.
* Use {@link #containsType(String)} to check if type is registered
*/
public RefType getRefType(String className)
{
RefType refType = (RefType) nameToClass.get(className);
if(refType==null) {
throw new IllegalStateException("RefType "+className+" not loaded. " +
"If you tried to get the RefType of a library class, did you call loadNecessaryClasses()? " +
"Otherwise please check Soot's classpath.");
}
return refType;
}
/**
* Returns the {@link RefType} for {@link Object}.
*/
public RefType getObjectType() {
return getRefType("java.lang.Object");
}
/**
* Returns the RefType with the given className.
*/
public void addRefType(RefType type)
{
nameToClass.put(type.getClassName(), type);
}
/**
* Returns the SootClass with the given className.
*/
public SootClass getSootClass(String className) {
RefType type = (RefType) nameToClass.get(className);
SootClass toReturn = null;
if (type != null)
toReturn = type.getSootClass();
if (toReturn != null) {
return toReturn;
} else if (allowsPhantomRefs() ||
className.equals(SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME)) {
SootClass c = new SootClass(className);
addClass(c);
c.setPhantom(true);
return c;
} else {
throw new RuntimeException(System.getProperty("line.separator")
+ "Aborting: can't find classfile " + className);
}
}
/**
* Returns an backed chain of the classes in this manager.
*/
public Chain<SootClass> getClasses()
{
return classes;
}
/* The four following chains are mutually disjoint. */
/**
* Returns a chain of the application classes in this scene.
* These classes are the ones which can be freely analysed & modified.
*/
public Chain<SootClass> getApplicationClasses()
{
return applicationClasses;
}
/**
* Returns a chain of the library classes in this scene.
* These classes can be analysed but not modified.
*/
public Chain<SootClass> getLibraryClasses()
{
return libraryClasses;
}
/**
* Returns a chain of the phantom classes in this scene.
* These classes are referred to by other classes, but cannot be loaded.
*/
public Chain<SootClass> getPhantomClasses()
{
return phantomClasses;
}
Chain<SootClass> getContainingChain(SootClass c)
{
if (c.isApplicationClass())
return getApplicationClasses();
else if (c.isLibraryClass())
return getLibraryClasses();
else if (c.isPhantomClass())
return getPhantomClasses();
return null;
}
/****************************************************************************/
/**
Retrieves the active side-effect analysis
*/
public SideEffectAnalysis getSideEffectAnalysis()
{
if(!hasSideEffectAnalysis()) {
setSideEffectAnalysis( new SideEffectAnalysis(
getPointsToAnalysis(),
getCallGraph() ) );
}
return activeSideEffectAnalysis;
}
/**
Sets the active side-effect analysis
*/
public void setSideEffectAnalysis(SideEffectAnalysis sea)
{
activeSideEffectAnalysis = sea;
}
public boolean hasSideEffectAnalysis()
{
return activeSideEffectAnalysis != null;
}
public void releaseSideEffectAnalysis()
{
activeSideEffectAnalysis = null;
}
/****************************************************************************/
/**
Retrieves the active pointer analysis
*/
public PointsToAnalysis getPointsToAnalysis()
{
if(!hasPointsToAnalysis()) {
return DumbPointerAnalysis.v();
}
return activePointsToAnalysis;
}
/**
Sets the active pointer analysis
*/
public void setPointsToAnalysis(PointsToAnalysis pa)
{
activePointsToAnalysis = pa;
}
public boolean hasPointsToAnalysis()
{
return activePointsToAnalysis != null;
}
public void releasePointsToAnalysis()
{
activePointsToAnalysis = null;
}
/****************************************************************************/
/** Makes a new fast hierarchy is none is active, and returns the active
* fast hierarchy. */
public FastHierarchy getOrMakeFastHierarchy() {
if(!hasFastHierarchy() ) {
setFastHierarchy( new FastHierarchy() );
}
return getFastHierarchy();
}
/**
Retrieves the active fast hierarchy
*/
public FastHierarchy getFastHierarchy()
{
if(!hasFastHierarchy())
throw new RuntimeException("no active FastHierarchy present for scene");
return activeFastHierarchy;
}
/**
Sets the active hierarchy
*/
public void setFastHierarchy(FastHierarchy hierarchy)
{
activeFastHierarchy = hierarchy;
}
public boolean hasFastHierarchy()
{
return activeFastHierarchy != null;
}
public void releaseFastHierarchy()
{
activeFastHierarchy = null;
}
/****************************************************************************/
/**
Retrieves the active hierarchy
*/
public Hierarchy getActiveHierarchy()
{
if(!hasActiveHierarchy())
//throw new RuntimeException("no active Hierarchy present for scene");
setActiveHierarchy( new Hierarchy() );
return activeHierarchy;
}
/**
Sets the active hierarchy
*/
public void setActiveHierarchy(Hierarchy hierarchy)
{
activeHierarchy = hierarchy;
}
public boolean hasActiveHierarchy()
{
return activeHierarchy != null;
}
public void releaseActiveHierarchy()
{
activeHierarchy = null;
}
public boolean hasCustomEntryPoints() {
return entryPoints!=null;
}
/** Get the set of entry points that are used to build the call graph. */
public List<SootMethod> getEntryPoints() {
if( entryPoints == null ) {
entryPoints = EntryPoints.v().all();
}
return entryPoints;
}
/** Change the set of entry point methods used to build the call graph. */
public void setEntryPoints( List<SootMethod> entryPoints ) {
this.entryPoints = entryPoints;
}
private ContextSensitiveCallGraph cscg;
public ContextSensitiveCallGraph getContextSensitiveCallGraph() {
if(cscg == null) throw new RuntimeException("No context-sensitive call graph present in Scene. You can bulid one with Paddle.");
return cscg;
}
public void setContextSensitiveCallGraph(ContextSensitiveCallGraph cscg) {
this.cscg = cscg;
}
public CallGraph getCallGraph()
{
if(!hasCallGraph()) {
throw new RuntimeException( "No call graph present in Scene. Maybe you want Whole Program mode (-w)." );
}
return activeCallGraph;
}
public void setCallGraph(CallGraph cg)
{
reachableMethods = null;
activeCallGraph = cg;
}
public boolean hasCallGraph()
{
return activeCallGraph != null;
}
public void releaseCallGraph()
{
activeCallGraph = null;
reachableMethods = null;
}
public ReachableMethods getReachableMethods() {
if( reachableMethods == null ) {
reachableMethods = new ReachableMethods(
getCallGraph(), new ArrayList<MethodOrMethodContext>(getEntryPoints()) );
}
reachableMethods.update();
return reachableMethods;
}
public void setReachableMethods( ReachableMethods rm ) {
reachableMethods = rm;
}
public boolean hasReachableMethods() {
return reachableMethods != null;
}
public void releaseReachableMethods() {
reachableMethods = null;
}
public boolean getPhantomRefs()
{
//if( !Options.v().allow_phantom_refs() ) return false;
//return allowsPhantomRefs;
return Options.v().allow_phantom_refs();
}
public void setPhantomRefs(boolean value)
{
allowsPhantomRefs = value;
}
public boolean allowsPhantomRefs()
{
return getPhantomRefs();
}
public Numberer kindNumberer() { return kindNumberer; }
public ArrayNumberer getTypeNumberer() { return typeNumberer; }
public ArrayNumberer getMethodNumberer() { return methodNumberer; }
public Numberer getContextNumberer() { return contextNumberer; }
public Numberer getUnitNumberer() { return unitNumberer; }
public ArrayNumberer getFieldNumberer() { return fieldNumberer; }
public ArrayNumberer getClassNumberer() { return classNumberer; }
public StringNumberer getSubSigNumberer() { return subSigNumberer; }
public ArrayNumberer getLocalNumberer() { return localNumberer; }
public void setContextNumberer( Numberer n ) {
if( contextNumberer != null )
throw new RuntimeException(
"Attempt to set context numberer when it is already set." );
contextNumberer = n;
}
/**
* Returns the {@link ThrowAnalysis} to be used by default when
* constructing CFGs which include exceptional control flow.
*
* @return the default {@link ThrowAnalysis}
*/
public ThrowAnalysis getDefaultThrowAnalysis()
{
if( defaultThrowAnalysis == null ) {
int optionsThrowAnalysis = Options.v().throw_analysis();
switch (optionsThrowAnalysis) {
case Options.throw_analysis_pedantic:
defaultThrowAnalysis = PedanticThrowAnalysis.v();
break;
case Options.throw_analysis_unit:
defaultThrowAnalysis = UnitThrowAnalysis.v();
break;
default:
throw new IllegalStateException("Options.v().throw_analysi() == " +
Options.v().throw_analysis());
}
}
return defaultThrowAnalysis;
}
/**
* Sets the {@link ThrowAnalysis} to be used by default when
* constructing CFGs which include exceptional control flow.
*
* @param ta the default {@link ThrowAnalysis}.
*/
public void setDefaultThrowAnalysis(ThrowAnalysis ta)
{
defaultThrowAnalysis = ta;
}
private void setReservedNames()
{
Set<String> rn = getReservedNames();
rn.add("newarray");
rn.add("newmultiarray");
rn.add("nop");
rn.add("ret");
rn.add("specialinvoke");
rn.add("staticinvoke");
rn.add("tableswitch");
rn.add("virtualinvoke");
rn.add("null_type");
rn.add("unknown");
rn.add("cmp");
rn.add("cmpg");
rn.add("cmpl");
rn.add("entermonitor");
rn.add("exitmonitor");
rn.add("interfaceinvoke");
rn.add("lengthof");
rn.add("lookupswitch");
rn.add("neg");
rn.add("if");
rn.add("abstract");
rn.add("annotation");
rn.add("boolean");
rn.add("break");
rn.add("byte");
rn.add("case");
rn.add("catch");
rn.add("char");
rn.add("class");
rn.add("final");
rn.add("native");
rn.add("public");
rn.add("protected");
rn.add("private");
rn.add("static");
rn.add("synchronized");
rn.add("transient");
rn.add("volatile");
rn.add("interface");
rn.add("void");
rn.add("short");
rn.add("int");
rn.add("long");
rn.add("float");
rn.add("double");
rn.add("extends");
rn.add("implements");
rn.add("breakpoint");
rn.add("default");
rn.add("goto");
rn.add("instanceof");
rn.add("new");
rn.add("return");
rn.add("throw");
rn.add("throws");
rn.add("null");
rn.add("from");
rn.add("to");
}
private final Set<String>[] basicclasses=new Set[4];
private void addSootBasicClasses() {
basicclasses[SootClass.HIERARCHY] = new HashSet<String>();
basicclasses[SootClass.SIGNATURES] = new HashSet<String>();
basicclasses[SootClass.BODIES] = new HashSet<String>();
addBasicClass("java.lang.Object");
addBasicClass("java.lang.Class", SootClass.SIGNATURES);
addBasicClass("java.lang.Void", SootClass.SIGNATURES);
addBasicClass("java.lang.Boolean", SootClass.SIGNATURES);
addBasicClass("java.lang.Byte", SootClass.SIGNATURES);
addBasicClass("java.lang.Character", SootClass.SIGNATURES);
addBasicClass("java.lang.Short", SootClass.SIGNATURES);
addBasicClass("java.lang.Integer", SootClass.SIGNATURES);
addBasicClass("java.lang.Long", SootClass.SIGNATURES);
addBasicClass("java.lang.Float", SootClass.SIGNATURES);
addBasicClass("java.lang.Double", SootClass.SIGNATURES);
addBasicClass("java.lang.String");
addBasicClass("java.lang.StringBuffer", SootClass.SIGNATURES);
addBasicClass("java.lang.Error");
addBasicClass("java.lang.AssertionError", SootClass.SIGNATURES);
addBasicClass("java.lang.Throwable", SootClass.SIGNATURES);
addBasicClass("java.lang.NoClassDefFoundError", SootClass.SIGNATURES);
addBasicClass("java.lang.ExceptionInInitializerError");
addBasicClass("java.lang.RuntimeException");
addBasicClass("java.lang.ClassNotFoundException");
addBasicClass("java.lang.ArithmeticException");
addBasicClass("java.lang.ArrayStoreException");
addBasicClass("java.lang.ClassCastException");
addBasicClass("java.lang.IllegalMonitorStateException");
addBasicClass("java.lang.IndexOutOfBoundsException");
addBasicClass("java.lang.ArrayIndexOutOfBoundsException");
addBasicClass("java.lang.NegativeArraySizeException");
addBasicClass("java.lang.NullPointerException");
addBasicClass("java.lang.InstantiationError");
addBasicClass("java.lang.InternalError");
addBasicClass("java.lang.OutOfMemoryError");
addBasicClass("java.lang.StackOverflowError");
addBasicClass("java.lang.UnknownError");
addBasicClass("java.lang.ThreadDeath");
addBasicClass("java.lang.ClassCircularityError");
addBasicClass("java.lang.ClassFormatError");
addBasicClass("java.lang.IllegalAccessError");
addBasicClass("java.lang.IncompatibleClassChangeError");
addBasicClass("java.lang.LinkageError");
addBasicClass("java.lang.VerifyError");
addBasicClass("java.lang.NoSuchFieldError");
addBasicClass("java.lang.AbstractMethodError");
addBasicClass("java.lang.NoSuchMethodError");
addBasicClass("java.lang.UnsatisfiedLinkError");
addBasicClass("java.lang.Thread");
addBasicClass("java.lang.Runnable");
addBasicClass("java.lang.Cloneable");
addBasicClass("java.io.Serializable");
addBasicClass("java.lang.ref.Finalizer");
}
public void addBasicClass(String name) {
addBasicClass(name,SootClass.HIERARCHY);
}
public void addBasicClass(String name,int level) {
basicclasses[level].add(name);
}
/** Load just the set of basic classes soot needs, ignoring those
* specified on the command-line. You don't need to use both this and
* loadNecessaryClasses, though it will only waste time.
*/
public void loadBasicClasses() {
addReflectionTraceClasses();
for(int i=SootClass.BODIES;i>=SootClass.HIERARCHY;i--) {
for(String name: basicclasses[i]) {
tryLoadClass(name,i);
}
}
}
public Set<String> getBasicClasses() {
Set<String> all = new HashSet<String>();
for(int i=0;i<basicclasses.length;i++) {
Set<String> classes = basicclasses[i];
if(classes!=null)
all.addAll(classes);
}
return all;
}
private void addReflectionTraceClasses() {
CGOptions options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
String log = options.reflection_log();
Set<String> classNames = new HashSet<String>();
if(log!=null && log.length()>0) {
BufferedReader reader;
String line="";
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(log)));
while((line=reader.readLine())!=null) {
if(line.length()==0) continue;
String[] portions = line.split(";",-1);
String kind = portions[0];
String target = portions[1];
String source = portions[2];
String sourceClassName = source.substring(0,source.lastIndexOf("."));
classNames.add(sourceClassName);
if(kind.equals("Class.forName")) {
classNames.add(target);
} else if(kind.equals("Class.newInstance")) {
classNames.add(target);
} else if(kind.equals("Method.invoke") || kind.equals("Constructor.newInstance")) {
classNames.add(signatureToClass(target));
} else if(kind.equals("Field.set*") || kind.equals("Field.get*")) {
classNames.add(signatureToClass(target));
} else throw new RuntimeException("Unknown entry kind: "+kind);
}
} catch (Exception e) {
throw new RuntimeException("Line: '"+line+"'", e);
}
}
for (String c : classNames) {
addBasicClass(c, SootClass.BODIES);
}
}
private List<SootClass> dynamicClasses;
public Collection<SootClass> dynamicClasses() {
if(dynamicClasses==null) {
throw new IllegalStateException("Have to call loadDynamicClasses() first!");
}
return dynamicClasses;
}
private void loadNecessaryClass(String name) {
SootClass c;
c = loadClassAndSupport(name);
c.setApplicationClass();
}
/** Load the set of classes that soot needs, including those specified on the
* command-line. This is the standard way of initialising the list of
* classes soot should use.
*/
public void loadNecessaryClasses() {
loadBasicClasses();
Iterator<String> it = Options.v().classes().iterator();
while (it.hasNext()) {
String name = (String) it.next();
loadNecessaryClass(name);
}
loadDynamicClasses();
if(Options.v().oaat()) {
if(Options.v().process_dir().isEmpty()) {
throw new IllegalArgumentException("If switch -oaat is used, then also -process-dir must be given.");
}
} else {
for( Iterator<String> pathIt = Options.v().process_dir().iterator(); pathIt.hasNext(); ) {
final String path = (String) pathIt.next();
for (String cl : SourceLocator.v().getClassesUnder(path)) {
loadClassAndSupport(cl).setApplicationClass();
}
}
}
prepareClasses();
setDoneResolving();
}
public void loadDynamicClasses() {
dynamicClasses = new ArrayList<SootClass>();
HashSet<String> dynClasses = new HashSet<String>();
dynClasses.addAll(Options.v().dynamic_class());
for( Iterator<String> pathIt = Options.v().dynamic_dir().iterator(); pathIt.hasNext(); ) {
final String path = (String) pathIt.next();
dynClasses.addAll(SourceLocator.v().getClassesUnder(path));
}
for( Iterator<String> pkgIt = Options.v().dynamic_package().iterator(); pkgIt.hasNext(); ) {
final String pkg = (String) pkgIt.next();
dynClasses.addAll(SourceLocator.v().classesInDynamicPackage(pkg));
}
for (String className : dynClasses) {
dynamicClasses.add( loadClassAndSupport(className) );
}
//remove non-concrete classes that may accidentally have been loaded
for (Iterator<SootClass> iterator = dynamicClasses.iterator(); iterator.hasNext();) {
SootClass c = iterator.next();
if(!c.isConcrete()) {
if(Options.v().verbose()) {
G.v().out.println("Warning: dynamic class "+c.getName()+" is abstract or an interface, and it will not be considered.");
}
iterator.remove();
}
}
}
/* Generate classes to process, adding or removing package marked by
* command line options.
*/
private void prepareClasses() {
// Remove/add all classes from packageInclusionMask as per -i option
Chain<SootClass> processedClasses = new HashChain<SootClass>();
while(true) {
Chain<SootClass> unprocessedClasses = new HashChain<SootClass>(getClasses());
unprocessedClasses.removeAll(processedClasses);
if( unprocessedClasses.isEmpty() ) break;
processedClasses.addAll(unprocessedClasses);
for (SootClass s : unprocessedClasses) {
if( s.isPhantom() ) continue;
if(Options.v().app()) {
s.setApplicationClass();
}
if (Options.v().classes().contains(s.getName())) {
s.setApplicationClass();
continue;
}
for( Iterator<String> pkgIt = excludedPackages.iterator(); pkgIt.hasNext(); ) {
final String pkg = (String) pkgIt.next();
if (s.isApplicationClass()
&& (s.getPackageName()+".").startsWith(pkg)) {
s.setLibraryClass();
}
}
for( Iterator<String> pkgIt = Options.v().include().iterator(); pkgIt.hasNext(); ) {
final String pkg = (String) pkgIt.next();
if ((s.getPackageName()+".").startsWith(pkg))
s.setApplicationClass();
}
if(s.isApplicationClass()) {
// make sure we have the support
loadClassAndSupport(s.getName());
}
}
}
}
public boolean isExcluded(SootClass sc) {
String name = sc.getName();
for (String pkg : excludedPackages) {
if (name.startsWith(pkg)) {
for (String inc : (List<String>) Options.v().include()) {
if (name.startsWith(inc)) {
return false;
}
}
return true;
}
}
return false;
}
ArrayList<String> pkgList;
public void setPkgList(ArrayList<String> list){
pkgList = list;
}
public ArrayList<String> getPkgList(){
return pkgList;
}
/** Create an unresolved reference to a method. */
public SootMethodRef makeMethodRef(
SootClass declaringClass,
String name,
List<Type> parameterTypes,
Type returnType,
boolean isStatic ) {
return new SootMethodRefImpl(declaringClass, name, parameterTypes,
returnType, isStatic);
}
/** Create an unresolved reference to a constructor. */
public SootMethodRef makeConstructorRef(
SootClass declaringClass,
List<Type> parameterTypes) {
return makeMethodRef(declaringClass, SootMethod.constructorName,
parameterTypes, VoidType.v(), false );
}
/** Create an unresolved reference to a field. */
public SootFieldRef makeFieldRef(
SootClass declaringClass,
String name,
Type type,
boolean isStatic) {
return new AbstractSootFieldRef(declaringClass, name, type, isStatic);
}
/** Returns the list of SootClasses that have been resolved at least to
* the level specified. */
public List/*SootClass*/<SootClass> getClasses(int desiredLevel) {
List<SootClass> ret = new ArrayList<SootClass>();
for( Iterator<SootClass> clIt = getClasses().iterator(); clIt.hasNext(); ) {
final SootClass cl = (SootClass) clIt.next();
if( cl.resolvingLevel() >= desiredLevel ) ret.add(cl);
}
return ret;
}
private boolean doneResolving = false;
private boolean incrementalBuild;
protected LinkedList<String> excludedPackages;
public boolean doneResolving() { return doneResolving; }
public void setDoneResolving() { doneResolving = true; }
public void setMainClassFromOptions() {
if(mainClass != null) return;
if( Options.v().main_class() != null
&& Options.v().main_class().length() > 0 ) {
setMainClass(getSootClass(Options.v().main_class()));
} else {
// try to infer a main class from the command line if none is given
for (Iterator<String> classIter = Options.v().classes().iterator(); classIter.hasNext();) {
SootClass c = getSootClass(classIter.next());
if (c.declaresMethod ("main", new SingletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v()))
{
G.v().out.println("No main class given. Inferred '"+c.getName()+"' as main class.");
setMainClass(c);
return;
}
}
// try to infer a main class from the usual classpath if none is given
for (Iterator<SootClass> classIter = getApplicationClasses().iterator(); classIter.hasNext();) {
SootClass c = (SootClass) classIter.next();
if (c.declaresMethod ("main", new SingletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v()))
{
G.v().out.println("No main class given. Inferred '"+c.getName()+"' as main class.");
setMainClass(c);
return;
}
}
}
}
/**
* This method returns true when in incremental build mode.
* Other classes can query this flag and change the way in which they use the Scene,
* depending on the flag's value.
*/
public boolean isIncrementalBuild() {
return incrementalBuild;
}
public void initiateIncrementalBuild() {
this.incrementalBuild = true;
}
public void incrementalBuildFinished() {
this.incrementalBuild = false;
}
/*
* Forces Soot to resolve the class with the given name to the given level,
* even if resolving has actually already finished.
*/
public SootClass forceResolve(String className, int level) {
boolean tmp = doneResolving;
doneResolving = false;
SootClass c;
try {
c = SootResolver.v().resolveClass(className, level);
} finally {
doneResolving = tmp;
}
return c;
}
}
| src/soot/Scene.java | /* Soot - a J*va Optimization Framework
* Copyright (C) 1997-1999 Raja Vallee-Rai
* Copyright (C) 2004 Ondrej Lhotak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.ContextSensitiveCallGraph;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import soot.jimple.toolkits.pointer.DumbPointerAnalysis;
import soot.jimple.toolkits.pointer.SideEffectAnalysis;
import soot.options.CGOptions;
import soot.options.Options;
import soot.toolkits.exceptions.PedanticThrowAnalysis;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.exceptions.UnitThrowAnalysis;
import soot.util.ArrayNumberer;
import soot.util.Chain;
import soot.util.HashChain;
import soot.util.MapNumberer;
import soot.util.Numberer;
import soot.util.SingletonList;
import soot.util.StringNumberer;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.AXmlResourceParser;
import test.AXMLPrinter;
/** Manages the SootClasses of the application being analyzed. */
public class Scene //extends AbstractHost
{
public Scene ( Singletons.Global g )
{
setReservedNames();
// load soot.class.path system property, if defined
String scp = System.getProperty("soot.class.path");
if (scp != null)
setSootClassPath(scp);
kindNumberer.add( Kind.INVALID );
kindNumberer.add( Kind.STATIC );
kindNumberer.add( Kind.VIRTUAL );
kindNumberer.add( Kind.INTERFACE );
kindNumberer.add( Kind.SPECIAL );
kindNumberer.add( Kind.CLINIT );
kindNumberer.add( Kind.THREAD );
kindNumberer.add( Kind.FINALIZE );
kindNumberer.add( Kind.INVOKE_FINALIZE );
kindNumberer.add( Kind.PRIVILEGED );
kindNumberer.add( Kind.NEWINSTANCE );
addSootBasicClasses();
determineExcludedPackages();
}
private void determineExcludedPackages() {
excludedPackages = new LinkedList<String>();
if (Options.v().exclude() != null)
excludedPackages.addAll(Options.v().exclude());
if( !Options.v().include_all() ) {
excludedPackages.add("java.");
excludedPackages.add("sun.");
excludedPackages.add("javax.");
excludedPackages.add("com.sun.");
excludedPackages.add("com.ibm.");
excludedPackages.add("org.xml.");
excludedPackages.add("org.w3c.");
excludedPackages.add("apple.awt.");
excludedPackages.add("com.apple.");
}
}
public static Scene v() { return G.v().soot_Scene (); }
Chain<SootClass> classes = new HashChain<SootClass>();
Chain<SootClass> applicationClasses = new HashChain<SootClass>();
Chain<SootClass> libraryClasses = new HashChain<SootClass>();
Chain<SootClass> phantomClasses = new HashChain<SootClass>();
private final Map<String,Type> nameToClass = new HashMap<String,Type>();
ArrayNumberer kindNumberer = new ArrayNumberer();
ArrayNumberer typeNumberer = new ArrayNumberer();
ArrayNumberer methodNumberer = new ArrayNumberer();
Numberer unitNumberer = new MapNumberer();
Numberer contextNumberer = null;
ArrayNumberer fieldNumberer = new ArrayNumberer();
ArrayNumberer classNumberer = new ArrayNumberer();
StringNumberer subSigNumberer = new StringNumberer();
ArrayNumberer localNumberer = new ArrayNumberer();
private Hierarchy activeHierarchy;
private FastHierarchy activeFastHierarchy;
private CallGraph activeCallGraph;
private ReachableMethods reachableMethods;
private PointsToAnalysis activePointsToAnalysis;
private SideEffectAnalysis activeSideEffectAnalysis;
private List<SootMethod> entryPoints;
boolean allowsPhantomRefs = false;
SootClass mainClass;
String sootClassPath = null;
// Two default values for constructing ExceptionalUnitGraphs:
private ThrowAnalysis defaultThrowAnalysis = null;
public void setMainClass(SootClass m)
{
mainClass = m;
if(!m.declaresMethod(getSubSigNumberer().findOrAdd( "void main(java.lang.String[])" ))) {
throw new RuntimeException("Main-class has no main method!");
}
}
Set<String> reservedNames = new HashSet<String>();
/**
Returns a set of tokens which are reserved. Any field, class, method, or local variable with such a name will be quoted.
*/
public Set<String> getReservedNames()
{
return reservedNames;
}
/**
If this name is in the set of reserved names, then return a quoted version of it. Else pass it through.
*/
public String quotedNameOf(String s)
{
if(reservedNames.contains(s))
return "\'" + s + "\'";
else
return s;
}
public boolean hasMainClass() {
if(mainClass == null) {
setMainClassFromOptions();
}
return mainClass!=null;
}
public SootClass getMainClass()
{
if(!hasMainClass())
throw new RuntimeException("There is no main class set!");
return mainClass;
}
public SootMethod getMainMethod() {
if(mainClass==null) {
throw new RuntimeException("There is no main class set!");
}
if (!mainClass.declaresMethod ("main", new SingletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v())) {
throw new RuntimeException("Main class declares no main method!");
}
return mainClass.getMethod ("main", new SingletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v());
}
public void setSootClassPath(String p)
{
sootClassPath = p;
SourceLocator.v().invalidateClassPath();
}
public String getSootClassPath()
{
if( sootClassPath == null ) {
String optionscp = Options.v().soot_classpath();
if( optionscp.length() > 0 )
sootClassPath = optionscp;
String defaultSootClassPath = defaultClassPath();
//if no classpath is given on the command line, take the default
if( sootClassPath == null ) {
sootClassPath = defaultSootClassPath;
} else {
//if one is given...
if(Options.v().prepend_classpath()) {
//if the prepend flag is set, append the default classpath
sootClassPath += File.pathSeparator + defaultSootClassPath;
}
//else, leave it as it is
}
//add process-dirs
List<String> process_dir = Options.v().process_dir();
StringBuffer pds = new StringBuffer();
for (String path : process_dir) {
if(!sootClassPath.contains(path)) {
pds.append(path);
pds.append(File.pathSeparator);
}
}
sootClassPath = pds + sootClassPath;
}
return sootClassPath;
}
public String getAndroidJarPath(String jars, String apk) {
File jarsF = new File(jars);
File apkF = new File(apk);
int APIVersion = -1;
String jarPath = "";
if (!jarsF.exists())
throw new RuntimeException("file '" + jars + "' does not exist!");
if (!apkF.exists())
throw new RuntimeException("file '" + apk + "' does not exist!");
// get AndroidManifest
InputStream manifestIS = null;
try {
ZipFile archive = new ZipFile(apkF);
for (@SuppressWarnings("rawtypes") Enumeration entries = archive.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String entryName = entry.getName();
// We are dealing with the Android manifest
if (entryName.equals("AndroidManifest.xml")) {
manifestIS = archive.getInputStream(entry);
break;
}
}
} catch (Exception e) {
throw new RuntimeException("Error when looking for manifest in apk: " + e);
}
final int defaultSdkVersion = 15;
if (manifestIS == null) {
G.v().out.println("Could not find sdk version in Android manifest! Using default: "+defaultSdkVersion);
APIVersion = defaultSdkVersion;
} else {
// process AndroidManifest.xml
int sdkTargetVersion = -1;
int minSdkVersion = -1;
try {
AXmlResourceParser parser = new AXmlResourceParser();
parser.open(manifestIS);
int depth = 0;
while (true) {
int type = parser.next();
if (type == XmlPullParser.END_DOCUMENT) {
// throw new RuntimeException
// ("target sdk version not found in Android manifest ("+
// apkF +")");
break;
}
switch (type) {
case XmlPullParser.START_DOCUMENT: {
break;
}
case XmlPullParser.START_TAG: {
depth++;
String tagName = parser.getName();
if (depth == 2 && tagName.equals("uses-sdk")) {
for (int i = 0; i != parser.getAttributeCount(); ++i) {
String attributeName = parser.getAttributeName(i);
String attributeValue = AXMLPrinter.getAttributeValue(parser, i);
if (attributeName.equals("targetSdkVersion")) {
sdkTargetVersion = Integer.parseInt(attributeValue);
} else if (attributeName.equals("minSdkVersion")) {
minSdkVersion = Integer.parseInt(attributeValue);
}
}
}
break;
}
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.TEXT:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (sdkTargetVersion != -1) {
APIVersion = sdkTargetVersion;
} else if (minSdkVersion != -1) {
APIVersion = minSdkVersion;
} else {
G.v().out.println("Could not find sdk version in Android manifest! Using default: "+defaultSdkVersion);
APIVersion = defaultSdkVersion;
}
if (APIVersion <= 2)
APIVersion = 3;
}
// get path to appropriate android.jar
jarPath = jars + File.separator + "android-" + APIVersion + File.separator + "android.jar";
return jarPath;
}
public String defaultClassPath() {
StringBuffer sb = new StringBuffer();
if(System.getProperty("os.name").equals("Mac OS X")) {
//in older Mac OS X versions, rt.jar was split into classes.jar and ui.jar
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("..");
sb.append(File.separator);
sb.append("Classes");
sb.append(File.separator);
sb.append("classes.jar");
sb.append(File.pathSeparator);
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("..");
sb.append(File.separator);
sb.append("Classes");
sb.append(File.separator);
sb.append("ui.jar");
sb.append(File.pathSeparator);
}
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("lib");
sb.append(File.separator);
sb.append("rt.jar");
if(Options.v().whole_program() || Options.v().output_format()==Options.output_format_dava) {
//add jce.jar, which is necessary for whole program mode
//(java.security.Signature from rt.jar import javax.crypto.Cipher from jce.jar
sb.append(File.pathSeparator+
System.getProperty("java.home")+File.separator+"lib"+File.separator+"jce.jar");
}
String defaultClassPath = sb.toString();
if (Options.v().src_prec() == Options.src_prec_apk) {
// check that android.jar is not in classpath
if (!defaultClassPath.contains ("android.jar")) {
String androidJars = Options.v().android_jars();
String forceAndroidJar = Options.v().force_android_jar();
if (androidJars.equals("") && forceAndroidJar.equals("")) {
throw new RuntimeException("You are analyzing an Android application but did not define android.jar. Options -android-jars or -force-android-jar should be used.");
}
String jarPath = "";
if (!forceAndroidJar.equals("")) {
jarPath = forceAndroidJar;
} else if (!androidJars.equals("")) {
List<String> classPathEntries = new LinkedList<String>(Arrays.asList(Options.v().soot_classpath().split(File.pathSeparator)));
classPathEntries.addAll(Options.v().process_dir());
Set<String> targetApks = new HashSet<String>();
for (String entry : classPathEntries) {
if(entry.endsWith(".apk"))
targetApks.add(entry);
}
if (targetApks.size() == 0)
throw new RuntimeException("no apk file given");
else if (targetApks.size() > 1)
throw new RuntimeException("only one Android application can be analyzed when using option -android-jars.");
jarPath = getAndroidJarPath (androidJars, (String)targetApks.toArray()[0]);
}
if (jarPath.equals(""))
throw new RuntimeException("android.jar not found.");
File f = new File (jarPath);
if (!f.exists())
throw new RuntimeException("file '"+ jarPath +"' does not exist!");
else
G.v().out.println("Using '"+ jarPath +"' as android.jar");
defaultClassPath = jarPath + File.pathSeparator + defaultClassPath;
} else {
G.v().out.println("warning: defaultClassPath contains android.jar! Options -android-jars and -force-android-jar are ignored!");
}
}
return defaultClassPath;
}
private int stateCount;
public int getState() { return this.stateCount; }
private void modifyHierarchy() {
stateCount++;
activeHierarchy = null;
activeFastHierarchy = null;
activeSideEffectAnalysis = null;
activePointsToAnalysis = null;
}
public void addClass(SootClass c)
{
if(c.isInScene())
throw new RuntimeException("already managed: "+c.getName());
if(containsClass(c.getName()))
throw new RuntimeException("duplicate class: "+c.getName());
classes.add(c);
c.setLibraryClass();
nameToClass.put(c.getName(), c.getType());
c.getType().setSootClass(c);
c.setInScene(true);
modifyHierarchy();
}
public void removeClass(SootClass c)
{
if(!c.isInScene())
throw new RuntimeException();
classes.remove(c);
if(c.isLibraryClass()) {
libraryClasses.remove(c);
} else if(c.isPhantomClass()) {
phantomClasses.remove(c);
} else if(c.isApplicationClass()) {
applicationClasses.remove(c);
}
c.getType().setSootClass(null);
c.setInScene(false);
modifyHierarchy();
}
public boolean containsClass(String className)
{
RefType type = (RefType) nameToClass.get(className);
if( type == null ) return false;
if( !type.hasSootClass() ) return false;
SootClass c = type.getSootClass();
return c.isInScene();
}
public boolean containsType(String className)
{
return nameToClass.containsKey(className);
}
public String signatureToClass(String sig) {
if( sig.charAt(0) != '<' ) throw new RuntimeException("oops "+sig);
if( sig.charAt(sig.length()-1) != '>' ) throw new RuntimeException("oops "+sig);
int index = sig.indexOf( ":" );
if( index < 0 ) throw new RuntimeException("oops "+sig);
return sig.substring(1,index);
}
public String signatureToSubsignature(String sig) {
if( sig.charAt(0) != '<' ) throw new RuntimeException("oops "+sig);
if( sig.charAt(sig.length()-1) != '>' ) throw new RuntimeException("oops "+sig);
int index = sig.indexOf( ":" );
if( index < 0 ) throw new RuntimeException("oops "+sig);
return sig.substring(index+2,sig.length()-1);
}
private SootField grabField(String fieldSignature)
{
String cname = signatureToClass( fieldSignature );
String fname = signatureToSubsignature( fieldSignature );
if( !containsClass(cname) ) return null;
SootClass c = getSootClass(cname);
if( !c.declaresField( fname ) ) return null;
return c.getField( fname );
}
public boolean containsField(String fieldSignature)
{
return grabField(fieldSignature) != null;
}
private SootMethod grabMethod(String methodSignature)
{
String cname = signatureToClass( methodSignature );
String mname = signatureToSubsignature( methodSignature );
if( !containsClass(cname) ) return null;
SootClass c = getSootClass(cname);
if( !c.declaresMethod( mname ) ) return null;
return c.getMethod( mname );
}
public boolean containsMethod(String methodSignature)
{
return grabMethod(methodSignature) != null;
}
public SootField getField(String fieldSignature)
{
SootField f = grabField( fieldSignature );
if (f != null)
return f;
throw new RuntimeException("tried to get nonexistent field "+fieldSignature);
}
public SootMethod getMethod(String methodSignature)
{
SootMethod m = grabMethod( methodSignature );
if (m != null)
return m;
throw new RuntimeException("tried to get nonexistent method "+methodSignature);
}
/**
* Attempts to load the given class and all of the required support classes.
* Returns the original class if it was loaded, or null otherwise.
*/
public SootClass tryLoadClass(String className, int desiredLevel)
{
/*
if(Options.v().time())
Main.v().resolveTimer.start();
*/
setPhantomRefs(true);
//SootResolver resolver = new SootResolver();
if( !getPhantomRefs()
&& SourceLocator.v().getClassSource(className) == null ) {
setPhantomRefs(false);
return null;
}
SootResolver resolver = SootResolver.v();
SootClass toReturn = resolver.resolveClass(className, desiredLevel);
setPhantomRefs(false);
return toReturn;
/*
if(Options.v().time())
Main.v().resolveTimer.end(); */
}
/**
* Loads the given class and all of the required support classes. Returns the first class.
*/
public SootClass loadClassAndSupport(String className)
{
SootClass ret = loadClass(className, SootClass.SIGNATURES);
if( !ret.isPhantom() ) ret = loadClass(className, SootClass.BODIES);
return ret;
}
public SootClass loadClass(String className, int desiredLevel)
{
/*
if(Options.v().time())
Main.v().resolveTimer.start();
*/
setPhantomRefs(true);
//SootResolver resolver = new SootResolver();
SootResolver resolver = SootResolver.v();
SootClass toReturn = resolver.resolveClass(className, desiredLevel);
setPhantomRefs(false);
return toReturn;
/*
if(Options.v().time())
Main.v().resolveTimer.end(); */
}
/**
* Returns the RefType with the given className.
* @throws IllegalStateException if the RefType for this class cannot be found.
* Use {@link #containsType(String)} to check if type is registered
*/
public RefType getRefType(String className)
{
RefType refType = (RefType) nameToClass.get(className);
if(refType==null) {
throw new IllegalStateException("RefType "+className+" not loaded. " +
"If you tried to get the RefType of a library class, did you call loadNecessaryClasses()? " +
"Otherwise please check Soot's classpath.");
}
return refType;
}
/**
* Returns the {@link RefType} for {@link Object}.
*/
public RefType getObjectType() {
return getRefType("java.lang.Object");
}
/**
* Returns the RefType with the given className.
*/
public void addRefType(RefType type)
{
nameToClass.put(type.getClassName(), type);
}
/**
* Returns the SootClass with the given className.
*/
public SootClass getSootClass(String className) {
RefType type = (RefType) nameToClass.get(className);
SootClass toReturn = null;
if (type != null)
toReturn = type.getSootClass();
if (toReturn != null) {
return toReturn;
} else if (allowsPhantomRefs() ||
className.equals(SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME)) {
SootClass c = new SootClass(className);
addClass(c);
c.setPhantom(true);
return c;
} else {
throw new RuntimeException(System.getProperty("line.separator")
+ "Aborting: can't find classfile " + className);
}
}
/**
* Returns an backed chain of the classes in this manager.
*/
public Chain<SootClass> getClasses()
{
return classes;
}
/* The four following chains are mutually disjoint. */
/**
* Returns a chain of the application classes in this scene.
* These classes are the ones which can be freely analysed & modified.
*/
public Chain<SootClass> getApplicationClasses()
{
return applicationClasses;
}
/**
* Returns a chain of the library classes in this scene.
* These classes can be analysed but not modified.
*/
public Chain<SootClass> getLibraryClasses()
{
return libraryClasses;
}
/**
* Returns a chain of the phantom classes in this scene.
* These classes are referred to by other classes, but cannot be loaded.
*/
public Chain<SootClass> getPhantomClasses()
{
return phantomClasses;
}
Chain<SootClass> getContainingChain(SootClass c)
{
if (c.isApplicationClass())
return getApplicationClasses();
else if (c.isLibraryClass())
return getLibraryClasses();
else if (c.isPhantomClass())
return getPhantomClasses();
return null;
}
/****************************************************************************/
/**
Retrieves the active side-effect analysis
*/
public SideEffectAnalysis getSideEffectAnalysis()
{
if(!hasSideEffectAnalysis()) {
setSideEffectAnalysis( new SideEffectAnalysis(
getPointsToAnalysis(),
getCallGraph() ) );
}
return activeSideEffectAnalysis;
}
/**
Sets the active side-effect analysis
*/
public void setSideEffectAnalysis(SideEffectAnalysis sea)
{
activeSideEffectAnalysis = sea;
}
public boolean hasSideEffectAnalysis()
{
return activeSideEffectAnalysis != null;
}
public void releaseSideEffectAnalysis()
{
activeSideEffectAnalysis = null;
}
/****************************************************************************/
/**
Retrieves the active pointer analysis
*/
public PointsToAnalysis getPointsToAnalysis()
{
if(!hasPointsToAnalysis()) {
return DumbPointerAnalysis.v();
}
return activePointsToAnalysis;
}
/**
Sets the active pointer analysis
*/
public void setPointsToAnalysis(PointsToAnalysis pa)
{
activePointsToAnalysis = pa;
}
public boolean hasPointsToAnalysis()
{
return activePointsToAnalysis != null;
}
public void releasePointsToAnalysis()
{
activePointsToAnalysis = null;
}
/****************************************************************************/
/** Makes a new fast hierarchy is none is active, and returns the active
* fast hierarchy. */
public FastHierarchy getOrMakeFastHierarchy() {
if(!hasFastHierarchy() ) {
setFastHierarchy( new FastHierarchy() );
}
return getFastHierarchy();
}
/**
Retrieves the active fast hierarchy
*/
public FastHierarchy getFastHierarchy()
{
if(!hasFastHierarchy())
throw new RuntimeException("no active FastHierarchy present for scene");
return activeFastHierarchy;
}
/**
Sets the active hierarchy
*/
public void setFastHierarchy(FastHierarchy hierarchy)
{
activeFastHierarchy = hierarchy;
}
public boolean hasFastHierarchy()
{
return activeFastHierarchy != null;
}
public void releaseFastHierarchy()
{
activeFastHierarchy = null;
}
/****************************************************************************/
/**
Retrieves the active hierarchy
*/
public Hierarchy getActiveHierarchy()
{
if(!hasActiveHierarchy())
//throw new RuntimeException("no active Hierarchy present for scene");
setActiveHierarchy( new Hierarchy() );
return activeHierarchy;
}
/**
Sets the active hierarchy
*/
public void setActiveHierarchy(Hierarchy hierarchy)
{
activeHierarchy = hierarchy;
}
public boolean hasActiveHierarchy()
{
return activeHierarchy != null;
}
public void releaseActiveHierarchy()
{
activeHierarchy = null;
}
public boolean hasCustomEntryPoints() {
return entryPoints!=null;
}
/** Get the set of entry points that are used to build the call graph. */
public List<SootMethod> getEntryPoints() {
if( entryPoints == null ) {
entryPoints = EntryPoints.v().all();
}
return entryPoints;
}
/** Change the set of entry point methods used to build the call graph. */
public void setEntryPoints( List<SootMethod> entryPoints ) {
this.entryPoints = entryPoints;
}
private ContextSensitiveCallGraph cscg;
public ContextSensitiveCallGraph getContextSensitiveCallGraph() {
if(cscg == null) throw new RuntimeException("No context-sensitive call graph present in Scene. You can bulid one with Paddle.");
return cscg;
}
public void setContextSensitiveCallGraph(ContextSensitiveCallGraph cscg) {
this.cscg = cscg;
}
public CallGraph getCallGraph()
{
if(!hasCallGraph()) {
throw new RuntimeException( "No call graph present in Scene. Maybe you want Whole Program mode (-w)." );
}
return activeCallGraph;
}
public void setCallGraph(CallGraph cg)
{
reachableMethods = null;
activeCallGraph = cg;
}
public boolean hasCallGraph()
{
return activeCallGraph != null;
}
public void releaseCallGraph()
{
activeCallGraph = null;
reachableMethods = null;
}
public ReachableMethods getReachableMethods() {
if( reachableMethods == null ) {
reachableMethods = new ReachableMethods(
getCallGraph(), new ArrayList<MethodOrMethodContext>(getEntryPoints()) );
}
reachableMethods.update();
return reachableMethods;
}
public void setReachableMethods( ReachableMethods rm ) {
reachableMethods = rm;
}
public boolean hasReachableMethods() {
return reachableMethods != null;
}
public void releaseReachableMethods() {
reachableMethods = null;
}
public boolean getPhantomRefs()
{
//if( !Options.v().allow_phantom_refs() ) return false;
//return allowsPhantomRefs;
return Options.v().allow_phantom_refs();
}
public void setPhantomRefs(boolean value)
{
allowsPhantomRefs = value;
}
public boolean allowsPhantomRefs()
{
return getPhantomRefs();
}
public Numberer kindNumberer() { return kindNumberer; }
public ArrayNumberer getTypeNumberer() { return typeNumberer; }
public ArrayNumberer getMethodNumberer() { return methodNumberer; }
public Numberer getContextNumberer() { return contextNumberer; }
public Numberer getUnitNumberer() { return unitNumberer; }
public ArrayNumberer getFieldNumberer() { return fieldNumberer; }
public ArrayNumberer getClassNumberer() { return classNumberer; }
public StringNumberer getSubSigNumberer() { return subSigNumberer; }
public ArrayNumberer getLocalNumberer() { return localNumberer; }
public void setContextNumberer( Numberer n ) {
if( contextNumberer != null )
throw new RuntimeException(
"Attempt to set context numberer when it is already set." );
contextNumberer = n;
}
/**
* Returns the {@link ThrowAnalysis} to be used by default when
* constructing CFGs which include exceptional control flow.
*
* @return the default {@link ThrowAnalysis}
*/
public ThrowAnalysis getDefaultThrowAnalysis()
{
if( defaultThrowAnalysis == null ) {
int optionsThrowAnalysis = Options.v().throw_analysis();
switch (optionsThrowAnalysis) {
case Options.throw_analysis_pedantic:
defaultThrowAnalysis = PedanticThrowAnalysis.v();
break;
case Options.throw_analysis_unit:
defaultThrowAnalysis = UnitThrowAnalysis.v();
break;
default:
throw new IllegalStateException("Options.v().throw_analysi() == " +
Options.v().throw_analysis());
}
}
return defaultThrowAnalysis;
}
/**
* Sets the {@link ThrowAnalysis} to be used by default when
* constructing CFGs which include exceptional control flow.
*
* @param ta the default {@link ThrowAnalysis}.
*/
public void setDefaultThrowAnalysis(ThrowAnalysis ta)
{
defaultThrowAnalysis = ta;
}
private void setReservedNames()
{
Set<String> rn = getReservedNames();
rn.add("newarray");
rn.add("newmultiarray");
rn.add("nop");
rn.add("ret");
rn.add("specialinvoke");
rn.add("staticinvoke");
rn.add("tableswitch");
rn.add("virtualinvoke");
rn.add("null_type");
rn.add("unknown");
rn.add("cmp");
rn.add("cmpg");
rn.add("cmpl");
rn.add("entermonitor");
rn.add("exitmonitor");
rn.add("interfaceinvoke");
rn.add("lengthof");
rn.add("lookupswitch");
rn.add("neg");
rn.add("if");
rn.add("abstract");
rn.add("annotation");
rn.add("boolean");
rn.add("break");
rn.add("byte");
rn.add("case");
rn.add("catch");
rn.add("char");
rn.add("class");
rn.add("final");
rn.add("native");
rn.add("public");
rn.add("protected");
rn.add("private");
rn.add("static");
rn.add("synchronized");
rn.add("transient");
rn.add("volatile");
rn.add("interface");
rn.add("void");
rn.add("short");
rn.add("int");
rn.add("long");
rn.add("float");
rn.add("double");
rn.add("extends");
rn.add("implements");
rn.add("breakpoint");
rn.add("default");
rn.add("goto");
rn.add("instanceof");
rn.add("new");
rn.add("return");
rn.add("throw");
rn.add("throws");
rn.add("null");
rn.add("from");
rn.add("to");
}
private final Set<String>[] basicclasses=new Set[4];
private void addSootBasicClasses() {
basicclasses[SootClass.HIERARCHY] = new HashSet<String>();
basicclasses[SootClass.SIGNATURES] = new HashSet<String>();
basicclasses[SootClass.BODIES] = new HashSet<String>();
addBasicClass("java.lang.Object");
addBasicClass("java.lang.Class", SootClass.SIGNATURES);
addBasicClass("java.lang.Void", SootClass.SIGNATURES);
addBasicClass("java.lang.Boolean", SootClass.SIGNATURES);
addBasicClass("java.lang.Byte", SootClass.SIGNATURES);
addBasicClass("java.lang.Character", SootClass.SIGNATURES);
addBasicClass("java.lang.Short", SootClass.SIGNATURES);
addBasicClass("java.lang.Integer", SootClass.SIGNATURES);
addBasicClass("java.lang.Long", SootClass.SIGNATURES);
addBasicClass("java.lang.Float", SootClass.SIGNATURES);
addBasicClass("java.lang.Double", SootClass.SIGNATURES);
addBasicClass("java.lang.String");
addBasicClass("java.lang.StringBuffer", SootClass.SIGNATURES);
addBasicClass("java.lang.Error");
addBasicClass("java.lang.AssertionError", SootClass.SIGNATURES);
addBasicClass("java.lang.Throwable", SootClass.SIGNATURES);
addBasicClass("java.lang.NoClassDefFoundError", SootClass.SIGNATURES);
addBasicClass("java.lang.ExceptionInInitializerError");
addBasicClass("java.lang.RuntimeException");
addBasicClass("java.lang.ClassNotFoundException");
addBasicClass("java.lang.ArithmeticException");
addBasicClass("java.lang.ArrayStoreException");
addBasicClass("java.lang.ClassCastException");
addBasicClass("java.lang.IllegalMonitorStateException");
addBasicClass("java.lang.IndexOutOfBoundsException");
addBasicClass("java.lang.ArrayIndexOutOfBoundsException");
addBasicClass("java.lang.NegativeArraySizeException");
addBasicClass("java.lang.NullPointerException");
addBasicClass("java.lang.InstantiationError");
addBasicClass("java.lang.InternalError");
addBasicClass("java.lang.OutOfMemoryError");
addBasicClass("java.lang.StackOverflowError");
addBasicClass("java.lang.UnknownError");
addBasicClass("java.lang.ThreadDeath");
addBasicClass("java.lang.ClassCircularityError");
addBasicClass("java.lang.ClassFormatError");
addBasicClass("java.lang.IllegalAccessError");
addBasicClass("java.lang.IncompatibleClassChangeError");
addBasicClass("java.lang.LinkageError");
addBasicClass("java.lang.VerifyError");
addBasicClass("java.lang.NoSuchFieldError");
addBasicClass("java.lang.AbstractMethodError");
addBasicClass("java.lang.NoSuchMethodError");
addBasicClass("java.lang.UnsatisfiedLinkError");
addBasicClass("java.lang.Thread");
addBasicClass("java.lang.Runnable");
addBasicClass("java.lang.Cloneable");
addBasicClass("java.io.Serializable");
addBasicClass("java.lang.ref.Finalizer");
}
public void addBasicClass(String name) {
addBasicClass(name,SootClass.HIERARCHY);
}
public void addBasicClass(String name,int level) {
basicclasses[level].add(name);
}
/** Load just the set of basic classes soot needs, ignoring those
* specified on the command-line. You don't need to use both this and
* loadNecessaryClasses, though it will only waste time.
*/
public void loadBasicClasses() {
addReflectionTraceClasses();
for(int i=SootClass.BODIES;i>=SootClass.HIERARCHY;i--) {
for(String name: basicclasses[i]) {
tryLoadClass(name,i);
}
}
}
public Set<String> getBasicClasses() {
Set<String> all = new HashSet<String>();
for(int i=0;i<basicclasses.length;i++) {
Set<String> classes = basicclasses[i];
if(classes!=null)
all.addAll(classes);
}
return all;
}
private void addReflectionTraceClasses() {
CGOptions options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
String log = options.reflection_log();
Set<String> classNames = new HashSet<String>();
if(log!=null && log.length()>0) {
BufferedReader reader;
String line="";
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(log)));
while((line=reader.readLine())!=null) {
if(line.length()==0) continue;
String[] portions = line.split(";",-1);
String kind = portions[0];
String target = portions[1];
String source = portions[2];
String sourceClassName = source.substring(0,source.lastIndexOf("."));
classNames.add(sourceClassName);
if(kind.equals("Class.forName")) {
classNames.add(target);
} else if(kind.equals("Class.newInstance")) {
classNames.add(target);
} else if(kind.equals("Method.invoke") || kind.equals("Constructor.newInstance")) {
classNames.add(signatureToClass(target));
} else if(kind.equals("Field.set*") || kind.equals("Field.get*")) {
classNames.add(signatureToClass(target));
} else throw new RuntimeException("Unknown entry kind: "+kind);
}
} catch (Exception e) {
throw new RuntimeException("Line: '"+line+"'", e);
}
}
for (String c : classNames) {
addBasicClass(c, SootClass.BODIES);
}
}
private List<SootClass> dynamicClasses;
public Collection<SootClass> dynamicClasses() {
if(dynamicClasses==null) {
throw new IllegalStateException("Have to call loadDynamicClasses() first!");
}
return dynamicClasses;
}
private void loadNecessaryClass(String name) {
SootClass c;
c = loadClassAndSupport(name);
c.setApplicationClass();
}
/** Load the set of classes that soot needs, including those specified on the
* command-line. This is the standard way of initialising the list of
* classes soot should use.
*/
public void loadNecessaryClasses() {
loadBasicClasses();
Iterator<String> it = Options.v().classes().iterator();
while (it.hasNext()) {
String name = (String) it.next();
loadNecessaryClass(name);
}
loadDynamicClasses();
if(Options.v().oaat()) {
if(Options.v().process_dir().isEmpty()) {
throw new IllegalArgumentException("If switch -oaat is used, then also -process-dir must be given.");
}
} else {
for( Iterator<String> pathIt = Options.v().process_dir().iterator(); pathIt.hasNext(); ) {
final String path = (String) pathIt.next();
for (String cl : SourceLocator.v().getClassesUnder(path)) {
loadClassAndSupport(cl).setApplicationClass();
}
}
}
prepareClasses();
setDoneResolving();
}
public void loadDynamicClasses() {
dynamicClasses = new ArrayList<SootClass>();
HashSet<String> dynClasses = new HashSet<String>();
dynClasses.addAll(Options.v().dynamic_class());
for( Iterator<String> pathIt = Options.v().dynamic_dir().iterator(); pathIt.hasNext(); ) {
final String path = (String) pathIt.next();
dynClasses.addAll(SourceLocator.v().getClassesUnder(path));
}
for( Iterator<String> pkgIt = Options.v().dynamic_package().iterator(); pkgIt.hasNext(); ) {
final String pkg = (String) pkgIt.next();
dynClasses.addAll(SourceLocator.v().classesInDynamicPackage(pkg));
}
for (String className : dynClasses) {
dynamicClasses.add( loadClassAndSupport(className) );
}
//remove non-concrete classes that may accidentally have been loaded
for (Iterator<SootClass> iterator = dynamicClasses.iterator(); iterator.hasNext();) {
SootClass c = iterator.next();
if(!c.isConcrete()) {
if(Options.v().verbose()) {
G.v().out.println("Warning: dynamic class "+c.getName()+" is abstract or an interface, and it will not be considered.");
}
iterator.remove();
}
}
}
/* Generate classes to process, adding or removing package marked by
* command line options.
*/
private void prepareClasses() {
// Remove/add all classes from packageInclusionMask as per -i option
Chain<SootClass> processedClasses = new HashChain<SootClass>();
while(true) {
Chain<SootClass> unprocessedClasses = new HashChain<SootClass>(getClasses());
unprocessedClasses.removeAll(processedClasses);
if( unprocessedClasses.isEmpty() ) break;
processedClasses.addAll(unprocessedClasses);
for (SootClass s : unprocessedClasses) {
if( s.isPhantom() ) continue;
if(Options.v().app()) {
s.setApplicationClass();
}
if (Options.v().classes().contains(s.getName())) {
s.setApplicationClass();
continue;
}
for( Iterator<String> pkgIt = excludedPackages.iterator(); pkgIt.hasNext(); ) {
final String pkg = (String) pkgIt.next();
if (s.isApplicationClass()
&& (s.getPackageName()+".").startsWith(pkg)) {
s.setLibraryClass();
}
}
for( Iterator<String> pkgIt = Options.v().include().iterator(); pkgIt.hasNext(); ) {
final String pkg = (String) pkgIt.next();
if ((s.getPackageName()+".").startsWith(pkg))
s.setApplicationClass();
}
if(s.isApplicationClass()) {
// make sure we have the support
loadClassAndSupport(s.getName());
}
}
}
}
public boolean isExcluded(SootClass sc) {
String name = sc.getName();
for (String pkg : excludedPackages) {
if (name.startsWith(pkg)) {
for (String inc : (List<String>) Options.v().include()) {
if (name.startsWith(inc)) {
return false;
}
}
return true;
}
}
return false;
}
ArrayList<String> pkgList;
public void setPkgList(ArrayList<String> list){
pkgList = list;
}
public ArrayList<String> getPkgList(){
return pkgList;
}
/** Create an unresolved reference to a method. */
public SootMethodRef makeMethodRef(
SootClass declaringClass,
String name,
List<Type> parameterTypes,
Type returnType,
boolean isStatic ) {
return new SootMethodRefImpl(declaringClass, name, parameterTypes,
returnType, isStatic);
}
/** Create an unresolved reference to a constructor. */
public SootMethodRef makeConstructorRef(
SootClass declaringClass,
List<Type> parameterTypes) {
return makeMethodRef(declaringClass, SootMethod.constructorName,
parameterTypes, VoidType.v(), false );
}
/** Create an unresolved reference to a field. */
public SootFieldRef makeFieldRef(
SootClass declaringClass,
String name,
Type type,
boolean isStatic) {
return new AbstractSootFieldRef(declaringClass, name, type, isStatic);
}
/** Returns the list of SootClasses that have been resolved at least to
* the level specified. */
public List/*SootClass*/<SootClass> getClasses(int desiredLevel) {
List<SootClass> ret = new ArrayList<SootClass>();
for( Iterator<SootClass> clIt = getClasses().iterator(); clIt.hasNext(); ) {
final SootClass cl = (SootClass) clIt.next();
if( cl.resolvingLevel() >= desiredLevel ) ret.add(cl);
}
return ret;
}
private boolean doneResolving = false;
private boolean incrementalBuild;
protected LinkedList<String> excludedPackages;
public boolean doneResolving() { return doneResolving; }
public void setDoneResolving() { doneResolving = true; }
public void setMainClassFromOptions() {
if(mainClass != null) return;
if( Options.v().main_class() != null
&& Options.v().main_class().length() > 0 ) {
setMainClass(getSootClass(Options.v().main_class()));
} else {
// try to infer a main class from the command line if none is given
for (Iterator<String> classIter = Options.v().classes().iterator(); classIter.hasNext();) {
SootClass c = getSootClass(classIter.next());
if (c.declaresMethod ("main", new SingletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v()))
{
G.v().out.println("No main class given. Inferred '"+c.getName()+"' as main class.");
setMainClass(c);
return;
}
}
// try to infer a main class from the usual classpath if none is given
for (Iterator<SootClass> classIter = getApplicationClasses().iterator(); classIter.hasNext();) {
SootClass c = (SootClass) classIter.next();
if (c.declaresMethod ("main", new SingletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v()))
{
G.v().out.println("No main class given. Inferred '"+c.getName()+"' as main class.");
setMainClass(c);
return;
}
}
}
}
/**
* This method returns true when in incremental build mode.
* Other classes can query this flag and change the way in which they use the Scene,
* depending on the flag's value.
*/
public boolean isIncrementalBuild() {
return incrementalBuild;
}
public void initiateIncrementalBuild() {
this.incrementalBuild = true;
}
public void incrementalBuildFinished() {
this.incrementalBuild = false;
}
/*
* Forces Soot to resolve the class with the given name to the given level,
* even if resolving has actually already finished.
*/
public SootClass forceResolve(String className, int level) {
boolean tmp = doneResolving;
doneResolving = false;
SootClass c;
try {
c = SootResolver.v().resolveClass(className, level);
} finally {
doneResolving = tmp;
}
return c;
}
}
| Scene fields are now private
| src/soot/Scene.java | Scene fields are now private |
|
Java | unlicense | 38d364ee02db42feb5b965fb2b99813be3093026 | 0 | SleepyTrousers/EnderIO,HenryLoenwind/EnderIO | package crazypants.enderio.conduits.conduit.liquid;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import javax.annotation.Nonnull;
import com.enderio.core.common.fluid.IFluidWrapper.ITankInfoWrapper;
import com.enderio.core.common.util.RoundRobinIterator;
import crazypants.enderio.base.conduit.item.FunctionUpgrade;
import crazypants.enderio.base.conduit.item.ItemFunctionUpgrade;
import crazypants.enderio.base.filter.fluid.IFluidFilter;
import crazypants.enderio.conduits.conduit.AbstractConduitNetwork;
import crazypants.enderio.conduits.config.ConduitConfig;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidTankProperties;
public class EnderLiquidConduitNetwork extends AbstractConduitNetwork<ILiquidConduit, EnderLiquidConduit> {
List<NetworkTank> tanks = new ArrayList<NetworkTank>();
Map<NetworkTankKey, NetworkTank> tankMap = new HashMap<NetworkTankKey, NetworkTank>();
Set<NetworkTankKey> hasMultipleTanksSet = new HashSet<NetworkTankKey>();
Map<NetworkTank, RoundRobinIterator<NetworkTank>> iterators;
boolean filling;
public EnderLiquidConduitNetwork() {
super(EnderLiquidConduit.class, ILiquidConduit.class);
}
public void connectionChanged(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
NetworkTankKey key = new NetworkTankKey(con, conDir);
NetworkTank tank = new NetworkTank(con, conDir);
tanks.remove(tank); // remove old tank, NB: =/hash is only calced on location and dir
tanks.add(tank);
tankMap.remove(key);
tankMap.put(key, tank);
hasMultipleTanksSet.remove(key);
if (tank.isValid() && !tank.externalTank.getTankInfoWrappers().isEmpty()) {
hasMultipleTanksSet.add(key);
}
tanks.sort((left, right) -> right.priority - left.priority);
}
public boolean extractFrom(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
NetworkTank tank = getTank(con, conDir);
if (!tank.isValid()) {
return false;
}
FluidStack drained = tank.externalTank.getAvailableFluid();
boolean firstTry = tryExtract(con, conDir, tank, drained);
if (!firstTry && hasMultipleTanksSet.contains(new NetworkTankKey(con, conDir))) {
for (ITankInfoWrapper tankInfoWrapper : tank.externalTank.getTankInfoWrappers()) {
FluidStack toDrain = tankInfoWrapper.getIFluidTankProperties().getContents();
// Don't try to drain the same fluid twice
if (toDrain != null && toDrain.isFluidEqual(drained)) {
continue;
}
if (tryExtract(con, conDir, tank, toDrain)) {
return true;
}
}
}
return firstTry;
}
private boolean tryExtract(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir, @Nonnull NetworkTank tank, FluidStack drained) {
if (drained == null || drained.amount <= 0 || !matchedFilter(drained, con, conDir, true)) {
return false;
}
drained = drained.copy();
drained.amount = Math.min(drained.amount, ConduitConfig.fluid_tier3_extractRate.get() * getExtractSpeedMultiplier(tank) / 2);
int amountAccepted = fillFrom(tank, drained.copy(), true);
if (amountAccepted <= 0) {
return false;
}
drained.amount = amountAccepted;
drained = tank.externalTank.drain(drained);
if (drained == null || drained.amount <= 0) {
return false;
}
// if(drained.amount != amountAccepted) {
// Log.warn("EnderLiquidConduit.extractFrom: Extracted fluid volume is not equal to inserted volume. Drained=" + drained.amount + " filled="
// + amountAccepted + " Fluid: " + drained + " Accepted=" + amountAccepted);
// }
return true;
}
@Nonnull
private NetworkTank getTank(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
return tankMap.get(new NetworkTankKey(con, conDir));
}
public int fillFrom(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir, FluidStack resource, boolean doFill) {
return fillFrom(getTank(con, conDir), resource, doFill);
}
public int fillFrom(@Nonnull NetworkTank tank, FluidStack resource, boolean doFill) {
if (filling) {
return 0;
}
try {
filling = true;
if (resource == null || !matchedFilter(resource, tank.con, tank.conDir, true)) {
return 0;
}
resource = resource.copy();
resource.amount = Math.min(resource.amount, ConduitConfig.fluid_tier3_maxIO.get() * getExtractSpeedMultiplier(tank) / 2);
int filled = 0;
int remaining = resource.amount;
// TODO: Only change starting pos of iterator is doFill is true so a false then true returns the same
for (NetworkTank target : getIteratorForTank(tank)) {
if ((!target.equals(tank) || tank.selfFeed) && target.acceptsOuput && target.isValid() && target.inputColor == tank.outputColor
&& matchedFilter(resource, target.con, target.conDir, false)) {
int vol = doFill ? target.externalTank.fill(resource.copy()) : target.externalTank.offer(resource.copy());
remaining -= vol;
filled += vol;
if (remaining <= 0) {
return filled;
}
resource.amount = remaining;
}
}
return filled;
} finally {
if (!tank.roundRobin) {
getIteratorForTank(tank).reset();
}
filling = false;
}
}
private int getExtractSpeedMultiplier(NetworkTank tank) {
int extractSpeedMultiplier = 2;
ItemStack upgradeStack = tank.con.getFunctionUpgrade(tank.conDir);
if (!upgradeStack.isEmpty()) {
FunctionUpgrade upgrade = ItemFunctionUpgrade.getFunctionUpgrade(upgradeStack);
if (upgrade == FunctionUpgrade.EXTRACT_SPEED_UPGRADE) {
extractSpeedMultiplier += FunctionUpgrade.LIQUID_MAX_EXTRACTED_SCALER * Math.min(upgrade.maxStackSize, upgradeStack.getCount());
} else if (upgrade == FunctionUpgrade.EXTRACT_SPEED_DOWNGRADE) {
extractSpeedMultiplier = 1;
}
}
return extractSpeedMultiplier;
}
private boolean matchedFilter(FluidStack drained, @Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir, boolean isInput) {
if (drained == null) {
return false;
}
IFluidFilter filter = con.getFilter(conDir, isInput);
if (filter == null || filter.isEmpty()) {
return true;
}
return filter.matchesFilter(drained);
}
private RoundRobinIterator<NetworkTank> getIteratorForTank(@Nonnull NetworkTank tank) {
if (iterators == null) {
iterators = new HashMap<NetworkTank, RoundRobinIterator<NetworkTank>>();
}
RoundRobinIterator<NetworkTank> res = iterators.get(tank);
if (res == null) {
res = new RoundRobinIterator<NetworkTank>(tanks);
iterators.put(tank, res);
}
return res;
}
public IFluidTankProperties[] getTankProperties(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
List<IFluidTankProperties> res = new ArrayList<IFluidTankProperties>(tanks.size());
NetworkTank tank = getTank(con, conDir);
for (NetworkTank target : tanks) {
if (!target.equals(tank) && target.isValid()) {
for (ITankInfoWrapper info : target.externalTank.getTankInfoWrappers()) {
res.add(info.getIFluidTankProperties());
}
}
}
return res.toArray(new IFluidTankProperties[res.size()]);
}
static class NetworkTankKey {
EnumFacing conDir;
BlockPos conduitLoc;
public NetworkTankKey(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
this(con.getBundle().getLocation(), conDir);
}
public NetworkTankKey(@Nonnull BlockPos conduitLoc, @Nonnull EnumFacing conDir) {
this.conDir = conDir;
this.conduitLoc = conduitLoc;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((conDir == null) ? 0 : conDir.hashCode());
result = prime * result + ((conduitLoc == null) ? 0 : conduitLoc.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
NetworkTankKey other = (NetworkTankKey) obj;
if (conDir != other.conDir) {
return false;
}
if (conduitLoc == null) {
if (other.conduitLoc != null) {
return false;
}
} else if (!conduitLoc.equals(other.conduitLoc)) {
return false;
}
return true;
}
}
}
| enderio-conduits/src/main/java/crazypants/enderio/conduits/conduit/liquid/EnderLiquidConduitNetwork.java | package crazypants.enderio.conduits.conduit.liquid;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import com.enderio.core.common.fluid.IFluidWrapper.ITankInfoWrapper;
import com.enderio.core.common.util.RoundRobinIterator;
import crazypants.enderio.base.conduit.item.FunctionUpgrade;
import crazypants.enderio.base.conduit.item.ItemFunctionUpgrade;
import crazypants.enderio.base.filter.fluid.IFluidFilter;
import crazypants.enderio.conduits.conduit.AbstractConduitNetwork;
import crazypants.enderio.conduits.config.ConduitConfig;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidTankProperties;
public class EnderLiquidConduitNetwork extends AbstractConduitNetwork<ILiquidConduit, EnderLiquidConduit> {
List<NetworkTank> tanks = new ArrayList<NetworkTank>();
Map<NetworkTankKey, NetworkTank> tankMap = new HashMap<NetworkTankKey, NetworkTank>();
Map<NetworkTank, RoundRobinIterator<NetworkTank>> iterators;
boolean filling;
public EnderLiquidConduitNetwork() {
super(EnderLiquidConduit.class, ILiquidConduit.class);
}
public void connectionChanged(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
NetworkTankKey key = new NetworkTankKey(con, conDir);
NetworkTank tank = new NetworkTank(con, conDir);
tanks.remove(tank); // remove old tank, NB: =/hash is only calced on location and dir
tanks.add(tank);
tankMap.remove(key);
tankMap.put(key, tank);
tanks.sort((left, right) -> right.priority - left.priority);
}
public boolean extractFrom(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
NetworkTank tank = getTank(con, conDir);
if (!tank.isValid()) {
return false;
}
FluidStack drained = tank.externalTank.getAvailableFluid();
boolean firstTry = tryExtract(con, conDir, tank, drained);
if (!firstTry) {
for (ITankInfoWrapper tankInfoWrapper : tank.externalTank.getTankInfoWrappers()) {
FluidStack toDrain = tankInfoWrapper.getIFluidTankProperties().getContents();
// Don't try to drain the same fluid twice
if (toDrain != null && toDrain.isFluidEqual(drained)) {
continue;
}
if (tryExtract(con, conDir, tank, toDrain)) {
return true;
}
}
}
return firstTry;
}
private boolean tryExtract(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir, @Nonnull NetworkTank tank, FluidStack drained) {
if (drained == null || drained.amount <= 0 || !matchedFilter(drained, con, conDir, true)) {
return false;
}
drained = drained.copy();
drained.amount = Math.min(drained.amount, ConduitConfig.fluid_tier3_extractRate.get() * getExtractSpeedMultiplier(tank) / 2);
int amountAccepted = fillFrom(tank, drained.copy(), true);
if (amountAccepted <= 0) {
return false;
}
drained.amount = amountAccepted;
drained = tank.externalTank.drain(drained);
if (drained == null || drained.amount <= 0) {
return false;
}
// if(drained.amount != amountAccepted) {
// Log.warn("EnderLiquidConduit.extractFrom: Extracted fluid volume is not equal to inserted volume. Drained=" + drained.amount + " filled="
// + amountAccepted + " Fluid: " + drained + " Accepted=" + amountAccepted);
// }
return true;
}
@Nonnull
private NetworkTank getTank(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
return tankMap.get(new NetworkTankKey(con, conDir));
}
public int fillFrom(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir, FluidStack resource, boolean doFill) {
return fillFrom(getTank(con, conDir), resource, doFill);
}
public int fillFrom(@Nonnull NetworkTank tank, FluidStack resource, boolean doFill) {
if (filling) {
return 0;
}
try {
filling = true;
if (resource == null || !matchedFilter(resource, tank.con, tank.conDir, true)) {
return 0;
}
resource = resource.copy();
resource.amount = Math.min(resource.amount, ConduitConfig.fluid_tier3_maxIO.get() * getExtractSpeedMultiplier(tank) / 2);
int filled = 0;
int remaining = resource.amount;
// TODO: Only change starting pos of iterator is doFill is true so a false then true returns the same
for (NetworkTank target : getIteratorForTank(tank)) {
if ((!target.equals(tank) || tank.selfFeed) && target.acceptsOuput && target.isValid() && target.inputColor == tank.outputColor
&& matchedFilter(resource, target.con, target.conDir, false)) {
int vol = doFill ? target.externalTank.fill(resource.copy()) : target.externalTank.offer(resource.copy());
remaining -= vol;
filled += vol;
if (remaining <= 0) {
return filled;
}
resource.amount = remaining;
}
}
return filled;
} finally {
if (!tank.roundRobin) {
getIteratorForTank(tank).reset();
}
filling = false;
}
}
private int getExtractSpeedMultiplier(NetworkTank tank) {
int extractSpeedMultiplier = 2;
ItemStack upgradeStack = tank.con.getFunctionUpgrade(tank.conDir);
if (!upgradeStack.isEmpty()) {
FunctionUpgrade upgrade = ItemFunctionUpgrade.getFunctionUpgrade(upgradeStack);
if (upgrade == FunctionUpgrade.EXTRACT_SPEED_UPGRADE) {
extractSpeedMultiplier += FunctionUpgrade.LIQUID_MAX_EXTRACTED_SCALER * Math.min(upgrade.maxStackSize, upgradeStack.getCount());
} else if (upgrade == FunctionUpgrade.EXTRACT_SPEED_DOWNGRADE) {
extractSpeedMultiplier = 1;
}
}
return extractSpeedMultiplier;
}
private boolean matchedFilter(FluidStack drained, @Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir, boolean isInput) {
if (drained == null) {
return false;
}
IFluidFilter filter = con.getFilter(conDir, isInput);
if (filter == null || filter.isEmpty()) {
return true;
}
return filter.matchesFilter(drained);
}
private RoundRobinIterator<NetworkTank> getIteratorForTank(@Nonnull NetworkTank tank) {
if (iterators == null) {
iterators = new HashMap<NetworkTank, RoundRobinIterator<NetworkTank>>();
}
RoundRobinIterator<NetworkTank> res = iterators.get(tank);
if (res == null) {
res = new RoundRobinIterator<NetworkTank>(tanks);
iterators.put(tank, res);
}
return res;
}
public IFluidTankProperties[] getTankProperties(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
List<IFluidTankProperties> res = new ArrayList<IFluidTankProperties>(tanks.size());
NetworkTank tank = getTank(con, conDir);
for (NetworkTank target : tanks) {
if (!target.equals(tank) && target.isValid()) {
for (ITankInfoWrapper info : target.externalTank.getTankInfoWrappers()) {
res.add(info.getIFluidTankProperties());
}
}
}
return res.toArray(new IFluidTankProperties[res.size()]);
}
static class NetworkTankKey {
EnumFacing conDir;
BlockPos conduitLoc;
public NetworkTankKey(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
this(con.getBundle().getLocation(), conDir);
}
public NetworkTankKey(@Nonnull BlockPos conduitLoc, @Nonnull EnumFacing conDir) {
this.conDir = conDir;
this.conduitLoc = conduitLoc;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((conDir == null) ? 0 : conDir.hashCode());
result = prime * result + ((conduitLoc == null) ? 0 : conduitLoc.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
NetworkTankKey other = (NetworkTankKey) obj;
if (conDir != other.conDir) {
return false;
}
if (conduitLoc == null) {
if (other.conduitLoc != null) {
return false;
}
} else if (!conduitLoc.equals(other.conduitLoc)) {
return false;
}
return true;
}
}
}
| Cache whether NetworkTanks have multiple tanks
| enderio-conduits/src/main/java/crazypants/enderio/conduits/conduit/liquid/EnderLiquidConduitNetwork.java | Cache whether NetworkTanks have multiple tanks |
|
Java | apache-2.0 | ed0b88ee431aa84e3a2492724abd36c702fa4033 | 0 | apache/shindig,apache/shindig,apache/shindig,apparentlymart/shindig,apache/shindig,apparentlymart/shindig,apparentlymart/shindig,apache/shindig,apparentlymart/shindig | /*
* 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.shindig.gadgets.config;
import com.google.inject.ImplementedBy;
import java.util.List;
import java.util.Map;
import org.apache.shindig.gadgets.Gadget;
@ImplementedBy(DefaultConfigProcessor.class)
public interface ConfigProcessor {
// TODO: Clean up ConfigContributor interfaces so this lame uber-interface is not needed.
Map<String, Object> getConfig(String container, List<String> features, String host,
Gadget gadget);
}
| java/gadgets/src/main/java/org/apache/shindig/gadgets/config/ConfigProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.apache.shindig.gadgets.config;
import java.util.List;
import java.util.Map;
import org.apache.shindig.gadgets.Gadget;
public interface ConfigProcessor {
// TODO: Clean up ConfigContributor interfaces so this lame uber-interface is not needed.
Map<String, Object> getConfig(String container, List<String> features, String host,
Gadget gadget);
}
| Set default injection for ConfigProcessor
git-svn-id: 84334937b86421baa0e582c4ab1a9d358324cbeb@1099945 13f79535-47bb-0310-9956-ffa450edef68
| java/gadgets/src/main/java/org/apache/shindig/gadgets/config/ConfigProcessor.java | Set default injection for ConfigProcessor |
|
Java | apache-2.0 | d1121e859ba5a5b92334309d178b0e8eb6a93a82 | 0 | darranl/directory-server,lucastheisen/apache-directory-server,drankye/directory-server,lucastheisen/apache-directory-server,darranl/directory-server,apache/directory-server,drankye/directory-server,apache/directory-server | /*
* 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.directory.server.kerberos.shared.crypto.encryption;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.directory.server.kerberos.shared.exceptions.ErrorType;
import org.apache.directory.server.kerberos.shared.exceptions.KerberosException;
import org.apache.directory.server.kerberos.shared.io.decoder.AuthenticatorDecoder;
import org.apache.directory.server.kerberos.shared.io.decoder.AuthorizationDataDecoder;
import org.apache.directory.server.kerberos.shared.io.decoder.Decoder;
import org.apache.directory.server.kerberos.shared.io.decoder.DecoderFactory;
import org.apache.directory.server.kerberos.shared.io.decoder.EncKrbPrivPartDecoder;
import org.apache.directory.server.kerberos.shared.io.decoder.EncTicketPartDecoder;
import org.apache.directory.server.kerberos.shared.io.decoder.EncryptedTimestampDecoder;
import org.apache.directory.server.kerberos.shared.io.encoder.AuthenticatorEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncApRepPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncAsRepPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncKrbPrivPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncTgsRepPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncTicketPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.Encoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncoderFactory;
import org.apache.directory.server.kerberos.shared.io.encoder.EncryptedTimestampEncoder;
import org.apache.directory.server.kerberos.shared.messages.AuthenticationReply;
import org.apache.directory.server.kerberos.shared.messages.Encodable;
import org.apache.directory.server.kerberos.shared.messages.TicketGrantReply;
import org.apache.directory.server.kerberos.shared.messages.components.Authenticator;
import org.apache.directory.server.kerberos.shared.messages.components.EncApRepPart;
import org.apache.directory.server.kerberos.shared.messages.components.EncKrbPrivPart;
import org.apache.directory.server.kerberos.shared.messages.components.EncTicketPart;
import org.apache.directory.server.kerberos.shared.messages.value.AuthorizationData;
import org.apache.directory.server.kerberos.shared.messages.value.EncryptedData;
import org.apache.directory.server.kerberos.shared.messages.value.EncryptedTimeStamp;
import org.apache.directory.server.kerberos.shared.messages.value.EncryptionKey;
/**
* A Hashed Adapter encapsulating ASN.1 encoders and decoders and cipher text engines to
* perform seal() and unseal() operations. A seal() operation performs an encode and an
* encrypt, while an unseal() operation performs a decrypt and a decode.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class CipherTextHandler
{
/** a map of the default encodable class names to the encoder class names */
private static final Map DEFAULT_ENCODERS;
/** a map of the default encodable class names to the decoder class names */
private static final Map DEFAULT_DECODERS;
/** a map of the default encryption types to the encryption engine class names */
private static final Map DEFAULT_CIPHERS;
static
{
Map<Class, Class> map = new HashMap<Class, Class>();
map.put( EncryptedTimeStamp.class, EncryptedTimestampEncoder.class );
map.put( EncTicketPart.class, EncTicketPartEncoder.class );
map.put( AuthenticationReply.class, EncAsRepPartEncoder.class );
map.put( TicketGrantReply.class, EncTgsRepPartEncoder.class );
map.put( EncKrbPrivPart.class, EncKrbPrivPartEncoder.class );
map.put( EncApRepPart.class, EncApRepPartEncoder.class );
map.put( Authenticator.class, AuthenticatorEncoder.class );
DEFAULT_ENCODERS = Collections.unmodifiableMap( map );
}
static
{
Map<Class, Class> map = new HashMap<Class, Class>();
map.put( EncTicketPart.class, EncTicketPartDecoder.class );
map.put( Authenticator.class, AuthenticatorDecoder.class );
map.put( EncryptedTimeStamp.class, EncryptedTimestampDecoder.class );
map.put( AuthorizationData.class, AuthorizationDataDecoder.class );
map.put( EncKrbPrivPart.class, EncKrbPrivPartDecoder.class );
DEFAULT_DECODERS = Collections.unmodifiableMap( map );
}
static
{
Map<EncryptionType, Class> map = new HashMap<EncryptionType, Class>();
map.put( EncryptionType.DES_CBC_MD5, DesCbcMd5Encryption.class );
map.put( EncryptionType.DES3_CBC_SHA1_KD, Des3CbcSha1KdEncryption.class );
map.put( EncryptionType.AES128_CTS_HMAC_SHA1_96, Aes128CtsSha1Encryption.class );
map.put( EncryptionType.AES256_CTS_HMAC_SHA1_96, Aes256CtsSha1Encryption.class );
map.put( EncryptionType.RC4_HMAC, ArcFourHmacMd5Encryption.class );
DEFAULT_CIPHERS = Collections.unmodifiableMap( map );
}
/**
* Performs an encode and an encrypt.
*
* @param key The key to use for encrypting.
* @param encodable The Kerberos object to encode.
* @param usage The key usage.
* @return The Kerberos EncryptedData.
* @throws KerberosException
*/
public EncryptedData seal( EncryptionKey key, Encodable encodable, KeyUsage usage ) throws KerberosException
{
try
{
return encrypt( key, encode( encodable ), usage );
}
catch ( IOException ioe )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, ioe );
}
catch ( ClassCastException cce )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, cce );
}
}
/**
* Perform a decrypt and a decode.
*
* @param hint The class the encrypted data is expected to contain.
* @param key The key to use for decryption.
* @param data The data to decrypt.
* @param usage The key usage.
* @return The Kerberos object resulting from a successful decrypt and decode.
* @throws KerberosException
*/
public Encodable unseal( Class hint, EncryptionKey key, EncryptedData data, KeyUsage usage )
throws KerberosException
{
try
{
return decode( hint, decrypt( key, data, usage ) );
}
catch ( IOException ioe )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, ioe );
}
catch ( ClassCastException cce )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, cce );
}
}
private EncryptedData encrypt( EncryptionKey key, byte[] plainText, KeyUsage usage ) throws KerberosException
{
EncryptionEngine engine = getEngine( key );
return engine.getEncryptedData( key, plainText, usage );
}
private byte[] decrypt( EncryptionKey key, EncryptedData data, KeyUsage usage ) throws KerberosException
{
EncryptionEngine engine = getEngine( key );
return engine.getDecryptedData( key, data, usage );
}
private byte[] encode( Encodable encodable ) throws IOException
{
Class encodableClass = encodable.getClass();
Class clazz = ( Class ) DEFAULT_ENCODERS.get( encodableClass );
if ( clazz == null )
{
throw new IOException( "Encoder unavailable for " + encodableClass );
}
EncoderFactory factory = null;
try
{
factory = ( EncoderFactory ) clazz.newInstance();
}
catch ( IllegalAccessException iae )
{
throw new IOException( "Error accessing encoder for " + encodableClass );
}
catch ( InstantiationException ie )
{
throw new IOException( "Error instantiating encoder for " + encodableClass );
}
Encoder encoder = factory.getEncoder();
return encoder.encode( encodable );
}
private Encodable decode( Class encodable, byte[] plainText ) throws IOException
{
Class clazz = ( Class ) DEFAULT_DECODERS.get( encodable );
if ( clazz == null )
{
throw new IOException( "Decoder unavailable for " + encodable );
}
DecoderFactory factory = null;
try
{
factory = ( DecoderFactory ) clazz.newInstance();
}
catch ( IllegalAccessException iae )
{
throw new IOException( "Error accessing decoder for " + encodable );
}
catch ( InstantiationException ie )
{
throw new IOException( "Error instantiating decoder for " + encodable );
}
Decoder decoder = factory.getDecoder();
return decoder.decode( plainText );
}
private EncryptionEngine getEngine( EncryptionKey key ) throws KerberosException
{
EncryptionType encryptionType = key.getKeyType();
Class clazz = ( Class ) DEFAULT_CIPHERS.get( encryptionType );
if ( clazz == null )
{
throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP );
}
try
{
return ( EncryptionEngine ) clazz.newInstance();
}
catch ( IllegalAccessException iae )
{
throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP, iae );
}
catch ( InstantiationException ie )
{
throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP, ie );
}
}
}
| kerberos-shared/src/main/java/org/apache/directory/server/kerberos/shared/crypto/encryption/CipherTextHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.kerberos.shared.crypto.encryption;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.directory.server.kerberos.shared.exceptions.ErrorType;
import org.apache.directory.server.kerberos.shared.exceptions.KerberosException;
import org.apache.directory.server.kerberos.shared.io.decoder.AuthenticatorDecoder;
import org.apache.directory.server.kerberos.shared.io.decoder.AuthorizationDataDecoder;
import org.apache.directory.server.kerberos.shared.io.decoder.Decoder;
import org.apache.directory.server.kerberos.shared.io.decoder.DecoderFactory;
import org.apache.directory.server.kerberos.shared.io.decoder.EncKrbPrivPartDecoder;
import org.apache.directory.server.kerberos.shared.io.decoder.EncTicketPartDecoder;
import org.apache.directory.server.kerberos.shared.io.decoder.EncryptedTimestampDecoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncApRepPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncAsRepPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncKrbPrivPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncTgsRepPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncTicketPartEncoder;
import org.apache.directory.server.kerberos.shared.io.encoder.Encoder;
import org.apache.directory.server.kerberos.shared.io.encoder.EncoderFactory;
import org.apache.directory.server.kerberos.shared.io.encoder.EncryptedTimestampEncoder;
import org.apache.directory.server.kerberos.shared.messages.AuthenticationReply;
import org.apache.directory.server.kerberos.shared.messages.Encodable;
import org.apache.directory.server.kerberos.shared.messages.TicketGrantReply;
import org.apache.directory.server.kerberos.shared.messages.components.Authenticator;
import org.apache.directory.server.kerberos.shared.messages.components.EncApRepPart;
import org.apache.directory.server.kerberos.shared.messages.components.EncKrbPrivPart;
import org.apache.directory.server.kerberos.shared.messages.components.EncTicketPart;
import org.apache.directory.server.kerberos.shared.messages.value.AuthorizationData;
import org.apache.directory.server.kerberos.shared.messages.value.EncryptedData;
import org.apache.directory.server.kerberos.shared.messages.value.EncryptedTimeStamp;
import org.apache.directory.server.kerberos.shared.messages.value.EncryptionKey;
/**
* A Hashed Adapter encapsulating ASN.1 encoders and decoders and cipher text engines to
* perform seal() and unseal() operations. A seal() operation performs an encode and an
* encrypt, while an unseal() operation performs a decrypt and a decode.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class CipherTextHandler
{
/** a map of the default encodable class names to the encoder class names */
private static final Map DEFAULT_ENCODERS;
/** a map of the default encodable class names to the decoder class names */
private static final Map DEFAULT_DECODERS;
/** a map of the default encryption types to the encryption engine class names */
private static final Map DEFAULT_CIPHERS;
static
{
Map<Class, Class> map = new HashMap<Class, Class>();
map.put( EncryptedTimeStamp.class, EncryptedTimestampEncoder.class );
map.put( EncTicketPart.class, EncTicketPartEncoder.class );
map.put( AuthenticationReply.class, EncAsRepPartEncoder.class );
map.put( TicketGrantReply.class, EncTgsRepPartEncoder.class );
map.put( EncKrbPrivPart.class, EncKrbPrivPartEncoder.class );
map.put( EncApRepPart.class, EncApRepPartEncoder.class );
DEFAULT_ENCODERS = Collections.unmodifiableMap( map );
}
static
{
Map<Class, Class> map = new HashMap<Class, Class>();
map.put( EncTicketPart.class, EncTicketPartDecoder.class );
map.put( Authenticator.class, AuthenticatorDecoder.class );
map.put( EncryptedTimeStamp.class, EncryptedTimestampDecoder.class );
map.put( AuthorizationData.class, AuthorizationDataDecoder.class );
map.put( EncKrbPrivPart.class, EncKrbPrivPartDecoder.class );
DEFAULT_DECODERS = Collections.unmodifiableMap( map );
}
static
{
Map<EncryptionType, Class> map = new HashMap<EncryptionType, Class>();
map.put( EncryptionType.DES_CBC_MD5, DesCbcMd5Encryption.class );
map.put( EncryptionType.DES3_CBC_SHA1_KD, Des3CbcSha1KdEncryption.class );
map.put( EncryptionType.AES128_CTS_HMAC_SHA1_96, Aes128CtsSha1Encryption.class );
map.put( EncryptionType.AES256_CTS_HMAC_SHA1_96, Aes256CtsSha1Encryption.class );
map.put( EncryptionType.RC4_HMAC, ArcFourHmacMd5Encryption.class );
DEFAULT_CIPHERS = Collections.unmodifiableMap( map );
}
/**
* Performs an encode and an encrypt.
*
* @param key The key to use for encrypting.
* @param encodable The Kerberos object to encode.
* @param usage The key usage.
* @return The Kerberos EncryptedData.
* @throws KerberosException
*/
public EncryptedData seal( EncryptionKey key, Encodable encodable, KeyUsage usage ) throws KerberosException
{
try
{
return encrypt( key, encode( encodable ), usage );
}
catch ( IOException ioe )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, ioe );
}
catch ( ClassCastException cce )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, cce );
}
}
/**
* Perform a decrypt and a decode.
*
* @param hint The class the encrypted data is expected to contain.
* @param key The key to use for decryption.
* @param data The data to decrypt.
* @param usage The key usage.
* @return The Kerberos object resulting from a successful decrypt and decode.
* @throws KerberosException
*/
public Encodable unseal( Class hint, EncryptionKey key, EncryptedData data, KeyUsage usage )
throws KerberosException
{
try
{
return decode( hint, decrypt( key, data, usage ) );
}
catch ( IOException ioe )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, ioe );
}
catch ( ClassCastException cce )
{
throw new KerberosException( ErrorType.KRB_AP_ERR_BAD_INTEGRITY, cce );
}
}
private EncryptedData encrypt( EncryptionKey key, byte[] plainText, KeyUsage usage ) throws KerberosException
{
EncryptionEngine engine = getEngine( key );
return engine.getEncryptedData( key, plainText, usage );
}
private byte[] decrypt( EncryptionKey key, EncryptedData data, KeyUsage usage ) throws KerberosException
{
EncryptionEngine engine = getEngine( key );
return engine.getDecryptedData( key, data, usage );
}
private byte[] encode( Encodable encodable ) throws IOException
{
Class encodableClass = encodable.getClass();
Class clazz = ( Class ) DEFAULT_ENCODERS.get( encodableClass );
if ( clazz == null )
{
throw new IOException( "Encoder unavailable for " + encodableClass );
}
EncoderFactory factory = null;
try
{
factory = ( EncoderFactory ) clazz.newInstance();
}
catch ( IllegalAccessException iae )
{
throw new IOException( "Error accessing encoder for " + encodableClass );
}
catch ( InstantiationException ie )
{
throw new IOException( "Error instantiating encoder for " + encodableClass );
}
Encoder encoder = factory.getEncoder();
return encoder.encode( encodable );
}
private Encodable decode( Class encodable, byte[] plainText ) throws IOException
{
Class clazz = ( Class ) DEFAULT_DECODERS.get( encodable );
if ( clazz == null )
{
throw new IOException( "Decoder unavailable for " + encodable );
}
DecoderFactory factory = null;
try
{
factory = ( DecoderFactory ) clazz.newInstance();
}
catch ( IllegalAccessException iae )
{
throw new IOException( "Error accessing decoder for " + encodable );
}
catch ( InstantiationException ie )
{
throw new IOException( "Error instantiating decoder for " + encodable );
}
Decoder decoder = factory.getDecoder();
return decoder.decode( plainText );
}
private EncryptionEngine getEngine( EncryptionKey key ) throws KerberosException
{
EncryptionType encryptionType = key.getKeyType();
Class clazz = ( Class ) DEFAULT_CIPHERS.get( encryptionType );
if ( clazz == null )
{
throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP );
}
try
{
return ( EncryptionEngine ) clazz.newInstance();
}
catch ( IllegalAccessException iae )
{
throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP, iae );
}
catch ( InstantiationException ie )
{
throw new KerberosException( ErrorType.KDC_ERR_ETYPE_NOSUPP, ie );
}
}
}
| Enabled Authenticator sealing in the CipherTextHandler.
git-svn-id: 90776817adfbd895fc5cfa90f675377e0a62e745@546371 13f79535-47bb-0310-9956-ffa450edef68
| kerberos-shared/src/main/java/org/apache/directory/server/kerberos/shared/crypto/encryption/CipherTextHandler.java | Enabled Authenticator sealing in the CipherTextHandler. |
|
Java | apache-2.0 | 0559f8f877b6006adb44cc8b293326dfc6ac1c61 | 0 | robertdale/tinkerpop,vtslab/incubator-tinkerpop,apache/tinkerpop,RedSeal-co/incubator-tinkerpop,krlohnes/tinkerpop,edgarRd/incubator-tinkerpop,n-tran/incubator-tinkerpop,edgarRd/incubator-tinkerpop,samiunn/incubator-tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,krlohnes/tinkerpop,samiunn/incubator-tinkerpop,n-tran/incubator-tinkerpop,apache/tinkerpop,dalaro/incubator-tinkerpop,newkek/incubator-tinkerpop,jorgebay/tinkerpop,artem-aliev/tinkerpop,apache/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,jorgebay/tinkerpop,edgarRd/incubator-tinkerpop,samiunn/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,apache/incubator-tinkerpop,artem-aliev/tinkerpop,mike-tr-adamson/incubator-tinkerpop,velo/incubator-tinkerpop,velo/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,krlohnes/tinkerpop,dalaro/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,apache/tinkerpop,BrynCooke/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,newkek/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,jorgebay/tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,robertdale/tinkerpop,velo/incubator-tinkerpop,pluradj/incubator-tinkerpop,apache/tinkerpop,RedSeal-co/incubator-tinkerpop,robertdale/tinkerpop,krlohnes/tinkerpop,pluradj/incubator-tinkerpop,vtslab/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,robertdale/tinkerpop,vtslab/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,n-tran/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,dalaro/incubator-tinkerpop,rmagen/incubator-tinkerpop,krlohnes/tinkerpop,apache/incubator-tinkerpop,jorgebay/tinkerpop,rmagen/incubator-tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,newkek/incubator-tinkerpop,rmagen/incubator-tinkerpop | /*
* 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.tinkerpop.gremlin.tinkergraph.structure;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.tinkergraph.process.computer.TinkerGraphComputer;
import org.apache.tinkerpop.gremlin.tinkergraph.process.computer.TinkerGraphView;
import org.apache.tinkerpop.gremlin.tinkergraph.process.traversal.strategy.optimization.TinkerGraphStepStrategy;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
/**
* An in-sideEffects, reference implementation of the property graph interfaces provided by Gremlin3.
*
* @author Marko A. Rodriguez (http://markorodriguez.com)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
@Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_STANDARD)
@Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_PERFORMANCE)
@Graph.OptIn(Graph.OptIn.SUITE_PROCESS_STANDARD)
@Graph.OptIn(Graph.OptIn.SUITE_PROCESS_COMPUTER)
@Graph.OptIn(Graph.OptIn.SUITE_PROCESS_PERFORMANCE)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_PROCESS_STANDARD)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_PROCESS_COMPUTER)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_ENVIRONMENT)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_ENVIRONMENT_INTEGRATE)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_ENVIRONMENT_PERFORMANCE)
public class TinkerGraph implements Graph {
static {
TraversalStrategies.GlobalCache.registerStrategies(TinkerGraph.class, TraversalStrategies.GlobalCache.getStrategies(Graph.class).clone().addStrategies(TinkerGraphStepStrategy.instance()));
}
private static final Configuration EMPTY_CONFIGURATION = new BaseConfiguration() {{
this.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
}};
public static final String CONFIG_VERTEX_ID = "tinkergraph.vertex.id";
public static final String CONFIG_EDGE_ID = "tinkergraph.edge.id";
public static final String CONFIG_VERTEX_PROPERTY_ID = "tinkergraph.vertex-property.id";
protected Long currentId = -1l;
protected Map<Object, Vertex> vertices = new ConcurrentHashMap<>();
protected Map<Object, Edge> edges = new ConcurrentHashMap<>();
protected TinkerGraphVariables variables = null;
protected TinkerGraphView graphView = null;
protected TinkerIndex<TinkerVertex> vertexIndex = null;
protected TinkerIndex<TinkerEdge> edgeIndex = null;
private final static TinkerGraph EMPTY_GRAPH = new TinkerGraph(EMPTY_CONFIGURATION);
protected IdManager<?> vertexIdManager;
protected IdManager<?> edgeIdManager;
protected IdManager<?> vertexPropertyIdManager;
private final Configuration configuration;
/**
* An empty private constructor that initializes {@link TinkerGraph}.
*/
private TinkerGraph(final Configuration configuration) {
this.configuration = configuration;
final String vertexIdManagerConfigValue = configuration.getString(CONFIG_VERTEX_ID, DefaultIdManager.ANY.name());
try {
vertexIdManager = DefaultIdManager.valueOf(vertexIdManagerConfigValue);
} catch (IllegalArgumentException iae) {
try {
vertexIdManager = (IdManager) Class.forName(vertexIdManagerConfigValue).newInstance();
} catch (Exception ex) {
throw new IllegalStateException(String.format("Could not configure TinkerGraph vertex id manager with %s", vertexIdManagerConfigValue));
}
}
final String edgeIdManagerConfigValue = configuration.getString(CONFIG_EDGE_ID, DefaultIdManager.ANY.name());
try {
edgeIdManager = DefaultIdManager.valueOf(edgeIdManagerConfigValue);
} catch (IllegalArgumentException iae) {
try {
edgeIdManager = (IdManager) Class.forName(edgeIdManagerConfigValue).newInstance();
} catch (Exception ex) {
throw new IllegalStateException(String.format("Could not configure TinkerGraph edge id manager with %s", edgeIdManagerConfigValue));
}
}
final String vertexPropIdManagerConfigValue = configuration.getString(CONFIG_VERTEX_PROPERTY_ID, DefaultIdManager.ANY.name());
try {
vertexPropertyIdManager = DefaultIdManager.valueOf(vertexPropIdManagerConfigValue);
} catch (IllegalArgumentException iae) {
try {
vertexPropertyIdManager = (IdManager) Class.forName(vertexPropIdManagerConfigValue).newInstance();
} catch (Exception ex) {
throw new IllegalStateException(String.format("Could not configure TinkerGraph vertex property id manager with %s", vertexPropIdManagerConfigValue));
}
}
}
public static TinkerGraph empty() {
return EMPTY_GRAPH;
}
/**
* Open a new {@link TinkerGraph} instance.
* <p/>
* <b>Reference Implementation Help:</b> If a {@link org.apache.tinkerpop.gremlin.structure.Graph } implementation does not require a
* {@link org.apache.commons.configuration.Configuration} (or perhaps has a default configuration) it can choose to implement a zero argument
* open() method. This is an optional constructor method for TinkerGraph. It is not enforced by the Gremlin
* Test Suite.
*/
public static TinkerGraph open() {
return open(EMPTY_CONFIGURATION);
}
/**
* Open a new {@link TinkerGraph} instance.
* <p/>
* <b>Reference Implementation Help:</b> This method is the one use by the
* {@link org.apache.tinkerpop.gremlin.structure.util.GraphFactory} to instantiate
* {@link org.apache.tinkerpop.gremlin.structure.Graph} instances. This method must be overridden for the Structure Test
* Suite to pass. Implementers have latitude in terms of how exceptions are handled within this method. Such
* exceptions will be considered implementation specific by the test suite as all test generate graph instances
* by way of {@link org.apache.tinkerpop.gremlin.structure.util.GraphFactory}. As such, the exceptions get generalized
* behind that facade and since {@link org.apache.tinkerpop.gremlin.structure.util.GraphFactory} is the preferred method
* to opening graphs it will be consistent at that level.
*
* @param configuration the configuration for the instance
* @return a newly opened {@link org.apache.tinkerpop.gremlin.structure.Graph}
*/
public static TinkerGraph open(final Configuration configuration) {
return new TinkerGraph(configuration);
}
////////////// STRUCTURE API METHODS //////////////////
@Override
public Vertex addVertex(final Object... keyValues) {
ElementHelper.legalPropertyKeyValueArray(keyValues);
Object idValue = ElementHelper.getIdValue(keyValues).orElse(null);
final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
if (null != idValue) {
if (this.vertices.containsKey(idValue))
throw Exceptions.vertexWithIdAlreadyExists(idValue);
} else {
idValue = vertexIdManager.getNextId(this);
}
final Vertex vertex = new TinkerVertex(idValue, label, this);
this.vertices.put(vertex.id(), vertex);
ElementHelper.attachProperties(vertex, VertexProperty.Cardinality.list, keyValues);
return vertex;
}
@Override
public <C extends GraphComputer> C compute(final Class<C> graphComputerClass) {
if (!graphComputerClass.equals(TinkerGraphComputer.class))
throw Graph.Exceptions.graphDoesNotSupportProvidedGraphComputer(graphComputerClass);
return (C) new TinkerGraphComputer(this);
}
@Override
public GraphComputer compute() {
return new TinkerGraphComputer(this);
}
@Override
public Variables variables() {
if (null == this.variables)
this.variables = new TinkerGraphVariables();
return this.variables;
}
@Override
public String toString() {
return StringFactory.graphString(this, "vertices:" + this.vertices.size() + " edges:" + this.edges.size());
}
public void clear() {
this.vertices.clear();
this.edges.clear();
this.variables = null;
this.currentId = 0l;
this.vertexIndex = null;
this.edgeIndex = null;
}
@Override
public void close() {
this.graphView = null;
}
@Override
public Transaction tx() {
throw Exceptions.transactionsNotSupported();
}
@Override
public Configuration configuration() {
return configuration;
}
@Override
public Iterator<Vertex> vertices(final Object... vertexIds) {
// todo: this code looks a lot like edges() code - better reuse here somewhere?
// todo: what if we have Reference/DetachedVertex???????????????????????????
if (0 == vertexIds.length) {
return this.vertices.values().iterator();
} else if (1 == vertexIds.length) {
if (vertexIds[0] instanceof Vertex) {
// no need to get the vertex again, so just flip it back - some implementation may want to treat this
// as a refresh operation. that's not necessary for tinkergraph.
return IteratorUtils.of((Vertex) vertexIds[0]);
} else {
// convert the id to the expected data type and lookup the vertex
final Vertex vertex = this.vertices.get(vertexIdManager.convert(vertexIds[0]));
return null == vertex ? Collections.emptyIterator() : IteratorUtils.of(vertex);
}
} else {
// base the conversion function on the first item in the id list as the expectation is that these
// id values will be a uniform list
if (vertexIds[0] instanceof Vertex) {
// based on the first item assume all vertices in the argument list
if (!Stream.of(vertexIds).allMatch(id -> id instanceof Vertex))
throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();
// no need to get the vertices again, so just flip it back - some implementation may want to treat this
// as a refresh operation. that's not necessary for tinkergraph.
return Stream.of(vertexIds).map(id -> (Vertex) id).iterator();
} else {
final Class<?> firstClass = vertexIds[0].getClass();
if (!Stream.of(vertexIds).map(Object::getClass).allMatch(firstClass::equals))
throw Graph.Exceptions.idArgsMustBeEitherIdOrElement(); // todo: change exception to be ids of the same type
return Stream.of(vertexIds).map(vertexIdManager::convert).map(this.vertices::get).filter(Objects::nonNull).iterator();
}
}
}
@Override
public Iterator<Edge> edges(final Object... edgeIds) {
if (0 == edgeIds.length) {
return this.edges.values().iterator();
} else if (1 == edgeIds.length) {
if (edgeIds[0] instanceof Edge) {
// no need to get the edge again, so just flip it back - some implementation may want to treat this
// as a refresh operation. that's not necessary for tinkergraph.
return IteratorUtils.of((Edge) edgeIds[0]);
} else {
// convert the id to the expected data type and lookup the vertex
final Edge edge = this.edges.get(edgeIdManager.convert(edgeIds[0]));
return null == edge ? Collections.emptyIterator() : IteratorUtils.of(edge);
}
} else {
// base the conversion function on the first item in the id list as the expectation is that these
// id values will be a uniform list
if (edgeIds[0] instanceof Edge) {
// based on the first item assume all vertices in the argument list
if (!Stream.of(edgeIds).allMatch(id -> id instanceof Edge))
throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();
// no need to get the vertices again, so just flip it back - some implementation may want to treat this
// as a refresh operation. that's not necessary for tinkergraph.
return Stream.of(edgeIds).map(id -> (Edge) id).iterator();
} else {
final Class<?> firstClass = edgeIds[0].getClass();
if (!Stream.of(edgeIds).map(Object::getClass).allMatch(firstClass::equals))
throw Graph.Exceptions.idArgsMustBeEitherIdOrElement(); // todo: change exception to be ids of the same type
return Stream.of(edgeIds).map(edgeIdManager::convert).map(this.edges::get).filter(Objects::nonNull).iterator();
}
}
}
/**
* Return TinkerGraph feature set.
* <p/>
* <b>Reference Implementation Help:</b> Implementers only need to implement features for which there are
* negative or instance configured features. By default, all {@link Features} return true.
*/
@Override
public Features features() {
return TinkerGraphFeatures.INSTANCE;
}
public static class TinkerGraphFeatures implements Features {
static final TinkerGraphFeatures INSTANCE = new TinkerGraphFeatures();
private TinkerGraphFeatures() {
}
@Override
public GraphFeatures graph() {
return TinkerGraphGraphFeatures.INSTANCE;
}
@Override
public EdgeFeatures edge() {
return TinkerGraphEdgeFeatures.INSTANCE;
}
@Override
public VertexFeatures vertex() {
return TinkerGraphVertexFeatures.INSTANCE;
}
@Override
public String toString() {
return StringFactory.featureString(this);
}
}
public static class TinkerGraphVertexFeatures implements Features.VertexFeatures {
static final TinkerGraphVertexFeatures INSTANCE = new TinkerGraphVertexFeatures();
private TinkerGraphVertexFeatures() {
}
@Override
public boolean supportsCustomIds() {
return false;
}
}
public static class TinkerGraphEdgeFeatures implements Features.EdgeFeatures {
static final TinkerGraphEdgeFeatures INSTANCE = new TinkerGraphEdgeFeatures();
private TinkerGraphEdgeFeatures() {
}
@Override
public boolean supportsCustomIds() {
return false;
}
}
public static class TinkerGraphGraphFeatures implements Features.GraphFeatures {
static final TinkerGraphGraphFeatures INSTANCE = new TinkerGraphGraphFeatures();
private TinkerGraphGraphFeatures() {
}
@Override
public boolean supportsTransactions() {
return false;
}
@Override
public boolean supportsPersistence() {
return false;
}
@Override
public boolean supportsThreadedTransactions() {
return false;
}
}
///////////// GRAPH SPECIFIC INDEXING METHODS ///////////////
/**
* Create an index for said element class ({@link Vertex} or {@link Edge}) and said property key.
* Whenever an element has the specified key mutated, the index is updated.
* When the index is created, all existing elements are indexed to ensure that they are captured by the index.
*
* @param key the property key to index
* @param elementClass the element class to index
* @param <E> The type of the element class
*/
public <E extends Element> void createIndex(final String key, final Class<E> elementClass) {
if (Vertex.class.isAssignableFrom(elementClass)) {
if (null == this.vertexIndex) this.vertexIndex = new TinkerIndex<>(this, TinkerVertex.class);
this.vertexIndex.createKeyIndex(key);
} else if (Edge.class.isAssignableFrom(elementClass)) {
if (null == this.edgeIndex) this.edgeIndex = new TinkerIndex<>(this, TinkerEdge.class);
this.edgeIndex.createKeyIndex(key);
} else {
throw new IllegalArgumentException("Class is not indexable: " + elementClass);
}
}
/**
* Drop the index for the specified element class ({@link Vertex} or {@link Edge}) and key.
*
* @param key the property key to stop indexing
* @param elementClass the element class of the index to drop
* @param <E> The type of the element class
*/
public <E extends Element> void dropIndex(final String key, final Class<E> elementClass) {
if (Vertex.class.isAssignableFrom(elementClass)) {
if (null != this.vertexIndex) this.vertexIndex.dropKeyIndex(key);
} else if (Edge.class.isAssignableFrom(elementClass)) {
if (null != this.edgeIndex) this.edgeIndex.dropKeyIndex(key);
} else {
throw new IllegalArgumentException("Class is not indexable: " + elementClass);
}
}
/**
* Return all the keys currently being index for said element class ({@link Vertex} or {@link Edge}).
*
* @param elementClass the element class to get the indexed keys for
* @param <E> The type of the element class
* @return the set of keys currently being indexed
*/
public <E extends Element> Set<String> getIndexedKeys(final Class<E> elementClass) {
if (Vertex.class.isAssignableFrom(elementClass)) {
return null == this.vertexIndex ? Collections.emptySet() : this.vertexIndex.getIndexedKeys();
} else if (Edge.class.isAssignableFrom(elementClass)) {
return null == this.edgeIndex ? Collections.emptySet() : this.edgeIndex.getIndexedKeys();
} else {
throw new IllegalArgumentException("Class is not indexable: " + elementClass);
}
}
///////////// HELPERS METHODS ///////////////
/**
* Function to coerce a provided identifier to a different type given the expected id type of an element.
* This allows something like {@code g.V(1,2,3)} and {@code g.V(1l,2l,3l)} to both mean the same thing.
*/
private UnaryOperator<Object> convertToId(final Object id, final Class<?> elementIdClass) {
if (id instanceof Number) {
if (elementIdClass != null) {
if (elementIdClass.equals(Long.class)) {
return o -> ((Number) o).longValue();
} else if (elementIdClass.equals(Integer.class)) {
return o -> ((Number) o).intValue();
} else if (elementIdClass.equals(Double.class)) {
return o -> ((Number) o).doubleValue();
} else if (elementIdClass.equals(Float.class)) {
return o -> ((Number) o).floatValue();
} else if (elementIdClass.equals(String.class)) {
return o -> o.toString();
}
}
} else if (id instanceof String) {
if (elementIdClass != null) {
final String s = (String) id;
if (elementIdClass.equals(Long.class)) {
return o -> Long.parseLong(s);
} else if (elementIdClass.equals(Integer.class)) {
return o -> Integer.parseInt(s);
} else if (elementIdClass.equals(Double.class)) {
return o -> Double.parseDouble(s);
} else if (elementIdClass.equals(Float.class)) {
return o -> Float.parseFloat(s);
} else if (elementIdClass.equals(UUID.class)) {
return o -> UUID.fromString(s);
}
}
}
return UnaryOperator.identity();
}
/**
* TinkerGraph will use an implementation of this interface to generate identifiers when a user does not supply
* them and to handle identifier conversions when querying to provide better flexibility with respect to
* handling different data types that mean the same thing. For example, the
* {@link DefaultIdManager#LONG} implementation will allow {@code g.vertices(1l, 2l)} and
* {@code g.vertices(1, 2)} to both return values.
*
* @param <T> the id type
*/
public interface IdManager<T> {
/**
* Generate an identifier which should be unique to the {@link TinkerGraph} instance.
*/
T getNextId(final TinkerGraph graph);
/**
* Convert an identifier to the type required by the manager.
*/
T convert(final Object id);
}
public enum DefaultIdManager implements IdManager {
LONG {
private long currentId = -1l;
@Override
public Long getNextId(final TinkerGraph graph) {
return Stream.generate(() -> (++currentId)).filter(id -> !graph.vertices.containsKey(id) && !graph.edges.containsKey(id)).findAny().get();
}
@Override
public Object convert(final Object id) {
if (id instanceof Number)
return ((Number) id).longValue();
else if (id instanceof String)
return Long.parseLong((String) id);
else
throw new IllegalArgumentException("Expected an id that is convertible to Long");
}
},
INTEGER {
private int currentId = -1;
@Override
public Integer getNextId(final TinkerGraph graph) {
return Stream.generate(() -> (++currentId)).filter(id -> !graph.vertices.containsKey(id) && !graph.edges.containsKey(id)).findAny().get();
}
@Override
public Object convert(final Object id) {
if (id instanceof Number)
return ((Number) id).intValue();
else if (id instanceof String)
return Integer.parseInt((String) id);
else
throw new IllegalArgumentException("Expected an id that is convertible to Integer");
}
},
UUID {
@Override
public UUID getNextId(final TinkerGraph graph) {
return java.util.UUID.randomUUID();
}
@Override
public Object convert(final Object id) {
if (id instanceof java.util.UUID)
return id;
else if (id instanceof String)
return java.util.UUID.fromString((String) id);
else
throw new IllegalArgumentException("Expected an id that is convertible to UUID");
}
},
ANY {
private long currentId = -1l;
@Override
public Long getNextId(final TinkerGraph graph) {
return Stream.generate(() -> (++currentId)).filter(id -> !graph.vertices.containsKey(id) && !graph.edges.containsKey(id)).findAny().get();
}
@Override
public Object convert(final Object id) {
return id;
}
}
}
}
| tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.tinkergraph.structure;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.tinkergraph.process.computer.TinkerGraphComputer;
import org.apache.tinkerpop.gremlin.tinkergraph.process.computer.TinkerGraphView;
import org.apache.tinkerpop.gremlin.tinkergraph.process.traversal.strategy.optimization.TinkerGraphStepStrategy;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
/**
* An in-sideEffects, reference implementation of the property graph interfaces provided by Gremlin3.
*
* @author Marko A. Rodriguez (http://markorodriguez.com)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
@Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_STANDARD)
@Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_PERFORMANCE)
@Graph.OptIn(Graph.OptIn.SUITE_PROCESS_STANDARD)
@Graph.OptIn(Graph.OptIn.SUITE_PROCESS_COMPUTER)
@Graph.OptIn(Graph.OptIn.SUITE_PROCESS_PERFORMANCE)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_PROCESS_STANDARD)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_PROCESS_COMPUTER)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_ENVIRONMENT)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_ENVIRONMENT_INTEGRATE)
@Graph.OptIn(Graph.OptIn.SUITE_GROOVY_ENVIRONMENT_PERFORMANCE)
public class TinkerGraph implements Graph {
static {
TraversalStrategies.GlobalCache.registerStrategies(TinkerGraph.class, TraversalStrategies.GlobalCache.getStrategies(Graph.class).clone().addStrategies(TinkerGraphStepStrategy.instance()));
}
private static final Configuration EMPTY_CONFIGURATION = new BaseConfiguration() {{
this.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
}};
public static final String CONFIG_VERTEX_ID = "tinkergraph.vertex.id";
public static final String CONFIG_EDGE_ID = "tinkergraph.edge.id";
public static final String CONFIG_VERTEX_PROPERTY_ID = "tinkergraph.vertex-property.id";
protected Long currentId = -1l;
protected Map<Object, Vertex> vertices = new ConcurrentHashMap<>();
protected Map<Object, Edge> edges = new ConcurrentHashMap<>();
protected TinkerGraphVariables variables = null;
protected TinkerGraphView graphView = null;
protected TinkerIndex<TinkerVertex> vertexIndex = null;
protected TinkerIndex<TinkerEdge> edgeIndex = null;
private final static TinkerGraph EMPTY_GRAPH = new TinkerGraph(EMPTY_CONFIGURATION);
protected IdManager<?> vertexIdManager;
protected IdManager<?> edgeIdManager;
protected IdManager<?> vertexPropertyIdManager;
private final Configuration configuration;
/**
* An empty private constructor that initializes {@link TinkerGraph}.
*/
private TinkerGraph(final Configuration configuration) {
this.configuration = configuration;
final String vertexIdManagerConfigValue = configuration.getString(CONFIG_VERTEX_ID, DefaultIdManager.ANY.name());
try {
vertexIdManager = DefaultIdManager.valueOf(vertexIdManagerConfigValue);
} catch (IllegalArgumentException iae) {
try {
vertexIdManager = (IdManager) Class.forName(vertexIdManagerConfigValue).newInstance();
} catch (Exception ex) {
throw new IllegalStateException(String.format("Could not configure TinkerGraph vertex id manager with %s", vertexIdManagerConfigValue));
}
}
final String edgeIdManagerConfigValue = configuration.getString(CONFIG_EDGE_ID, DefaultIdManager.ANY.name());
try {
edgeIdManager = DefaultIdManager.valueOf(edgeIdManagerConfigValue);
} catch (IllegalArgumentException iae) {
try {
edgeIdManager = (IdManager) Class.forName(edgeIdManagerConfigValue).newInstance();
} catch (Exception ex) {
throw new IllegalStateException(String.format("Could not configure TinkerGraph edge id manager with %s", edgeIdManagerConfigValue));
}
}
final String vertexPropIdManagerConfigValue = configuration.getString(CONFIG_VERTEX_PROPERTY_ID, DefaultIdManager.ANY.name());
try {
vertexPropertyIdManager = DefaultIdManager.valueOf(vertexPropIdManagerConfigValue);
} catch (IllegalArgumentException iae) {
try {
vertexPropertyIdManager = (IdManager) Class.forName(vertexPropIdManagerConfigValue).newInstance();
} catch (Exception ex) {
throw new IllegalStateException(String.format("Could not configure TinkerGraph vertex property id manager with %s", vertexPropIdManagerConfigValue));
}
}
}
public static TinkerGraph empty() {
return EMPTY_GRAPH;
}
/**
* Open a new {@link TinkerGraph} instance.
* <p/>
* <b>Reference Implementation Help:</b> If a {@link org.apache.tinkerpop.gremlin.structure.Graph } implementation does not require a
* {@link org.apache.commons.configuration.Configuration} (or perhaps has a default configuration) it can choose to implement a zero argument
* open() method. This is an optional constructor method for TinkerGraph. It is not enforced by the Gremlin
* Test Suite.
*/
public static TinkerGraph open() {
return open(EMPTY_CONFIGURATION);
}
/**
* Open a new {@link TinkerGraph} instance.
* <p/>
* <b>Reference Implementation Help:</b> This method is the one use by the
* {@link org.apache.tinkerpop.gremlin.structure.util.GraphFactory} to instantiate
* {@link org.apache.tinkerpop.gremlin.structure.Graph} instances. This method must be overridden for the Structure Test
* Suite to pass. Implementers have latitude in terms of how exceptions are handled within this method. Such
* exceptions will be considered implementation specific by the test suite as all test generate graph instances
* by way of {@link org.apache.tinkerpop.gremlin.structure.util.GraphFactory}. As such, the exceptions get generalized
* behind that facade and since {@link org.apache.tinkerpop.gremlin.structure.util.GraphFactory} is the preferred method
* to opening graphs it will be consistent at that level.
*
* @param configuration the configuration for the instance
* @return a newly opened {@link org.apache.tinkerpop.gremlin.structure.Graph}
*/
public static TinkerGraph open(final Configuration configuration) {
return new TinkerGraph(configuration);
}
////////////// STRUCTURE API METHODS //////////////////
@Override
public Vertex addVertex(final Object... keyValues) {
ElementHelper.legalPropertyKeyValueArray(keyValues);
Object idValue = ElementHelper.getIdValue(keyValues).orElse(null);
final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
if (null != idValue) {
if (this.vertices.containsKey(idValue))
throw Exceptions.vertexWithIdAlreadyExists(idValue);
} else {
idValue = vertexIdManager.getNextId(this);
}
final Vertex vertex = new TinkerVertex(idValue, label, this);
this.vertices.put(vertex.id(), vertex);
ElementHelper.attachProperties(vertex, VertexProperty.Cardinality.list, keyValues);
return vertex;
}
@Override
public <C extends GraphComputer> C compute(final Class<C> graphComputerClass) {
if (!graphComputerClass.equals(TinkerGraphComputer.class))
throw Graph.Exceptions.graphDoesNotSupportProvidedGraphComputer(graphComputerClass);
return (C) new TinkerGraphComputer(this);
}
@Override
public GraphComputer compute() {
return new TinkerGraphComputer(this);
}
@Override
public Variables variables() {
if (null == this.variables)
this.variables = new TinkerGraphVariables();
return this.variables;
}
@Override
public String toString() {
return StringFactory.graphString(this, "vertices:" + this.vertices.size() + " edges:" + this.edges.size());
}
public void clear() {
this.vertices.clear();
this.edges.clear();
this.variables = null;
this.currentId = 0l;
this.vertexIndex = null;
this.edgeIndex = null;
}
@Override
public void close() {
this.graphView = null;
}
@Override
public Transaction tx() {
throw Exceptions.transactionsNotSupported();
}
@Override
public Configuration configuration() {
return configuration;
}
@Override
public Iterator<Vertex> vertices(final Object... vertexIds) {
// todo: this code looks a lot like edges() code - better reuse here somewhere?
// todo: what if we have Reference/DetachedVertex???????????????????????????
if (0 == vertexIds.length) {
return this.vertices.values().iterator();
} else if (1 == vertexIds.length) {
if (vertexIds[0] instanceof Vertex) {
// no need to get the vertex again, so just flip it back - some implementation may want to treat this
// as a refresh operation. that's not necessary for tinkergraph.
return IteratorUtils.of((Vertex) vertexIds[0]);
} else {
// convert the id to the expected data type and lookup the vertex
final Vertex vertex = this.vertices.get(vertexIdManager.convert(vertexIds[0]));
return null == vertex ? Collections.emptyIterator() : IteratorUtils.of(vertex);
}
} else {
// base the conversion function on the first item in the id list as the expectation is that these
// id values will be a uniform list
if (vertexIds[0] instanceof Vertex) {
// based on the first item assume all vertices in the argument list
if (!Stream.of(vertexIds).allMatch(id -> id instanceof Vertex))
throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();
// no need to get the vertices again, so just flip it back - some implementation may want to treat this
// as a refresh operation. that's not necessary for tinkergraph.
return Stream.of(vertexIds).map(id -> (Vertex) id).iterator();
} else {
final Class<?> firstClass = vertexIds[0].getClass();
if (!Stream.of(vertexIds).map(Object::getClass).allMatch(firstClass::equals))
throw Graph.Exceptions.idArgsMustBeEitherIdOrElement(); // todo: change exception to be ids of the same type
return Stream.of(vertexIds).map(vertexIdManager::convert).map(this.vertices::get).filter(Objects::nonNull).iterator();
}
}
}
@Override
public Iterator<Edge> edges(final Object... edgeIds) {
if (0 == edgeIds.length) {
return this.edges.values().iterator();
} else if (1 == edgeIds.length) {
if (edgeIds[0] instanceof Edge) {
// no need to get the edge again, so just flip it back - some implementation may want to treat this
// as a refresh operation. that's not necessary for tinkergraph.
return IteratorUtils.of((Edge) edgeIds[0]);
} else {
// convert the id to the expected data type and lookup the vertex
final Edge edge = this.edges.get(edgeIdManager.convert(edgeIds[0]));
return null == edge ? Collections.emptyIterator() : IteratorUtils.of(edge);
}
} else {
// base the conversion function on the first item in the id list as the expectation is that these
// id values will be a uniform list
if (edgeIds[0] instanceof Edge) {
// based on the first item assume all vertices in the argument list
if (!Stream.of(edgeIds).allMatch(id -> id instanceof Edge))
throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();
// no need to get the vertices again, so just flip it back - some implementation may want to treat this
// as a refresh operation. that's not necessary for tinkergraph.
return Stream.of(edgeIds).map(id -> (Edge) id).iterator();
} else {
final Class<?> firstClass = edgeIds[0].getClass();
if (!Stream.of(edgeIds).map(Object::getClass).allMatch(firstClass::equals))
throw Graph.Exceptions.idArgsMustBeEitherIdOrElement(); // todo: change exception to be ids of the same type
return Stream.of(edgeIds).map(edgeIdManager::convert).map(this.edges::get).filter(Objects::nonNull).iterator();
}
}
}
/**
* Return TinkerGraph feature set.
* <p/>
* <b>Reference Implementation Help:</b> Implementers only need to implement features for which there are
* negative or instance configured features. By default, all {@link Features} return true.
*/
@Override
public Features features() {
return TinkerGraphFeatures.INSTANCE;
}
public static class TinkerGraphFeatures implements Features {
static final TinkerGraphFeatures INSTANCE = new TinkerGraphFeatures();
private TinkerGraphFeatures() {
}
@Override
public GraphFeatures graph() {
return TinkerGraphGraphFeatures.INSTANCE;
}
@Override
public EdgeFeatures edge() {
return TinkerGraphEdgeFeatures.INSTANCE;
}
@Override
public VertexFeatures vertex() {
return TinkerGraphVertexFeatures.INSTANCE;
}
@Override
public String toString() {
return StringFactory.featureString(this);
}
}
public static class TinkerGraphVertexFeatures implements Features.VertexFeatures {
static final TinkerGraphVertexFeatures INSTANCE = new TinkerGraphVertexFeatures();
private TinkerGraphVertexFeatures() {
}
@Override
public boolean supportsCustomIds() {
return false;
}
}
public static class TinkerGraphEdgeFeatures implements Features.EdgeFeatures {
static final TinkerGraphEdgeFeatures INSTANCE = new TinkerGraphEdgeFeatures();
private TinkerGraphEdgeFeatures() {
}
@Override
public boolean supportsCustomIds() {
return false;
}
}
public static class TinkerGraphGraphFeatures implements Features.GraphFeatures {
static final TinkerGraphGraphFeatures INSTANCE = new TinkerGraphGraphFeatures();
private TinkerGraphGraphFeatures() {
}
@Override
public boolean supportsTransactions() {
return false;
}
@Override
public boolean supportsPersistence() {
return false;
}
@Override
public boolean supportsThreadedTransactions() {
return false;
}
}
///////////// GRAPH SPECIFIC INDEXING METHODS ///////////////
/**
* Create an index for said element class ({@link Vertex} or {@link Edge}) and said property key.
* Whenever an element has the specified key mutated, the index is updated.
* When the index is created, all existing elements are indexed to ensure that they are captured by the index.
*
* @param key the property key to index
* @param elementClass the element class to index
* @param <E> The type of the element class
*/
public <E extends Element> void createIndex(final String key, final Class<E> elementClass) {
if (Vertex.class.isAssignableFrom(elementClass)) {
if (null == this.vertexIndex) this.vertexIndex = new TinkerIndex<>(this, TinkerVertex.class);
this.vertexIndex.createKeyIndex(key);
} else if (Edge.class.isAssignableFrom(elementClass)) {
if (null == this.edgeIndex) this.edgeIndex = new TinkerIndex<>(this, TinkerEdge.class);
this.edgeIndex.createKeyIndex(key);
} else {
throw new IllegalArgumentException("Class is not indexable: " + elementClass);
}
}
/**
* Drop the index for the specified element class ({@link Vertex} or {@link Edge}) and key.
*
* @param key the property key to stop indexing
* @param elementClass the element class of the index to drop
* @param <E> The type of the element class
*/
public <E extends Element> void dropIndex(final String key, final Class<E> elementClass) {
if (Vertex.class.isAssignableFrom(elementClass)) {
if (null != this.vertexIndex) this.vertexIndex.dropKeyIndex(key);
} else if (Edge.class.isAssignableFrom(elementClass)) {
if (null != this.edgeIndex) this.edgeIndex.dropKeyIndex(key);
} else {
throw new IllegalArgumentException("Class is not indexable: " + elementClass);
}
}
/**
* Return all the keys currently being index for said element class ({@link Vertex} or {@link Edge}).
*
* @param elementClass the element class to get the indexed keys for
* @param <E> The type of the element class
* @return the set of keys currently being indexed
*/
public <E extends Element> Set<String> getIndexedKeys(final Class<E> elementClass) {
if (Vertex.class.isAssignableFrom(elementClass)) {
return null == this.vertexIndex ? Collections.emptySet() : this.vertexIndex.getIndexedKeys();
} else if (Edge.class.isAssignableFrom(elementClass)) {
return null == this.edgeIndex ? Collections.emptySet() : this.edgeIndex.getIndexedKeys();
} else {
throw new IllegalArgumentException("Class is not indexable: " + elementClass);
}
}
///////////// HELPERS METHODS ///////////////
/**
* Function to coerce a provided identifier to a different type given the expected id type of an element.
* This allows something like {@code g.V(1,2,3)} and {@code g.V(1l,2l,3l)} to both mean the same thing.
*/
private UnaryOperator<Object> convertToId(final Object id, final Class<?> elementIdClass) {
if (id instanceof Number) {
if (elementIdClass != null) {
if (elementIdClass.equals(Long.class)) {
return o -> ((Number) o).longValue();
} else if (elementIdClass.equals(Integer.class)) {
return o -> ((Number) o).intValue();
} else if (elementIdClass.equals(Double.class)) {
return o -> ((Number) o).doubleValue();
} else if (elementIdClass.equals(Float.class)) {
return o -> ((Number) o).floatValue();
} else if (elementIdClass.equals(String.class)) {
return o -> o.toString();
}
}
} else if (id instanceof String) {
if (elementIdClass != null) {
final String s = (String) id;
if (elementIdClass.equals(Long.class)) {
return o -> Long.parseLong(s);
} else if (elementIdClass.equals(Integer.class)) {
return o -> Integer.parseInt(s);
} else if (elementIdClass.equals(Double.class)) {
return o -> Double.parseDouble(s);
} else if (elementIdClass.equals(Float.class)) {
return o -> Float.parseFloat(s);
} else if (elementIdClass.equals(UUID.class)) {
return o -> UUID.fromString(s);
}
}
}
return UnaryOperator.identity();
}
public interface IdManager<T> {
T getNextId(final TinkerGraph graph);
T convert(final Object o);
}
public enum DefaultIdManager implements IdManager {
LONG {
private long currentId = -1l;
@Override
public Long getNextId(final TinkerGraph graph) {
return Stream.generate(() -> (++currentId)).filter(id -> !graph.vertices.containsKey(id) && !graph.edges.containsKey(id)).findAny().get();
}
@Override
public Object convert(final Object o) {
if (o instanceof Number)
return ((Number) o).longValue();
else if (o instanceof String)
return Long.parseLong((String) o);
else
throw new IllegalArgumentException("Expected an id that is convertible to Long");
}
},
INTEGER {
private int currentId = -1;
@Override
public Integer getNextId(final TinkerGraph graph) {
return Stream.generate(() -> (++currentId)).filter(id -> !graph.vertices.containsKey(id) && !graph.edges.containsKey(id)).findAny().get();
}
@Override
public Object convert(final Object o) {
if (o instanceof Number)
return ((Number) o).intValue();
else if (o instanceof String)
return Integer.parseInt((String) o);
else
throw new IllegalArgumentException("Expected an id that is convertible to Integer");
}
},
UUID {
@Override
public UUID getNextId(final TinkerGraph graph) {
return java.util.UUID.randomUUID();
}
@Override
public Object convert(final Object o) {
if (o instanceof java.util.UUID)
return o;
else if (o instanceof String)
return java.util.UUID.fromString((String) o);
else
throw new IllegalArgumentException("Expected an id that is convertible to UUID");
}
},
ANY {
private long currentId = -1l;
@Override
public Long getNextId(final TinkerGraph graph) {
return Stream.generate(() -> (++currentId)).filter(id -> !graph.vertices.containsKey(id) && !graph.edges.containsKey(id)).findAny().get();
}
@Override
public Object convert(final Object o) {
return o;
}
}
}
}
| Add some javadoc to the TinkerGraph.IdManager interface.
| tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java | Add some javadoc to the TinkerGraph.IdManager interface. |
|
Java | apache-2.0 | a4841c74d0c273a1299a012e42eac128d2d1e045 | 0 | telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform | package es.tid.cosmos.mobility.itineraries;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import com.twitter.elephantbird.mapreduce.io.ProtobufWritable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Reducer;
import es.tid.cosmos.mobility.Config;
import es.tid.cosmos.mobility.data.ItinMovementUtil;
import es.tid.cosmos.mobility.data.MobDataUtil;
import es.tid.cosmos.mobility.data.generated.MobProtocol.ItinTime;
import es.tid.cosmos.mobility.data.generated.MobProtocol.MobData;
/**
* Input: <Long, ItinTime>
* Output: <Long, ItinMovement>
*
* @author dmicol
*/
public class ItinMoveClientPoisReducer extends Reducer<LongWritable,
ProtobufWritable<MobData>, LongWritable, ProtobufWritable<MobData>> {
private final static int MINS_IN_ONE_HOUR = 60;
private final static int HOURS_IN_ONE_DAY = 24;
private final static int MINS_IN_ONE_DAY = MINS_IN_ONE_HOUR *
HOURS_IN_ONE_DAY;
private int maxMinutesInMoves;
private int minMinutesInMoves;
@Override
protected void setup(Context context) throws IOException,
InterruptedException {
final Configuration conf = context.getConfiguration();
this.maxMinutesInMoves = conf.getInt(Config.MAX_MINUTES_IN_MOVES,
Integer.MAX_VALUE);
this.minMinutesInMoves = conf.getInt(Config.MIN_MINUTES_IN_MOVES,
Integer.MIN_VALUE);
}
@Override
protected void reduce(LongWritable key,
Iterable<ProtobufWritable<MobData>> values,
Context context) throws IOException, InterruptedException {
List<ItinTime> locList = new LinkedList<ItinTime>();
for (ProtobufWritable<MobData> value : values) {
value.setConverter(MobData.class);
final MobData mobData = value.get();
locList.add(mobData.getItinTime());
}
final GregorianCalendar calendar = new GregorianCalendar();
for (ItinTime loc1 : locList) {
int minDistance = Integer.MAX_VALUE;
int minDifMonth = Integer.MAX_VALUE;
ItinTime minDistLoc = null;
for (ItinTime loc2 : locList) {
if (loc2 == loc1) {
continue;
}
// TODO: migrate to Java's date classes
int difMonth = loc2.getDate().getMonth()
- loc1.getDate().getMonth();
int difDay = loc2.getDate().getDay()
- loc1.getDate().getDay();
int difHour = loc2.getTime().getHour()
- loc1.getTime().getHour();
int difMin = loc2.getTime().getMinute()
- loc1.getTime().getMinute();
int nMinsMonth;
switch (loc1.getDate().getMonth()) {
case 4: case 6: case 9: case 11:
nMinsMonth = MINS_IN_ONE_DAY * 30;
break;
case 2:
if (calendar.isLeapYear(loc1.getDate().getYear())) {
nMinsMonth = MINS_IN_ONE_DAY * 29;
} else {
nMinsMonth = MINS_IN_ONE_DAY * 28;
}
break;
default:
nMinsMonth = MINS_IN_ONE_DAY * 31;
}
// TODO: we must consider the year as well
int distance = (nMinsMonth * difMonth)
+ (MINS_IN_ONE_DAY * difDay)
+ (MINS_IN_ONE_HOUR * difHour) + difMin;
if (distance >= 0 && distance < minDistance) {
minDistance = distance;
minDifMonth = difMonth;
minDistLoc = loc2;
}
}
if (minDistLoc == null ||
(minDistLoc.getBts() == loc1.getBts()) ||
(minDifMonth > 1)) {
continue;
}
// Filter movements by diff of time
if (minDistance <= this.maxMinutesInMoves &&
minDistance >= this.minMinutesInMoves) {
ProtobufWritable<MobData> move = MobDataUtil.createAndWrap(
ItinMovementUtil.create(loc1, minDistLoc));
context.write(key, move);
}
}
}
}
| cosmos/models/mobility/src/main/java/es/tid/cosmos/mobility/itineraries/ItinMoveClientPoisReducer.java | package es.tid.cosmos.mobility.itineraries;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import com.twitter.elephantbird.mapreduce.io.ProtobufWritable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Reducer;
import es.tid.cosmos.mobility.Config;
import es.tid.cosmos.mobility.data.ItinMovementUtil;
import es.tid.cosmos.mobility.data.MobDataUtil;
import es.tid.cosmos.mobility.data.generated.MobProtocol.ItinTime;
import es.tid.cosmos.mobility.data.generated.MobProtocol.MobData;
/**
* Input: <Long, ItinTime>
* Output: <Long, ItinMovement>
*
* @author dmicol
*/
public class ItinMoveClientPoisReducer extends Reducer<LongWritable,
ProtobufWritable<MobData>, LongWritable, ProtobufWritable<MobData>> {
private final static int MINS_IN_ONE_HOUR = 60;
private final static int HOURS_IN_ONE_DAY = 24;
private final static int MINS_IN_ONE_DAY = MINS_IN_ONE_HOUR *
HOURS_IN_ONE_DAY;
private int maxMinutesInMoves;
private int minMinutesInMoves;
@Override
protected void setup(Context context) throws IOException,
InterruptedException {
final Configuration conf = context.getConfiguration();
this.maxMinutesInMoves = conf.getInt(Config.MAX_MINUTES_IN_MOVES,
Integer.MAX_VALUE);
this.minMinutesInMoves = conf.getInt(Config.MIN_MINUTES_IN_MOVES,
Integer.MIN_VALUE);
}
@Override
protected void reduce(LongWritable key,
Iterable<ProtobufWritable<MobData>> values,
Context context) throws IOException, InterruptedException {
List<ItinTime> locList = new LinkedList<ItinTime>();
for (ProtobufWritable<MobData> value : values) {
value.setConverter(MobData.class);
final MobData mobData = value.get();
locList.add(mobData.getItinTime());
}
final GregorianCalendar calendar = new GregorianCalendar();
for (ItinTime loc1 : locList) {
int minDistance = Integer.MAX_VALUE;
int minDifMonth = Integer.MAX_VALUE;
ItinTime minDistLoc = null;
for (ItinTime loc2 : locList) {
if (loc2 == loc1) {
continue;
}
int difMonth = loc2.getDate().getMonth()
- loc1.getDate().getMonth();
int difDay = loc2.getDate().getDay()
- loc1.getDate().getDay();
int difHour = loc2.getTime().getHour()
- loc1.getTime().getHour();
int difMin = loc2.getTime().getMinute()
- loc1.getTime().getMinute();
int nMinsMonth;
switch (loc1.getDate().getMonth()) {
case 4: case 6: case 9: case 11:
nMinsMonth = MINS_IN_ONE_DAY * 30;
break;
case 2:
if (calendar.isLeapYear(loc1.getDate().getYear())) {
nMinsMonth = MINS_IN_ONE_DAY * 29;
} else {
nMinsMonth = MINS_IN_ONE_DAY * 28;
}
break;
default:
nMinsMonth = MINS_IN_ONE_DAY * 31;
}
// TODO: we must consider the year as well
int distance = (nMinsMonth * difMonth)
+ (MINS_IN_ONE_DAY * difDay)
+ (MINS_IN_ONE_HOUR * difHour) + difMin;
if (distance >= 0 && distance < minDistance) {
minDistance = distance;
minDifMonth = difMonth;
minDistLoc = loc2;
}
}
if (minDistLoc == null ||
(minDistLoc.getBts() == loc1.getBts()) ||
(minDifMonth > 1)) {
continue;
}
// Filter movements by diff of time
if (minDistance <= this.maxMinutesInMoves &&
minDistance >= this.minMinutesInMoves) {
ProtobufWritable<MobData> move = MobDataUtil.createAndWrap(
ItinMovementUtil.create(loc1, minDistLoc));
context.write(key, move);
}
}
}
}
| Add TODO.
| cosmos/models/mobility/src/main/java/es/tid/cosmos/mobility/itineraries/ItinMoveClientPoisReducer.java | Add TODO. |
|
Java | apache-2.0 | 38230f1de9287b52f33c183d557e1a3a28e5a3dd | 0 | Akylas/StickyListHeaders | package se.emilsjolander.stickylistheaders;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
import se.emilsjolander.stickylistheaders.WrapperViewList.LifeCycleListener;
/**
* Even though this is a FrameLayout subclass we still consider it a ListView.
* This is because of 2 reasons:
* 1. It acts like as ListView.
* 2. It used to be a ListView subclass and refactoring the name would cause compatibility errors.
*
* @author Emil Sjölander
*/
public class StickyListHeadersListView extends FrameLayout {
public interface OnHeaderClickListener {
void onHeaderClick(StickyListHeadersListView l, View header,
int itemPosition, long headerId, boolean currentlySticky);
}
/**
* Notifies the listener when the sticky headers top offset has changed.
*/
public interface OnStickyHeaderOffsetChangedListener {
/**
* @param l The view parent
* @param header The currently sticky header being offset.
* This header is not guaranteed to have it's measurements set.
* It is however guaranteed that this view has been measured,
* therefor you should user getMeasured* methods instead of
* get* methods for determining the view's size.
* @param offset The amount the sticky header is offset by towards to top of the screen.
*/
void onStickyHeaderOffsetChanged(StickyListHeadersListView l, View header, int offset);
}
/**
* Notifies the listener when the sticky header has been updated
*/
public interface OnStickyHeaderChangedListener {
/**
* @param l The view parent
* @param header The new sticky header view.
* @param itemPosition The position of the item within the adapter's data set of
* the item whose header is now sticky.
* @param headerId The id of the new sticky header.
*/
void onStickyHeaderChanged(StickyListHeadersListView l, View header,
int itemPosition, long headerId);
}
/* --- Children --- */
private WrapperViewList mList;
private View mHeader;
/* --- Header state --- */
private Long mHeaderId;
// used to not have to call getHeaderId() all the time
private Integer mHeaderPosition;
private Integer mHeaderOffset;
/* --- Delegates --- */
private OnScrollListener mOnScrollListenerDelegate;
private AdapterWrapper mAdapter;
/* --- Settings --- */
private boolean mAreHeadersSticky = true;
private boolean mClippingToPadding = true;
private boolean mIsDrawingListUnderStickyHeader = true;
private int mStickyHeaderTopOffset = 0;
private int mPaddingLeft = 0;
private int mPaddingTop = 0;
private int mPaddingRight = 0;
private int mPaddingBottom = 0;
/* --- Other --- */
private OnHeaderClickListener mOnHeaderClickListener;
private OnStickyHeaderOffsetChangedListener mOnStickyHeaderOffsetChangedListener;
private OnStickyHeaderChangedListener mOnStickyHeaderChangedListener;
private AdapterWrapperDataSetObserver mDataSetObserver;
private Drawable mDivider;
private int mDividerHeight;
public StickyListHeadersListView(Context context) {
this(context, null);
}
public StickyListHeadersListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public StickyListHeadersListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Initialize the wrapped list
mList = new WrapperViewList(context);
// null out divider, dividers are handled by adapter so they look good with headers
mDivider = mList.getDivider();
mDividerHeight = mList.getDividerHeight();
mList.setDivider(null);
mList.setDividerHeight(0);
if (attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.StickyListHeadersListView, 0, 0);
try {
// -- View attributes --
int padding = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_padding, 0);
mPaddingLeft = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingLeft, padding);
mPaddingTop = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingTop, padding);
mPaddingRight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingRight, padding);
mPaddingBottom = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingBottom, padding);
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
// Set clip to padding on the list and reset value to default on
// wrapper
mClippingToPadding = a.getBoolean(R.styleable.StickyListHeadersListView_android_clipToPadding, true);
super.setClipToPadding(true);
mList.setClipToPadding(mClippingToPadding);
// scrollbars
final int scrollBars = a.getInt(R.styleable.StickyListHeadersListView_android_scrollbars, 0x00000200);
mList.setVerticalScrollBarEnabled((scrollBars & 0x00000200) != 0);
mList.setHorizontalScrollBarEnabled((scrollBars & 0x00000100) != 0);
// overscroll
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
mList.setOverScrollMode(a.getInt(R.styleable.StickyListHeadersListView_android_overScrollMode, 0));
}
// -- ListView attributes --
mList.setFadingEdgeLength(a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_fadingEdgeLength,
mList.getVerticalFadingEdgeLength()));
final int fadingEdge = a.getInt(R.styleable.StickyListHeadersListView_android_requiresFadingEdge, 0);
if (fadingEdge == 0x00001000) {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(true);
} else if (fadingEdge == 0x00002000) {
mList.setVerticalFadingEdgeEnabled(true);
mList.setHorizontalFadingEdgeEnabled(false);
} else {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(false);
}
mList.setCacheColorHint(a
.getColor(R.styleable.StickyListHeadersListView_android_cacheColorHint, mList.getCacheColorHint()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setChoiceMode(a.getInt(R.styleable.StickyListHeadersListView_android_choiceMode,
mList.getChoiceMode()));
}
mList.setDrawSelectorOnTop(a.getBoolean(R.styleable.StickyListHeadersListView_android_drawSelectorOnTop, false));
mList.setFastScrollEnabled(a.getBoolean(R.styleable.StickyListHeadersListView_android_fastScrollEnabled,
mList.isFastScrollEnabled()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setFastScrollAlwaysVisible(a.getBoolean(
R.styleable.StickyListHeadersListView_android_fastScrollAlwaysVisible,
mList.isFastScrollAlwaysVisible()));
}
mList.setScrollBarStyle(a.getInt(R.styleable.StickyListHeadersListView_android_scrollbarStyle, 0));
if (a.hasValue(R.styleable.StickyListHeadersListView_android_listSelector)) {
mList.setSelector(a.getDrawable(R.styleable.StickyListHeadersListView_android_listSelector));
}
mList.setScrollingCacheEnabled(a.getBoolean(R.styleable.StickyListHeadersListView_android_scrollingCache,
mList.isScrollingCacheEnabled()));
if (a.hasValue(R.styleable.StickyListHeadersListView_android_divider)) {
mDivider = a.getDrawable(R.styleable.StickyListHeadersListView_android_divider);
}
mDividerHeight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_dividerHeight,
mDividerHeight);
mList.setTranscriptMode(a.getInt(R.styleable.StickyListHeadersListView_android_transcriptMode,
ListView.TRANSCRIPT_MODE_DISABLED));
// -- StickyListHeaders attributes --
mAreHeadersSticky = a.getBoolean(R.styleable.StickyListHeadersListView_hasStickyHeaders, true);
mIsDrawingListUnderStickyHeader = a.getBoolean(
R.styleable.StickyListHeadersListView_isDrawingListUnderStickyHeader,
true);
} finally {
a.recycle();
}
}
// attach some listeners to the wrapped list
mList.setLifeCycleListener(new WrapperViewListLifeCycleListener());
mList.setOnScrollListener(new WrapperListScrollListener());
addView(mList);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureHeader(mHeader);
}
private void ensureHeaderHasCorrectLayoutParams(View header) {
ViewGroup.LayoutParams lp = header.getLayoutParams();
if (lp == null) {
lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
header.setLayoutParams(lp);
} else if (lp.height == LayoutParams.MATCH_PARENT || lp.width == LayoutParams.WRAP_CONTENT) {
lp.height = LayoutParams.WRAP_CONTENT;
lp.width = LayoutParams.MATCH_PARENT;
header.setLayoutParams(lp);
}
}
private void measureHeader(View header) {
if (header != null) {
final int width = getMeasuredWidth() - mPaddingLeft - mPaddingRight;
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
measureChild(header, parentWidthMeasureSpec,
parentHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mList.layout(0, 0, mList.getMeasuredWidth(), getHeight());
if (mHeader != null) {
MarginLayoutParams lp = (MarginLayoutParams) mHeader.getLayoutParams();
int headerTop = lp.topMargin + stickyHeaderTop();
mHeader.layout(mPaddingLeft, headerTop, mHeader.getMeasuredWidth()
+ mPaddingLeft, headerTop + mHeader.getMeasuredHeight());
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
// Only draw the list here.
// The header should be drawn right after the lists children are drawn.
// This is done so that the header is above the list items
// but below the list decorators (scroll bars etc).
if (mList.getVisibility() == VISIBLE || mList.getAnimation() != null) {
drawChild(canvas, mList, 0);
}
}
// Reset values tied the header. also remove header form layout
// This is called in response to the data set or the adapter changing
private void clearHeader() {
if (mHeader != null) {
removeView(mHeader);
mHeader = null;
mHeaderId = null;
mHeaderPosition = null;
mHeaderOffset = null;
// reset the top clipping length
mList.setTopClippingLength(0);
updateHeaderVisibilities();
}
}
private void updateOrClearHeader(int firstVisiblePosition) {
final int adapterCount = mAdapter == null ? 0 : mAdapter.getCount();
if (adapterCount == 0 || !mAreHeadersSticky) {
return;
}
final int childCount = mList.getChildCount();
final int headerViewCount = mList.getHeaderViewsCount();
int headerPosition = firstVisiblePosition - headerViewCount;
if (childCount > 0) {
View firstItem = mList.getChildAt(0);
if (firstItem.getBottom() < stickyHeaderTop()) {
headerPosition++;
}
}
// It is not a mistake to call getFirstVisiblePosition() here.
// Most of the time getFixedFirstVisibleItem() should be called
// but that does not work great together with getChildAt()
final boolean doesListHaveChildren = mList.getChildCount() != 0;
final boolean isFirstViewBelowTop = doesListHaveChildren
&& mList.getFirstVisiblePosition() <= headerViewCount
&& mList.getChildAt(0).getTop() >= stickyHeaderTop();
final boolean isHeaderPositionOutsideAdapterRange = headerPosition > adapterCount - 1
|| headerPosition < 0;
if (!doesListHaveChildren || isHeaderPositionOutsideAdapterRange || isFirstViewBelowTop) {
clearHeader();
return;
}
updateHeader(Math.max(0, headerPosition));
}
private void updateHeader(int headerPosition) {
// check if there is a new header should be sticky
if (mHeaderPosition == null || mHeaderPosition != headerPosition) {
mHeaderPosition = headerPosition;
final long headerId = mAdapter.getHeaderId(headerPosition);
if (mHeaderId == null || mHeaderId != headerId) {
mHeaderId = headerId;
final View header = mAdapter.getHeaderView(mHeaderPosition, mHeader, this);
if (mHeader != header) {
if (header == null) {
throw new NullPointerException("header may not be null");
}
swapHeader(header);
}
else if(mHeader != null) {
final ViewParent parent = this.mHeader.getParent();
if(parent != this) {
if(parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(this.mHeader);
}
addView(this.mHeader);
}
}
ensureHeaderHasCorrectLayoutParams(mHeader);
measureHeader(mHeader);
if(mOnStickyHeaderChangedListener != null) {
mOnStickyHeaderChangedListener.onStickyHeaderChanged(this, mHeader, headerPosition, mHeaderId);
}
// Reset mHeaderOffset to null ensuring
// that it will be set on the header and
// not skipped for performance reasons.
mHeaderOffset = null;
}
}
int headerOffset = 0;
// Calculate new header offset
// Skip looking at the first view. it never matters because it always
// results in a headerOffset = 0
int headerBottom = mHeader.getMeasuredHeight() + stickyHeaderTop();
for (int i = 0; i < mList.getChildCount(); i++) {
final View child = mList.getChildAt(i);
final boolean doesChildHaveHeader = child instanceof WrapperView && ((WrapperView) child).hasHeader();
final boolean isChildFooter = mList.containsFooterView(child);
if (child.getTop() > stickyHeaderTop() && (doesChildHaveHeader || isChildFooter)) {
headerOffset = Math.min(child.getTop() - headerBottom, 0);
break;
}
}
setHeaderOffet(headerOffset);
if (!mIsDrawingListUnderStickyHeader) {
mList.setTopClippingLength(mHeader.getMeasuredHeight()
+ mHeaderOffset);
}
updateHeaderVisibilities();
}
private void swapHeader(View newHeader) {
if (mHeader != null) {
removeView(mHeader);
//reset transformation on removed header
transformYView(mHeader, 0);
}
final ViewParent parent = newHeader.getParent();
if(parent != this) {
if(parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(newHeader);
}
addView(newHeader);
}
mHeader = newHeader;
if (mOnHeaderClickListener != null) {
mHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mOnHeaderClickListener.onHeaderClick(
StickyListHeadersListView.this, mHeader,
mHeaderPosition, mHeaderId, true);
}
});
}
mHeader.setClickable(true);
}
// hides the headers in the list under the sticky header.
// Makes sure the other ones are showing
private void updateHeaderVisibilities() {
int top;
if (mHeader != null) {
top = mHeader.getMeasuredHeight() + (mHeaderOffset != null ? mHeaderOffset : 0) + mStickyHeaderTopOffset;
} else {
top = stickyHeaderTop();
}
int childCount = mList.getChildCount();
for (int i = 0; i < childCount; i++) {
// ensure child is a wrapper view
View child = mList.getChildAt(i);
if (!(child instanceof WrapperView)) {
continue;
}
// ensure wrapper view child has a header
WrapperView wrapperViewChild = (WrapperView) child;
if (!wrapperViewChild.hasHeader()) {
continue;
}
// update header views visibility
View childHeader = wrapperViewChild.mHeader;
if (wrapperViewChild.getTop() < top) {
if (childHeader != this.mHeader && childHeader.getVisibility() != View.INVISIBLE) {
childHeader.setVisibility(View.INVISIBLE);
}
} else {
final ViewParent parent = childHeader.getParent();
//make sure we dont remove the parent if we are the parent = sticky header
if(parent != wrapperViewChild && parent != this) {
if(parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(childHeader);
}
wrapperViewChild.addView(childHeader);
}
if (childHeader.getVisibility() != View.VISIBLE) {
childHeader.setVisibility(View.VISIBLE);
}
}
}
}
private void transformYView(View view, int offsetY) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
view.setTranslationY(offsetY);
} else {
MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.topMargin = offsetY;
view.setLayoutParams(params);
}
}
// Wrapper around setting the header offset in different ways depending on
// the API version
@SuppressLint("NewApi")
private void setHeaderOffet(int offset) {
if (mHeaderOffset == null || mHeaderOffset != offset) {
mHeaderOffset = offset;
transformYView(mHeader, mHeaderOffset);
if (mOnStickyHeaderOffsetChangedListener != null) {
mOnStickyHeaderOffsetChangedListener.onStickyHeaderOffsetChanged(this, mHeader, -mHeaderOffset);
}
}
}
private class AdapterWrapperDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
clearHeader();
}
@Override
public void onInvalidated() {
clearHeader();
}
}
private class WrapperListScrollListener implements OnScrollListener {
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScroll(view, firstVisibleItem,
visibleItemCount, totalItemCount);
}
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScrollStateChanged(view,
scrollState);
}
}
}
private class WrapperViewListLifeCycleListener implements LifeCycleListener {
@Override
public void onDispatchDrawOccurred(Canvas canvas) {
// onScroll is not called often at all before froyo
// therefor we need to update the header here as well.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
if (mHeader != null) {
if (mClippingToPadding) {
canvas.save();
canvas.clipRect(0, mPaddingTop, getRight(), getBottom());
drawChild(canvas, mHeader, 0);
canvas.restore();
} else {
drawChild(canvas, mHeader, 0);
}
}
}
}
private class AdapterWrapperHeaderClickHandler implements
AdapterWrapper.OnHeaderClickListener {
@Override
public void onHeaderClick(View header, int itemPosition, long headerId) {
mOnHeaderClickListener.onHeaderClick(
StickyListHeadersListView.this, header, itemPosition,
headerId, false);
}
}
private boolean isStartOfSection(int position) {
return position == 0 || mAdapter.getHeaderId(position) != mAdapter.getHeaderId(position - 1);
}
public int getHeaderOverlap(int position) {
boolean isStartOfSection = isStartOfSection(Math.max(0, position - getHeaderViewsCount()));
if (!isStartOfSection) {
View header = mAdapter.getHeaderView(position, null, mList);
if (header == null) {
throw new NullPointerException("header may not be null");
}
ensureHeaderHasCorrectLayoutParams(header);
measureHeader(header);
return header.getMeasuredHeight();
}
return 0;
}
private int stickyHeaderTop() {
return mStickyHeaderTopOffset + (mClippingToPadding ? mPaddingTop : 0);
}
/* ---------- StickyListHeaders specific API ---------- */
public void setAreHeadersSticky(boolean areHeadersSticky) {
mAreHeadersSticky = areHeadersSticky;
if (!areHeadersSticky) {
clearHeader();
} else {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
// invalidating the list will trigger dispatchDraw()
mList.invalidate();
}
public boolean areHeadersSticky() {
return mAreHeadersSticky;
}
/**
* Use areHeadersSticky() method instead
*/
@Deprecated
public boolean getAreHeadersSticky() {
return areHeadersSticky();
}
/**
*
* @param stickyHeaderTopOffset
* The offset of the sticky header fom the top of the view
*/
public void setStickyHeaderTopOffset(int stickyHeaderTopOffset) {
mStickyHeaderTopOffset = stickyHeaderTopOffset;
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
public int getStickyHeaderTopOffset() {
return mStickyHeaderTopOffset;
}
public void setDrawingListUnderStickyHeader(
boolean drawingListUnderStickyHeader) {
mIsDrawingListUnderStickyHeader = drawingListUnderStickyHeader;
// reset the top clipping length
mList.setTopClippingLength(0);
}
public boolean isDrawingListUnderStickyHeader() {
return mIsDrawingListUnderStickyHeader;
}
public void setOnHeaderClickListener(OnHeaderClickListener listener) {
mOnHeaderClickListener = listener;
if (mAdapter != null) {
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
if (mHeader != null) {
mHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mOnHeaderClickListener.onHeaderClick(
StickyListHeadersListView.this, mHeader,
mHeaderPosition, mHeaderId, true);
}
});
}
} else {
mAdapter.setOnHeaderClickListener(null);
}
}
}
public void setOnStickyHeaderOffsetChangedListener(OnStickyHeaderOffsetChangedListener listener) {
mOnStickyHeaderOffsetChangedListener = listener;
}
public void setOnStickyHeaderChangedListener(OnStickyHeaderChangedListener listener) {
mOnStickyHeaderChangedListener = listener;
}
public View getListChildAt(int index) {
return mList.getChildAt(index);
}
public int getListChildCount() {
return mList.getChildCount();
}
/**
* Use the method with extreme caution!! Changing any values on the
* underlying ListView might break everything.
*
* @return the ListView backing this view.
*/
public ListView getWrappedList() {
return mList;
}
private boolean requireSdkVersion(int versionCode) {
if (Build.VERSION.SDK_INT < versionCode) {
Log.e("StickyListHeaders", "Api lvl must be at least "+versionCode+" to call this method");
return false;
}
return true;
}
/* ---------- ListView delegate methods ---------- */
public void setAdapter(StickyListHeadersAdapter adapter) {
if (adapter == null) {
mList.setAdapter(null);
clearHeader();
return;
}
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
if (adapter instanceof SectionIndexer) {
mAdapter = new SectionIndexerAdapterWrapper(getContext(), adapter);
} else {
mAdapter = new AdapterWrapper(getContext(), adapter);
}
mDataSetObserver = new AdapterWrapperDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
mAdapter.setDivider(mDivider, mDividerHeight);
mList.setAdapter(mAdapter);
clearHeader();
}
public StickyListHeadersAdapter getAdapter() {
return mAdapter == null ? null : mAdapter.mDelegate;
}
public void setDivider(Drawable divider) {
mDivider = divider;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public void setDividerHeight(int dividerHeight) {
mDividerHeight = dividerHeight;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public Drawable getDivider() {
return mDivider;
}
public int getDividerHeight() {
return mDividerHeight;
}
public void setOnScrollListener(OnScrollListener onScrollListener) {
mOnScrollListenerDelegate = onScrollListener;
}
@Override
public void setOnTouchListener(final OnTouchListener l) {
if (l != null) {
mList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return l.onTouch(StickyListHeadersListView.this, event);
}
});
} else {
mList.setOnTouchListener(null);
}
}
public void setOnItemClickListener(OnItemClickListener listener) {
mList.setOnItemClickListener(listener);
}
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
mList.setOnItemLongClickListener(listener);
}
public void addHeaderView(View v, Object data, boolean isSelectable) {
mList.addHeaderView(v, data, isSelectable);
}
public void addHeaderView(View v) {
mList.addHeaderView(v);
}
public void removeHeaderView(View v) {
mList.removeHeaderView(v);
}
public int getHeaderViewsCount() {
return mList.getHeaderViewsCount();
}
public void addFooterView(View v, Object data, boolean isSelectable) {
mList.addFooterView(v, data, isSelectable);
}
public void addFooterView(View v) {
mList.addFooterView(v);
}
public void removeFooterView(View v) {
mList.removeFooterView(v);
}
public int getFooterViewsCount() {
return mList.getFooterViewsCount();
}
public void setEmptyView(View v) {
mList.setEmptyView(v);
}
public View getEmptyView() {
return mList.getEmptyView();
}
@Override
public boolean isVerticalScrollBarEnabled() {
return mList.isVerticalScrollBarEnabled();
}
@Override
public boolean isHorizontalScrollBarEnabled() {
return mList.isHorizontalScrollBarEnabled();
}
@Override
public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
mList.setVerticalScrollBarEnabled(verticalScrollBarEnabled);
}
@Override
public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
mList.setHorizontalScrollBarEnabled(horizontalScrollBarEnabled);
}
@Override
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public int getOverScrollMode() {
if (requireSdkVersion(Build.VERSION_CODES.GINGERBREAD)) {
return mList.getOverScrollMode();
}
return 0;
}
@Override
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void setOverScrollMode(int mode) {
if (requireSdkVersion(Build.VERSION_CODES.GINGERBREAD)) {
if (mList != null) {
mList.setOverScrollMode(mode);
}
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollBy(int distance, int duration) {
if (requireSdkVersion(Build.VERSION_CODES.FROYO)) {
mList.smoothScrollBy(distance, duration);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollByOffset(int offset) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
mList.smoothScrollByOffset(offset);
}
}
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position) {
if (requireSdkVersion(Build.VERSION_CODES.FROYO)) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mList.smoothScrollToPosition(position);
} else {
int offset = mAdapter == null ? 0 : getHeaderOverlap(position);
offset -= mClippingToPadding ? 0 : mPaddingTop;
mList.smoothScrollToPositionFromTop(position, offset);
}
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position, int boundPosition) {
if (requireSdkVersion(Build.VERSION_CODES.FROYO)) {
mList.smoothScrollToPosition(position, boundPosition);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
offset -= mClippingToPadding ? 0 : mPaddingTop;
mList.smoothScrollToPositionFromTop(position, offset);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset,
int duration) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
offset -= mClippingToPadding ? 0 : mPaddingTop;
mList.smoothScrollToPositionFromTop(position, offset, duration);
}
}
public void setSelection(int position) {
setSelectionFromTop(position, 0);
}
public void setSelectionAfterHeaderView() {
mList.setSelectionAfterHeaderView();
}
public void setSelectionFromTop(int position, int y) {
y += mAdapter == null ? 0 : getHeaderOverlap(position);
y -= mClippingToPadding ? 0 : mPaddingTop;
mList.setSelectionFromTop(position, y);
}
public void setSelector(Drawable sel) {
mList.setSelector(sel);
}
public void setSelector(int resID) {
mList.setSelector(resID);
}
public int getFirstVisiblePosition() {
return mList.getFirstVisiblePosition();
}
public int getLastVisiblePosition() {
return mList.getLastVisiblePosition();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setChoiceMode(int choiceMode) {
mList.setChoiceMode(choiceMode);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setItemChecked(int position, boolean value) {
mList.setItemChecked(position, value);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public int getCheckedItemCount() {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
return mList.getCheckedItemCount();
}
return 0;
}
@TargetApi(Build.VERSION_CODES.FROYO)
public long[] getCheckedItemIds() {
if (requireSdkVersion(Build.VERSION_CODES.FROYO)) {
return mList.getCheckedItemIds();
}
return null;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public int getCheckedItemPosition() {
return mList.getCheckedItemPosition();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public SparseBooleanArray getCheckedItemPositions() {
return mList.getCheckedItemPositions();
}
public int getCount() {
return mList.getCount();
}
public Object getItemAtPosition(int position) {
return mList.getItemAtPosition(position);
}
public long getItemIdAtPosition(int position) {
return mList.getItemIdAtPosition(position);
}
@Override
public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
mList.setOnCreateContextMenuListener(l);
}
@Override
public boolean showContextMenu() {
return mList.showContextMenu();
}
public void invalidateViews() {
mList.invalidateViews();
}
@Override
public void setClipToPadding(boolean clipToPadding) {
if (mList != null) {
mList.setClipToPadding(clipToPadding);
}
mClippingToPadding = clipToPadding;
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
mPaddingLeft = left;
mPaddingTop = top;
mPaddingRight = right;
mPaddingBottom = bottom;
if (mList != null) {
mList.setPadding(left, top, right, bottom);
}
super.setPadding(0, 0, 0, 0);
requestLayout();
}
/*
* Overrides an @hide method in View
*/
protected void recomputePadding() {
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
@Override
public int getPaddingLeft() {
return mPaddingLeft;
}
@Override
public int getPaddingTop() {
return mPaddingTop;
}
@Override
public int getPaddingRight() {
return mPaddingRight;
}
@Override
public int getPaddingBottom() {
return mPaddingBottom;
}
public void setFastScrollEnabled(boolean fastScrollEnabled) {
mList.setFastScrollEnabled(fastScrollEnabled);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setFastScrollAlwaysVisible(boolean alwaysVisible) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
mList.setFastScrollAlwaysVisible(alwaysVisible);
}
}
/**
* @return true if the fast scroller will always show. False on pre-Honeycomb devices.
* @see android.widget.AbsListView#isFastScrollAlwaysVisible()
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean isFastScrollAlwaysVisible() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return false;
}
return mList.isFastScrollAlwaysVisible();
}
public void setScrollBarStyle(int style) {
mList.setScrollBarStyle(style);
}
public int getScrollBarStyle() {
return mList.getScrollBarStyle();
}
public int getPositionForView(View view) {
return mList.getPositionForView(view);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setMultiChoiceModeListener(MultiChoiceModeListener listener) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
mList.setMultiChoiceModeListener(listener);
}
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
if (superState != BaseSavedState.EMPTY_STATE) {
throw new IllegalStateException("Handling non empty state of parent class is not implemented");
}
return mList.onSaveInstanceState();
}
@Override
public void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(BaseSavedState.EMPTY_STATE);
mList.onRestoreInstanceState(state);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public boolean canScrollVertically(int direction) {
return mList.canScrollVertically(direction);
}
public void setTranscriptMode (int mode) {
mList.setTranscriptMode(mode);
}
public void setBlockLayoutChildren(boolean blockLayoutChildren) {
mList.setBlockLayoutChildren(blockLayoutChildren);
}
}
| library/src/se/emilsjolander/stickylistheaders/StickyListHeadersListView.java | package se.emilsjolander.stickylistheaders;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
import se.emilsjolander.stickylistheaders.WrapperViewList.LifeCycleListener;
/**
* Even though this is a FrameLayout subclass we still consider it a ListView.
* This is because of 2 reasons:
* 1. It acts like as ListView.
* 2. It used to be a ListView subclass and refactoring the name would cause compatibility errors.
*
* @author Emil Sjölander
*/
public class StickyListHeadersListView extends FrameLayout {
public interface OnHeaderClickListener {
void onHeaderClick(StickyListHeadersListView l, View header,
int itemPosition, long headerId, boolean currentlySticky);
}
/**
* Notifies the listener when the sticky headers top offset has changed.
*/
public interface OnStickyHeaderOffsetChangedListener {
/**
* @param l The view parent
* @param header The currently sticky header being offset.
* This header is not guaranteed to have it's measurements set.
* It is however guaranteed that this view has been measured,
* therefor you should user getMeasured* methods instead of
* get* methods for determining the view's size.
* @param offset The amount the sticky header is offset by towards to top of the screen.
*/
void onStickyHeaderOffsetChanged(StickyListHeadersListView l, View header, int offset);
}
/**
* Notifies the listener when the sticky header has been updated
*/
public interface OnStickyHeaderChangedListener {
/**
* @param l The view parent
* @param header The new sticky header view.
* @param itemPosition The position of the item within the adapter's data set of
* the item whose header is now sticky.
* @param headerId The id of the new sticky header.
*/
void onStickyHeaderChanged(StickyListHeadersListView l, View header,
int itemPosition, long headerId);
}
/* --- Children --- */
private WrapperViewList mList;
private View mHeader;
/* --- Header state --- */
private Long mHeaderId;
// used to not have to call getHeaderId() all the time
private Integer mHeaderPosition;
private Integer mHeaderOffset;
/* --- Delegates --- */
private OnScrollListener mOnScrollListenerDelegate;
private AdapterWrapper mAdapter;
/* --- Settings --- */
private boolean mAreHeadersSticky = true;
private boolean mClippingToPadding = true;
private boolean mIsDrawingListUnderStickyHeader = true;
private int mStickyHeaderTopOffset = 0;
private int mPaddingLeft = 0;
private int mPaddingTop = 0;
private int mPaddingRight = 0;
private int mPaddingBottom = 0;
/* --- Other --- */
private OnHeaderClickListener mOnHeaderClickListener;
private OnStickyHeaderOffsetChangedListener mOnStickyHeaderOffsetChangedListener;
private OnStickyHeaderChangedListener mOnStickyHeaderChangedListener;
private AdapterWrapperDataSetObserver mDataSetObserver;
private Drawable mDivider;
private int mDividerHeight;
public StickyListHeadersListView(Context context) {
this(context, null);
}
public StickyListHeadersListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public StickyListHeadersListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Initialize the wrapped list
mList = new WrapperViewList(context);
// null out divider, dividers are handled by adapter so they look good with headers
mDivider = mList.getDivider();
mDividerHeight = mList.getDividerHeight();
mList.setDivider(null);
mList.setDividerHeight(0);
if (attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.StickyListHeadersListView, 0, 0);
try {
// -- View attributes --
int padding = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_padding, 0);
mPaddingLeft = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingLeft, padding);
mPaddingTop = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingTop, padding);
mPaddingRight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingRight, padding);
mPaddingBottom = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingBottom, padding);
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
// Set clip to padding on the list and reset value to default on
// wrapper
mClippingToPadding = a.getBoolean(R.styleable.StickyListHeadersListView_android_clipToPadding, true);
super.setClipToPadding(true);
mList.setClipToPadding(mClippingToPadding);
// scrollbars
final int scrollBars = a.getInt(R.styleable.StickyListHeadersListView_android_scrollbars, 0x00000200);
mList.setVerticalScrollBarEnabled((scrollBars & 0x00000200) != 0);
mList.setHorizontalScrollBarEnabled((scrollBars & 0x00000100) != 0);
// overscroll
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
mList.setOverScrollMode(a.getInt(R.styleable.StickyListHeadersListView_android_overScrollMode, 0));
}
// -- ListView attributes --
mList.setFadingEdgeLength(a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_fadingEdgeLength,
mList.getVerticalFadingEdgeLength()));
final int fadingEdge = a.getInt(R.styleable.StickyListHeadersListView_android_requiresFadingEdge, 0);
if (fadingEdge == 0x00001000) {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(true);
} else if (fadingEdge == 0x00002000) {
mList.setVerticalFadingEdgeEnabled(true);
mList.setHorizontalFadingEdgeEnabled(false);
} else {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(false);
}
mList.setCacheColorHint(a
.getColor(R.styleable.StickyListHeadersListView_android_cacheColorHint, mList.getCacheColorHint()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setChoiceMode(a.getInt(R.styleable.StickyListHeadersListView_android_choiceMode,
mList.getChoiceMode()));
}
mList.setDrawSelectorOnTop(a.getBoolean(R.styleable.StickyListHeadersListView_android_drawSelectorOnTop, false));
mList.setFastScrollEnabled(a.getBoolean(R.styleable.StickyListHeadersListView_android_fastScrollEnabled,
mList.isFastScrollEnabled()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setFastScrollAlwaysVisible(a.getBoolean(
R.styleable.StickyListHeadersListView_android_fastScrollAlwaysVisible,
mList.isFastScrollAlwaysVisible()));
}
mList.setScrollBarStyle(a.getInt(R.styleable.StickyListHeadersListView_android_scrollbarStyle, 0));
if (a.hasValue(R.styleable.StickyListHeadersListView_android_listSelector)) {
mList.setSelector(a.getDrawable(R.styleable.StickyListHeadersListView_android_listSelector));
}
mList.setScrollingCacheEnabled(a.getBoolean(R.styleable.StickyListHeadersListView_android_scrollingCache,
mList.isScrollingCacheEnabled()));
if (a.hasValue(R.styleable.StickyListHeadersListView_android_divider)) {
mDivider = a.getDrawable(R.styleable.StickyListHeadersListView_android_divider);
}
mDividerHeight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_dividerHeight,
mDividerHeight);
mList.setTranscriptMode(a.getInt(R.styleable.StickyListHeadersListView_android_transcriptMode,
ListView.TRANSCRIPT_MODE_DISABLED));
// -- StickyListHeaders attributes --
mAreHeadersSticky = a.getBoolean(R.styleable.StickyListHeadersListView_hasStickyHeaders, true);
mIsDrawingListUnderStickyHeader = a.getBoolean(
R.styleable.StickyListHeadersListView_isDrawingListUnderStickyHeader,
true);
} finally {
a.recycle();
}
}
// attach some listeners to the wrapped list
mList.setLifeCycleListener(new WrapperViewListLifeCycleListener());
mList.setOnScrollListener(new WrapperListScrollListener());
addView(mList);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureHeader(mHeader);
}
private void ensureHeaderHasCorrectLayoutParams(View header) {
ViewGroup.LayoutParams lp = header.getLayoutParams();
if (lp == null) {
lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
header.setLayoutParams(lp);
} else if (lp.height == LayoutParams.MATCH_PARENT || lp.width == LayoutParams.WRAP_CONTENT) {
lp.height = LayoutParams.WRAP_CONTENT;
lp.width = LayoutParams.MATCH_PARENT;
header.setLayoutParams(lp);
}
}
private void measureHeader(View header) {
if (header != null) {
final int width = getMeasuredWidth() - mPaddingLeft - mPaddingRight;
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
measureChild(header, parentWidthMeasureSpec,
parentHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mList.layout(0, 0, mList.getMeasuredWidth(), getHeight());
if (mHeader != null) {
MarginLayoutParams lp = (MarginLayoutParams) mHeader.getLayoutParams();
int headerTop = lp.topMargin + stickyHeaderTop();
mHeader.layout(mPaddingLeft, headerTop, mHeader.getMeasuredWidth()
+ mPaddingLeft, headerTop + mHeader.getMeasuredHeight());
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
// Only draw the list here.
// The header should be drawn right after the lists children are drawn.
// This is done so that the header is above the list items
// but below the list decorators (scroll bars etc).
if (mList.getVisibility() == VISIBLE || mList.getAnimation() != null) {
drawChild(canvas, mList, 0);
}
}
// Reset values tied the header. also remove header form layout
// This is called in response to the data set or the adapter changing
private void clearHeader() {
if (mHeader != null) {
removeView(mHeader);
mHeader = null;
mHeaderId = null;
mHeaderPosition = null;
mHeaderOffset = null;
// reset the top clipping length
mList.setTopClippingLength(0);
updateHeaderVisibilities();
}
}
private void updateOrClearHeader(int firstVisiblePosition) {
final int adapterCount = mAdapter == null ? 0 : mAdapter.getCount();
if (adapterCount == 0 || !mAreHeadersSticky) {
return;
}
final int childCount = mList.getChildCount();
final int headerViewCount = mList.getHeaderViewsCount();
int headerPosition = firstVisiblePosition - headerViewCount;
if (childCount > 0) {
View firstItem = mList.getChildAt(0);
if (firstItem.getBottom() < stickyHeaderTop()) {
headerPosition++;
}
}
// It is not a mistake to call getFirstVisiblePosition() here.
// Most of the time getFixedFirstVisibleItem() should be called
// but that does not work great together with getChildAt()
final boolean doesListHaveChildren = mList.getChildCount() != 0;
final boolean isFirstViewBelowTop = doesListHaveChildren
&& mList.getFirstVisiblePosition() <= headerViewCount
&& mList.getChildAt(0).getTop() >= stickyHeaderTop();
final boolean isHeaderPositionOutsideAdapterRange = headerPosition > adapterCount - 1
|| headerPosition < 0;
if (!doesListHaveChildren || isHeaderPositionOutsideAdapterRange || isFirstViewBelowTop) {
clearHeader();
return;
}
updateHeader(Math.max(0, headerPosition));
}
private void updateHeader(int headerPosition) {
// check if there is a new header should be sticky
if (mHeaderPosition == null || mHeaderPosition != headerPosition) {
mHeaderPosition = headerPosition;
final long headerId = mAdapter.getHeaderId(headerPosition);
if (mHeaderId == null || mHeaderId != headerId) {
mHeaderId = headerId;
final View header = mAdapter.getHeaderView(mHeaderPosition, mHeader, this);
if (mHeader != header) {
if (header == null) {
throw new NullPointerException("header may not be null");
}
swapHeader(header);
}
else if(mHeader != null) {
final ViewParent parent = this.mHeader.getParent();
if(parent != this) {
if(parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(this.mHeader);
}
addView(this.mHeader);
}
}
ensureHeaderHasCorrectLayoutParams(mHeader);
measureHeader(mHeader);
if(mOnStickyHeaderChangedListener != null) {
mOnStickyHeaderChangedListener.onStickyHeaderChanged(this, mHeader, headerPosition, mHeaderId);
}
// Reset mHeaderOffset to null ensuring
// that it will be set on the header and
// not skipped for performance reasons.
mHeaderOffset = null;
}
}
int headerOffset = 0;
// Calculate new header offset
// Skip looking at the first view. it never matters because it always
// results in a headerOffset = 0
int headerBottom = mHeader.getMeasuredHeight() + stickyHeaderTop();
for (int i = 0; i < mList.getChildCount(); i++) {
final View child = mList.getChildAt(i);
final boolean doesChildHaveHeader = child instanceof WrapperView && ((WrapperView) child).hasHeader();
final boolean isChildFooter = mList.containsFooterView(child);
if (child.getTop() > stickyHeaderTop() && (doesChildHaveHeader || isChildFooter)) {
headerOffset = Math.min(child.getTop() - headerBottom, 0);
break;
}
}
setHeaderOffet(headerOffset);
if (!mIsDrawingListUnderStickyHeader) {
mList.setTopClippingLength(mHeader.getMeasuredHeight()
+ mHeaderOffset);
}
updateHeaderVisibilities();
}
private void swapHeader(View newHeader) {
if (mHeader != null) {
removeView(mHeader);
}
final ViewParent parent = newHeader.getParent();
if(parent != this) {
if(parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(newHeader);
}
addView(newHeader);
}
mHeader = newHeader;
if (mOnHeaderClickListener != null) {
mHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mOnHeaderClickListener.onHeaderClick(
StickyListHeadersListView.this, mHeader,
mHeaderPosition, mHeaderId, true);
}
});
}
mHeader.setClickable(true);
}
// hides the headers in the list under the sticky header.
// Makes sure the other ones are showing
private void updateHeaderVisibilities() {
int top;
if (mHeader != null) {
top = mHeader.getMeasuredHeight() + (mHeaderOffset != null ? mHeaderOffset : 0) + mStickyHeaderTopOffset;
} else {
top = stickyHeaderTop();
}
int childCount = mList.getChildCount();
for (int i = 0; i < childCount; i++) {
// ensure child is a wrapper view
View child = mList.getChildAt(i);
if (!(child instanceof WrapperView)) {
continue;
}
// ensure wrapper view child has a header
WrapperView wrapperViewChild = (WrapperView) child;
if (!wrapperViewChild.hasHeader()) {
continue;
}
// update header views visibility
View childHeader = wrapperViewChild.mHeader;
if (wrapperViewChild.getTop() < top) {
if (childHeader.getVisibility() != View.INVISIBLE) {
childHeader.setVisibility(View.INVISIBLE);
}
} else {
final ViewParent parent = childHeader.getParent();
if(parent != wrapperViewChild) {
if(parent instanceof ViewGroup) {
((ViewGroup) parent).removeView(childHeader);
}
wrapperViewChild.addView(childHeader);
}
if (childHeader.getVisibility() != View.VISIBLE) {
childHeader.setVisibility(View.VISIBLE);
}
}
}
}
// Wrapper around setting the header offset in different ways depending on
// the API version
@SuppressLint("NewApi")
private void setHeaderOffet(int offset) {
if (mHeaderOffset == null || mHeaderOffset != offset) {
mHeaderOffset = offset;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mHeader.setTranslationY(mHeaderOffset);
} else {
MarginLayoutParams params = (MarginLayoutParams) mHeader.getLayoutParams();
params.topMargin = mHeaderOffset;
mHeader.setLayoutParams(params);
}
if (mOnStickyHeaderOffsetChangedListener != null) {
mOnStickyHeaderOffsetChangedListener.onStickyHeaderOffsetChanged(this, mHeader, -mHeaderOffset);
}
}
}
private class AdapterWrapperDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
clearHeader();
}
@Override
public void onInvalidated() {
clearHeader();
}
}
private class WrapperListScrollListener implements OnScrollListener {
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScroll(view, firstVisibleItem,
visibleItemCount, totalItemCount);
}
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScrollStateChanged(view,
scrollState);
}
}
}
private class WrapperViewListLifeCycleListener implements LifeCycleListener {
@Override
public void onDispatchDrawOccurred(Canvas canvas) {
// onScroll is not called often at all before froyo
// therefor we need to update the header here as well.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
if (mHeader != null) {
if (mClippingToPadding) {
canvas.save();
canvas.clipRect(0, mPaddingTop, getRight(), getBottom());
drawChild(canvas, mHeader, 0);
canvas.restore();
} else {
drawChild(canvas, mHeader, 0);
}
}
}
}
private class AdapterWrapperHeaderClickHandler implements
AdapterWrapper.OnHeaderClickListener {
@Override
public void onHeaderClick(View header, int itemPosition, long headerId) {
mOnHeaderClickListener.onHeaderClick(
StickyListHeadersListView.this, header, itemPosition,
headerId, false);
}
}
private boolean isStartOfSection(int position) {
return position == 0 || mAdapter.getHeaderId(position) != mAdapter.getHeaderId(position - 1);
}
public int getHeaderOverlap(int position) {
boolean isStartOfSection = isStartOfSection(Math.max(0, position - getHeaderViewsCount()));
if (!isStartOfSection) {
View header = mAdapter.getHeaderView(position, null, mList);
if (header == null) {
throw new NullPointerException("header may not be null");
}
ensureHeaderHasCorrectLayoutParams(header);
measureHeader(header);
return header.getMeasuredHeight();
}
return 0;
}
private int stickyHeaderTop() {
return mStickyHeaderTopOffset + (mClippingToPadding ? mPaddingTop : 0);
}
/* ---------- StickyListHeaders specific API ---------- */
public void setAreHeadersSticky(boolean areHeadersSticky) {
mAreHeadersSticky = areHeadersSticky;
if (!areHeadersSticky) {
clearHeader();
} else {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
// invalidating the list will trigger dispatchDraw()
mList.invalidate();
}
public boolean areHeadersSticky() {
return mAreHeadersSticky;
}
/**
* Use areHeadersSticky() method instead
*/
@Deprecated
public boolean getAreHeadersSticky() {
return areHeadersSticky();
}
/**
*
* @param stickyHeaderTopOffset
* The offset of the sticky header fom the top of the view
*/
public void setStickyHeaderTopOffset(int stickyHeaderTopOffset) {
mStickyHeaderTopOffset = stickyHeaderTopOffset;
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
public int getStickyHeaderTopOffset() {
return mStickyHeaderTopOffset;
}
public void setDrawingListUnderStickyHeader(
boolean drawingListUnderStickyHeader) {
mIsDrawingListUnderStickyHeader = drawingListUnderStickyHeader;
// reset the top clipping length
mList.setTopClippingLength(0);
}
public boolean isDrawingListUnderStickyHeader() {
return mIsDrawingListUnderStickyHeader;
}
public void setOnHeaderClickListener(OnHeaderClickListener listener) {
mOnHeaderClickListener = listener;
if (mAdapter != null) {
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
if (mHeader != null) {
mHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mOnHeaderClickListener.onHeaderClick(
StickyListHeadersListView.this, mHeader,
mHeaderPosition, mHeaderId, true);
}
});
}
} else {
mAdapter.setOnHeaderClickListener(null);
}
}
}
public void setOnStickyHeaderOffsetChangedListener(OnStickyHeaderOffsetChangedListener listener) {
mOnStickyHeaderOffsetChangedListener = listener;
}
public void setOnStickyHeaderChangedListener(OnStickyHeaderChangedListener listener) {
mOnStickyHeaderChangedListener = listener;
}
public View getListChildAt(int index) {
return mList.getChildAt(index);
}
public int getListChildCount() {
return mList.getChildCount();
}
/**
* Use the method with extreme caution!! Changing any values on the
* underlying ListView might break everything.
*
* @return the ListView backing this view.
*/
public ListView getWrappedList() {
return mList;
}
private boolean requireSdkVersion(int versionCode) {
if (Build.VERSION.SDK_INT < versionCode) {
Log.e("StickyListHeaders", "Api lvl must be at least "+versionCode+" to call this method");
return false;
}
return true;
}
/* ---------- ListView delegate methods ---------- */
public void setAdapter(StickyListHeadersAdapter adapter) {
if (adapter == null) {
mList.setAdapter(null);
clearHeader();
return;
}
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
if (adapter instanceof SectionIndexer) {
mAdapter = new SectionIndexerAdapterWrapper(getContext(), adapter);
} else {
mAdapter = new AdapterWrapper(getContext(), adapter);
}
mDataSetObserver = new AdapterWrapperDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
mAdapter.setDivider(mDivider, mDividerHeight);
mList.setAdapter(mAdapter);
clearHeader();
}
public StickyListHeadersAdapter getAdapter() {
return mAdapter == null ? null : mAdapter.mDelegate;
}
public void setDivider(Drawable divider) {
mDivider = divider;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public void setDividerHeight(int dividerHeight) {
mDividerHeight = dividerHeight;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public Drawable getDivider() {
return mDivider;
}
public int getDividerHeight() {
return mDividerHeight;
}
public void setOnScrollListener(OnScrollListener onScrollListener) {
mOnScrollListenerDelegate = onScrollListener;
}
@Override
public void setOnTouchListener(final OnTouchListener l) {
if (l != null) {
mList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return l.onTouch(StickyListHeadersListView.this, event);
}
});
} else {
mList.setOnTouchListener(null);
}
}
public void setOnItemClickListener(OnItemClickListener listener) {
mList.setOnItemClickListener(listener);
}
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
mList.setOnItemLongClickListener(listener);
}
public void addHeaderView(View v, Object data, boolean isSelectable) {
mList.addHeaderView(v, data, isSelectable);
}
public void addHeaderView(View v) {
mList.addHeaderView(v);
}
public void removeHeaderView(View v) {
mList.removeHeaderView(v);
}
public int getHeaderViewsCount() {
return mList.getHeaderViewsCount();
}
public void addFooterView(View v, Object data, boolean isSelectable) {
mList.addFooterView(v, data, isSelectable);
}
public void addFooterView(View v) {
mList.addFooterView(v);
}
public void removeFooterView(View v) {
mList.removeFooterView(v);
}
public int getFooterViewsCount() {
return mList.getFooterViewsCount();
}
public void setEmptyView(View v) {
mList.setEmptyView(v);
}
public View getEmptyView() {
return mList.getEmptyView();
}
@Override
public boolean isVerticalScrollBarEnabled() {
return mList.isVerticalScrollBarEnabled();
}
@Override
public boolean isHorizontalScrollBarEnabled() {
return mList.isHorizontalScrollBarEnabled();
}
@Override
public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
mList.setVerticalScrollBarEnabled(verticalScrollBarEnabled);
}
@Override
public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
mList.setHorizontalScrollBarEnabled(horizontalScrollBarEnabled);
}
@Override
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public int getOverScrollMode() {
if (requireSdkVersion(Build.VERSION_CODES.GINGERBREAD)) {
return mList.getOverScrollMode();
}
return 0;
}
@Override
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void setOverScrollMode(int mode) {
if (requireSdkVersion(Build.VERSION_CODES.GINGERBREAD)) {
if (mList != null) {
mList.setOverScrollMode(mode);
}
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollBy(int distance, int duration) {
if (requireSdkVersion(Build.VERSION_CODES.FROYO)) {
mList.smoothScrollBy(distance, duration);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollByOffset(int offset) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
mList.smoothScrollByOffset(offset);
}
}
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position) {
if (requireSdkVersion(Build.VERSION_CODES.FROYO)) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mList.smoothScrollToPosition(position);
} else {
int offset = mAdapter == null ? 0 : getHeaderOverlap(position);
offset -= mClippingToPadding ? 0 : mPaddingTop;
mList.smoothScrollToPositionFromTop(position, offset);
}
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position, int boundPosition) {
if (requireSdkVersion(Build.VERSION_CODES.FROYO)) {
mList.smoothScrollToPosition(position, boundPosition);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
offset -= mClippingToPadding ? 0 : mPaddingTop;
mList.smoothScrollToPositionFromTop(position, offset);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset,
int duration) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
offset -= mClippingToPadding ? 0 : mPaddingTop;
mList.smoothScrollToPositionFromTop(position, offset, duration);
}
}
public void setSelection(int position) {
setSelectionFromTop(position, 0);
}
public void setSelectionAfterHeaderView() {
mList.setSelectionAfterHeaderView();
}
public void setSelectionFromTop(int position, int y) {
y += mAdapter == null ? 0 : getHeaderOverlap(position);
y -= mClippingToPadding ? 0 : mPaddingTop;
mList.setSelectionFromTop(position, y);
}
public void setSelector(Drawable sel) {
mList.setSelector(sel);
}
public void setSelector(int resID) {
mList.setSelector(resID);
}
public int getFirstVisiblePosition() {
return mList.getFirstVisiblePosition();
}
public int getLastVisiblePosition() {
return mList.getLastVisiblePosition();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setChoiceMode(int choiceMode) {
mList.setChoiceMode(choiceMode);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setItemChecked(int position, boolean value) {
mList.setItemChecked(position, value);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public int getCheckedItemCount() {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
return mList.getCheckedItemCount();
}
return 0;
}
@TargetApi(Build.VERSION_CODES.FROYO)
public long[] getCheckedItemIds() {
if (requireSdkVersion(Build.VERSION_CODES.FROYO)) {
return mList.getCheckedItemIds();
}
return null;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public int getCheckedItemPosition() {
return mList.getCheckedItemPosition();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public SparseBooleanArray getCheckedItemPositions() {
return mList.getCheckedItemPositions();
}
public int getCount() {
return mList.getCount();
}
public Object getItemAtPosition(int position) {
return mList.getItemAtPosition(position);
}
public long getItemIdAtPosition(int position) {
return mList.getItemIdAtPosition(position);
}
@Override
public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
mList.setOnCreateContextMenuListener(l);
}
@Override
public boolean showContextMenu() {
return mList.showContextMenu();
}
public void invalidateViews() {
mList.invalidateViews();
}
@Override
public void setClipToPadding(boolean clipToPadding) {
if (mList != null) {
mList.setClipToPadding(clipToPadding);
}
mClippingToPadding = clipToPadding;
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
mPaddingLeft = left;
mPaddingTop = top;
mPaddingRight = right;
mPaddingBottom = bottom;
if (mList != null) {
mList.setPadding(left, top, right, bottom);
}
super.setPadding(0, 0, 0, 0);
requestLayout();
}
/*
* Overrides an @hide method in View
*/
protected void recomputePadding() {
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
@Override
public int getPaddingLeft() {
return mPaddingLeft;
}
@Override
public int getPaddingTop() {
return mPaddingTop;
}
@Override
public int getPaddingRight() {
return mPaddingRight;
}
@Override
public int getPaddingBottom() {
return mPaddingBottom;
}
public void setFastScrollEnabled(boolean fastScrollEnabled) {
mList.setFastScrollEnabled(fastScrollEnabled);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setFastScrollAlwaysVisible(boolean alwaysVisible) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
mList.setFastScrollAlwaysVisible(alwaysVisible);
}
}
/**
* @return true if the fast scroller will always show. False on pre-Honeycomb devices.
* @see android.widget.AbsListView#isFastScrollAlwaysVisible()
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean isFastScrollAlwaysVisible() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return false;
}
return mList.isFastScrollAlwaysVisible();
}
public void setScrollBarStyle(int style) {
mList.setScrollBarStyle(style);
}
public int getScrollBarStyle() {
return mList.getScrollBarStyle();
}
public int getPositionForView(View view) {
return mList.getPositionForView(view);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setMultiChoiceModeListener(MultiChoiceModeListener listener) {
if (requireSdkVersion(Build.VERSION_CODES.HONEYCOMB)) {
mList.setMultiChoiceModeListener(listener);
}
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
if (superState != BaseSavedState.EMPTY_STATE) {
throw new IllegalStateException("Handling non empty state of parent class is not implemented");
}
return mList.onSaveInstanceState();
}
@Override
public void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(BaseSavedState.EMPTY_STATE);
mList.onRestoreInstanceState(state);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public boolean canScrollVertically(int direction) {
return mList.canScrollVertically(direction);
}
public void setTranscriptMode (int mode) {
mList.setTranscriptMode(mode);
}
public void setBlockLayoutChildren(boolean blockLayoutChildren) {
mList.setBlockLayoutChildren(blockLayoutChildren);
}
}
| reset mHeader transform when swaping so that if it is reused
it has the right transform
| library/src/se/emilsjolander/stickylistheaders/StickyListHeadersListView.java | reset mHeader transform when swaping so that if it is reused |
|
Java | apache-2.0 | c15882eb59827cbd16add6816349b5ce2175057d | 0 | neuro-sys/logging-log4j2,codescale/logging-log4j2,lburgazzoli/apache-logging-log4j2,lburgazzoli/apache-logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,apache/logging-log4j2,pisfly/logging-log4j2,jinxuan/logging-log4j2,jinxuan/logging-log4j2,lburgazzoli/logging-log4j2,lburgazzoli/apache-logging-log4j2,lqbweb/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,renchunxiao/logging-log4j2,MagicWiz/log4j2,lburgazzoli/logging-log4j2,pisfly/logging-log4j2,neuro-sys/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2,lqbweb/logging-log4j2,renchunxiao/logging-log4j2,xnslong/logging-log4j2,ChetnaChaudhari/logging-log4j2,lqbweb/logging-log4j2,ChetnaChaudhari/logging-log4j2,apache/logging-log4j2,GFriedrich/logging-log4j2,MagicWiz/log4j2,GFriedrich/logging-log4j2,lburgazzoli/logging-log4j2 | /*
* 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.core.layout;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.net.Severity;
import org.apache.logging.log4j.core.util.KeyValuePair;
import org.apache.logging.log4j.status.StatusLogger;
import com.fasterxml.jackson.core.io.JsonStringEncoder;
/**
* Lays out events in the Graylog Extended Log Format (GELF) 1.1.
* <p>
* This layout compresses JSON to GZIP or ZLIB (the {@code compressionType}) if log event data is larger than 1024 bytes
* (the {@code compressionThreshold}). This layout does not implement chunking.
* </p>
* <p>
* Configure as follows to send to a Graylog2 server:
* </p>
*
* <pre>
* <Appenders>
* <Socket name="Graylog" protocol="udp" host="graylog.domain.com" port="12201">
* <GelfLayout host="someserver" compressionType="GZIP" compressionThreshold="1024">
* <KeyValuePair key="additionalField1" value="additional value 1"/>
* <KeyValuePair key="additionalField2" value="additional value 2"/>
* </GelfLayout>
* </Socket>
* </Appenders>
* </pre>
*
* @see <a href="http://graylog2.org/gelf">GELF home page</a>
* @see <a href="http://graylog2.org/resources/gelf/specification">GELF specification</a>
*/
@Plugin(name = "GelfLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
public final class GelfLayout extends AbstractStringLayout {
public static enum CompressionType {
GZIP {
@Override
public DeflaterOutputStream createDeflaterOutputStream(final OutputStream os) throws IOException {
return new GZIPOutputStream(os);
}
},
ZLIB {
@Override
public DeflaterOutputStream createDeflaterOutputStream(final OutputStream os) throws IOException {
return new DeflaterOutputStream(os);
}
},
OFF {
@Override
public DeflaterOutputStream createDeflaterOutputStream(final OutputStream os) throws IOException {
return null;
}
};
public abstract DeflaterOutputStream createDeflaterOutputStream(OutputStream os) throws IOException;
}
private static final char C = ',';
private static final int COMPRESSION_THRESHOLD = 1024;
private static final char Q = '\"';
private static final String QC = "\",";
private static final String QU = "\"_";
private static final long serialVersionUID = 1L;
private static final BigDecimal TIME_DIVISOR = new BigDecimal(1000);
@PluginFactory
public static GelfLayout createLayout(
//@formatter:off
@PluginAttribute("host") final String host,
@PluginElement("AdditionalField") final KeyValuePair[] additionalFields,
@PluginAttribute(value = "compressionType",
defaultString = "GZIP") final CompressionType compressionType,
@PluginAttribute(value = "compressionThreshold",
defaultInt= COMPRESSION_THRESHOLD) final int compressionThreshold) {
// @formatter:on
return new GelfLayout(host, additionalFields, compressionType, compressionThreshold);
}
/**
* http://en.wikipedia.org/wiki/Syslog#Severity_levels
*/
static int formatLevel(final Level level) {
return Severity.getSeverity(level).getCode();
}
static String formatThrowable(final Throwable throwable) {
// stack traces are big enough to provide a reasonably large initial capacity here
final StringWriter sw = new StringWriter(2048);
final PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
pw.flush();
return sw.toString();
}
static String formatTimestamp(final long timeMillis) {
return new BigDecimal(timeMillis).divide(TIME_DIVISOR).toPlainString();
}
private final KeyValuePair[] additionalFields;
private final int compressionThreshold;
private final CompressionType compressionType;
private final String host;
public GelfLayout(final String host, final KeyValuePair[] additionalFields, final CompressionType compressionType,
final int compressionThreshold) {
super(StandardCharsets.UTF_8);
this.host = host;
this.additionalFields = additionalFields;
this.compressionType = compressionType;
this.compressionThreshold = compressionThreshold;
}
private byte[] compress(final byte[] bytes) {
try {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(compressionThreshold / 8);
try (final DeflaterOutputStream stream = compressionType.createDeflaterOutputStream(baos)) {
if (stream == null) {
return bytes;
}
stream.write(bytes);
stream.finish();
}
return baos.toByteArray();
} catch (final IOException e) {
StatusLogger.getLogger().error(e);
return bytes;
}
}
@Override
public Map<String, String> getContentFormat() {
return Collections.emptyMap();
}
@Override
public String getContentType() {
return JsonLayout.CONTENT_TYPE + "; charset=" + this.getCharset();
}
@Override
public byte[] toByteArray(final LogEvent event) {
final byte[] bytes = getBytes(toSerializable(event));
return bytes.length > compressionThreshold ? compress(bytes) : bytes;
}
@Override
public String toSerializable(final LogEvent event) {
final StringBuilder builder = new StringBuilder(256);
final JsonStringEncoder jsonEncoder = JsonStringEncoder.getInstance();
builder.append('{');
builder.append("\"version\":\"1.1\",");
builder.append("\"host\":\"").append(jsonEncoder.quoteAsString(host)).append(QC);
builder.append("\"timestamp\":").append(formatTimestamp(event.getTimeMillis())).append(C);
builder.append("\"level\":").append(formatLevel(event.getLevel())).append(C);
if (event.getThreadName() != null) {
builder.append("\"_thread\":\"").append(jsonEncoder.quoteAsString(event.getThreadName())).append(QC);
}
if (event.getLoggerName() != null) {
builder.append("\"_logger\":\"").append(jsonEncoder.quoteAsString(event.getLoggerName())).append(QC);
}
for (final KeyValuePair additionalField : additionalFields) {
builder.append(QU).append(jsonEncoder.quoteAsString(additionalField.getKey())).append("\":\"")
.append(jsonEncoder.quoteAsString(additionalField.getValue())).append(QC);
}
for (final Map.Entry<String, String> entry : event.getContextMap().entrySet()) {
builder.append(QU).append(jsonEncoder.quoteAsString(entry.getKey())).append("\":\"")
.append(jsonEncoder.quoteAsString(entry.getValue())).append(QC);
}
if (event.getThrown() != null) {
builder.append("\"full_message\":\"").append(jsonEncoder.quoteAsString(formatThrowable(event.getThrown())))
.append(QC);
}
builder.append("\"short_message\":\"")
.append(jsonEncoder.quoteAsString(event.getMessage().getFormattedMessage())).append(Q);
builder.append('}');
return builder.toString();
}
}
| log4j-core/src/main/java/org/apache/logging/log4j/core/layout/GelfLayout.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.layout;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.net.Severity;
import org.apache.logging.log4j.core.util.KeyValuePair;
import org.apache.logging.log4j.status.StatusLogger;
import com.fasterxml.jackson.core.io.JsonStringEncoder;
/**
* Lays out events in the Graylog Extended Log Format (GELF) 1.1.
* <p>
* This layout compresses JSON to GZIP or ZLIB (the {@code compressionType}) if log event data is larger than 1024 bytes
* (the {@code compressionThreshold}). This layout does not implement chunking.
* </p>
* <p>
* Configure as follows to send to a Graylog2 server:
* </p>
*
* <pre>
* <Appenders>
* <Socket name="Graylog" protocol="udp" host="graylog.domain.com" port="12201">
* <GelfLayout host="someserver" compressionType="GZIP" compressionThreshold="1024">
* <KeyValuePair key="additionalField1" value="additional value 1"/>
* <KeyValuePair key="additionalField2" value="additional value 2"/>
* </GelfLayout>
* </Socket>
* </Appenders>
* </pre>
*
* @see <a href="http://graylog2.org/gelf">GELF home page</a>
* @see <a href="http://graylog2.org/resources/gelf/specification">GELF specification</a>
*/
@Plugin(name = "GelfLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
public final class GelfLayout extends AbstractStringLayout {
public static enum CompressionType {
GZIP {
@Override
public DeflaterOutputStream createDeflaterOutputStream(final OutputStream os) throws IOException {
return new GZIPOutputStream(os);
}
},
ZLIB {
@Override
public DeflaterOutputStream createDeflaterOutputStream(final OutputStream os) throws IOException {
return new DeflaterOutputStream(os);
}
},
OFF {
@Override
public DeflaterOutputStream createDeflaterOutputStream(final OutputStream os) throws IOException {
return null;
}
};
public abstract DeflaterOutputStream createDeflaterOutputStream(OutputStream os) throws IOException;
}
private static final char C = ',';
private static final int COMPRESSION_THRESHOLD = 1024;
private static final char Q = '\"';
private static final String QC = "\",";
private static final String QU = "\"_";
private static final long serialVersionUID = 1L;
private static final BigDecimal TIME_DIVISOR = new BigDecimal(1000);
@PluginFactory
public static GelfLayout createLayout(
//@formatter:off
@PluginAttribute("host") final String host,
@PluginElement("AdditionalField") final KeyValuePair[] additionalFields,
@PluginAttribute(value = "compressionType",
defaultString = "GZIP") final CompressionType compressionType,
@PluginAttribute(value = "compressionThreshold",
defaultInt= COMPRESSION_THRESHOLD) final int compressionThreshold) {
// @formatter:on
return new GelfLayout(host, additionalFields, compressionType, compressionThreshold);
}
/**
* http://en.wikipedia.org/wiki/Syslog#Severity_levels
*/
static int formatLevel(final Level level) {
return Severity.getSeverity(level).getCode();
}
static String formatThrowable(final Throwable throwable) {
// stack traces are big enough to provide a reasonably large initial capacity here
final StringWriter sw = new StringWriter(2048);
final PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
pw.flush();
return sw.toString();
}
static String formatTimestamp(final long timeMillis) {
return new BigDecimal(timeMillis).divide(TIME_DIVISOR).toPlainString();
}
private final KeyValuePair[] additionalFields;
private final int compressionThreshold;
private final CompressionType compressionType;
private final String host;
public GelfLayout(final String host, final KeyValuePair[] additionalFields, final CompressionType compressionType,
final int compressionThreshold) {
super(StandardCharsets.UTF_8);
this.host = host;
this.additionalFields = additionalFields;
this.compressionType = compressionType;
this.compressionThreshold = compressionThreshold;
}
private byte[] compress(final byte[] bytes) {
try {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(compressionThreshold / 8);
final DeflaterOutputStream stream = compressionType.createDeflaterOutputStream(baos);
if (stream == null) {
return bytes;
}
stream.write(bytes);
stream.finish();
stream.close();
return baos.toByteArray();
} catch (final IOException e) {
StatusLogger.getLogger().error(e);
return bytes;
}
}
@Override
public Map<String, String> getContentFormat() {
return Collections.emptyMap();
}
@Override
public String getContentType() {
return JsonLayout.CONTENT_TYPE + "; charset=" + this.getCharset();
}
@Override
public byte[] toByteArray(final LogEvent event) {
final byte[] bytes = getBytes(toSerializable(event));
return bytes.length > compressionThreshold ? compress(bytes) : bytes;
}
@Override
public String toSerializable(final LogEvent event) {
final StringBuilder builder = new StringBuilder(256);
final JsonStringEncoder jsonEncoder = JsonStringEncoder.getInstance();
builder.append('{');
builder.append("\"version\":\"1.1\",");
builder.append("\"host\":\"").append(jsonEncoder.quoteAsString(host)).append(QC);
builder.append("\"timestamp\":").append(formatTimestamp(event.getTimeMillis())).append(C);
builder.append("\"level\":").append(formatLevel(event.getLevel())).append(C);
if (event.getThreadName() != null) {
builder.append("\"_thread\":\"").append(jsonEncoder.quoteAsString(event.getThreadName())).append(QC);
}
if (event.getLoggerName() != null) {
builder.append("\"_logger\":\"").append(jsonEncoder.quoteAsString(event.getLoggerName())).append(QC);
}
for (final KeyValuePair additionalField : additionalFields) {
builder.append(QU).append(jsonEncoder.quoteAsString(additionalField.getKey())).append("\":\"")
.append(jsonEncoder.quoteAsString(additionalField.getValue())).append(QC);
}
for (final Map.Entry<String, String> entry : event.getContextMap().entrySet()) {
builder.append(QU).append(jsonEncoder.quoteAsString(entry.getKey())).append("\":\"")
.append(jsonEncoder.quoteAsString(entry.getValue())).append(QC);
}
if (event.getThrown() != null) {
builder.append("\"full_message\":\"").append(jsonEncoder.quoteAsString(formatThrowable(event.getThrown())))
.append(QC);
}
builder.append("\"short_message\":\"")
.append(jsonEncoder.quoteAsString(event.getMessage().getFormattedMessage())).append(Q);
builder.append('}');
return builder.toString();
}
}
| Use Java 7 try-with-resources. | log4j-core/src/main/java/org/apache/logging/log4j/core/layout/GelfLayout.java | Use Java 7 try-with-resources. |
|
Java | apache-2.0 | b42f3ca6c55d261057166cd45816b79e2d157c99 | 0 | wso2/carbon-apimgt,ruks/carbon-apimgt,malinthaprasan/carbon-apimgt,malinthaprasan/carbon-apimgt,prasa7/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,fazlan-nazeem/carbon-apimgt,prasa7/carbon-apimgt,ruks/carbon-apimgt,chamilaadhi/carbon-apimgt,ruks/carbon-apimgt,chamilaadhi/carbon-apimgt,tharindu1st/carbon-apimgt,malinthaprasan/carbon-apimgt,fazlan-nazeem/carbon-apimgt,isharac/carbon-apimgt,prasa7/carbon-apimgt,wso2/carbon-apimgt,tharindu1st/carbon-apimgt,uvindra/carbon-apimgt,uvindra/carbon-apimgt,prasa7/carbon-apimgt,tharindu1st/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharikaGitHub/carbon-apimgt,praminda/carbon-apimgt,praminda/carbon-apimgt,praminda/carbon-apimgt,wso2/carbon-apimgt,tharikaGitHub/carbon-apimgt,wso2/carbon-apimgt,malinthaprasan/carbon-apimgt,fazlan-nazeem/carbon-apimgt,isharac/carbon-apimgt,tharikaGitHub/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,ruks/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,uvindra/carbon-apimgt,uvindra/carbon-apimgt,isharac/carbon-apimgt,chamilaadhi/carbon-apimgt,fazlan-nazeem/carbon-apimgt,tharindu1st/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamilaadhi/carbon-apimgt,isharac/carbon-apimgt | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.gateway.utils;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.jwt.proc.BadJWTException;
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.util.UIDGenerator;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.clustering.ClusteringAgent;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.Mediator;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.commons.json.JsonUtil;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.RESTConstants;
import org.apache.synapse.transport.nhttp.NhttpConstants;
import org.apache.synapse.transport.passthru.PassThroughConstants;
import org.apache.synapse.transport.passthru.Pipe;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.ExceptionCodes;
import org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO;
import org.wso2.carbon.apimgt.common.gateway.dto.JWTInfoDto;
import org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo;
import org.wso2.carbon.apimgt.gateway.APIMgtGatewayConstants;
import org.wso2.carbon.apimgt.gateway.dto.IPRange;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityConstants;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException;
import org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext;
import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.gateway.threatprotection.utils.ThreatProtectorConstants;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.keymgt.SubscriptionDataHolder;
import org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore;
import org.wso2.carbon.apimgt.keymgt.model.entity.API;
import org.wso2.carbon.apimgt.tracing.TracingSpan;
import org.wso2.carbon.apimgt.tracing.Util;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.mediation.registry.RegistryServiceHolder;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GatewayUtils {
private static final Log log = LogFactory.getLog(GatewayUtils.class);
public static boolean isClusteringEnabled() {
ClusteringAgent agent = ServiceReferenceHolder.getInstance().getServerConfigurationContext().
getAxisConfiguration().getClusteringAgent();
if (agent != null) {
return true;
}
return false;
}
public static <T> Map<String, T> generateMap(Collection<T> list) {
Map<String, T> map = new HashMap<String, T>();
for (T el : list) {
map.put(el.toString(), el);
}
return map;
}
public static Map<String, Set<IPRange>> generateIpRangeMap(List<IPRange> ipRangeList) {
Map<String, Set<IPRange>> ipRangeMap = new HashMap<>();
for (IPRange ipRange : ipRangeList) {
Set<IPRange> tenantWiseIpRangeList;
if (!ipRangeMap.containsKey(ipRange.getTenantDomain())) {
tenantWiseIpRangeList = new HashSet<>();
} else {
tenantWiseIpRangeList = ipRangeMap.get(ipRange.getTenantDomain());
}
if (APIConstants.BLOCK_CONDITION_IP_RANGE.equals(ipRange.getType())) {
convertIpRangeBigIntValue(ipRange);
}
tenantWiseIpRangeList.add(ipRange);
ipRangeMap.put(ipRange.getTenantDomain(), tenantWiseIpRangeList);
}
return ipRangeMap;
}
private static void convertIpRangeBigIntValue(IPRange ipRange) {
ipRange.setStartingIpBigIntValue(APIUtil.ipToBigInteger(ipRange.getStartingIP()));
ipRange.setEndingIpBigIntValue(APIUtil.ipToBigInteger(ipRange.getEndingIp()));
}
/**
* Extracts the IP from Message Context.
*
* @param messageContext Axis2 Message Context.
* @return IP as a String.
*/
public static String getIp(MessageContext messageContext) {
//Set transport headers of the message
Map<String, String> transportHeaderMap = (Map<String, String>) messageContext
.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
// Assigning an Empty String so that when doing comparisons, .equals method can be used without explicitly
// checking for nullity.
String remoteIP = "";
//Check whether headers map is null and x forwarded for header is present
if (transportHeaderMap != null) {
remoteIP = transportHeaderMap.get(APIMgtGatewayConstants.X_FORWARDED_FOR);
}
//Setting IP of the client by looking at x forded for header and if it's empty get remote address
if (remoteIP != null && !remoteIP.isEmpty()) {
if (remoteIP.indexOf(",") > 0) {
remoteIP = remoteIP.substring(0, remoteIP.indexOf(","));
}
} else {
remoteIP = (String) messageContext.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);
}
return remoteIP;
}
/**
* Can be used to extract Query Params from {@code org.apache.axis2.context.MessageContext}.
*
* @param messageContext The Axis2 MessageContext
* @return A Map with Name Value pairs.
*/
public static Map<String, String> getQueryParams(MessageContext messageContext) {
String queryString = (String) messageContext.getProperty(NhttpConstants.REST_URL_POSTFIX);
if (!StringUtils.isEmpty(queryString)) {
if (queryString.indexOf("?") > -1) {
queryString = queryString.substring(queryString.indexOf("?") + 1);
}
String[] queryParams = queryString.split("&");
Map<String, String> queryParamsMap = new HashMap<String, String>();
String[] queryParamArray;
String queryParamName, queryParamValue = "";
for (String queryParam : queryParams) {
queryParamArray = queryParam.split("=");
if (queryParamArray.length == 2) {
queryParamName = queryParamArray[0];
queryParamValue = queryParamArray[1];
} else {
queryParamName = queryParamArray[0];
}
queryParamsMap.put(queryParamName, queryParamValue);
}
return queryParamsMap;
}
return null;
}
/**
* Get the config system registry for tenants
*
* @param tenantDomain - The tenant domain
* @return - A UserRegistry instance for the tenant
* @throws APIManagementException
*/
public static UserRegistry getRegistry(String tenantDomain) throws APIManagementException {
PrivilegedCarbonContext.startTenantFlow();
if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
}
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
UserRegistry registry;
try {
registry = RegistryServiceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
} catch (RegistryException e) {
String msg = "Failed to get registry instance for the tenant : " + tenantDomain + e.getMessage();
throw new APIManagementException(msg, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return registry;
}
/**
* Delete the given registry property from the given tenant registry path
*
* @param propertyName property name
* @param path resource path
* @param tenantDomain
* @throws AxisFault
*/
public static void deleteRegistryProperty(String propertyName, String path, String tenantDomain)
throws AxisFault {
try {
UserRegistry registry = getRegistry(tenantDomain);
PrivilegedCarbonContext.startTenantFlow();
if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
}
Resource resource = registry.get(path);
if (resource != null && resource.getProperty(propertyName) != null) {
resource.removeProperty(propertyName);
registry.put(resource.getPath(), resource);
resource.discard();
}
} catch (RegistryException | APIManagementException e) {
String msg = "Failed to delete secure endpoint password alias " + e.getMessage();
throw new AxisFault(msg, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Add/Update the given registry property from the given tenant registry
* path
*
* @param propertyName property name
* @param propertyValue property value
* @param path resource path
* @param tenantDomain
* @throws APIManagementException
*/
public static void setRegistryProperty(String propertyName, String propertyValue, String path, String tenantDomain)
throws APIManagementException {
UserRegistry registry = getRegistry(tenantDomain);
PrivilegedCarbonContext.startTenantFlow();
if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
}
try {
Resource resource = registry.get(path);
// add or update property
if (resource.getProperty(propertyName) != null) {
resource.setProperty(propertyName, propertyValue);
} else {
resource.addProperty(propertyName, propertyValue);
}
registry.put(resource.getPath(), resource);
resource.discard();
} catch (RegistryException e) {
throw new APIManagementException("Error while reading registry resource " + path + " for tenant " +
tenantDomain);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Returns the alias string of API endpoint security password
*
* @param apiProviderName
* @param apiName
* @param version
* @return
*/
public static String getAPIEndpointSecretAlias(String apiProviderName, String apiName, String version) {
String secureVaultAlias = apiProviderName + "--" + apiName + version;
return secureVaultAlias;
}
/**
* return existing correlation ID in the message context or set new correlation ID to the message context.
*
* @param messageContext synapse message context
* @return correlation ID
*/
public static String getAndSetCorrelationID(org.apache.synapse.MessageContext messageContext) {
Object correlationObj = messageContext.getProperty(APIMgtGatewayConstants.AM_CORRELATION_ID);
String correlationID;
if (correlationObj != null) {
correlationID = (String) correlationObj;
} else {
correlationID = UUID.randomUUID().toString();
messageContext.setProperty(APIMgtGatewayConstants.AM_CORRELATION_ID, correlationID);
if (log.isDebugEnabled()) {
log.debug("Setting correlation ID to message context.");
}
}
return correlationID;
}
/**
* This method handles threat violations. If the request propagates a threat, this method generates
* an custom exception.
*
* @param messageContext contains the message properties of the relevant API request which was
* enabled the regexValidator message mediation in flow.
* @param errorCode It depends on status of the error message.
* @param desc Description of the error message.It describes the vulnerable type and where it happens.
* @return here return true to continue the sequence. No need to return any value from this method.
*/
public static boolean handleThreat(org.apache.synapse.MessageContext messageContext,
String errorCode, String desc) {
messageContext.setProperty(APIMgtGatewayConstants.THREAT_FOUND, true);
messageContext.setProperty(APIMgtGatewayConstants.THREAT_CODE, errorCode);
messageContext.setProperty(SynapseConstants.ERROR_CODE, Integer.parseInt(errorCode));
if (messageContext.isResponse()) {
messageContext.setProperty(APIMgtGatewayConstants.THREAT_MSG, APIMgtGatewayConstants.BAD_RESPONSE);
messageContext.setProperty(SynapseConstants.ERROR_MESSAGE, APIMgtGatewayConstants.BAD_RESPONSE);
} else {
messageContext.setProperty(APIMgtGatewayConstants.THREAT_MSG, APIMgtGatewayConstants.BAD_REQUEST);
messageContext.setProperty(SynapseConstants.ERROR_MESSAGE, APIMgtGatewayConstants.BAD_REQUEST);
}
messageContext.setProperty(APIMgtGatewayConstants.THREAT_DESC, desc);
messageContext.setProperty(SynapseConstants.ERROR_DETAIL, desc);
Mediator sequence = messageContext.getSequence(APIMgtGatewayConstants.THREAT_FAULT);
// Invoke the custom error handler specified by the user
if (sequence != null && !sequence.mediate(messageContext)) {
// If needed user should be able to prevent the rest of the fault handling
// logic from getting executed
return false;
}
return true;
}
/**
* This method use to clone the InputStream from the the message context. Basically
* clone the request body.
*
* @param messageContext contains the message properties of the relevant API request which was
* enabled the regexValidator message mediation in flow.
* @return cloned InputStreams.
* @throws IOException this exception might occurred while cloning the inputStream.
*/
public static Map<String, InputStream> cloneRequestMessage(org.apache.synapse.MessageContext messageContext)
throws IOException {
BufferedInputStream bufferedInputStream = null;
Map<String, InputStream> inputStreamMap;
InputStream inputStreamSchema = null;
InputStream inputStreamXml = null;
InputStream inputStreamJSON = null;
InputStream inputStreamOriginal = null;
int requestBufferSize = 1024;
org.apache.axis2.context.MessageContext axis2MC;
Pipe pipe;
axis2MC = ((Axis2MessageContext) messageContext).
getAxis2MessageContext();
Object bufferSize = messageContext.getProperty(ThreatProtectorConstants.REQUEST_BUFFER_SIZE);
if (bufferSize != null) {
requestBufferSize = Integer.parseInt(bufferSize.toString());
}
pipe = (Pipe) axis2MC.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
if (pipe != null) {
bufferedInputStream = new BufferedInputStream(pipe.getInputStream());
}
inputStreamMap = new HashMap<>();
String contentType = axis2MC.getProperty(ThreatProtectorConstants.CONTENT_TYPE).toString();
if (bufferedInputStream != null) {
bufferedInputStream.mark(0);
if (bufferedInputStream.read() != -1) {
bufferedInputStream.reset();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[requestBufferSize];
int length;
while ((length = bufferedInputStream.read(buffer)) > -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
byteArrayOutputStream.flush();
inputStreamSchema = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
inputStreamXml = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
inputStreamOriginal = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
inputStreamJSON = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} else {
String payload;
if (ThreatProtectorConstants.APPLICATION_JSON.equals(contentType)) {
inputStreamJSON = JsonUtil.getJsonPayload(axis2MC);
} else {
payload = axis2MC.getEnvelope().getBody().getFirstElement().toString();
inputStreamXml = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
}
}
}
inputStreamMap.put(ThreatProtectorConstants.SCHEMA, inputStreamSchema);
inputStreamMap.put(ThreatProtectorConstants.XML, inputStreamXml);
inputStreamMap.put(ThreatProtectorConstants.ORIGINAL, inputStreamOriginal);
inputStreamMap.put(ThreatProtectorConstants.JSON, inputStreamJSON);
return inputStreamMap;
}
/**
* This method use to set the originInput stream to the message Context
*
* @param inputStreams cloned InputStreams
* @param axis2MC axis2 message context
*/
public static void setOriginalInputStream(Map<String, InputStream> inputStreams,
org.apache.axis2.context.MessageContext axis2MC) {
InputStream inputStreamOriginal;
if (inputStreams != null) {
inputStreamOriginal = inputStreams.get(ThreatProtectorConstants.ORIGINAL);
if (inputStreamOriginal != null) {
BufferedInputStream bufferedInputStreamOriginal = new BufferedInputStream(inputStreamOriginal);
axis2MC.setProperty(PassThroughConstants.BUFFERED_INPUT_STREAM, bufferedInputStreamOriginal);
}
}
}
public static String extractResource(org.apache.synapse.MessageContext mc) {
Pattern resourcePattern = Pattern.compile("^/.+?/.+?([/?].+)$");
String resource = "/";
Matcher matcher = resourcePattern.matcher((String) mc.getProperty(RESTConstants.REST_FULL_REQUEST_PATH));
if (matcher.find()) {
resource = matcher.group(1);
}
return resource;
}
public static String getHostName(org.apache.synapse.MessageContext messageContext) {
String hostname = System.getProperty("datacenterId");
if (hostname == null) {
hostname = (String) messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME);
}
return hostname;
}
public static String getQualifiedApiName(String apiName, String version) {
return apiName + ":v" + version;
}
public static String getQualifiedDefaultApiName(String apiName) {
return apiName;
}
/**
* This method extracts the endpoint address base path if query parameters are contained in endpoint
*
* @param mc The message context
* @return The endpoint address base path
*/
public static String extractAddressBasePath(org.apache.synapse.MessageContext mc) {
String endpointAddress = (String) mc.getProperty(APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS);
if (endpointAddress == null) {
endpointAddress = APIMgtGatewayConstants.DUMMY_ENDPOINT_ADDRESS;
}
if (endpointAddress.contains("?")) {
endpointAddress = endpointAddress.substring(0, endpointAddress.indexOf("?"));
}
return endpointAddress;
}
public static AuthenticationContext generateAuthenticationContext(String jti,
JWTValidationInfo jwtValidationInfo,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO,
String endUserToken,
boolean isOauth) {
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
authContext.setApiKey(jti);
authContext.setUsername(getEndUserFromJWTValidationInfo(jwtValidationInfo, apiKeyValidationInfoDTO));
if (apiKeyValidationInfoDTO != null) {
authContext.setApiTier(apiKeyValidationInfoDTO.getApiTier());
authContext.setKeyType(apiKeyValidationInfoDTO.getType());
authContext.setApplicationId(apiKeyValidationInfoDTO.getApplicationId());
authContext.setApplicationUUID(apiKeyValidationInfoDTO.getApplicationUUID());
authContext.setApplicationName(apiKeyValidationInfoDTO.getApplicationName());
authContext.setApplicationTier(apiKeyValidationInfoDTO.getApplicationTier());
authContext.setSubscriber(apiKeyValidationInfoDTO.getSubscriber());
authContext.setTier(apiKeyValidationInfoDTO.getTier());
authContext.setSubscriberTenantDomain(apiKeyValidationInfoDTO.getSubscriberTenantDomain());
authContext.setApiName(apiKeyValidationInfoDTO.getApiName());
authContext.setApiPublisher(apiKeyValidationInfoDTO.getApiPublisher());
authContext.setStopOnQuotaReach(apiKeyValidationInfoDTO.isStopOnQuotaReach());
authContext.setSpikeArrestLimit(apiKeyValidationInfoDTO.getSpikeArrestLimit());
authContext.setSpikeArrestUnit(apiKeyValidationInfoDTO.getSpikeArrestUnit());
authContext.setConsumerKey(apiKeyValidationInfoDTO.getConsumerKey());
authContext.setIsContentAware(apiKeyValidationInfoDTO.isContentAware());
}
if (isOauth) {
authContext.setConsumerKey(jwtValidationInfo.getConsumerKey());
if (jwtValidationInfo.getIssuer() != null) {
authContext.setIssuer(jwtValidationInfo.getIssuer());
}
}
// Set JWT token sent to the backend
if (StringUtils.isNotEmpty(endUserToken)) {
authContext.setCallerToken(endUserToken);
}
return authContext;
}
/**
* This method returns the end username from the JWTValidationInfo.
* If isAppToken true subscriber username from APIKeyValidationInfoDTO with tenant domain is returned as end
* username.
* If false, tenant domain of the subscriber is appended to the username from JWTValidationInfo.
* If null, same username from JWTValidation info is returned as it is.
*
* @param jwtValidationInfo JWTValidationInfo
* @param apiKeyValidationInfoDTO APIKeyValidationInfoDTO
* @return String end username
*/
private static String getEndUserFromJWTValidationInfo(JWTValidationInfo jwtValidationInfo,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO) {
Boolean isAppToken = jwtValidationInfo.getAppToken();
String endUsername = jwtValidationInfo.getUser();
if (isAppToken != null) {
if (isAppToken) {
endUsername = apiKeyValidationInfoDTO.getSubscriber();
if (!APIConstants.SUPER_TENANT_DOMAIN.equals(apiKeyValidationInfoDTO.getSubscriberTenantDomain())) {
return endUsername;
}
}
return endUsername + UserCoreConstants.TENANT_DOMAIN_COMBINER
+ apiKeyValidationInfoDTO.getSubscriberTenantDomain();
}
return endUsername;
}
public static AuthenticationContext generateAuthenticationContext(String tokenSignature, JWTClaimsSet payload,
JSONObject api, String apiLevelPolicy)
throws java.text.ParseException {
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
authContext.setApiKey(tokenSignature);
authContext.setUsername(payload.getSubject());
if (payload.getClaim(APIConstants.JwtTokenConstants.KEY_TYPE) != null) {
authContext.setKeyType(payload.getStringClaim(APIConstants.JwtTokenConstants.KEY_TYPE));
} else {
authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
}
authContext.setApiTier(apiLevelPolicy);
if (api != null) {
authContext.setTier(APIConstants.UNLIMITED_TIER);
authContext.setApiName(api.getAsString(APIConstants.JwtTokenConstants.API_NAME));
authContext.setApiPublisher(api.getAsString(APIConstants.JwtTokenConstants.API_PUBLISHER));
}
return authContext;
}
public static AuthenticationContext generateAuthenticationContext(String tokenSignature, JWTClaimsSet payload,
JSONObject api,
String apiLevelPolicy, String endUserToken,
org.apache.synapse.MessageContext synCtx)
throws java.text.ParseException {
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
authContext.setApiKey(tokenSignature);
authContext.setUsername(payload.getSubject());
if (payload.getClaim(APIConstants.JwtTokenConstants.KEY_TYPE) != null) {
authContext.setKeyType(payload.getStringClaim(APIConstants.JwtTokenConstants.KEY_TYPE));
} else {
authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
}
authContext.setApiTier(apiLevelPolicy);
if (payload.getClaim(APIConstants.JwtTokenConstants.APPLICATION) != null) {
JSONObject
applicationObj = payload.getJSONObjectClaim(APIConstants.JwtTokenConstants.APPLICATION);
authContext
.setApplicationId(
String.valueOf(applicationObj.getAsNumber(APIConstants.JwtTokenConstants.APPLICATION_ID)));
authContext.setApplicationUUID(
String.valueOf(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_UUID)));
authContext.setApplicationName(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_NAME));
authContext.setApplicationTier(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_TIER));
authContext.setSubscriber(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_OWNER));
if (applicationObj.containsKey(APIConstants.JwtTokenConstants.QUOTA_TYPE)
&& APIConstants.JwtTokenConstants.QUOTA_TYPE_BANDWIDTH
.equals(applicationObj.getAsString(APIConstants.JwtTokenConstants.QUOTA_TYPE))) {
authContext.setIsContentAware(true);
;
}
}
if (api != null) {
// If the user is subscribed to the API
String subscriptionTier = api.getAsString(APIConstants.JwtTokenConstants.SUBSCRIPTION_TIER);
authContext.setTier(subscriptionTier);
authContext.setSubscriberTenantDomain(
api.getAsString(APIConstants.JwtTokenConstants.SUBSCRIBER_TENANT_DOMAIN));
JSONObject tierInfo = payload.getJSONObjectClaim(APIConstants.JwtTokenConstants.TIER_INFO);
authContext.setApiName(api.getAsString(APIConstants.JwtTokenConstants.API_NAME));
authContext.setApiPublisher(api.getAsString(APIConstants.JwtTokenConstants.API_PUBLISHER));
if (tierInfo.get(subscriptionTier) != null) {
JSONObject subscriptionTierObj = (JSONObject) tierInfo.get(subscriptionTier);
authContext.setStopOnQuotaReach(
Boolean.parseBoolean(
subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.STOP_ON_QUOTA_REACH)));
authContext.setSpikeArrestLimit
(subscriptionTierObj.getAsNumber(APIConstants.JwtTokenConstants.SPIKE_ARREST_LIMIT).intValue());
if (!"null".equals(
subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.SPIKE_ARREST_UNIT))) {
authContext.setSpikeArrestUnit(
subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.SPIKE_ARREST_UNIT));
}
//check whether the quota type is there and it is equal to bandwithVolume type.
if (subscriptionTierObj.containsKey(APIConstants.JwtTokenConstants.QUOTA_TYPE)
&& APIConstants.JwtTokenConstants.QUOTA_TYPE_BANDWIDTH
.equals(subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.QUOTA_TYPE))) {
authContext.setIsContentAware(true);
;
}
if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
Integer graphQLMaxDepth = (int) (long) subscriptionTierObj.get(APIConstants.GRAPHQL_MAX_DEPTH);
Integer graphQLMaxComplexity =
(int) (long) subscriptionTierObj.get(APIConstants.GRAPHQL_MAX_COMPLEXITY);
synCtx.setProperty(APIConstants.MAXIMUM_QUERY_DEPTH, graphQLMaxDepth);
synCtx.setProperty(APIConstants.MAXIMUM_QUERY_COMPLEXITY, graphQLMaxComplexity);
}
}
}
// Set JWT token sent to the backend
if (StringUtils.isNotEmpty(endUserToken)) {
authContext.setCallerToken(endUserToken);
}
return authContext;
}
/**
* Validate whether the user is subscribed to the invoked API. If subscribed, return a JSON object containing
* the API information.
*
* @param apiContext API context
* @param apiVersion API version
* @param jwtValidationInfo The payload of the JWT token
* @return an JSON object containing subscribed API information retrieved from token payload.
* If the subscription information is not found, return a null object.
* @throws APISecurityException if the user is not subscribed to the API
*/
public static JSONObject validateAPISubscription(String apiContext, String apiVersion,
JWTValidationInfo jwtValidationInfo,
String jwtHeader, boolean isOauth)
throws APISecurityException {
JSONObject api = null;
if (jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS) != null) {
// Subscription validation
JSONArray subscribedAPIs =
(JSONArray) jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS);
for (int i = 0; i < subscribedAPIs.size(); i++) {
JSONObject subscribedAPIsJSONObject =
(JSONObject) subscribedAPIs.get(i);
if (apiContext
.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_CONTEXT)) &&
apiVersion
.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_VERSION)
)) {
api = subscribedAPIsJSONObject;
if (log.isDebugEnabled()) {
log.debug("User is subscribed to the API: " + apiContext + ", " +
"version: " + apiVersion + ". Token: " + getMaskedToken(jwtHeader));
}
break;
}
}
if (api == null) {
if (log.isDebugEnabled()) {
log.debug("User is not subscribed to access the API: " + apiContext +
", version: " + apiVersion + ". Token: " + getMaskedToken(jwtHeader));
}
log.error("User is not subscribed to access the API.");
throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
}
} else {
if (log.isDebugEnabled()) {
log.debug("No subscription information found in the token.");
}
// we perform mandatory authentication for Api Keys
if (!isOauth) {
log.error("User is not subscribed to access the API.");
throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
}
}
return api;
}
/**
* Validate whether the user is subscribed to the invoked API. If subscribed, return a JSON object containing
* the API information.
*
* @param apiContext API context
* @param apiVersion API version
* @param payload The payload of the JWT token
* @return an JSON object containing subscribed API information retrieved from token payload.
* If the subscription information is not found, return a null object.
* @throws APISecurityException if the user is not subscribed to the API
*/
public static JSONObject validateAPISubscription(String apiContext, String apiVersion, JWTClaimsSet payload,
String[] splitToken, boolean isOauth)
throws APISecurityException {
JSONObject api = null;
if (payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS) != null) {
// Subscription validation
JSONArray subscribedAPIs =
(JSONArray) payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS);
for (Object subscribedAPI : subscribedAPIs) {
JSONObject subscribedAPIsJSONObject = (JSONObject) subscribedAPI;
if (apiContext
.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_CONTEXT)) &&
apiVersion
.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_VERSION)
)) {
api = subscribedAPIsJSONObject;
if (log.isDebugEnabled()) {
log.debug("User is subscribed to the API: " + apiContext + ", " +
"version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0]));
}
break;
}
}
if (api == null) {
if (log.isDebugEnabled()) {
log.debug("User is not subscribed to access the API: " + apiContext +
", version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0]));
}
log.error("User is not subscribed to access the API.");
throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
}
} else {
if (log.isDebugEnabled()) {
log.debug("No subscription information found in the token.");
}
// we perform mandatory authentication for Api Keys
if (!isOauth) {
log.error("User is not subscribed to access the API.");
throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
}
}
return api;
}
/**
* Verify the JWT token signature.
*
* @param jwt SignedJwt Token
* @param alias public certificate keystore alias
* @return whether the signature is verified or or not
* @throws APISecurityException in case of signature verification failure
*/
public static boolean verifyTokenSignature(SignedJWT jwt, String alias) throws APISecurityException {
Certificate publicCert = null;
//Read the client-truststore.jks into a KeyStore
try {
publicCert = APIUtil.getCertificateFromTrustStore(alias);
} catch (APIManagementException e) {
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE, e);
}
if (publicCert != null) {
JWSAlgorithm algorithm = jwt.getHeader().getAlgorithm();
if (algorithm != null && (JWSAlgorithm.RS256.equals(algorithm) || JWSAlgorithm.RS512.equals(algorithm) ||
JWSAlgorithm.RS384.equals(algorithm))) {
return verifyTokenSignature(jwt, (RSAPublicKey) publicCert.getPublicKey());
} else {
log.error("Public key is not a RSA");
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
} else {
log.error("Couldn't find a public certificate to verify signature with alias " + alias);
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
}
/**
* Verify the JWT token signature.
*
* @param jwt SignedJwt Token
* @param publicKey public certificate
* @return whether the signature is verified or or not
* @throws APISecurityException in case of signature verification failure
*/
public static boolean verifyTokenSignature(SignedJWT jwt, RSAPublicKey publicKey) throws APISecurityException {
JWSAlgorithm algorithm = jwt.getHeader().getAlgorithm();
if (algorithm != null && (JWSAlgorithm.RS256.equals(algorithm) || JWSAlgorithm.RS512.equals(algorithm) ||
JWSAlgorithm.RS384.equals(algorithm))) {
try {
JWSVerifier jwsVerifier = new RSASSAVerifier(publicKey);
return jwt.verify(jwsVerifier);
} catch (JOSEException e) {
log.error("Error while verifying JWT signature");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE, e);
}
} else {
log.error("Public key is not a RSA");
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
}
public static String getMaskedToken(String token) {
if (token.length() >= 10) {
return "XXXXX" + token.substring(token.length() - 10);
} else {
return "XXXXX" + token.substring(token.length() / 2);
}
}
public static boolean isGatewayTokenCacheEnabled() {
try {
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfiguration();
String cacheEnabled = config.getFirstProperty(APIConstants.GATEWAY_TOKEN_CACHE_ENABLED);
return Boolean.parseBoolean(cacheEnabled);
} catch (Exception e) {
log.error("Did not found valid API Validation Information cache configuration. " +
"Use default configuration.", e);
}
return true;
}
/**
* Return tenant domain of the API being invoked.
*
* @return tenant domain
*/
public static String getTenantDomain() {
return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
}
public static String getAccessTokenCacheKey(String accessToken, String apiContext, String apiVersion,
String resourceUri, String httpVerb) {
return accessToken + ":" + apiContext + ":" + apiVersion + ":" + resourceUri + ":" + httpVerb;
}
public static JWTInfoDto generateJWTInfoDto(JWTValidationInfo jwtValidationInfo,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO, String apiContext,
String apiVersion) {
JWTInfoDto jwtInfoDto = new JWTInfoDto();
jwtInfoDto.setJwtValidationInfo(jwtValidationInfo);
//jwtInfoDto.setMessageContext(null);
jwtInfoDto.setApiContext(apiContext);
jwtInfoDto.setVersion(apiVersion);
constructJWTContent(null, apiKeyValidationInfoDTO, jwtInfoDto);
return jwtInfoDto;
}
private static void constructJWTContent(JSONObject subscribedAPI,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO, JWTInfoDto jwtInfoDto) {
if (jwtInfoDto.getJwtValidationInfo() != null) {
jwtInfoDto.setEndUser(getEndUserFromJWTValidationInfo(jwtInfoDto.getJwtValidationInfo(),
apiKeyValidationInfoDTO));
}
if (apiKeyValidationInfoDTO != null) {
jwtInfoDto.setApplicationId(apiKeyValidationInfoDTO.getApplicationId());
jwtInfoDto.setApplicationName(apiKeyValidationInfoDTO.getApplicationName());
jwtInfoDto.setApplicationTier(apiKeyValidationInfoDTO.getApplicationTier());
jwtInfoDto.setKeyType(apiKeyValidationInfoDTO.getType());
jwtInfoDto.setSubscriber(apiKeyValidationInfoDTO.getSubscriber());
jwtInfoDto.setSubscriptionTier(apiKeyValidationInfoDTO.getTier());
jwtInfoDto.setApiName(apiKeyValidationInfoDTO.getApiName());
jwtInfoDto.setEndUserTenantId(
APIUtil.getTenantIdFromTenantDomain(apiKeyValidationInfoDTO.getSubscriberTenantDomain()));
jwtInfoDto.setApplicationUUId(apiKeyValidationInfoDTO.getApplicationUUID());
jwtInfoDto.setAppAttributes(apiKeyValidationInfoDTO.getAppAttributes());
} else if (subscribedAPI != null) {
// If the user is subscribed to the API
String apiName = subscribedAPI.getAsString(APIConstants.JwtTokenConstants.API_NAME);
jwtInfoDto.setApiName(apiName);
String subscriptionTier = subscribedAPI.getAsString(APIConstants.JwtTokenConstants.SUBSCRIPTION_TIER);
String subscriptionTenantDomain =
subscribedAPI.getAsString(APIConstants.JwtTokenConstants.SUBSCRIBER_TENANT_DOMAIN);
jwtInfoDto.setSubscriptionTier(subscriptionTier);
jwtInfoDto.setEndUserTenantId(APIUtil.getTenantIdFromTenantDomain(subscriptionTenantDomain));
Map<String, Object> claims = jwtInfoDto.getJwtValidationInfo().getClaims();
if (claims.get(APIConstants.JwtTokenConstants.APPLICATION) != null) {
JSONObject
applicationObj = (JSONObject) claims.get(APIConstants.JwtTokenConstants.APPLICATION);
jwtInfoDto.setApplicationId(
String.valueOf(applicationObj.getAsNumber(APIConstants.JwtTokenConstants.APPLICATION_ID)));
jwtInfoDto
.setApplicationName(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_NAME));
jwtInfoDto
.setApplicationTier(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_TIER));
jwtInfoDto.setSubscriber(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_OWNER));
}
}
}
public static JWTInfoDto generateJWTInfoDto(JSONObject subscribedAPI, JWTValidationInfo jwtValidationInfo,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO,
org.apache.synapse.MessageContext synCtx) {
JWTInfoDto jwtInfoDto = new JWTInfoDto();
jwtInfoDto.setJwtValidationInfo(jwtValidationInfo);
//jwtInfoDto.setMessageContext(synCtx);
String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
jwtInfoDto.setApiContext(apiContext);
jwtInfoDto.setVersion(apiVersion);
constructJWTContent(subscribedAPI, apiKeyValidationInfoDTO, jwtInfoDto);
return jwtInfoDto;
}
public static void setAPIRelatedTags(TracingSpan tracingSpan, org.apache.synapse.MessageContext messageContext) {
Object electedResource = messageContext.getProperty(APIMgtGatewayConstants.API_ELECTED_RESOURCE);
if (electedResource != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_RESOURCE, (String) electedResource);
}
Object api = messageContext.getProperty(APIMgtGatewayConstants.API);
if (api != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_API_NAME, (String) api);
}
Object version = messageContext.getProperty(APIMgtGatewayConstants.VERSION);
if (version != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_API_VERSION, (String) version);
}
Object consumerKey = messageContext.getProperty(APIMgtGatewayConstants.CONSUMER_KEY);
if (consumerKey != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_APPLICATION_CONSUMER_KEY, (String) consumerKey);
}
}
private static void setTracingId(TracingSpan tracingSpan, MessageContext axis2MessageContext) {
Map headersMap =
(Map) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
if (headersMap.containsKey(APIConstants.ACTIVITY_ID)) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_ACTIVITY_ID,
(String) headersMap.get(APIConstants.ACTIVITY_ID));
} else {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_ACTIVITY_ID, axis2MessageContext.getMessageID());
}
}
public static void setRequestRelatedTags(TracingSpan tracingSpan,
org.apache.synapse.MessageContext messageContext) {
org.apache.axis2.context.MessageContext axis2MessageContext =
((Axis2MessageContext) messageContext).getAxis2MessageContext();
Object restUrlPostfix = axis2MessageContext.getProperty(APIMgtGatewayConstants.REST_URL_POSTFIX);
String httpMethod = (String) (axis2MessageContext.getProperty(Constants.Configuration.HTTP_METHOD));
if (restUrlPostfix != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_REQUEST_PATH, (String) restUrlPostfix);
}
if (httpMethod != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_REQUEST_METHOD, httpMethod);
}
setTracingId(tracingSpan, axis2MessageContext);
}
public static void setEndpointRelatedInformation(TracingSpan tracingSpan,
org.apache.synapse.MessageContext messageContext) {
Object endpoint = messageContext.getProperty(APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS);
if (endpoint != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_ENDPOINT, (String) endpoint);
}
}
public static List<String> retrieveDeployedSequences(String apiName, String version, String tenantDomain)
throws APIManagementException {
try {
List<String> deployedSequences = new ArrayList<>();
String inSequenceExtensionName =
APIUtil.getSequenceExtensionName(apiName, version) + APIConstants.API_CUSTOM_SEQ_IN_EXT;
String outSequenceExtensionName =
APIUtil.getSequenceExtensionName(apiName, version) + APIConstants.API_CUSTOM_SEQ_OUT_EXT;
String faultSequenceExtensionName =
APIUtil.getSequenceExtensionName(apiName, version) + APIConstants.API_CUSTOM_SEQ_FAULT_EXT;
SequenceAdminServiceProxy sequenceAdminServiceProxy = new SequenceAdminServiceProxy(tenantDomain);
MessageContext.setCurrentMessageContext(createAxis2MessageContext());
if (sequenceAdminServiceProxy.isExistingSequence(inSequenceExtensionName)) {
OMElement sequence = sequenceAdminServiceProxy.getSequence(inSequenceExtensionName);
deployedSequences.add(sequence.toString());
}
if (sequenceAdminServiceProxy.isExistingSequence(outSequenceExtensionName)) {
OMElement sequence = sequenceAdminServiceProxy.getSequence(outSequenceExtensionName);
deployedSequences.add(sequence.toString());
}
if (sequenceAdminServiceProxy.isExistingSequence(faultSequenceExtensionName)) {
OMElement sequence = sequenceAdminServiceProxy.getSequence(faultSequenceExtensionName);
deployedSequences.add(sequence.toString());
}
return deployedSequences;
} catch (AxisFault axisFault) {
throw new APIManagementException("Error while retrieving Deployed Sequences", axisFault,
ExceptionCodes.INTERNAL_ERROR);
} finally {
MessageContext.destroyCurrentMessageContext();
}
}
public static List<String> retrieveDeployedLocalEntries(String apiName, String version, String tenantDomain)
throws APIManagementException {
try {
SubscriptionDataStore tenantSubscriptionStore =
SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(tenantDomain);
List<String> deployedLocalEntries = new ArrayList<>();
if (tenantSubscriptionStore != null) {
API retrievedAPI = tenantSubscriptionStore.getApiByNameAndVersion(apiName, version);
if (retrievedAPI != null) {
MessageContext.setCurrentMessageContext(createAxis2MessageContext());
LocalEntryServiceProxy localEntryServiceProxy = new LocalEntryServiceProxy(tenantDomain);
String localEntryKey = retrievedAPI.getUuid();
if (APIConstants.GRAPHQL_API.equals(retrievedAPI.getApiType())) {
localEntryKey = retrievedAPI.getUuid().concat(APIConstants.GRAPHQL_LOCAL_ENTRY_EXTENSION);
}
if (localEntryServiceProxy.isEntryExists(localEntryKey)) {
OMElement entry = localEntryServiceProxy.getEntry(localEntryKey);
deployedLocalEntries.add(entry.toString());
}
}
}
return deployedLocalEntries;
} catch (AxisFault axisFault) {
throw new APIManagementException("Error while retrieving LocalEntries", axisFault,
ExceptionCodes.INTERNAL_ERROR);
} finally {
MessageContext.destroyCurrentMessageContext();
}
}
public static List<String> retrieveDeployedEndpoints(String apiName, String version, String tenantDomain)
throws APIManagementException {
List<String> deployedEndpoints = new ArrayList<>();
try {
MessageContext.setCurrentMessageContext(createAxis2MessageContext());
EndpointAdminServiceProxy endpointAdminServiceProxy = new EndpointAdminServiceProxy(tenantDomain);
String productionEndpointKey = apiName.concat("--v").concat(version).concat("_APIproductionEndpoint");
String sandboxEndpointKey = apiName.concat("--v").concat(version).concat("_APIsandboxEndpoint");
if (endpointAdminServiceProxy.isEndpointExist(productionEndpointKey)) {
String entry = endpointAdminServiceProxy.getEndpoint(productionEndpointKey);
deployedEndpoints.add(entry);
}
if (endpointAdminServiceProxy.isEndpointExist(sandboxEndpointKey)) {
String entry = endpointAdminServiceProxy.getEndpoint(sandboxEndpointKey);
deployedEndpoints.add(entry);
}
} catch (AxisFault e) {
throw new APIManagementException("Error in fetching deployed endpoints from Synapse Configuration", e,
ExceptionCodes.INTERNAL_ERROR);
} finally {
MessageContext.destroyCurrentMessageContext();
}
return deployedEndpoints;
}
public static String retrieveDeployedAPI(String apiName, String version, String tenantDomain)
throws APIManagementException {
try {
MessageContext.setCurrentMessageContext(createAxis2MessageContext());
RESTAPIAdminServiceProxy restapiAdminServiceProxy = new RESTAPIAdminServiceProxy(tenantDomain);
String qualifiedName = GatewayUtils.getQualifiedApiName(apiName, version);
OMElement api = restapiAdminServiceProxy.getApiContent(qualifiedName);
if (api != null) {
return api.toString();
}
return null;
} catch (AxisFault axisFault) {
throw new APIManagementException("Error while retrieving API Artifacts", axisFault,
ExceptionCodes.INTERNAL_ERROR);
} finally {
MessageContext.destroyCurrentMessageContext();
}
}
public static org.apache.axis2.context.MessageContext createAxis2MessageContext() throws AxisFault {
AxisService axisService = new AxisService();
axisService.addParameter("adminService", true);
org.apache.axis2.context.MessageContext axis2MsgCtx = new org.apache.axis2.context.MessageContext();
axis2MsgCtx.setMessageID(UIDGenerator.generateURNString());
axis2MsgCtx.setConfigurationContext(ServiceReferenceHolder.getInstance()
.getConfigurationContextService().getServerConfigContext());
axis2MsgCtx.setProperty(org.apache.axis2.context.MessageContext.CLIENT_API_NON_BLOCKING, Boolean.TRUE);
axis2MsgCtx.setServerSide(true);
axis2MsgCtx.setAxisService(axisService);
return axis2MsgCtx;
}
public static API getAPI(org.apache.synapse.MessageContext messageContext) {
Object api = messageContext.getProperty(APIMgtGatewayConstants.API_OBJECT);
if (api != null) {
return (API) api;
} else {
synchronized (messageContext) {
api = messageContext.getProperty(APIMgtGatewayConstants.API_OBJECT);
if (api != null) {
return (API) api;
}
String context = (String) messageContext.getProperty(RESTConstants.REST_API_CONTEXT);
String version = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
SubscriptionDataStore tenantSubscriptionStore =
SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(getTenantDomain());
if (tenantSubscriptionStore != null) {
API api1 = tenantSubscriptionStore.getApiByContextAndVersion(context, version);
if (api1 != null) {
messageContext.setProperty(APIMgtGatewayConstants.API_OBJECT, api1);
return api1;
}
}
return null;
}
}
}
public static String getStatus(org.apache.synapse.MessageContext messageContext) {
Object status = messageContext.getProperty(APIMgtGatewayConstants.API_STATUS);
if (status != null) {
return (String) status;
}
API api = getAPI(messageContext);
if (api != null) {
String apiStatus = api.getStatus();
messageContext.setProperty(APIMgtGatewayConstants.API_STATUS, apiStatus);
return apiStatus;
}
return null;
}
public static boolean isAPIStatusPrototype(org.apache.synapse.MessageContext messageContext) {
return APIConstants.PROTOTYPED.equals(getStatus(messageContext));
}
public static String getAPINameFromContextAndVersion(org.apache.synapse.MessageContext messageContext) {
API api = getAPI(messageContext);
if (api != null) {
return api.getApiName();
}
return null;
}
public static String getApiProviderFromContextAndVersion(org.apache.synapse.MessageContext messageContext) {
API api = getAPI(messageContext);
if (api != null) {
return api.getApiProvider();
}
return null;
}
public static boolean isAPIKey(JWTClaimsSet jwtClaimsSet) {
Object tokenTypeClaim = jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.TOKEN_TYPE);
if (tokenTypeClaim != null) {
return APIConstants.JwtTokenConstants.API_KEY_TOKEN_TYPE.equals(tokenTypeClaim);
}
return jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.APPLICATION) != null;
}
public static boolean isInternalKey(JWTClaimsSet jwtClaimsSet) {
Object tokenTypeClaim = jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.TOKEN_TYPE);
if (tokenTypeClaim != null) {
return APIConstants.JwtTokenConstants.INTERNAL_KEY_TOKEN_TYPE.equals(tokenTypeClaim);
}
return false;
}
/**
* Check whether the jwt token is expired or not.
*
* @param payload The payload of the JWT token
* @return returns true if the JWT token is expired
*/
public static boolean isJwtTokenExpired(JWTClaimsSet payload) {
int timestampSkew = (int) OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds();
DefaultJWTClaimsVerifier jwtClaimsSetVerifier = new DefaultJWTClaimsVerifier();
jwtClaimsSetVerifier.setMaxClockSkew(timestampSkew);
try {
jwtClaimsSetVerifier.verify(payload);
if (log.isDebugEnabled()) {
log.debug("Token is not expired. User: " + payload.getSubject());
}
} catch (BadJWTException e) {
if ("Expired JWT".equals(e.getMessage())) {
return true;
}
}
if (log.isDebugEnabled()) {
log.debug("Token is not expired. User: " + payload.getSubject());
}
return false;
}
public static void setRequestDestination(org.apache.synapse.MessageContext messageContext) {
String requestDestination = null;
EndpointReference objectTo =
((Axis2MessageContext) messageContext).getAxis2MessageContext().getOptions().getTo();
if (objectTo != null) {
requestDestination = objectTo.getAddress();
}
if (requestDestination != null) {
messageContext.setProperty(APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS, requestDestination);
}
}
public static void setWebsocketEndpointsToBeRemoved(GatewayAPIDTO gatewayAPIDTO, String tenantDomain)
throws AxisFault {
String apiName = gatewayAPIDTO.getName();
String apiVersion = gatewayAPIDTO.getVersion();
if (apiName != null && apiVersion != null) {
String prefix = apiName.concat("--v").concat(apiVersion).concat("_API");
EndpointAdminServiceProxy endpointAdminServiceProxy = new EndpointAdminServiceProxy(tenantDomain);
String[] endpoints = endpointAdminServiceProxy.getEndpoints();
for (String endpoint : endpoints) {
if (endpoint.startsWith(prefix)) {
gatewayAPIDTO.setEndpointEntriesToBeRemove(
org.wso2.carbon.apimgt.impl.utils.GatewayUtils.addStringToList(endpoint,
gatewayAPIDTO.getEndpointEntriesToBeRemove()));
}
}
}
}
}
| components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.gateway.utils;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.jwt.proc.BadJWTException;
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.util.UIDGenerator;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.clustering.ClusteringAgent;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.Mediator;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.commons.json.JsonUtil;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.RESTConstants;
import org.apache.synapse.transport.nhttp.NhttpConstants;
import org.apache.synapse.transport.passthru.PassThroughConstants;
import org.apache.synapse.transport.passthru.Pipe;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.ExceptionCodes;
import org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO;
import org.wso2.carbon.apimgt.common.gateway.dto.JWTInfoDto;
import org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo;
import org.wso2.carbon.apimgt.gateway.APIMgtGatewayConstants;
import org.wso2.carbon.apimgt.gateway.dto.IPRange;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityConstants;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException;
import org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext;
import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.gateway.threatprotection.utils.ThreatProtectorConstants;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.keymgt.SubscriptionDataHolder;
import org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore;
import org.wso2.carbon.apimgt.keymgt.model.entity.API;
import org.wso2.carbon.apimgt.tracing.TracingSpan;
import org.wso2.carbon.apimgt.tracing.Util;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.mediation.registry.RegistryServiceHolder;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GatewayUtils {
private static final Log log = LogFactory.getLog(GatewayUtils.class);
public static boolean isClusteringEnabled() {
ClusteringAgent agent = ServiceReferenceHolder.getInstance().getServerConfigurationContext().
getAxisConfiguration().getClusteringAgent();
if (agent != null) {
return true;
}
return false;
}
public static <T> Map<String, T> generateMap(Collection<T> list) {
Map<String, T> map = new HashMap<String, T>();
for (T el : list) {
map.put(el.toString(), el);
}
return map;
}
public static Map<String, Set<IPRange>> generateIpRangeMap(List<IPRange> ipRangeList) {
Map<String, Set<IPRange>> ipRangeMap = new HashMap<>();
for (IPRange ipRange : ipRangeList) {
Set<IPRange> tenantWiseIpRangeList;
if (!ipRangeMap.containsKey(ipRange.getTenantDomain())) {
tenantWiseIpRangeList = new HashSet<>();
} else {
tenantWiseIpRangeList = ipRangeMap.get(ipRange.getTenantDomain());
}
if (APIConstants.BLOCK_CONDITION_IP_RANGE.equals(ipRange.getType())) {
convertIpRangeBigIntValue(ipRange);
}
tenantWiseIpRangeList.add(ipRange);
ipRangeMap.put(ipRange.getTenantDomain(), tenantWiseIpRangeList);
}
return ipRangeMap;
}
private static void convertIpRangeBigIntValue(IPRange ipRange) {
ipRange.setStartingIpBigIntValue(APIUtil.ipToBigInteger(ipRange.getStartingIP()));
ipRange.setEndingIpBigIntValue(APIUtil.ipToBigInteger(ipRange.getEndingIp()));
}
/**
* Extracts the IP from Message Context.
*
* @param messageContext Axis2 Message Context.
* @return IP as a String.
*/
public static String getIp(MessageContext messageContext) {
//Set transport headers of the message
Map<String, String> transportHeaderMap = (Map<String, String>) messageContext
.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
// Assigning an Empty String so that when doing comparisons, .equals method can be used without explicitly
// checking for nullity.
String remoteIP = "";
//Check whether headers map is null and x forwarded for header is present
if (transportHeaderMap != null) {
remoteIP = transportHeaderMap.get(APIMgtGatewayConstants.X_FORWARDED_FOR);
}
//Setting IP of the client by looking at x forded for header and if it's empty get remote address
if (remoteIP != null && !remoteIP.isEmpty()) {
if (remoteIP.indexOf(",") > 0) {
remoteIP = remoteIP.substring(0, remoteIP.indexOf(","));
}
} else {
remoteIP = (String) messageContext.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);
}
return remoteIP;
}
/**
* Can be used to extract Query Params from {@code org.apache.axis2.context.MessageContext}.
*
* @param messageContext The Axis2 MessageContext
* @return A Map with Name Value pairs.
*/
public static Map<String, String> getQueryParams(MessageContext messageContext) {
String queryString = (String) messageContext.getProperty(NhttpConstants.REST_URL_POSTFIX);
if (!StringUtils.isEmpty(queryString)) {
if (queryString.indexOf("?") > -1) {
queryString = queryString.substring(queryString.indexOf("?") + 1);
}
String[] queryParams = queryString.split("&");
Map<String, String> queryParamsMap = new HashMap<String, String>();
String[] queryParamArray;
String queryParamName, queryParamValue = "";
for (String queryParam : queryParams) {
queryParamArray = queryParam.split("=");
if (queryParamArray.length == 2) {
queryParamName = queryParamArray[0];
queryParamValue = queryParamArray[1];
} else {
queryParamName = queryParamArray[0];
}
queryParamsMap.put(queryParamName, queryParamValue);
}
return queryParamsMap;
}
return null;
}
/**
* Get the config system registry for tenants
*
* @param tenantDomain - The tenant domain
* @return - A UserRegistry instance for the tenant
* @throws APIManagementException
*/
public static UserRegistry getRegistry(String tenantDomain) throws APIManagementException {
PrivilegedCarbonContext.startTenantFlow();
if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
}
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
UserRegistry registry;
try {
registry = RegistryServiceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
} catch (RegistryException e) {
String msg = "Failed to get registry instance for the tenant : " + tenantDomain + e.getMessage();
throw new APIManagementException(msg, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return registry;
}
/**
* Delete the given registry property from the given tenant registry path
*
* @param propertyName property name
* @param path resource path
* @param tenantDomain
* @throws AxisFault
*/
public static void deleteRegistryProperty(String propertyName, String path, String tenantDomain)
throws AxisFault {
try {
UserRegistry registry = getRegistry(tenantDomain);
PrivilegedCarbonContext.startTenantFlow();
if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
}
Resource resource = registry.get(path);
if (resource != null && resource.getProperty(propertyName) != null) {
resource.removeProperty(propertyName);
registry.put(resource.getPath(), resource);
resource.discard();
}
} catch (RegistryException | APIManagementException e) {
String msg = "Failed to delete secure endpoint password alias " + e.getMessage();
throw new AxisFault(msg, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Add/Update the given registry property from the given tenant registry
* path
*
* @param propertyName property name
* @param propertyValue property value
* @param path resource path
* @param tenantDomain
* @throws APIManagementException
*/
public static void setRegistryProperty(String propertyName, String propertyValue, String path, String tenantDomain)
throws APIManagementException {
UserRegistry registry = getRegistry(tenantDomain);
PrivilegedCarbonContext.startTenantFlow();
if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
}
try {
Resource resource = registry.get(path);
// add or update property
if (resource.getProperty(propertyName) != null) {
resource.setProperty(propertyName, propertyValue);
} else {
resource.addProperty(propertyName, propertyValue);
}
registry.put(resource.getPath(), resource);
resource.discard();
} catch (RegistryException e) {
throw new APIManagementException("Error while reading registry resource " + path + " for tenant " +
tenantDomain);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Returns the alias string of API endpoint security password
*
* @param apiProviderName
* @param apiName
* @param version
* @return
*/
public static String getAPIEndpointSecretAlias(String apiProviderName, String apiName, String version) {
String secureVaultAlias = apiProviderName + "--" + apiName + version;
return secureVaultAlias;
}
/**
* return existing correlation ID in the message context or set new correlation ID to the message context.
*
* @param messageContext synapse message context
* @return correlation ID
*/
public static String getAndSetCorrelationID(org.apache.synapse.MessageContext messageContext) {
Object correlationObj = messageContext.getProperty(APIMgtGatewayConstants.AM_CORRELATION_ID);
String correlationID;
if (correlationObj != null) {
correlationID = (String) correlationObj;
} else {
correlationID = UUID.randomUUID().toString();
messageContext.setProperty(APIMgtGatewayConstants.AM_CORRELATION_ID, correlationID);
if (log.isDebugEnabled()) {
log.debug("Setting correlation ID to message context.");
}
}
return correlationID;
}
/**
* This method handles threat violations. If the request propagates a threat, this method generates
* an custom exception.
*
* @param messageContext contains the message properties of the relevant API request which was
* enabled the regexValidator message mediation in flow.
* @param errorCode It depends on status of the error message.
* @param desc Description of the error message.It describes the vulnerable type and where it happens.
* @return here return true to continue the sequence. No need to return any value from this method.
*/
public static boolean handleThreat(org.apache.synapse.MessageContext messageContext,
String errorCode, String desc) {
messageContext.setProperty(APIMgtGatewayConstants.THREAT_FOUND, true);
messageContext.setProperty(APIMgtGatewayConstants.THREAT_CODE, errorCode);
messageContext.setProperty(SynapseConstants.ERROR_CODE, errorCode);
if (messageContext.isResponse()) {
messageContext.setProperty(APIMgtGatewayConstants.THREAT_MSG, APIMgtGatewayConstants.BAD_RESPONSE);
messageContext.setProperty(SynapseConstants.ERROR_MESSAGE, APIMgtGatewayConstants.BAD_RESPONSE);
} else {
messageContext.setProperty(APIMgtGatewayConstants.THREAT_MSG, APIMgtGatewayConstants.BAD_REQUEST);
messageContext.setProperty(SynapseConstants.ERROR_MESSAGE, APIMgtGatewayConstants.BAD_REQUEST);
}
messageContext.setProperty(APIMgtGatewayConstants.THREAT_DESC, desc);
messageContext.setProperty(SynapseConstants.ERROR_DETAIL, desc);
Mediator sequence = messageContext.getSequence(APIMgtGatewayConstants.THREAT_FAULT);
// Invoke the custom error handler specified by the user
if (sequence != null && !sequence.mediate(messageContext)) {
// If needed user should be able to prevent the rest of the fault handling
// logic from getting executed
return false;
}
return true;
}
/**
* This method use to clone the InputStream from the the message context. Basically
* clone the request body.
*
* @param messageContext contains the message properties of the relevant API request which was
* enabled the regexValidator message mediation in flow.
* @return cloned InputStreams.
* @throws IOException this exception might occurred while cloning the inputStream.
*/
public static Map<String, InputStream> cloneRequestMessage(org.apache.synapse.MessageContext messageContext)
throws IOException {
BufferedInputStream bufferedInputStream = null;
Map<String, InputStream> inputStreamMap;
InputStream inputStreamSchema = null;
InputStream inputStreamXml = null;
InputStream inputStreamJSON = null;
InputStream inputStreamOriginal = null;
int requestBufferSize = 1024;
org.apache.axis2.context.MessageContext axis2MC;
Pipe pipe;
axis2MC = ((Axis2MessageContext) messageContext).
getAxis2MessageContext();
Object bufferSize = messageContext.getProperty(ThreatProtectorConstants.REQUEST_BUFFER_SIZE);
if (bufferSize != null) {
requestBufferSize = Integer.parseInt(bufferSize.toString());
}
pipe = (Pipe) axis2MC.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
if (pipe != null) {
bufferedInputStream = new BufferedInputStream(pipe.getInputStream());
}
inputStreamMap = new HashMap<>();
String contentType = axis2MC.getProperty(ThreatProtectorConstants.CONTENT_TYPE).toString();
if (bufferedInputStream != null) {
bufferedInputStream.mark(0);
if (bufferedInputStream.read() != -1) {
bufferedInputStream.reset();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[requestBufferSize];
int length;
while ((length = bufferedInputStream.read(buffer)) > -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
byteArrayOutputStream.flush();
inputStreamSchema = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
inputStreamXml = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
inputStreamOriginal = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
inputStreamJSON = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} else {
String payload;
if (ThreatProtectorConstants.APPLICATION_JSON.equals(contentType)) {
inputStreamJSON = JsonUtil.getJsonPayload(axis2MC);
} else {
payload = axis2MC.getEnvelope().getBody().getFirstElement().toString();
inputStreamXml = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
}
}
}
inputStreamMap.put(ThreatProtectorConstants.SCHEMA, inputStreamSchema);
inputStreamMap.put(ThreatProtectorConstants.XML, inputStreamXml);
inputStreamMap.put(ThreatProtectorConstants.ORIGINAL, inputStreamOriginal);
inputStreamMap.put(ThreatProtectorConstants.JSON, inputStreamJSON);
return inputStreamMap;
}
/**
* This method use to set the originInput stream to the message Context
*
* @param inputStreams cloned InputStreams
* @param axis2MC axis2 message context
*/
public static void setOriginalInputStream(Map<String, InputStream> inputStreams,
org.apache.axis2.context.MessageContext axis2MC) {
InputStream inputStreamOriginal;
if (inputStreams != null) {
inputStreamOriginal = inputStreams.get(ThreatProtectorConstants.ORIGINAL);
if (inputStreamOriginal != null) {
BufferedInputStream bufferedInputStreamOriginal = new BufferedInputStream(inputStreamOriginal);
axis2MC.setProperty(PassThroughConstants.BUFFERED_INPUT_STREAM, bufferedInputStreamOriginal);
}
}
}
public static String extractResource(org.apache.synapse.MessageContext mc) {
Pattern resourcePattern = Pattern.compile("^/.+?/.+?([/?].+)$");
String resource = "/";
Matcher matcher = resourcePattern.matcher((String) mc.getProperty(RESTConstants.REST_FULL_REQUEST_PATH));
if (matcher.find()) {
resource = matcher.group(1);
}
return resource;
}
public static String getHostName(org.apache.synapse.MessageContext messageContext) {
String hostname = System.getProperty("datacenterId");
if (hostname == null) {
hostname = (String) messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME);
}
return hostname;
}
public static String getQualifiedApiName(String apiName, String version) {
return apiName + ":v" + version;
}
public static String getQualifiedDefaultApiName(String apiName) {
return apiName;
}
/**
* This method extracts the endpoint address base path if query parameters are contained in endpoint
*
* @param mc The message context
* @return The endpoint address base path
*/
public static String extractAddressBasePath(org.apache.synapse.MessageContext mc) {
String endpointAddress = (String) mc.getProperty(APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS);
if (endpointAddress == null) {
endpointAddress = APIMgtGatewayConstants.DUMMY_ENDPOINT_ADDRESS;
}
if (endpointAddress.contains("?")) {
endpointAddress = endpointAddress.substring(0, endpointAddress.indexOf("?"));
}
return endpointAddress;
}
public static AuthenticationContext generateAuthenticationContext(String jti,
JWTValidationInfo jwtValidationInfo,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO,
String endUserToken,
boolean isOauth) {
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
authContext.setApiKey(jti);
authContext.setUsername(getEndUserFromJWTValidationInfo(jwtValidationInfo, apiKeyValidationInfoDTO));
if (apiKeyValidationInfoDTO != null) {
authContext.setApiTier(apiKeyValidationInfoDTO.getApiTier());
authContext.setKeyType(apiKeyValidationInfoDTO.getType());
authContext.setApplicationId(apiKeyValidationInfoDTO.getApplicationId());
authContext.setApplicationUUID(apiKeyValidationInfoDTO.getApplicationUUID());
authContext.setApplicationName(apiKeyValidationInfoDTO.getApplicationName());
authContext.setApplicationTier(apiKeyValidationInfoDTO.getApplicationTier());
authContext.setSubscriber(apiKeyValidationInfoDTO.getSubscriber());
authContext.setTier(apiKeyValidationInfoDTO.getTier());
authContext.setSubscriberTenantDomain(apiKeyValidationInfoDTO.getSubscriberTenantDomain());
authContext.setApiName(apiKeyValidationInfoDTO.getApiName());
authContext.setApiPublisher(apiKeyValidationInfoDTO.getApiPublisher());
authContext.setStopOnQuotaReach(apiKeyValidationInfoDTO.isStopOnQuotaReach());
authContext.setSpikeArrestLimit(apiKeyValidationInfoDTO.getSpikeArrestLimit());
authContext.setSpikeArrestUnit(apiKeyValidationInfoDTO.getSpikeArrestUnit());
authContext.setConsumerKey(apiKeyValidationInfoDTO.getConsumerKey());
authContext.setIsContentAware(apiKeyValidationInfoDTO.isContentAware());
}
if (isOauth) {
authContext.setConsumerKey(jwtValidationInfo.getConsumerKey());
if (jwtValidationInfo.getIssuer() != null) {
authContext.setIssuer(jwtValidationInfo.getIssuer());
}
}
// Set JWT token sent to the backend
if (StringUtils.isNotEmpty(endUserToken)) {
authContext.setCallerToken(endUserToken);
}
return authContext;
}
/**
* This method returns the end username from the JWTValidationInfo.
* If isAppToken true subscriber username from APIKeyValidationInfoDTO with tenant domain is returned as end
* username.
* If false, tenant domain of the subscriber is appended to the username from JWTValidationInfo.
* If null, same username from JWTValidation info is returned as it is.
*
* @param jwtValidationInfo JWTValidationInfo
* @param apiKeyValidationInfoDTO APIKeyValidationInfoDTO
* @return String end username
*/
private static String getEndUserFromJWTValidationInfo(JWTValidationInfo jwtValidationInfo,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO) {
Boolean isAppToken = jwtValidationInfo.getAppToken();
String endUsername = jwtValidationInfo.getUser();
if (isAppToken != null) {
if (isAppToken) {
endUsername = apiKeyValidationInfoDTO.getSubscriber();
if (!APIConstants.SUPER_TENANT_DOMAIN.equals(apiKeyValidationInfoDTO.getSubscriberTenantDomain())) {
return endUsername;
}
}
return endUsername + UserCoreConstants.TENANT_DOMAIN_COMBINER
+ apiKeyValidationInfoDTO.getSubscriberTenantDomain();
}
return endUsername;
}
public static AuthenticationContext generateAuthenticationContext(String tokenSignature, JWTClaimsSet payload,
JSONObject api, String apiLevelPolicy)
throws java.text.ParseException {
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
authContext.setApiKey(tokenSignature);
authContext.setUsername(payload.getSubject());
if (payload.getClaim(APIConstants.JwtTokenConstants.KEY_TYPE) != null) {
authContext.setKeyType(payload.getStringClaim(APIConstants.JwtTokenConstants.KEY_TYPE));
} else {
authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
}
authContext.setApiTier(apiLevelPolicy);
if (api != null) {
authContext.setTier(APIConstants.UNLIMITED_TIER);
authContext.setApiName(api.getAsString(APIConstants.JwtTokenConstants.API_NAME));
authContext.setApiPublisher(api.getAsString(APIConstants.JwtTokenConstants.API_PUBLISHER));
}
return authContext;
}
public static AuthenticationContext generateAuthenticationContext(String tokenSignature, JWTClaimsSet payload,
JSONObject api,
String apiLevelPolicy, String endUserToken,
org.apache.synapse.MessageContext synCtx)
throws java.text.ParseException {
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
authContext.setApiKey(tokenSignature);
authContext.setUsername(payload.getSubject());
if (payload.getClaim(APIConstants.JwtTokenConstants.KEY_TYPE) != null) {
authContext.setKeyType(payload.getStringClaim(APIConstants.JwtTokenConstants.KEY_TYPE));
} else {
authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
}
authContext.setApiTier(apiLevelPolicy);
if (payload.getClaim(APIConstants.JwtTokenConstants.APPLICATION) != null) {
JSONObject
applicationObj = payload.getJSONObjectClaim(APIConstants.JwtTokenConstants.APPLICATION);
authContext
.setApplicationId(
String.valueOf(applicationObj.getAsNumber(APIConstants.JwtTokenConstants.APPLICATION_ID)));
authContext.setApplicationUUID(
String.valueOf(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_UUID)));
authContext.setApplicationName(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_NAME));
authContext.setApplicationTier(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_TIER));
authContext.setSubscriber(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_OWNER));
if (applicationObj.containsKey(APIConstants.JwtTokenConstants.QUOTA_TYPE)
&& APIConstants.JwtTokenConstants.QUOTA_TYPE_BANDWIDTH
.equals(applicationObj.getAsString(APIConstants.JwtTokenConstants.QUOTA_TYPE))) {
authContext.setIsContentAware(true);
;
}
}
if (api != null) {
// If the user is subscribed to the API
String subscriptionTier = api.getAsString(APIConstants.JwtTokenConstants.SUBSCRIPTION_TIER);
authContext.setTier(subscriptionTier);
authContext.setSubscriberTenantDomain(
api.getAsString(APIConstants.JwtTokenConstants.SUBSCRIBER_TENANT_DOMAIN));
JSONObject tierInfo = payload.getJSONObjectClaim(APIConstants.JwtTokenConstants.TIER_INFO);
authContext.setApiName(api.getAsString(APIConstants.JwtTokenConstants.API_NAME));
authContext.setApiPublisher(api.getAsString(APIConstants.JwtTokenConstants.API_PUBLISHER));
if (tierInfo.get(subscriptionTier) != null) {
JSONObject subscriptionTierObj = (JSONObject) tierInfo.get(subscriptionTier);
authContext.setStopOnQuotaReach(
Boolean.parseBoolean(
subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.STOP_ON_QUOTA_REACH)));
authContext.setSpikeArrestLimit
(subscriptionTierObj.getAsNumber(APIConstants.JwtTokenConstants.SPIKE_ARREST_LIMIT).intValue());
if (!"null".equals(
subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.SPIKE_ARREST_UNIT))) {
authContext.setSpikeArrestUnit(
subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.SPIKE_ARREST_UNIT));
}
//check whether the quota type is there and it is equal to bandwithVolume type.
if (subscriptionTierObj.containsKey(APIConstants.JwtTokenConstants.QUOTA_TYPE)
&& APIConstants.JwtTokenConstants.QUOTA_TYPE_BANDWIDTH
.equals(subscriptionTierObj.getAsString(APIConstants.JwtTokenConstants.QUOTA_TYPE))) {
authContext.setIsContentAware(true);
;
}
if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
Integer graphQLMaxDepth = (int) (long) subscriptionTierObj.get(APIConstants.GRAPHQL_MAX_DEPTH);
Integer graphQLMaxComplexity =
(int) (long) subscriptionTierObj.get(APIConstants.GRAPHQL_MAX_COMPLEXITY);
synCtx.setProperty(APIConstants.MAXIMUM_QUERY_DEPTH, graphQLMaxDepth);
synCtx.setProperty(APIConstants.MAXIMUM_QUERY_COMPLEXITY, graphQLMaxComplexity);
}
}
}
// Set JWT token sent to the backend
if (StringUtils.isNotEmpty(endUserToken)) {
authContext.setCallerToken(endUserToken);
}
return authContext;
}
/**
* Validate whether the user is subscribed to the invoked API. If subscribed, return a JSON object containing
* the API information.
*
* @param apiContext API context
* @param apiVersion API version
* @param jwtValidationInfo The payload of the JWT token
* @return an JSON object containing subscribed API information retrieved from token payload.
* If the subscription information is not found, return a null object.
* @throws APISecurityException if the user is not subscribed to the API
*/
public static JSONObject validateAPISubscription(String apiContext, String apiVersion,
JWTValidationInfo jwtValidationInfo,
String jwtHeader, boolean isOauth)
throws APISecurityException {
JSONObject api = null;
if (jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS) != null) {
// Subscription validation
JSONArray subscribedAPIs =
(JSONArray) jwtValidationInfo.getClaims().get(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS);
for (int i = 0; i < subscribedAPIs.size(); i++) {
JSONObject subscribedAPIsJSONObject =
(JSONObject) subscribedAPIs.get(i);
if (apiContext
.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_CONTEXT)) &&
apiVersion
.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_VERSION)
)) {
api = subscribedAPIsJSONObject;
if (log.isDebugEnabled()) {
log.debug("User is subscribed to the API: " + apiContext + ", " +
"version: " + apiVersion + ". Token: " + getMaskedToken(jwtHeader));
}
break;
}
}
if (api == null) {
if (log.isDebugEnabled()) {
log.debug("User is not subscribed to access the API: " + apiContext +
", version: " + apiVersion + ". Token: " + getMaskedToken(jwtHeader));
}
log.error("User is not subscribed to access the API.");
throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
}
} else {
if (log.isDebugEnabled()) {
log.debug("No subscription information found in the token.");
}
// we perform mandatory authentication for Api Keys
if (!isOauth) {
log.error("User is not subscribed to access the API.");
throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
}
}
return api;
}
/**
* Validate whether the user is subscribed to the invoked API. If subscribed, return a JSON object containing
* the API information.
*
* @param apiContext API context
* @param apiVersion API version
* @param payload The payload of the JWT token
* @return an JSON object containing subscribed API information retrieved from token payload.
* If the subscription information is not found, return a null object.
* @throws APISecurityException if the user is not subscribed to the API
*/
public static JSONObject validateAPISubscription(String apiContext, String apiVersion, JWTClaimsSet payload,
String[] splitToken, boolean isOauth)
throws APISecurityException {
JSONObject api = null;
if (payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS) != null) {
// Subscription validation
JSONArray subscribedAPIs =
(JSONArray) payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS);
for (Object subscribedAPI : subscribedAPIs) {
JSONObject subscribedAPIsJSONObject = (JSONObject) subscribedAPI;
if (apiContext
.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_CONTEXT)) &&
apiVersion
.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_VERSION)
)) {
api = subscribedAPIsJSONObject;
if (log.isDebugEnabled()) {
log.debug("User is subscribed to the API: " + apiContext + ", " +
"version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0]));
}
break;
}
}
if (api == null) {
if (log.isDebugEnabled()) {
log.debug("User is not subscribed to access the API: " + apiContext +
", version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0]));
}
log.error("User is not subscribed to access the API.");
throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
}
} else {
if (log.isDebugEnabled()) {
log.debug("No subscription information found in the token.");
}
// we perform mandatory authentication for Api Keys
if (!isOauth) {
log.error("User is not subscribed to access the API.");
throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN,
APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
}
}
return api;
}
/**
* Verify the JWT token signature.
*
* @param jwt SignedJwt Token
* @param alias public certificate keystore alias
* @return whether the signature is verified or or not
* @throws APISecurityException in case of signature verification failure
*/
public static boolean verifyTokenSignature(SignedJWT jwt, String alias) throws APISecurityException {
Certificate publicCert = null;
//Read the client-truststore.jks into a KeyStore
try {
publicCert = APIUtil.getCertificateFromTrustStore(alias);
} catch (APIManagementException e) {
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE, e);
}
if (publicCert != null) {
JWSAlgorithm algorithm = jwt.getHeader().getAlgorithm();
if (algorithm != null && (JWSAlgorithm.RS256.equals(algorithm) || JWSAlgorithm.RS512.equals(algorithm) ||
JWSAlgorithm.RS384.equals(algorithm))) {
return verifyTokenSignature(jwt, (RSAPublicKey) publicCert.getPublicKey());
} else {
log.error("Public key is not a RSA");
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
} else {
log.error("Couldn't find a public certificate to verify signature with alias " + alias);
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
}
/**
* Verify the JWT token signature.
*
* @param jwt SignedJwt Token
* @param publicKey public certificate
* @return whether the signature is verified or or not
* @throws APISecurityException in case of signature verification failure
*/
public static boolean verifyTokenSignature(SignedJWT jwt, RSAPublicKey publicKey) throws APISecurityException {
JWSAlgorithm algorithm = jwt.getHeader().getAlgorithm();
if (algorithm != null && (JWSAlgorithm.RS256.equals(algorithm) || JWSAlgorithm.RS512.equals(algorithm) ||
JWSAlgorithm.RS384.equals(algorithm))) {
try {
JWSVerifier jwsVerifier = new RSASSAVerifier(publicKey);
return jwt.verify(jwsVerifier);
} catch (JOSEException e) {
log.error("Error while verifying JWT signature");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE, e);
}
} else {
log.error("Public key is not a RSA");
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
}
public static String getMaskedToken(String token) {
if (token.length() >= 10) {
return "XXXXX" + token.substring(token.length() - 10);
} else {
return "XXXXX" + token.substring(token.length() / 2);
}
}
public static boolean isGatewayTokenCacheEnabled() {
try {
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfiguration();
String cacheEnabled = config.getFirstProperty(APIConstants.GATEWAY_TOKEN_CACHE_ENABLED);
return Boolean.parseBoolean(cacheEnabled);
} catch (Exception e) {
log.error("Did not found valid API Validation Information cache configuration. " +
"Use default configuration.", e);
}
return true;
}
/**
* Return tenant domain of the API being invoked.
*
* @return tenant domain
*/
public static String getTenantDomain() {
return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
}
public static String getAccessTokenCacheKey(String accessToken, String apiContext, String apiVersion,
String resourceUri, String httpVerb) {
return accessToken + ":" + apiContext + ":" + apiVersion + ":" + resourceUri + ":" + httpVerb;
}
public static JWTInfoDto generateJWTInfoDto(JWTValidationInfo jwtValidationInfo,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO, String apiContext,
String apiVersion) {
JWTInfoDto jwtInfoDto = new JWTInfoDto();
jwtInfoDto.setJwtValidationInfo(jwtValidationInfo);
//jwtInfoDto.setMessageContext(null);
jwtInfoDto.setApiContext(apiContext);
jwtInfoDto.setVersion(apiVersion);
constructJWTContent(null, apiKeyValidationInfoDTO, jwtInfoDto);
return jwtInfoDto;
}
private static void constructJWTContent(JSONObject subscribedAPI,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO, JWTInfoDto jwtInfoDto) {
if (jwtInfoDto.getJwtValidationInfo() != null) {
jwtInfoDto.setEndUser(getEndUserFromJWTValidationInfo(jwtInfoDto.getJwtValidationInfo(),
apiKeyValidationInfoDTO));
}
if (apiKeyValidationInfoDTO != null) {
jwtInfoDto.setApplicationId(apiKeyValidationInfoDTO.getApplicationId());
jwtInfoDto.setApplicationName(apiKeyValidationInfoDTO.getApplicationName());
jwtInfoDto.setApplicationTier(apiKeyValidationInfoDTO.getApplicationTier());
jwtInfoDto.setKeyType(apiKeyValidationInfoDTO.getType());
jwtInfoDto.setSubscriber(apiKeyValidationInfoDTO.getSubscriber());
jwtInfoDto.setSubscriptionTier(apiKeyValidationInfoDTO.getTier());
jwtInfoDto.setApiName(apiKeyValidationInfoDTO.getApiName());
jwtInfoDto.setEndUserTenantId(
APIUtil.getTenantIdFromTenantDomain(apiKeyValidationInfoDTO.getSubscriberTenantDomain()));
jwtInfoDto.setApplicationUUId(apiKeyValidationInfoDTO.getApplicationUUID());
jwtInfoDto.setAppAttributes(apiKeyValidationInfoDTO.getAppAttributes());
} else if (subscribedAPI != null) {
// If the user is subscribed to the API
String apiName = subscribedAPI.getAsString(APIConstants.JwtTokenConstants.API_NAME);
jwtInfoDto.setApiName(apiName);
String subscriptionTier = subscribedAPI.getAsString(APIConstants.JwtTokenConstants.SUBSCRIPTION_TIER);
String subscriptionTenantDomain =
subscribedAPI.getAsString(APIConstants.JwtTokenConstants.SUBSCRIBER_TENANT_DOMAIN);
jwtInfoDto.setSubscriptionTier(subscriptionTier);
jwtInfoDto.setEndUserTenantId(APIUtil.getTenantIdFromTenantDomain(subscriptionTenantDomain));
Map<String, Object> claims = jwtInfoDto.getJwtValidationInfo().getClaims();
if (claims.get(APIConstants.JwtTokenConstants.APPLICATION) != null) {
JSONObject
applicationObj = (JSONObject) claims.get(APIConstants.JwtTokenConstants.APPLICATION);
jwtInfoDto.setApplicationId(
String.valueOf(applicationObj.getAsNumber(APIConstants.JwtTokenConstants.APPLICATION_ID)));
jwtInfoDto
.setApplicationName(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_NAME));
jwtInfoDto
.setApplicationTier(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_TIER));
jwtInfoDto.setSubscriber(applicationObj.getAsString(APIConstants.JwtTokenConstants.APPLICATION_OWNER));
}
}
}
public static JWTInfoDto generateJWTInfoDto(JSONObject subscribedAPI, JWTValidationInfo jwtValidationInfo,
APIKeyValidationInfoDTO apiKeyValidationInfoDTO,
org.apache.synapse.MessageContext synCtx) {
JWTInfoDto jwtInfoDto = new JWTInfoDto();
jwtInfoDto.setJwtValidationInfo(jwtValidationInfo);
//jwtInfoDto.setMessageContext(synCtx);
String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
jwtInfoDto.setApiContext(apiContext);
jwtInfoDto.setVersion(apiVersion);
constructJWTContent(subscribedAPI, apiKeyValidationInfoDTO, jwtInfoDto);
return jwtInfoDto;
}
public static void setAPIRelatedTags(TracingSpan tracingSpan, org.apache.synapse.MessageContext messageContext) {
Object electedResource = messageContext.getProperty(APIMgtGatewayConstants.API_ELECTED_RESOURCE);
if (electedResource != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_RESOURCE, (String) electedResource);
}
Object api = messageContext.getProperty(APIMgtGatewayConstants.API);
if (api != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_API_NAME, (String) api);
}
Object version = messageContext.getProperty(APIMgtGatewayConstants.VERSION);
if (version != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_API_VERSION, (String) version);
}
Object consumerKey = messageContext.getProperty(APIMgtGatewayConstants.CONSUMER_KEY);
if (consumerKey != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_APPLICATION_CONSUMER_KEY, (String) consumerKey);
}
}
private static void setTracingId(TracingSpan tracingSpan, MessageContext axis2MessageContext) {
Map headersMap =
(Map) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
if (headersMap.containsKey(APIConstants.ACTIVITY_ID)) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_ACTIVITY_ID,
(String) headersMap.get(APIConstants.ACTIVITY_ID));
} else {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_ACTIVITY_ID, axis2MessageContext.getMessageID());
}
}
public static void setRequestRelatedTags(TracingSpan tracingSpan,
org.apache.synapse.MessageContext messageContext) {
org.apache.axis2.context.MessageContext axis2MessageContext =
((Axis2MessageContext) messageContext).getAxis2MessageContext();
Object restUrlPostfix = axis2MessageContext.getProperty(APIMgtGatewayConstants.REST_URL_POSTFIX);
String httpMethod = (String) (axis2MessageContext.getProperty(Constants.Configuration.HTTP_METHOD));
if (restUrlPostfix != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_REQUEST_PATH, (String) restUrlPostfix);
}
if (httpMethod != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_REQUEST_METHOD, httpMethod);
}
setTracingId(tracingSpan, axis2MessageContext);
}
public static void setEndpointRelatedInformation(TracingSpan tracingSpan,
org.apache.synapse.MessageContext messageContext) {
Object endpoint = messageContext.getProperty(APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS);
if (endpoint != null) {
Util.setTag(tracingSpan, APIMgtGatewayConstants.SPAN_ENDPOINT, (String) endpoint);
}
}
public static List<String> retrieveDeployedSequences(String apiName, String version, String tenantDomain)
throws APIManagementException {
try {
List<String> deployedSequences = new ArrayList<>();
String inSequenceExtensionName =
APIUtil.getSequenceExtensionName(apiName, version) + APIConstants.API_CUSTOM_SEQ_IN_EXT;
String outSequenceExtensionName =
APIUtil.getSequenceExtensionName(apiName, version) + APIConstants.API_CUSTOM_SEQ_OUT_EXT;
String faultSequenceExtensionName =
APIUtil.getSequenceExtensionName(apiName, version) + APIConstants.API_CUSTOM_SEQ_FAULT_EXT;
SequenceAdminServiceProxy sequenceAdminServiceProxy = new SequenceAdminServiceProxy(tenantDomain);
MessageContext.setCurrentMessageContext(createAxis2MessageContext());
if (sequenceAdminServiceProxy.isExistingSequence(inSequenceExtensionName)) {
OMElement sequence = sequenceAdminServiceProxy.getSequence(inSequenceExtensionName);
deployedSequences.add(sequence.toString());
}
if (sequenceAdminServiceProxy.isExistingSequence(outSequenceExtensionName)) {
OMElement sequence = sequenceAdminServiceProxy.getSequence(outSequenceExtensionName);
deployedSequences.add(sequence.toString());
}
if (sequenceAdminServiceProxy.isExistingSequence(faultSequenceExtensionName)) {
OMElement sequence = sequenceAdminServiceProxy.getSequence(faultSequenceExtensionName);
deployedSequences.add(sequence.toString());
}
return deployedSequences;
} catch (AxisFault axisFault) {
throw new APIManagementException("Error while retrieving Deployed Sequences", axisFault,
ExceptionCodes.INTERNAL_ERROR);
} finally {
MessageContext.destroyCurrentMessageContext();
}
}
public static List<String> retrieveDeployedLocalEntries(String apiName, String version, String tenantDomain)
throws APIManagementException {
try {
SubscriptionDataStore tenantSubscriptionStore =
SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(tenantDomain);
List<String> deployedLocalEntries = new ArrayList<>();
if (tenantSubscriptionStore != null) {
API retrievedAPI = tenantSubscriptionStore.getApiByNameAndVersion(apiName, version);
if (retrievedAPI != null) {
MessageContext.setCurrentMessageContext(createAxis2MessageContext());
LocalEntryServiceProxy localEntryServiceProxy = new LocalEntryServiceProxy(tenantDomain);
String localEntryKey = retrievedAPI.getUuid();
if (APIConstants.GRAPHQL_API.equals(retrievedAPI.getApiType())) {
localEntryKey = retrievedAPI.getUuid().concat(APIConstants.GRAPHQL_LOCAL_ENTRY_EXTENSION);
}
if (localEntryServiceProxy.isEntryExists(localEntryKey)) {
OMElement entry = localEntryServiceProxy.getEntry(localEntryKey);
deployedLocalEntries.add(entry.toString());
}
}
}
return deployedLocalEntries;
} catch (AxisFault axisFault) {
throw new APIManagementException("Error while retrieving LocalEntries", axisFault,
ExceptionCodes.INTERNAL_ERROR);
} finally {
MessageContext.destroyCurrentMessageContext();
}
}
public static List<String> retrieveDeployedEndpoints(String apiName, String version, String tenantDomain)
throws APIManagementException {
List<String> deployedEndpoints = new ArrayList<>();
try {
MessageContext.setCurrentMessageContext(createAxis2MessageContext());
EndpointAdminServiceProxy endpointAdminServiceProxy = new EndpointAdminServiceProxy(tenantDomain);
String productionEndpointKey = apiName.concat("--v").concat(version).concat("_APIproductionEndpoint");
String sandboxEndpointKey = apiName.concat("--v").concat(version).concat("_APIsandboxEndpoint");
if (endpointAdminServiceProxy.isEndpointExist(productionEndpointKey)) {
String entry = endpointAdminServiceProxy.getEndpoint(productionEndpointKey);
deployedEndpoints.add(entry);
}
if (endpointAdminServiceProxy.isEndpointExist(sandboxEndpointKey)) {
String entry = endpointAdminServiceProxy.getEndpoint(sandboxEndpointKey);
deployedEndpoints.add(entry);
}
} catch (AxisFault e) {
throw new APIManagementException("Error in fetching deployed endpoints from Synapse Configuration", e,
ExceptionCodes.INTERNAL_ERROR);
} finally {
MessageContext.destroyCurrentMessageContext();
}
return deployedEndpoints;
}
public static String retrieveDeployedAPI(String apiName, String version, String tenantDomain)
throws APIManagementException {
try {
MessageContext.setCurrentMessageContext(createAxis2MessageContext());
RESTAPIAdminServiceProxy restapiAdminServiceProxy = new RESTAPIAdminServiceProxy(tenantDomain);
String qualifiedName = GatewayUtils.getQualifiedApiName(apiName, version);
OMElement api = restapiAdminServiceProxy.getApiContent(qualifiedName);
if (api != null) {
return api.toString();
}
return null;
} catch (AxisFault axisFault) {
throw new APIManagementException("Error while retrieving API Artifacts", axisFault,
ExceptionCodes.INTERNAL_ERROR);
} finally {
MessageContext.destroyCurrentMessageContext();
}
}
public static org.apache.axis2.context.MessageContext createAxis2MessageContext() throws AxisFault {
AxisService axisService = new AxisService();
axisService.addParameter("adminService", true);
org.apache.axis2.context.MessageContext axis2MsgCtx = new org.apache.axis2.context.MessageContext();
axis2MsgCtx.setMessageID(UIDGenerator.generateURNString());
axis2MsgCtx.setConfigurationContext(ServiceReferenceHolder.getInstance()
.getConfigurationContextService().getServerConfigContext());
axis2MsgCtx.setProperty(org.apache.axis2.context.MessageContext.CLIENT_API_NON_BLOCKING, Boolean.TRUE);
axis2MsgCtx.setServerSide(true);
axis2MsgCtx.setAxisService(axisService);
return axis2MsgCtx;
}
public static API getAPI(org.apache.synapse.MessageContext messageContext) {
Object api = messageContext.getProperty(APIMgtGatewayConstants.API_OBJECT);
if (api != null) {
return (API) api;
} else {
synchronized (messageContext) {
api = messageContext.getProperty(APIMgtGatewayConstants.API_OBJECT);
if (api != null) {
return (API) api;
}
String context = (String) messageContext.getProperty(RESTConstants.REST_API_CONTEXT);
String version = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
SubscriptionDataStore tenantSubscriptionStore =
SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(getTenantDomain());
if (tenantSubscriptionStore != null) {
API api1 = tenantSubscriptionStore.getApiByContextAndVersion(context, version);
if (api1 != null) {
messageContext.setProperty(APIMgtGatewayConstants.API_OBJECT, api1);
return api1;
}
}
return null;
}
}
}
public static String getStatus(org.apache.synapse.MessageContext messageContext) {
Object status = messageContext.getProperty(APIMgtGatewayConstants.API_STATUS);
if (status != null) {
return (String) status;
}
API api = getAPI(messageContext);
if (api != null) {
String apiStatus = api.getStatus();
messageContext.setProperty(APIMgtGatewayConstants.API_STATUS, apiStatus);
return apiStatus;
}
return null;
}
public static boolean isAPIStatusPrototype(org.apache.synapse.MessageContext messageContext) {
return APIConstants.PROTOTYPED.equals(getStatus(messageContext));
}
public static String getAPINameFromContextAndVersion(org.apache.synapse.MessageContext messageContext) {
API api = getAPI(messageContext);
if (api != null) {
return api.getApiName();
}
return null;
}
public static String getApiProviderFromContextAndVersion(org.apache.synapse.MessageContext messageContext) {
API api = getAPI(messageContext);
if (api != null) {
return api.getApiProvider();
}
return null;
}
public static boolean isAPIKey(JWTClaimsSet jwtClaimsSet) {
Object tokenTypeClaim = jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.TOKEN_TYPE);
if (tokenTypeClaim != null) {
return APIConstants.JwtTokenConstants.API_KEY_TOKEN_TYPE.equals(tokenTypeClaim);
}
return jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.APPLICATION) != null;
}
public static boolean isInternalKey(JWTClaimsSet jwtClaimsSet) {
Object tokenTypeClaim = jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.TOKEN_TYPE);
if (tokenTypeClaim != null) {
return APIConstants.JwtTokenConstants.INTERNAL_KEY_TOKEN_TYPE.equals(tokenTypeClaim);
}
return false;
}
/**
* Check whether the jwt token is expired or not.
*
* @param payload The payload of the JWT token
* @return returns true if the JWT token is expired
*/
public static boolean isJwtTokenExpired(JWTClaimsSet payload) {
int timestampSkew = (int) OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds();
DefaultJWTClaimsVerifier jwtClaimsSetVerifier = new DefaultJWTClaimsVerifier();
jwtClaimsSetVerifier.setMaxClockSkew(timestampSkew);
try {
jwtClaimsSetVerifier.verify(payload);
if (log.isDebugEnabled()) {
log.debug("Token is not expired. User: " + payload.getSubject());
}
} catch (BadJWTException e) {
if ("Expired JWT".equals(e.getMessage())) {
return true;
}
}
if (log.isDebugEnabled()) {
log.debug("Token is not expired. User: " + payload.getSubject());
}
return false;
}
public static void setRequestDestination(org.apache.synapse.MessageContext messageContext) {
String requestDestination = null;
EndpointReference objectTo =
((Axis2MessageContext) messageContext).getAxis2MessageContext().getOptions().getTo();
if (objectTo != null) {
requestDestination = objectTo.getAddress();
}
if (requestDestination != null) {
messageContext.setProperty(APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS, requestDestination);
}
}
public static void setWebsocketEndpointsToBeRemoved(GatewayAPIDTO gatewayAPIDTO, String tenantDomain)
throws AxisFault {
String apiName = gatewayAPIDTO.getName();
String apiVersion = gatewayAPIDTO.getVersion();
if (apiName != null && apiVersion != null) {
String prefix = apiName.concat("--v").concat(apiVersion).concat("_API");
EndpointAdminServiceProxy endpointAdminServiceProxy = new EndpointAdminServiceProxy(tenantDomain);
String[] endpoints = endpointAdminServiceProxy.getEndpoints();
for (String endpoint : endpoints) {
if (endpoint.startsWith(prefix)) {
gatewayAPIDTO.setEndpointEntriesToBeRemove(
org.wso2.carbon.apimgt.impl.utils.GatewayUtils.addStringToList(endpoint,
gatewayAPIDTO.getEndpointEntriesToBeRemove()));
}
}
}
}
}
| convert type of ERROR_CODE to int.
| components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java | convert type of ERROR_CODE to int. |
|
Java | apache-2.0 | 6b7e98ae06c4a92358f7c7c0636b5d58d865a408 | 0 | wso2/product-jaggery,thusithathilina/jaggery,rasika/jaggery,hmrajas/jaggery,maheshika/jaggery,Niranjan-K/jaggery,wso2/jaggery,maheshika/jaggery,rasika90/jaggery,sameerak/jaggery,hevayo/jaggery,manuranga/product-jaggery,Niranjan-K/jaggery,thusithathilina/jaggery,rasika/jaggery,maheshika/jaggery,hevayo/jaggery,charithag/product-jaggery,hmrajas/jaggery,Niranjan-K/jaggery,lalankea/product-jaggery,wso2/jaggery,DMHP/jaggery,charithag/product-jaggery,sameerak/jaggery,cnapagoda/jaggery,manuranga/product-jaggery,wso2/product-jaggery,cnapagoda/jaggery,charithag/product-jaggery,sameerak/jaggery,rasika90/jaggery,lalankea/product-jaggery,DMHP/jaggery,lalankea/product-jaggery,hevayo/jaggery,wso2/product-jaggery,manuranga/product-jaggery,manuranga/product-jaggery,wso2/product-jaggery,thusithathilina/jaggery,charithag/product-jaggery,lalankea/product-jaggery,DMHP/jaggery,rasika90/jaggery,wso2/jaggery,hmrajas/jaggery,cnapagoda/jaggery,rasika/jaggery | package org.jaggeryjs.hostobjects.db;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaggeryjs.hostobjects.stream.StreamHostObject;
import org.jaggeryjs.scriptengine.engine.RhinoEngine;
import org.jaggeryjs.scriptengine.exceptions.ScriptException;
import org.jaggeryjs.scriptengine.util.HostObjectUtil;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.wso2.carbon.ndatasource.common.DataSourceException;
import org.wso2.carbon.ndatasource.rdbms.RDBMSConfiguration;
import org.wso2.carbon.ndatasource.rdbms.RDBMSDataSource;
import org.wso2.carbon.ndatasource.core.CarbonDataSource;
import org.wso2.carbon.ndatasource.core.DataSourceManager;
import javax.sql.DataSource;
import java.sql.*;
import java.sql.Date;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DatabaseHostObject extends ScriptableObject {
private static final Log log = LogFactory.getLog(DatabaseHostObject.class);
private static final String hostObjectName = "Database";
public static final String COM_MYSQL_JDBC_DRIVER = "com.mysql.jdbc.Driver";
public static final String ORG_H2_DRIVER = "org.h2.Driver";
public static final String ORACLE_JDBC_ORACLE_DRIVER = "oracle.jdbc.OracleDriver";
public static final String MYSQL = "jdbc:mysql";
public static final String H2 = "jdbc:h2";
public static final String ORACLE = "jdbc:oracle";
private boolean autoCommit = true;
private Context context = null;
private Connection conn = null;
static RDBMSDataSource rdbmsDataSource = null;
private Map<String, Savepoint> savePoints = new HashMap<String, Savepoint>();
public DatabaseHostObject() {
}
@Override
public String getClassName() {
return hostObjectName;
}
public static Scriptable jsConstructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr)
throws ScriptException {
int argsCount = args.length;
DatabaseHostObject db = new DatabaseHostObject();
//args count 1 for dataSource name
if (argsCount != 1 && argsCount != 3 && argsCount != 4) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, hostObjectName, argsCount, true);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "1", "string", args[0], true);
}
if (argsCount == 1) {
String dataSourceName = (String) args[0];
DataSourceManager dataSourceManager = new DataSourceManager();
try {
CarbonDataSource carbonDataSource = dataSourceManager.getInstance().getDataSourceRepository().getDataSource(dataSourceName);
DataSource dataSource = (DataSource) carbonDataSource.getDSObject();
db.conn = dataSource.getConnection();
db.context = cx;
return db;
} catch (DataSourceException e) {
log.error("Failed to access datasource " + dataSourceName, e);
} catch (SQLException e) {
log.error("Failed to get connection", e);
}
}
if (!(args[1] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "2", "string", args[1], true);
}
if (!(args[2] instanceof String) && !(args[2] instanceof Integer)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "3", "string", args[2], true);
}
NativeObject configs = null;
if (argsCount == 4) {
if (!(args[3] instanceof NativeObject)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "4", "object", args[3], true);
}
configs = (NativeObject) args[3];
}
String dbUrl = (String) args[0];
RDBMSConfiguration rdbmsConfig = new RDBMSConfiguration();
try {
if (configs != null) {
Gson gson = new Gson();
rdbmsConfig = gson.fromJson(HostObjectUtil.serializeJSON(configs), RDBMSConfiguration.class);
}
if (rdbmsConfig.getDriverClassName() == null || rdbmsConfig.getDriverClassName().equals("")) {
rdbmsConfig.setDriverClassName(getDriverClassName(dbUrl));
}
rdbmsConfig.setUsername((String) args[1]);
rdbmsConfig.setPassword((String) args[2]);
rdbmsConfig.setUrl(dbUrl);
try {
rdbmsDataSource = new RDBMSDataSource(rdbmsConfig);
} catch (DataSourceException e) {
throw new ScriptException(e);
}
db.conn = rdbmsDataSource.getDataSource().getConnection();
db.context = cx;
return db;
} catch (SQLException e) {
String msg = "Error connecting to the database : " + dbUrl;
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
private static String getDriverClassName(String dburl) {
if (dburl.contains(MYSQL)) {
return COM_MYSQL_JDBC_DRIVER;
} else if (dburl.contains(H2)) {
return ORG_H2_DRIVER;
} else if (dburl.contains(ORACLE)) {
return ORACLE_JDBC_ORACLE_DRIVER;
} else {
return null;
}
}
public boolean jsGet_autoCommit() throws ScriptException {
return this.autoCommit;
}
public void jsSet_autoCommit(Object object) throws ScriptException {
if (!(object instanceof Boolean)) {
HostObjectUtil.invalidProperty(hostObjectName, "autoCommit", "boolean", object);
}
this.autoCommit = (Boolean) object;
}
public static Object jsFunction_query(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException, SQLException {
String functionName = "query";
int argsCount = args.length;
if (argsCount == 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
String query;
if (argsCount == 1) {
//query
Function callback = null;
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
query = (String) args[0];
PreparedStatement stmt = db.conn.prepareStatement(query);
return executeQuery(cx, db, stmt, query, callback, true);
} else if (argsCount == 2) {
if (!(args[0] instanceof String)) {
//batch
Function callback = null;
if (!(args[0] instanceof NativeArray)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
NativeArray queries = (NativeArray) args[0];
NativeArray values = null;
if (args[1] instanceof Function) {
callback = (Function) args[1];
} else if (args[1] instanceof NativeArray) {
values = (NativeArray) args[1];
} else {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "2", "array | function", args[0], false);
}
return executeBatch(cx, db, queries, values, callback);
} else {
//query
Function callback = null;
query = (String) args[0];
PreparedStatement stmt = db.conn.prepareStatement(query);
if (args[1] instanceof Function) {
callback = (Function) args[1];
} else {
setQueryParams(stmt, args, 1, 1);
}
return executeQuery(cx, db, stmt, query, callback, true);
}
} else if (argsCount == 3) {
if (!(args[0] instanceof String)) {
//batch
Function callback = null;
if (!(args[0] instanceof NativeArray)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "array", args[0], false);
}
if (!(args[1] instanceof NativeArray)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "2", "array", args[1], false);
}
if (!(args[2] instanceof Function)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "3", "function", args[2], false);
}
NativeArray queries = (NativeArray) args[0];
NativeArray values = (NativeArray) args[1];
callback = (Function) args[2];
return executeBatch(cx, db, queries, values, callback);
} else {
//query
Function callback = null;
query = (String) args[0];
PreparedStatement stmt = db.conn.prepareStatement(query);
if (args[2] instanceof Function) {
callback = (Function) args[2];
setQueryParams(stmt, args, 1, 1);
} else {
setQueryParams(stmt, args, 1, 2);
}
return executeQuery(cx, db, stmt, query, callback, true);
}
} else {
//args count > 3
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
Function callback = null;
query = (String) args[0];
PreparedStatement stmt = db.conn.prepareStatement(query);
if (args[argsCount - 1] instanceof Function) {
callback = (Function) args[argsCount - 1];
setQueryParams(stmt, args, 1, argsCount - 1);
} else {
setQueryParams(stmt, args, 1, argsCount - 1);
}
return executeQuery(cx, db, stmt, query, callback, true);
}
}
public static String jsFunction_savePoint(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException, SQLException {
String functionName = "savePoint";
int argsCount = args.length;
String savePoint;
if (argsCount == 0) {
savePoint = UUID.randomUUID().toString();
} else {
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
savePoint = (String) args[0];
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
db.savePoints.put(savePoint, db.conn.setSavepoint(savePoint));
return savePoint;
}
public static void jsFunction_releasePoint(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "releasePoint";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
String savePoint = (String) args[0];
DatabaseHostObject db = (DatabaseHostObject) thisObj;
try {
db.conn.releaseSavepoint(db.savePoints.remove(savePoint));
} catch (SQLException e) {
String msg = "Error while releasing the savepoint : " + savePoint;
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
public static void jsFunction_rollback(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "rollback";
int argsCount = args.length;
if (argsCount > 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
String savePoint = null;
if (argsCount == 1) {
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
savePoint = (String) args[0];
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
if (savePoint != null) {
try {
db.conn.rollback(db.savePoints.get(savePoint));
} catch (SQLException e) {
String msg = "Error while rolling back the transaction to savepoint : " + savePoint;
log.warn(msg, e);
throw new ScriptException(msg, e);
}
} else {
try {
db.conn.rollback();
} catch (SQLException e) {
String msg = "Error while rolling back the transaction";
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
}
public static void jsFunction_commit(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "commit";
int argsCount = args.length;
if (argsCount > 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
try {
db.conn.commit();
} catch (SQLException e) {
String msg = "Error while committing the transaction";
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
public static void jsFunction_close(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws ScriptException {
String functionName = "c";
int argsCount = args.length;
if (argsCount > 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
try {
db.conn.close();
if (rdbmsDataSource != null) {
rdbmsDataSource.getDataSource().close();
}
} catch (SQLException e) {
String msg = "Error while closing the Database Connection";
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
private static String replaceWildcards(DatabaseHostObject db, String query, NativeArray params) throws SQLException {
String openedChar = null;
String lastChar = null;
StringBuffer newQuery = new StringBuffer();
int paramIndex = 0;
for (int i = 0; i < query.length(); i++) {
String c = Character.toString(query.charAt(i));
if (lastChar == null) {
lastChar = c;
if (c.equals("'") || c.equals("\"")) {
openedChar = c;
}
newQuery.append(c);
continue;
}
if (c.equals("'")) {
if (openedChar == null) {
openedChar = c;
} else if (openedChar.equals(c)) {
if (!lastChar.equals("\\")) {
//closing reached
openedChar = null;
}
}
} else if (c.equals("\"")) {
if (openedChar == null) {
openedChar = c;
} else if (openedChar.equals(c)) {
if (!lastChar.equals("\\")) {
//closing reached
openedChar = null;
}
}
} else if (c.equals("?")) {
if (openedChar == null) {
//replace ?
newQuery.append(HostObjectUtil.serializeObject(params.get(paramIndex, db)));
paramIndex++;
continue;
} else if (lastChar.equals("'")) {
if (openedChar.equals("'")) {
String nextChart = Character.toString(query.charAt(i + 1));
if (nextChart.equals("'")) {
//replace '?'
newQuery.append(HostObjectUtil.serializeObject(params.get(paramIndex, db)));
continue;
}
}
} else if (lastChar.equals("\"")) {
if (openedChar.equals("\"")) {
String nextChart = Character.toString(query.charAt(i + 1));
if (nextChart.equals("\"")) {
//replace '?'
newQuery.append(HostObjectUtil.serializeObject(params.get(paramIndex, db)));
continue;
}
}
}
}
newQuery.append(c);
lastChar = c;
}
return newQuery.toString();
}
private static void setQueryParams(PreparedStatement stmt, Object[] params, int from, int to) throws SQLException {
for (int i = from; i < to + 1; i++) {
setQueryParam(stmt, params[i], i);
}
}
private static void setQueryParam(PreparedStatement stmt, Object obj, int index) throws SQLException {
if (obj instanceof String) {
stmt.setString(index, (String) obj);
} else if (obj instanceof Integer) {
stmt.setInt(index, (Integer) obj);
} else if (obj instanceof Double) {
stmt.setDouble(index, (Double) obj);
}
//Support for streams in queries
//Added 25/9/2013
else if (obj instanceof StreamHostObject) {
StreamHostObject stream=(StreamHostObject)obj;
stmt.setBinaryStream(index,stream.getStream());
}
else {
stmt.setString(index, HostObjectUtil.serializeObject(obj));
}
}
private static Object executeQuery(Context cx, final DatabaseHostObject db, final PreparedStatement stmt, String query,
final Function callback, final boolean keyed) throws ScriptException {
String regex = "^[\\s\\t\\r\\n]*[Ss][Ee][Ll][Ee][Cc][Tt].*";//select
final boolean isSelect = query.matches(regex);
if (callback != null) {
final ContextFactory factory = cx.getFactory();
final ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(new Callable() {
public Object call() throws Exception {
Context cx = RhinoEngine.enterContext(factory);
try {
Object result;
if (isSelect) {
result = processResults(cx, db, db, stmt.executeQuery(), keyed);
} else {
result = stmt.executeUpdate();
}
stmt.close();
callback.call(cx, db, db, new Object[]{result});
} catch (SQLException e) {
log.warn(e);
} finally {
es.shutdown();
RhinoEngine.exitContext();
}
return null;
}
});
return null;
} else {
try {
Object result;
if (isSelect) {
result = processResults(cx, db, db, stmt.executeQuery(), keyed);
} else {
result = stmt.executeUpdate();
}
stmt.close();
return result;
} catch (SQLException e) {
log.warn(e);
throw new ScriptException(e);
}
}
}
private static Object executeBatch(Context cx, final DatabaseHostObject db, NativeArray queries,
NativeArray params, final Function callback)
throws ScriptException, SQLException {
if (params != null && (queries.getLength() != params.getLength())) {
String msg = "Query array and values array should be in the same size. HostObject : " +
hostObjectName + ", Method : query";
log.warn(msg);
throw new ScriptException(msg);
}
final Statement stmt = db.conn.createStatement();
for (int index : (Integer[]) queries.getIds()) {
Object obj = queries.get(index, db);
if (!(obj instanceof String)) {
String msg = "Invalid query type : " + obj.toString() + ". Query should be a string";
log.warn(msg);
throw new ScriptException(msg);
}
String query = (String) obj;
if (params != null) {
Object valObj = params.get(index, db);
if (!(valObj instanceof NativeArray)) {
String msg = "Invalid value type : " + obj.toString() + " for the query " + query;
log.warn(msg);
throw new ScriptException(msg);
}
query = replaceWildcards(db, query, (NativeArray) valObj);
}
stmt.addBatch(query);
}
if (callback != null) {
final ContextFactory factory = cx.getFactory();
final ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(new Callable() {
public Object call() throws Exception {
Context ctx = RhinoEngine.enterContext(factory);
try {
int[] result = stmt.executeBatch();
callback.call(ctx, db, db, new Object[]{result});
} catch (SQLException e) {
log.warn(e);
} finally {
es.shutdown();
RhinoEngine.exitContext();
}
return null;
}
});
return null;
} else {
return stmt.executeBatch();
}
}
private static Scriptable processResults(Context cx, Scriptable scope, DatabaseHostObject db, ResultSet results, boolean keyed) throws SQLException, ScriptException {
List<ScriptableObject> rows = new ArrayList<ScriptableObject>();
while (results.next()) {
ScriptableObject row;
ResultSetMetaData rsmd = results.getMetaData();
if (keyed) {
row = (ScriptableObject) db.context.newObject(db);
for (int i = 0; i < rsmd.getColumnCount(); i++) {
String columnName = rsmd.getColumnLabel(i + 1);
Object columnValue = getValue(db, results, i + 1, rsmd.getColumnType(i + 1));
row.put(columnName, row, columnValue);
}
} else {
row = (ScriptableObject) cx.newArray(scope, rsmd.getColumnCount());
for (int i = 0; i < rsmd.getColumnCount(); i++) {
Object columnValue = getValue(db, results, i + 1, rsmd.getColumnType(i + 1));
row.put(i + 1, row, columnValue);
}
}
rows.add(row);
}
return db.context.newArray(db, rows.toArray());
}
private static Object getValue(DatabaseHostObject db, ResultSet results, int index, int type) throws SQLException, ScriptException {
Context cx = db.context;
//TODO : implement for other sql types
switch (type) {
case Types.ARRAY:
return (results.getArray(index) == null) ? null : cx.newArray(db, new Object[]{results.getArray(index)});
case Types.BIGINT:
return (results.getBigDecimal(index) == null) ? null : results.getBigDecimal(index).toPlainString();
case Types.BINARY:
case Types.LONGVARBINARY:
return results.getBinaryStream(index) == null ? null : cx.newObject(db, "Stream", new Object[]{results.getBinaryStream(index)});
case Types.CLOB:
return results.getClob(index) == null ? null : cx.newObject(db, "Stream", new Object[]{results.getClob(index).getAsciiStream()});
case Types.BLOB:
return results.getBlob(index) == null ? null : cx.newObject(db, "Stream", new Object[]{results.getBlob(index).getBinaryStream()});
case Types.TIMESTAMP:
Timestamp date = results.getTimestamp(index);
return date == null ? null : cx.newObject(db, "Date", new Object[] {date.getTime()});
default:
return results.getObject(index) == null ? null : results.getObject(index);
}
}
}
| components/hostobjects/org.jaggeryjs.hostobjects.db/src/main/java/org/jaggeryjs/hostobjects/db/DatabaseHostObject.java | package org.jaggeryjs.hostobjects.db;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaggeryjs.hostobjects.stream.StreamHostObject;
import org.jaggeryjs.scriptengine.engine.RhinoEngine;
import org.jaggeryjs.scriptengine.exceptions.ScriptException;
import org.jaggeryjs.scriptengine.util.HostObjectUtil;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.wso2.carbon.ndatasource.common.DataSourceException;
import org.wso2.carbon.ndatasource.rdbms.RDBMSConfiguration;
import org.wso2.carbon.ndatasource.rdbms.RDBMSDataSource;
import org.wso2.carbon.ndatasource.core.CarbonDataSource;
import org.wso2.carbon.ndatasource.core.DataSourceManager;
import javax.sql.DataSource;
import java.sql.*;
import java.sql.Date;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DatabaseHostObject extends ScriptableObject {
private static final Log log = LogFactory.getLog(DatabaseHostObject.class);
private static final String hostObjectName = "Database";
public static final String COM_MYSQL_JDBC_DRIVER = "com.mysql.jdbc.Driver";
public static final String ORG_H2_DRIVER = "org.h2.Driver";
public static final String ORACLE_JDBC_ORACLE_DRIVER = "oracle.jdbc.OracleDriver";
public static final String MYSQL = "jdbc:mysql";
public static final String H2 = "jdbc:h2";
public static final String ORACLE = "jdbc:oracle";
private boolean autoCommit = true;
private Context context = null;
private Connection conn = null;
static RDBMSDataSource rdbmsDataSource = null;
private Map<String, Savepoint> savePoints = new HashMap<String, Savepoint>();
public DatabaseHostObject() {
}
@Override
public String getClassName() {
return hostObjectName;
}
public static Scriptable jsConstructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr)
throws ScriptException {
int argsCount = args.length;
DatabaseHostObject db = new DatabaseHostObject();
//args count 1 for dataSource name
if (argsCount != 1 && argsCount != 3 && argsCount != 4) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, hostObjectName, argsCount, true);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "1", "string", args[0], true);
}
if (argsCount == 1) {
String dataSourceName = (String) args[0];
DataSourceManager dataSourceManager = new DataSourceManager();
try {
CarbonDataSource carbonDataSource = dataSourceManager.getInstance().getDataSourceRepository().getDataSource(dataSourceName);
DataSource dataSource = (DataSource) carbonDataSource.getDSObject();
db.conn = dataSource.getConnection();
db.context = cx;
return db;
} catch (DataSourceException e) {
log.error("Failed to access datasource " + dataSourceName, e);
} catch (SQLException e) {
log.error("Failed to get connection", e);
}
}
if (!(args[1] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "2", "string", args[1], true);
}
if (!(args[2] instanceof String) && !(args[2] instanceof Integer)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "3", "string", args[2], true);
}
NativeObject configs = null;
if (argsCount == 4) {
if (!(args[3] instanceof NativeObject)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "4", "object", args[3], true);
}
configs = (NativeObject) args[3];
}
String dbUrl = (String) args[0];
RDBMSConfiguration rdbmsConfig = new RDBMSConfiguration();
try {
if (configs != null) {
Gson gson = new Gson();
rdbmsConfig = gson.fromJson(HostObjectUtil.serializeJSON(configs), RDBMSConfiguration.class);
}
if (rdbmsConfig.getDriverClassName() == null || rdbmsConfig.getDriverClassName().equals("")) {
rdbmsConfig.setDriverClassName(getDriverClassName(dbUrl));
}
rdbmsConfig.setUsername((String) args[1]);
rdbmsConfig.setPassword((String) args[2]);
rdbmsConfig.setUrl(dbUrl);
try {
rdbmsDataSource = new RDBMSDataSource(rdbmsConfig);
} catch (DataSourceException e) {
throw new ScriptException(e);
}
db.conn = rdbmsDataSource.getDataSource().getConnection();
db.context = cx;
return db;
} catch (SQLException e) {
String msg = "Error connecting to the database : " + dbUrl;
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
private static String getDriverClassName(String dburl) {
if (dburl.contains(MYSQL)) {
return COM_MYSQL_JDBC_DRIVER;
} else if (dburl.contains(H2)) {
return ORG_H2_DRIVER;
} else if (dburl.contains(ORACLE)) {
return ORACLE_JDBC_ORACLE_DRIVER;
} else {
return null;
}
}
public boolean jsGet_autoCommit() throws ScriptException {
return this.autoCommit;
}
public void jsSet_autoCommit(Object object) throws ScriptException {
if (!(object instanceof Boolean)) {
HostObjectUtil.invalidProperty(hostObjectName, "autoCommit", "boolean", object);
}
this.autoCommit = (Boolean) object;
}
public static Object jsFunction_query(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException, SQLException {
String functionName = "query";
int argsCount = args.length;
if (argsCount == 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
String query;
if (argsCount == 1) {
//query
Function callback = null;
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
query = (String) args[0];
PreparedStatement stmt = db.conn.prepareStatement(query);
return executeQuery(cx, db, stmt, query, callback, true);
} else if (argsCount == 2) {
if (!(args[0] instanceof String)) {
//batch
Function callback = null;
if (!(args[0] instanceof NativeArray)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
NativeArray queries = (NativeArray) args[0];
NativeArray values = null;
if (args[1] instanceof Function) {
callback = (Function) args[1];
} else if (args[1] instanceof NativeArray) {
values = (NativeArray) args[1];
} else {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "2", "array | function", args[0], false);
}
return executeBatch(cx, db, queries, values, callback);
} else {
//query
Function callback = null;
query = (String) args[0];
PreparedStatement stmt = db.conn.prepareStatement(query);
if (args[1] instanceof Function) {
callback = (Function) args[1];
} else {
setQueryParams(stmt, args, 1, 1);
}
return executeQuery(cx, db, stmt, query, callback, true);
}
} else if (argsCount == 3) {
if (!(args[0] instanceof String)) {
//batch
Function callback = null;
if (!(args[0] instanceof NativeArray)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "array", args[0], false);
}
if (!(args[1] instanceof NativeArray)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "2", "array", args[1], false);
}
if (!(args[2] instanceof Function)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "3", "function", args[2], false);
}
NativeArray queries = (NativeArray) args[0];
NativeArray values = (NativeArray) args[1];
callback = (Function) args[2];
return executeBatch(cx, db, queries, values, callback);
} else {
//query
Function callback = null;
query = (String) args[0];
PreparedStatement stmt = db.conn.prepareStatement(query);
if (args[2] instanceof Function) {
callback = (Function) args[2];
setQueryParams(stmt, args, 1, 1);
} else {
setQueryParams(stmt, args, 1, 2);
}
return executeQuery(cx, db, stmt, query, callback, true);
}
} else {
//args count > 3
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
Function callback = null;
query = (String) args[0];
PreparedStatement stmt = db.conn.prepareStatement(query);
if (args[argsCount - 1] instanceof Function) {
callback = (Function) args[argsCount - 1];
setQueryParams(stmt, args, 1, argsCount - 1);
} else {
setQueryParams(stmt, args, 1, argsCount - 1);
}
return executeQuery(cx, db, stmt, query, callback, true);
}
}
public static String jsFunction_savePoint(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException, SQLException {
String functionName = "savePoint";
int argsCount = args.length;
String savePoint;
if (argsCount == 0) {
savePoint = UUID.randomUUID().toString();
} else {
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
savePoint = (String) args[0];
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
db.savePoints.put(savePoint, db.conn.setSavepoint(savePoint));
return savePoint;
}
public static void jsFunction_releasePoint(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "releasePoint";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
String savePoint = (String) args[0];
DatabaseHostObject db = (DatabaseHostObject) thisObj;
try {
db.conn.releaseSavepoint(db.savePoints.remove(savePoint));
} catch (SQLException e) {
String msg = "Error while releasing the savepoint : " + savePoint;
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
public static void jsFunction_rollback(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "rollback";
int argsCount = args.length;
if (argsCount > 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
String savePoint = null;
if (argsCount == 1) {
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
savePoint = (String) args[0];
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
if (savePoint != null) {
try {
db.conn.rollback(db.savePoints.get(savePoint));
} catch (SQLException e) {
String msg = "Error while rolling back the transaction to savepoint : " + savePoint;
log.warn(msg, e);
throw new ScriptException(msg, e);
}
} else {
try {
db.conn.rollback();
} catch (SQLException e) {
String msg = "Error while rolling back the transaction";
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
}
public static void jsFunction_commit(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "commit";
int argsCount = args.length;
if (argsCount > 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
try {
db.conn.commit();
} catch (SQLException e) {
String msg = "Error while committing the transaction";
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
public static void jsFunction_close(Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws ScriptException {
String functionName = "c";
int argsCount = args.length;
if (argsCount > 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
DatabaseHostObject db = (DatabaseHostObject) thisObj;
try {
db.conn.close();
if (rdbmsDataSource != null) {
rdbmsDataSource.getDataSource().close();
}
} catch (SQLException e) {
String msg = "Error while closing the Database Connection";
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
private static String replaceWildcards(DatabaseHostObject db, String query, NativeArray params) throws SQLException {
String openedChar = null;
String lastChar = null;
StringBuffer newQuery = new StringBuffer();
int paramIndex = 0;
for (int i = 0; i < query.length(); i++) {
String c = Character.toString(query.charAt(i));
if (lastChar == null) {
lastChar = c;
if (c.equals("'") || c.equals("\"")) {
openedChar = c;
}
newQuery.append(c);
continue;
}
if (c.equals("'")) {
if (openedChar == null) {
openedChar = c;
} else if (openedChar.equals(c)) {
if (!lastChar.equals("\\")) {
//closing reached
openedChar = null;
}
}
} else if (c.equals("\"")) {
if (openedChar == null) {
openedChar = c;
} else if (openedChar.equals(c)) {
if (!lastChar.equals("\\")) {
//closing reached
openedChar = null;
}
}
} else if (c.equals("?")) {
if (openedChar == null) {
//replace ?
newQuery.append(HostObjectUtil.serializeObject(params.get(paramIndex, db)));
paramIndex++;
continue;
} else if (lastChar.equals("'")) {
if (openedChar.equals("'")) {
String nextChart = Character.toString(query.charAt(i + 1));
if (nextChart.equals("'")) {
//replace '?'
newQuery.append(HostObjectUtil.serializeObject(params.get(paramIndex, db)));
continue;
}
}
} else if (lastChar.equals("\"")) {
if (openedChar.equals("\"")) {
String nextChart = Character.toString(query.charAt(i + 1));
if (nextChart.equals("\"")) {
//replace '?'
newQuery.append(HostObjectUtil.serializeObject(params.get(paramIndex, db)));
continue;
}
}
}
}
newQuery.append(c);
lastChar = c;
}
return newQuery.toString();
}
private static void setQueryParams(PreparedStatement stmt, Object[] params, int from, int to) throws SQLException {
for (int i = from; i < to + 1; i++) {
setQueryParam(stmt, params[i], i);
}
}
private static void setQueryParam(PreparedStatement stmt, Object obj, int index) throws SQLException {
if (obj instanceof String) {
stmt.setString(index, (String) obj);
} else if (obj instanceof Integer) {
stmt.setInt(index, (Integer) obj);
} else if (obj instanceof Double) {
stmt.setDouble(index, (Double) obj);
}
//Support for streams in queries
//Added 25/9/2013
else if (obj instanceof StreamHostObject) {
StreamHostObject stream=(StreamHostObject)obj;
stmt.setBinaryStream(index,stream.getStream());
}
else {
stmt.setString(index, HostObjectUtil.serializeObject(obj));
}
}
private static Object executeQuery(Context cx, final DatabaseHostObject db, final PreparedStatement stmt, String query,
final Function callback, final boolean keyed) throws ScriptException {
String regex = "^[\\s\\t\\r\\n]*[Ss][Ee][Ll][Ee][Cc][Tt].*";//select
final boolean isSelect = query.matches(regex);
if (callback != null) {
final ContextFactory factory = cx.getFactory();
final ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(new Callable() {
public Object call() throws Exception {
Context cx = RhinoEngine.enterContext(factory);
try {
Object result;
if (isSelect) {
result = processResults(cx, db, db, stmt.executeQuery(), keyed);
} else {
result = stmt.executeUpdate();
}
callback.call(cx, db, db, new Object[]{result});
} catch (SQLException e) {
log.warn(e);
} finally {
es.shutdown();
RhinoEngine.exitContext();
}
return null;
}
});
return null;
} else {
try {
if (isSelect) {
return processResults(cx, db, db, stmt.executeQuery(), keyed);
} else {
return stmt.executeUpdate();
}
} catch (SQLException e) {
log.warn(e);
throw new ScriptException(e);
}
}
}
private static Object executeBatch(Context cx, final DatabaseHostObject db, NativeArray queries,
NativeArray params, final Function callback)
throws ScriptException, SQLException {
if (params != null && (queries.getLength() != params.getLength())) {
String msg = "Query array and values array should be in the same size. HostObject : " +
hostObjectName + ", Method : query";
log.warn(msg);
throw new ScriptException(msg);
}
final Statement stmt = db.conn.createStatement();
for (int index : (Integer[]) queries.getIds()) {
Object obj = queries.get(index, db);
if (!(obj instanceof String)) {
String msg = "Invalid query type : " + obj.toString() + ". Query should be a string";
log.warn(msg);
throw new ScriptException(msg);
}
String query = (String) obj;
if (params != null) {
Object valObj = params.get(index, db);
if (!(valObj instanceof NativeArray)) {
String msg = "Invalid value type : " + obj.toString() + " for the query " + query;
log.warn(msg);
throw new ScriptException(msg);
}
query = replaceWildcards(db, query, (NativeArray) valObj);
}
stmt.addBatch(query);
}
if (callback != null) {
final ContextFactory factory = cx.getFactory();
final ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(new Callable() {
public Object call() throws Exception {
Context ctx = RhinoEngine.enterContext(factory);
try {
int[] result = stmt.executeBatch();
callback.call(ctx, db, db, new Object[]{result});
} catch (SQLException e) {
log.warn(e);
} finally {
es.shutdown();
RhinoEngine.exitContext();
}
return null;
}
});
return null;
} else {
return stmt.executeBatch();
}
}
private static Scriptable processResults(Context cx, Scriptable scope, DatabaseHostObject db, ResultSet results, boolean keyed) throws SQLException, ScriptException {
List<ScriptableObject> rows = new ArrayList<ScriptableObject>();
while (results.next()) {
ScriptableObject row;
ResultSetMetaData rsmd = results.getMetaData();
if (keyed) {
row = (ScriptableObject) db.context.newObject(db);
for (int i = 0; i < rsmd.getColumnCount(); i++) {
String columnName = rsmd.getColumnLabel(i + 1);
Object columnValue = getValue(db, results, i + 1, rsmd.getColumnType(i + 1));
row.put(columnName, row, columnValue);
}
} else {
row = (ScriptableObject) cx.newArray(scope, rsmd.getColumnCount());
for (int i = 0; i < rsmd.getColumnCount(); i++) {
Object columnValue = getValue(db, results, i + 1, rsmd.getColumnType(i + 1));
row.put(i + 1, row, columnValue);
}
}
rows.add(row);
}
return db.context.newArray(db, rows.toArray());
}
private static Object getValue(DatabaseHostObject db, ResultSet results, int index, int type) throws SQLException, ScriptException {
Context cx = db.context;
//TODO : implement for other sql types
switch (type) {
case Types.ARRAY:
return (results.getArray(index) == null) ? null : cx.newArray(db, new Object[]{results.getArray(index)});
case Types.BIGINT:
return (results.getBigDecimal(index) == null) ? null : results.getBigDecimal(index).toPlainString();
case Types.BINARY:
case Types.LONGVARBINARY:
return results.getBinaryStream(index) == null ? null : cx.newObject(db, "Stream", new Object[]{results.getBinaryStream(index)});
case Types.CLOB:
return results.getClob(index) == null ? null : cx.newObject(db, "Stream", new Object[]{results.getClob(index).getAsciiStream()});
case Types.BLOB:
return results.getBlob(index) == null ? null : cx.newObject(db, "Stream", new Object[]{results.getBlob(index).getBinaryStream()});
case Types.TIMESTAMP:
Timestamp date = results.getTimestamp(index);
return date == null ? null : cx.newObject(db, "Date", new Object[] {date.getTime()});
default:
return results.getObject(index) == null ? null : results.getObject(index);
}
}
}
| closing PreparedStatement
| components/hostobjects/org.jaggeryjs.hostobjects.db/src/main/java/org/jaggeryjs/hostobjects/db/DatabaseHostObject.java | closing PreparedStatement |
|
Java | apache-2.0 | b1a621f4742346a21f2106098781380745428067 | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | /*
* The Gemma project
*
* Copyright (c) 2007 University of British Columbia
*
* 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 ubic.gemma.analysis.expression.coexpression;
import java.util.ArrayList;
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 org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ubic.basecode.dataStructure.BitUtil;
import ubic.basecode.ontology.model.OntologyTerm;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressedGenesDetails;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressionCollectionValueObject;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressionValueObject;
import ubic.gemma.model.association.coexpression.Probe2ProbeCoexpressionService;
import ubic.gemma.model.expression.experiment.BioAssaySet;
import ubic.gemma.model.expression.experiment.ExpressionExperimentService;
import ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.gene.GeneService;
import ubic.gemma.ontology.providers.GeneOntologyService;
/**
* Perform gene-to-gene coexpression link analysis ("TMM-style"), based on stored probe-probe coexpression.
*
* @author paul
* @version $Id$
*/
@Service
public class ProbeLinkCoexpressionAnalyzer {
private static Log log = LogFactory.getLog( ProbeLinkCoexpressionAnalyzer.class.getName() );
private static final int MAX_GENES_TO_COMPUTE_GOOVERLAP = 25;
private static final int MAX_GENES_TO_COMPUTE_EESTESTEDIN = 200;
@Autowired
private GeneService geneService;
@Autowired
private Probe2ProbeCoexpressionService probe2ProbeCoexpressionService;
@Autowired
private GeneOntologyService geneOntologyService;
@Autowired
private ExpressionExperimentService expressionExperimentService;
/**
* Gene->EEs tested in. This is a cache that _should_ be safe to use, as it is only used in batch processing, which
* uses a 'short-lived' spring context build on the command line -- not the web application.
*/
private Map<Long, List<Boolean>> genesTestedIn = new HashMap<Long, List<Boolean>>();
/**
* Gene->ees tested in, in a faster access format - preordered by the ees. As for the genesTestedIn, this should not
* be used in webapps.
*/
private Map<Long, Boolean[]> geneTestStatusCache = new HashMap<Long, Boolean[]>();
private Map<Long, byte[]> geneTestStatusByteCache = new HashMap<Long, byte[]>();
/**
* @param genes
* @param ees Collection of ExpressionExperiments that will be considered.
* @param stringency A positive non-zero integer. If a value less than or equal to zero is entered, the value 1 will
* be silently used.
* @param knownGenesOnly if false, 'predicted genes' and 'probe aligned regions' will be populated.
* @param limit The maximum number of results that will be fully populated. Set to 0 to fill all (batch mode)
* @see ubic.gemma.model.genome.GeneDao.getCoexpressedGenes
* @see ubic.gemma.model.analysis.expression.coexpression.CoexpressionCollectionValueObject
* @return Fully initialized CoexpressionCollectionValueObject.
*/
public Map<Gene, CoexpressionCollectionValueObject> linkAnalysis( Collection<Gene> genes,
Collection<BioAssaySet> ees, int stringency, boolean knownGenesOnly, boolean interGenesOnly, int limit ) {
/*
* Start with raw results
*/
Map<Gene, CoexpressionCollectionValueObject> result = geneService.getCoexpressedGenes( genes, ees, stringency,
knownGenesOnly, interGenesOnly );
/*
* Perform postprocessing gene by gene. It is possible this could be sped up by doing batches.
*/
for ( Gene gene : genes ) {
CoexpressionCollectionValueObject coexpressions = result.get( gene );
/*
* Identify data sets the query gene is expressed in - this is fast (?) and provides an upper bound for EEs
* we need to search in the first place.
*/
Collection<BioAssaySet> eesQueryTestedIn = probe2ProbeCoexpressionService
.getExpressionExperimentsLinkTestedIn( gene, ees, false );
/*
* Finish the postprocessing.
*/
coexpressions.setEesQueryGeneTestedIn( eesQueryTestedIn );
if ( coexpressions.getAllGeneCoexpressionData( stringency ).size() == 0 ) {
continue;
}
// don't fill in the gene info etc if we're in batch mode.
if ( limit > 0 ) {
filter( coexpressions, limit, stringency ); // remove excess
fillInEEInfo( coexpressions ); // do first...
fillInGeneInfo( stringency, coexpressions );
computeGoStats( coexpressions, stringency );
}
computeEesTestedIn( ees, coexpressions, eesQueryTestedIn, stringency, limit );
}
return result;
}
/**
* @param gene
* @param ees Collection of ExpressionExperiments that will be considered.
* @param inputStringency A positive non-zero integer. If a value less than or equal to zero is entered, the value 1
* will be silently used.
* @param knownGenesOnly if false, 'predicted genes' and 'probe aligned regions' will be populated.
* @param limit The maximum number of results that will be fully populated. Set to 0 to fill all (batch mode)
* @see ubic.gemma.model.genome.GeneDao.getCoexpressedGenes
* @see ubic.gemma.model.analysis.expression.coexpression.CoexpressionCollectionValueObject
* @return Fully initialized CoexpressionCollectionValueObject.
*/
public CoexpressionCollectionValueObject linkAnalysis( Gene gene, Collection<BioAssaySet> ees, int inputStringency,
boolean knownGenesOnly, int limit ) {
int stringency = inputStringency <= 0 ? 1 : inputStringency;
if ( log.isDebugEnabled() )
log.debug( "Link query for " + gene.getName() + " stringency=" + stringency + " knowngenesonly?="
+ knownGenesOnly );
/*
* Identify data sets the query gene is expressed in - this is fast (?) and provides an upper bound for EEs we
* need to search in the first place.
*/
Collection<BioAssaySet> eesQueryTestedIn = probe2ProbeCoexpressionService.getExpressionExperimentsLinkTestedIn(
gene, ees, false );
if ( eesQueryTestedIn.size() == 0 ) {
CoexpressionCollectionValueObject r = new CoexpressionCollectionValueObject( gene, stringency );
r.setErrorState( "No experiments have coexpression data for " + gene.getOfficialSymbol() );
return r;
}
/*
* Perform the coexpression search, some postprocessing done. If eesQueryTestedIn is empty, this returns real
* quick.
*/
CoexpressionCollectionValueObject coexpressions = geneService.getCoexpressedGenes( gene, eesQueryTestedIn,
stringency, knownGenesOnly );
/*
* Finish the postprocessing.
*/
StopWatch timer = new StopWatch();
timer.start();
coexpressions.setEesQueryGeneTestedIn( eesQueryTestedIn );
if ( coexpressions.getAllGeneCoexpressionData( stringency ).size() == 0 ) {
return coexpressions;
}
// don't fill in the gene info etc if we're in batch mode.
if ( limit > 0 ) {
filter( coexpressions, limit, stringency ); // remove excess
fillInEEInfo( coexpressions ); // do first...
fillInGeneInfo( stringency, coexpressions );
computeGoStats( coexpressions, stringency );
}
computeEesTestedIn( ees, coexpressions, eesQueryTestedIn, stringency, limit );
timer.stop();
if ( timer.getTime() > 1000 ) {
log.info( "All Post-Postprocessing: " + timer.getTime() + "ms" );
}
log.debug( "Analysis completed" );
return coexpressions;
}
/**
* @param coexpressions
* @param limit
* @param stringency
*/
private void filter( CoexpressionCollectionValueObject coexpressions, int limit, int stringency ) {
CoexpressedGenesDetails coexps = coexpressions.getKnownGeneCoexpression();
coexps.filter( limit, stringency );
coexps = coexpressions.getPredictedGeneCoexpression();
coexps.filter( limit, stringency );
coexps = coexpressions.getProbeAlignedRegionCoexpression();
coexps.filter( limit, stringency );
}
/**
* @param coexpressions
*/
private void fillInEEInfo( CoexpressionCollectionValueObject coexpressions ) {
Collection<Long> eeIds = new HashSet<Long>();
log.debug( "Filling in EE info" );
CoexpressedGenesDetails coexps = coexpressions.getKnownGeneCoexpression();
fillInEEInfo( coexpressions, eeIds, coexps );
coexps = coexpressions.getPredictedGeneCoexpression();
fillInEEInfo( coexpressions, eeIds, coexps );
coexps = coexpressions.getProbeAlignedRegionCoexpression();
fillInEEInfo( coexpressions, eeIds, coexps );
}
/**
* @param coexpressions
* @param eeIds
* @param coexps
*/
private void fillInEEInfo( CoexpressionCollectionValueObject coexpressions, Collection<Long> eeIds,
CoexpressedGenesDetails coexps ) {
for ( ExpressionExperimentValueObject evo : coexpressions.getExpressionExperiments() ) {
eeIds.add( evo.getId() );
}
Collection<ExpressionExperimentValueObject> ees = expressionExperimentService.loadValueObjects( eeIds );
Map<Long, ExpressionExperimentValueObject> em = new HashMap<Long, ExpressionExperimentValueObject>();
for ( ExpressionExperimentValueObject evo : ees ) {
em.put( evo.getId(), evo );
}
for ( ExpressionExperimentValueObject evo : coexps.getExpressionExperiments() ) {
em.put( evo.getId(), evo );
}
for ( ExpressionExperimentValueObject evo : coexpressions.getExpressionExperiments() ) {
ExpressionExperimentValueObject ee = em.get( evo.getId() );
evo.setShortName( ee.getShortName() );
evo.setName( ee.getName() );
}
for ( ExpressionExperimentValueObject evo : coexps.getExpressionExperiments() ) {
ExpressionExperimentValueObject ee = em.get( evo.getId() );
evo.setShortName( ee.getShortName() );
evo.setName( ee.getName() );
}
}
/**
* @param stringency
* @param coexpressions
*/
private void fillInGeneInfo( int stringency, CoexpressionCollectionValueObject coexpressions ) {
log.debug( "Filling in Gene info" );
CoexpressedGenesDetails coexp = coexpressions.getKnownGeneCoexpression();
fillInGeneInfo( stringency, coexpressions, coexp );
coexp = coexpressions.getPredictedGeneCoexpression();
fillInGeneInfo( stringency, coexpressions, coexp );
coexp = coexpressions.getProbeAlignedRegionCoexpression();
fillInGeneInfo( stringency, coexpressions, coexp );
}
/**
* @param stringency
* @param coexpressions
* @param coexp
*/
private void fillInGeneInfo( int stringency, CoexpressionCollectionValueObject coexpressions,
CoexpressedGenesDetails coexp ) {
StopWatch timer = new StopWatch();
timer.start();
List<CoexpressionValueObject> coexpressionData = coexp.getCoexpressionData( stringency );
Collection<Long> geneIds = new HashSet<Long>();
for ( CoexpressionValueObject cod : coexpressionData ) {
geneIds.add( cod.getGeneId() );
}
Collection<Gene> genes = geneService.loadMultiple( geneIds ); // this can be slow if there are a lot.
Map<Long, Gene> gm = new HashMap<Long, Gene>();
for ( Gene g : genes ) {
gm.put( g.getId(), g );
}
for ( CoexpressionValueObject cod : coexpressionData ) {
Gene g = gm.get( cod.getGeneId() );
cod.setGeneName( g.getName() );
cod.setGeneOfficialName( g.getOfficialName() );
cod.setGeneType( g.getClass().getSimpleName() );
cod.setTaxonId( g.getTaxon().getId() );
coexpressions.add( cod );
}
timer.stop();
if ( timer.getTime() > 1000 ) {
log.info( "Filled in gene info: " + timer.getTime() + "ms" );
}
}
/**
* Fill in gene tested information for genes coexpressed with the query.
*
* @param ees ExpressionExperiments, including all that were used at the start of the query (including those the
* query gene is NOT expressed in)
* @param coexpressions
* @param eesQueryTestedIn
* @param stringency
* @param limit if zero, they are all collected and a batch-mode cache is used. This is MUCH slower if you are
* analyzing a single CoexpressionCollectionValueObject, but faster (and more memory-intensive) if many are
* going to be looked at (as in the case of a bulk Gene2Gene analysis).
*/
@SuppressWarnings("unchecked")
private void computeEesTestedIn( Collection<BioAssaySet> ees, CoexpressionCollectionValueObject coexpressions,
Collection eesQueryTestedIn, int stringency, int limit ) {
List<CoexpressionValueObject> coexpressionData = coexpressions.getKnownGeneCoexpressionData( stringency );
if ( limit == 0 ) {
// when we expecte to be analyzing many query genes. Note that we pass in the full set of experiments, not
// just the ones in which the query gene was tested in.
computeEesTestedInBatch( ees, coexpressionData );
} else {
// for when we are looking at just one gene at a time
computeEesTestedIn( eesQueryTestedIn, coexpressionData );
}
/*
* We can add this analysis to the predicted and pars if we want. I'm leaving it out for now.
*/
}
/**
* Provide a consistent mapping of experiments that can be used to index a vector. The actual ordering is not
* guaranteed to be anything in particular, just that repeated calls to this method with the same experiments will
* yield the same mapping.
*
* @param experiments
* @return Map of EE IDs to an index, where the index values are from 0 ... N-1 where N is the number of
* experiments.
*/
public static Map<Long, Integer> getOrderingMap( Collection<BioAssaySet> experiments ) {
List<Long> eeIds = new ArrayList<Long>();
for ( BioAssaySet ee : experiments ) {
eeIds.add( ee.getId() );
}
Collections.sort( eeIds );
Map<Long, Integer> result = new HashMap<Long, Integer>();
int index = 0;
for ( Long id : eeIds ) {
result.put( id, index );
index++;
}
assert result.size() == experiments.size();
return result;
}
/**
* For the genes that the query is coexpressed with; this retrieves the information for all the coexpressionData
* passed in (no limit) - all of them have to be for the same query gene!
*
* @param ees, including ALL experiments that were intially started with, NOT just the ones that the query gene was
* tested in.
* @param coexpressionData to check, the query gene must be the same for each of them.
*/
private void computeEesTestedInBatch( Collection<BioAssaySet> ees, List<CoexpressionValueObject> coexpressionData ) {
if ( coexpressionData.isEmpty() ) return;
StopWatch timer = new StopWatch();
timer.start();
if ( log.isDebugEnabled() ) {
log.debug( "Computing EEs tested in for " + coexpressionData.size() + " genes coexpressed with query." );
}
/*
* Note: we assume this is actually constant as we build a cache based on it. Small risk.
*/
Map<Long, Integer> eeIndexMap = ProbeLinkCoexpressionAnalyzer.getOrderingMap( ees );
assert eeIndexMap.size() == ees.size();
/*
* Save some computation in the inner loop by assuming the query gene is constant.
*/
CoexpressionValueObject initializer = coexpressionData.iterator().next();
Long queryGeneId = initializer.getQueryGene().getId();
Boolean[] queryGeneEETestStatus = getEETestedForGeneVector( queryGeneId, ees, eeIndexMap );
if ( queryGeneEETestStatus == null ) {
/*
* OK, this is bizarre. We shouldn't have any coexpression data and shouldn't be here.
*/
return;
}
geneTestStatusCache.put( queryGeneId, queryGeneEETestStatus );
byte[] queryGeneEETestStatusBytes;
if ( geneTestStatusByteCache.containsKey( queryGeneId ) ) {
queryGeneEETestStatusBytes = geneTestStatusByteCache.get( queryGeneId );
} else {
queryGeneEETestStatusBytes = computeTestedDatasetVector( queryGeneId, ees, eeIndexMap );
geneTestStatusByteCache.put( queryGeneId, queryGeneEETestStatusBytes );
}
/*
* This is a potential bottleneck, because there are often >500 ees and >1000 cvos, and each EE tests >20000
* genes. Therefore we try hard not to iterate over all the CVOEEs more than we need to. So this is coded very
* carefully. Once the cache is warmed up, this still can take over 500ms to run (Feb 2010). The total number of
* loops _easily_ exceeds a million.
*/
int loopcount = 0; // for performance statistics
for ( CoexpressionValueObject cvo : coexpressionData ) {
Long coexGeneId = cvo.getGeneId();
if ( !queryGeneId.equals( cvo.getQueryGene().getId() ) ) {
throw new IllegalArgumentException( "All coexpression value objects must have the same query gene here" );
}
/*
* Get the target gene info, from the cache if possible.
*/
byte[] targetGeneEETestStatus;
if ( geneTestStatusByteCache.containsKey( coexGeneId ) ) {
targetGeneEETestStatus = geneTestStatusByteCache.get( coexGeneId );
} else {
targetGeneEETestStatus = computeTestedDatasetVector( coexGeneId, ees, eeIndexMap );
geneTestStatusByteCache.put( coexGeneId, targetGeneEETestStatus );
}
assert targetGeneEETestStatus.length == queryGeneEETestStatusBytes.length;
byte[] answer = new byte[targetGeneEETestStatus.length];
for ( int i = 0; i < answer.length; i++ ) {
answer[i] = ( byte ) ( targetGeneEETestStatus[i] & queryGeneEETestStatusBytes[i] );
loopcount++;
}
cvo.setDatasetsTestedInBytes( answer );
// That there is no easy way to avoid this inner loop - however, in this batch processing case where this is
// used, we end up with a bit vector later, so we could consider constructing that now instead.
// for ( BioAssaySet ee : ees ) {
// /*
// * Both the query and the target have to have been tested in the given experiment.
// */
// if ( queryGeneEETestStatus[i] && targetGeneEETestStatus[i] ) {
// Long eeid = ee.getId();
// cvo.getDatasetsTestedIn().add( eeid );
// }
// loopcount++;
// i++;
// }
// sanity check.
// assert cvo.getDatasetsTestedIn().size() > 0 : "No data sets tested in for : " + cvo;
}
if ( timer.getTime() > 100 ) {
log.info( "Compute EEs tested in (batch ): " + timer.getTime() + "ms; " + loopcount + " loops" );
}
}
/**
* Method for batch processing. Should not be used in a web application context.
*
* @param geneId
* @param ees
* @param eeIndexMap Map of EE IDs to index in the 'eesTestingIn' where that EE is.
* @return boolean array of same length as ees, where true means the given gene was tested in that dataset.
*/
private Boolean[] getEETestedForGeneVector( Long geneId, Collection<BioAssaySet> ees, Map<Long, Integer> eeIndexMap ) {
/*
* This condition is, pretty much only true once in practice. That's because the first time through populates
* genesTestedIn for all the genes tested in any of the data sets, which is essentially all genes.
*/
if ( !genesTestedIn.containsKey( geneId ) ) {
cacheEesGeneTestedIn( ees, eeIndexMap );
}
List<Boolean> eesTestingGene = genesTestedIn.get( geneId );
if ( eesTestingGene == null ) {
log.info( "No data set tested gene: " + geneId );
return null;
}
Boolean[] queryGeneEETestStatus = new Boolean[ees.size()];
int i = 0;
// note: we assume that this collection does not change iteration order.
for ( BioAssaySet ee : ees ) {
Long eeid = ee.getId();
Integer index = eeIndexMap.get( eeid );
Boolean geneTested = eesTestingGene.get( index );
assert geneTested != null : "Null for index=" + index + ", EEID=" + eeid + ", GENEID=" + geneId;
queryGeneEETestStatus[i] = geneTested;
i++;
}
return queryGeneEETestStatus;
}
/**
* @param datasetsTestedIn
* @param eeIdOrder
* @return
*/
private byte[] computeTestedDatasetVector( Long geneId, Collection<BioAssaySet> ees, Map<Long, Integer> eeIdOrder ) {
/*
* This condition is, pretty much only true once in practice. That's because the first time through populates
* genesTestedIn for all the genes tested in any of the data sets.
*/
if ( !genesTestedIn.containsKey( geneId ) ) {
cacheEesGeneTestedIn( ees, eeIdOrder );
}
assert genesTestedIn.containsKey( geneId );
List<Boolean> eesTestingGene = genesTestedIn.get( geneId );
// initialize.
byte[] result = new byte[( int ) Math.ceil( eeIdOrder.size() / ( double ) Byte.SIZE )];
for ( int i = 0, j = result.length; i < j; i++ ) {
result[i] = 0x0;
}
int i = 0;
for ( BioAssaySet ee : ees ) {
Long eeid = ee.getId();
Integer index = eeIdOrder.get( eeid );
if ( eesTestingGene.get( index ) ) {
BitUtil.set( result, index );
}
i++;
}
return result;
}
/**
* For each experiment, get the genes it tested and populate a map. This is slow; but once we've seen a gene, we
* don't have to repeat it. We used to cache the ee->gene relationship, but doing it the other way around yields
* must faster code.
*
* @param ees
* @param eeIndexMap
*/
private void cacheEesGeneTestedIn( Collection<BioAssaySet> ees, Map<Long, Integer> eeIndexMap ) {
assert ees != null;
assert eeIndexMap != null;
assert !ees.isEmpty();
assert !eeIndexMap.isEmpty();
for ( BioAssaySet ee : ees ) {
Collection<Long> genes = probe2ProbeCoexpressionService.getGenesTestedBy( ee, false );
if ( genes.isEmpty() ) {
log.warn( "No genes were tested by " + ee );
continue;
}
// inverted map of gene -> ees tested in.
Integer indexOfEEInAr = eeIndexMap.get( ee.getId() );
assert indexOfEEInAr != null : "No index for EEID=" + ee.getId() + " in the eeIndexMap";
for ( Long geneId : genes ) {
if ( !genesTestedIn.containsKey( geneId ) ) {
// initialize the boolean array for this gene.
genesTestedIn.put( geneId, new ArrayList<Boolean>() );
for ( int i = 0; i < ees.size(); i++ ) {
genesTestedIn.get( geneId ).add( Boolean.FALSE );
}
}
// flip to true since the gene was tested in the ee
genesTestedIn.get( geneId ).set( indexOfEEInAr, Boolean.TRUE );
}
}
}
/**
* For the genes that the query is coexpressed with. This is limited to the top MAX_GENES_TO_COMPUTE_EESTESTEDIN.
* This is not very fast if MAX_GENES_TO_COMPUTE_EESTESTEDIN is large. We use this version for on-line requests.
*
* @param eesQueryTestedIn, limited to the ees that the query gene is tested in.
* @param coexpressionData
* @see ProbeLinkCoexpressionAnalyzer.computeEesTestedInBatch for the version used when requests are going to be
* done for many genes, so cache is built first time.
*/
private void computeEesTestedIn( Collection<BioAssaySet> eesQueryTestedIn,
List<CoexpressionValueObject> coexpressionData ) {
Collection<Long> coexGeneIds = new HashSet<Long>();
StopWatch timer = new StopWatch();
timer.start();
int i = 0;
Map<Long, CoexpressionValueObject> gmap = new HashMap<Long, CoexpressionValueObject>();
for ( CoexpressionValueObject o : coexpressionData ) {
coexGeneIds.add( o.getGeneId() );
gmap.put( o.getGeneId(), o );
i++;
if ( i >= MAX_GENES_TO_COMPUTE_EESTESTEDIN ) break;
}
log.debug( "Computing EEs tested in for " + coexGeneIds.size() + " genes." );
Map<Long, Collection<BioAssaySet>> eesTestedIn = probe2ProbeCoexpressionService
.getExpressionExperimentsTestedIn( coexGeneIds, eesQueryTestedIn, false );
for ( Long g : eesTestedIn.keySet() ) {
CoexpressionValueObject cvo = gmap.get( g );
assert cvo != null;
assert eesTestedIn.get( g ).size() <= eesQueryTestedIn.size();
Collection<Long> ids = new HashSet<Long>();
for ( BioAssaySet ee : eesTestedIn.get( g ) ) {
Long eeid = ee.getId();
ids.add( eeid );
}
cvo.setDatasetsTestedIn( ids );
}
timer.stop();
if ( timer.getTime() > 1000 ) {
log.info( "computeEesTestedIn: " + timer.getTime() + "ms" );
}
}
/**
* @param geneOntologyService
*/
public void setGeneOntologyService( GeneOntologyService geneOntologyService ) {
this.geneOntologyService = geneOntologyService;
}
/**
* @param geneService
*/
public void setGeneService( GeneService geneService ) {
this.geneService = geneService;
}
/**
* @param probe2ProbeCoexpressionService
*/
public void setProbe2ProbeCoexpressionService( Probe2ProbeCoexpressionService probe2ProbeCoexpressionService ) {
this.probe2ProbeCoexpressionService = probe2ProbeCoexpressionService;
}
/**
* @param queryGene
* @param numQueryGeneGOTerms
* @param coexpressionData
*/
private void computeGoOverlap( Gene queryGene, int numQueryGeneGOTerms,
List<CoexpressionValueObject> coexpressionData ) {
Collection<Long> overlapIds = new HashSet<Long>();
int i = 0;
for ( CoexpressionValueObject cvo : coexpressionData ) {
overlapIds.add( cvo.getGeneId() );
cvo.setNumQueryGeneGOTerms( numQueryGeneGOTerms );
if ( i++ > MAX_GENES_TO_COMPUTE_GOOVERLAP ) break;
}
Map<Long, Collection<OntologyTerm>> overlap = geneOntologyService
.calculateGoTermOverlap( queryGene, overlapIds );
for ( CoexpressionValueObject cvo : coexpressionData ) {
cvo.setGoOverlap( overlap.get( cvo.getGeneId() ) );
}
}
/**
* @param coexpressions
*/
private void computeGoStats( CoexpressionCollectionValueObject coexpressions, int stringency ) {
// don't compute this if we aren't loading GO into memory.
if ( !geneOntologyService.isGeneOntologyLoaded() ) {
return;
}
log.debug( "Computing GO stats" );
Gene queryGene = coexpressions.getQueryGene();
int numQueryGeneGOTerms = geneOntologyService.getGOTerms( queryGene ).size();
coexpressions.setQueryGeneGoTermCount( numQueryGeneGOTerms );
if ( numQueryGeneGOTerms == 0 ) return;
if ( coexpressions.getAllGeneCoexpressionData( stringency ).size() == 0 ) return;
List<CoexpressionValueObject> knownGeneCoexpressionData = coexpressions
.getKnownGeneCoexpressionData( stringency );
computeGoOverlap( queryGene, numQueryGeneGOTerms, knownGeneCoexpressionData );
// Only known genes have GO terms, so we don't need to look at Predicted and PARs.
}
public void setExpressionExperimentService( ExpressionExperimentService expressionExperimentService ) {
this.expressionExperimentService = expressionExperimentService;
}
}
| gemma-core/src/main/java/ubic/gemma/analysis/expression/coexpression/ProbeLinkCoexpressionAnalyzer.java | /*
* The Gemma project
*
* Copyright (c) 2007 University of British Columbia
*
* 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 ubic.gemma.analysis.expression.coexpression;
import java.util.ArrayList;
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 org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ubic.basecode.dataStructure.BitUtil;
import ubic.basecode.ontology.model.OntologyTerm;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressedGenesDetails;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressionCollectionValueObject;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressionValueObject;
import ubic.gemma.model.association.coexpression.Probe2ProbeCoexpressionService;
import ubic.gemma.model.expression.experiment.BioAssaySet;
import ubic.gemma.model.expression.experiment.ExpressionExperimentService;
import ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.gene.GeneService;
import ubic.gemma.ontology.providers.GeneOntologyService;
/**
* Perform gene-to-gene coexpression link analysis ("TMM-style"), based on stored probe-probe coexpression.
*
* @author paul
* @version $Id$
*/
@Service
public class ProbeLinkCoexpressionAnalyzer {
private static Log log = LogFactory.getLog( ProbeLinkCoexpressionAnalyzer.class.getName() );
private static final int MAX_GENES_TO_COMPUTE_GOOVERLAP = 25;
private static final int MAX_GENES_TO_COMPUTE_EESTESTEDIN = 200;
@Autowired
private GeneService geneService;
@Autowired
private Probe2ProbeCoexpressionService probe2ProbeCoexpressionService;
@Autowired
private GeneOntologyService geneOntologyService;
@Autowired
private ExpressionExperimentService expressionExperimentService;
/**
* Gene->EEs tested in. This is a cache that _should_ be safe to use, as it is only used in batch processing, which
* uses a 'short-lived' spring context build on the command line -- not the web application.
*/
private Map<Long, List<Boolean>> genesTestedIn = new HashMap<Long, List<Boolean>>();
/**
* Gene->ees tested in, in a faster access format - preordered by the ees. As for the genesTestedIn, this should not
* be used in webapps.
*/
private Map<Long, Boolean[]> geneTestStatusCache = new HashMap<Long, Boolean[]>();
private Map<Long, byte[]> geneTestStatusByteCache = new HashMap<Long, byte[]>();
/**
* @param genes
* @param ees Collection of ExpressionExperiments that will be considered.
* @param stringency A positive non-zero integer. If a value less than or equal to zero is entered, the value 1 will
* be silently used.
* @param knownGenesOnly if false, 'predicted genes' and 'probe aligned regions' will be populated.
* @param limit The maximum number of results that will be fully populated. Set to 0 to fill all (batch mode)
* @see ubic.gemma.model.genome.GeneDao.getCoexpressedGenes
* @see ubic.gemma.model.analysis.expression.coexpression.CoexpressionCollectionValueObject
* @return Fully initialized CoexpressionCollectionValueObject.
*/
public Map<Gene, CoexpressionCollectionValueObject> linkAnalysis( Collection<Gene> genes,
Collection<BioAssaySet> ees, int stringency, boolean knownGenesOnly, boolean interGenesOnly, int limit ) {
/*
* Start with raw results
*/
Map<Gene, CoexpressionCollectionValueObject> result = geneService.getCoexpressedGenes( genes, ees, stringency,
knownGenesOnly, interGenesOnly );
/*
* Perform postprocessing gene by gene. It is possible this could be sped up by doing batches.
*/
for ( Gene gene : genes ) {
CoexpressionCollectionValueObject coexpressions = result.get( gene );
/*
* Identify data sets the query gene is expressed in - this is fast (?) and provides an upper bound for EEs
* we need to search in the first place.
*/
Collection<BioAssaySet> eesQueryTestedIn = probe2ProbeCoexpressionService
.getExpressionExperimentsLinkTestedIn( gene, ees, false );
/*
* Finish the postprocessing.
*/
coexpressions.setEesQueryGeneTestedIn( eesQueryTestedIn );
if ( coexpressions.getAllGeneCoexpressionData( stringency ).size() == 0 ) {
continue;
}
// don't fill in the gene info etc if we're in batch mode.
if ( limit > 0 ) {
filter( coexpressions, limit, stringency ); // remove excess
fillInEEInfo( coexpressions ); // do first...
fillInGeneInfo( stringency, coexpressions );
computeGoStats( coexpressions, stringency );
}
computeEesTestedIn( ees, coexpressions, eesQueryTestedIn, stringency, limit );
}
return result;
}
/**
* @param gene
* @param ees Collection of ExpressionExperiments that will be considered.
* @param inputStringency A positive non-zero integer. If a value less than or equal to zero is entered, the value 1
* will be silently used.
* @param knownGenesOnly if false, 'predicted genes' and 'probe aligned regions' will be populated.
* @param limit The maximum number of results that will be fully populated. Set to 0 to fill all (batch mode)
* @see ubic.gemma.model.genome.GeneDao.getCoexpressedGenes
* @see ubic.gemma.model.analysis.expression.coexpression.CoexpressionCollectionValueObject
* @return Fully initialized CoexpressionCollectionValueObject.
*/
public CoexpressionCollectionValueObject linkAnalysis( Gene gene, Collection<BioAssaySet> ees, int inputStringency,
boolean knownGenesOnly, int limit ) {
int stringency = inputStringency <= 0 ? 1 : inputStringency;
if ( log.isDebugEnabled() )
log.debug( "Link query for " + gene.getName() + " stringency=" + stringency + " knowngenesonly?="
+ knownGenesOnly );
/*
* Identify data sets the query gene is expressed in - this is fast (?) and provides an upper bound for EEs we
* need to search in the first place.
*/
Collection<BioAssaySet> eesQueryTestedIn = probe2ProbeCoexpressionService.getExpressionExperimentsLinkTestedIn(
gene, ees, false );
if ( eesQueryTestedIn.size() == 0 ) {
CoexpressionCollectionValueObject r = new CoexpressionCollectionValueObject( gene, stringency );
r.setErrorState( "No experiments have coexpression data for " + gene.getOfficialSymbol() );
return r;
}
/*
* Perform the coexpression search, some postprocessing done. If eesQueryTestedIn is empty, this returns real
* quick.
*/
CoexpressionCollectionValueObject coexpressions = geneService.getCoexpressedGenes( gene, eesQueryTestedIn,
stringency, knownGenesOnly );
/*
* Finish the postprocessing.
*/
StopWatch timer = new StopWatch();
timer.start();
coexpressions.setEesQueryGeneTestedIn( eesQueryTestedIn );
if ( coexpressions.getAllGeneCoexpressionData( stringency ).size() == 0 ) {
return coexpressions;
}
// don't fill in the gene info etc if we're in batch mode.
if ( limit > 0 ) {
filter( coexpressions, limit, stringency ); // remove excess
fillInEEInfo( coexpressions ); // do first...
fillInGeneInfo( stringency, coexpressions );
computeGoStats( coexpressions, stringency );
}
computeEesTestedIn( ees, coexpressions, eesQueryTestedIn, stringency, limit );
timer.stop();
if ( timer.getTime() > 1000 ) {
log.info( "All Post-Postprocessing: " + timer.getTime() + "ms" );
}
log.debug( "Analysis completed" );
return coexpressions;
}
/**
* @param coexpressions
* @param limit
* @param stringency
*/
private void filter( CoexpressionCollectionValueObject coexpressions, int limit, int stringency ) {
CoexpressedGenesDetails coexps = coexpressions.getKnownGeneCoexpression();
coexps.filter( limit, stringency );
coexps = coexpressions.getPredictedGeneCoexpression();
coexps.filter( limit, stringency );
coexps = coexpressions.getProbeAlignedRegionCoexpression();
coexps.filter( limit, stringency );
}
/**
* @param coexpressions
*/
private void fillInEEInfo( CoexpressionCollectionValueObject coexpressions ) {
Collection<Long> eeIds = new HashSet<Long>();
log.debug( "Filling in EE info" );
CoexpressedGenesDetails coexps = coexpressions.getKnownGeneCoexpression();
fillInEEInfo( coexpressions, eeIds, coexps );
coexps = coexpressions.getPredictedGeneCoexpression();
fillInEEInfo( coexpressions, eeIds, coexps );
coexps = coexpressions.getProbeAlignedRegionCoexpression();
fillInEEInfo( coexpressions, eeIds, coexps );
}
/**
* @param coexpressions
* @param eeIds
* @param coexps
*/
private void fillInEEInfo( CoexpressionCollectionValueObject coexpressions, Collection<Long> eeIds,
CoexpressedGenesDetails coexps ) {
for ( ExpressionExperimentValueObject evo : coexpressions.getExpressionExperiments() ) {
eeIds.add( evo.getId() );
}
Collection<ExpressionExperimentValueObject> ees = expressionExperimentService.loadValueObjects( eeIds );
Map<Long, ExpressionExperimentValueObject> em = new HashMap<Long, ExpressionExperimentValueObject>();
for ( ExpressionExperimentValueObject evo : ees ) {
em.put( evo.getId(), evo );
}
for ( ExpressionExperimentValueObject evo : coexps.getExpressionExperiments() ) {
em.put( evo.getId(), evo );
}
for ( ExpressionExperimentValueObject evo : coexpressions.getExpressionExperiments() ) {
ExpressionExperimentValueObject ee = em.get( evo.getId() );
evo.setShortName( ee.getShortName() );
evo.setName( ee.getName() );
}
for ( ExpressionExperimentValueObject evo : coexps.getExpressionExperiments() ) {
ExpressionExperimentValueObject ee = em.get( evo.getId() );
evo.setShortName( ee.getShortName() );
evo.setName( ee.getName() );
}
}
/**
* @param stringency
* @param coexpressions
*/
private void fillInGeneInfo( int stringency, CoexpressionCollectionValueObject coexpressions ) {
log.debug( "Filling in Gene info" );
CoexpressedGenesDetails coexp = coexpressions.getKnownGeneCoexpression();
fillInGeneInfo( stringency, coexpressions, coexp );
coexp = coexpressions.getPredictedGeneCoexpression();
fillInGeneInfo( stringency, coexpressions, coexp );
coexp = coexpressions.getProbeAlignedRegionCoexpression();
fillInGeneInfo( stringency, coexpressions, coexp );
}
/**
* @param stringency
* @param coexpressions
* @param coexp
*/
private void fillInGeneInfo( int stringency, CoexpressionCollectionValueObject coexpressions,
CoexpressedGenesDetails coexp ) {
StopWatch timer = new StopWatch();
timer.start();
List<CoexpressionValueObject> coexpressionData = coexp.getCoexpressionData( stringency );
Collection<Long> geneIds = new HashSet<Long>();
for ( CoexpressionValueObject cod : coexpressionData ) {
geneIds.add( cod.getGeneId() );
}
Collection<Gene> genes = geneService.loadMultiple( geneIds ); // this can be slow if there are a lot.
Map<Long, Gene> gm = new HashMap<Long, Gene>();
for ( Gene g : genes ) {
gm.put( g.getId(), g );
}
for ( CoexpressionValueObject cod : coexpressionData ) {
Gene g = gm.get( cod.getGeneId() );
cod.setGeneName( g.getName() );
cod.setGeneOfficialName( g.getOfficialName() );
cod.setGeneType( g.getClass().getSimpleName() );
cod.setTaxonId( g.getTaxon().getId() );
coexpressions.add( cod );
}
timer.stop();
if ( timer.getTime() > 1000 ) {
log.info( "Filled in gene info: " + timer.getTime() + "ms" );
}
}
/**
* Fill in gene tested information for genes coexpressed with the query.
*
* @param ees ExpressionExperiments, including all that were used at the start of the query (including those the
* query gene is NOT expressed in)
* @param coexpressions
* @param eesQueryTestedIn
* @param stringency
* @param limit if zero, they are all collected and a batch-mode cache is used. This is MUCH slower if you are
* analyzing a single CoexpressionCollectionValueObject, but faster (and more memory-intensive) if many are
* going to be looked at (as in the case of a bulk Gene2Gene analysis).
*/
@SuppressWarnings("unchecked")
private void computeEesTestedIn( Collection<BioAssaySet> ees, CoexpressionCollectionValueObject coexpressions,
Collection eesQueryTestedIn, int stringency, int limit ) {
List<CoexpressionValueObject> coexpressionData = coexpressions.getKnownGeneCoexpressionData( stringency );
if ( limit == 0 ) {
// when we expecte to be analyzing many query genes. Note that we pass in the full set of experiments, not
// just the ones in which the query gene was tested in.
computeEesTestedInBatch( ees, coexpressionData );
} else {
// for when we are looking at just one gene at a time
computeEesTestedIn( eesQueryTestedIn, coexpressionData );
}
/*
* We can add this analysis to the predicted and pars if we want. I'm leaving it out for now.
*/
}
/**
* Provide a consistent mapping of experiments that can be used to index a vector. The actual ordering is not
* guaranteed to be anything in particular, just that repeated calls to this method with the same experiments will
* yield the same mapping.
*
* @param experiments
* @return Map of EE IDs to an index, where the index values are from 0 ... N-1 where N is the number of
* experiments.
*/
public static Map<Long, Integer> getOrderingMap( Collection<BioAssaySet> experiments ) {
List<Long> eeIds = new ArrayList<Long>();
for ( BioAssaySet ee : experiments ) {
eeIds.add( ee.getId() );
}
Collections.sort( eeIds );
Map<Long, Integer> result = new HashMap<Long, Integer>();
int index = 0;
for ( Long id : eeIds ) {
result.put( id, index );
index++;
}
assert result.size() == experiments.size();
return result;
}
/**
* For the genes that the query is coexpressed with; this retrieves the information for all the coexpressionData
* passed in (no limit) - all of them have to be for the same query gene!
*
* @param ees, including ALL experiments that were intially started with, NOT just the ones that the query gene was
* tested in.
* @param coexpressionData to check, the query gene must be the same for each of them.
*/
private void computeEesTestedInBatch( Collection<BioAssaySet> ees, List<CoexpressionValueObject> coexpressionData ) {
if ( coexpressionData.isEmpty() ) return;
StopWatch timer = new StopWatch();
timer.start();
if ( log.isDebugEnabled() ) {
log.debug( "Computing EEs tested in for " + coexpressionData.size() + " genes coexpressed with query." );
}
/*
* Note: we assume this is actually constant as we build a cache based on it. Small risk.
*/
Map<Long, Integer> eeIndexMap = ProbeLinkCoexpressionAnalyzer.getOrderingMap( ees );
assert eeIndexMap.size() == ees.size();
/*
* Save some computation in the inner loop by assuming the query gene is constant.
*/
CoexpressionValueObject initializer = coexpressionData.iterator().next();
Long queryGeneId = initializer.getQueryGene().getId();
Boolean[] queryGeneEETestStatus = getEETestedForGeneVector( queryGeneId, ees, eeIndexMap );
geneTestStatusCache.put( queryGeneId, queryGeneEETestStatus );
byte[] queryGeneEETestStatusBytes;
if ( geneTestStatusByteCache.containsKey( queryGeneId ) ) {
queryGeneEETestStatusBytes = geneTestStatusByteCache.get( queryGeneId );
} else {
queryGeneEETestStatusBytes = computeTestedDatasetVector( queryGeneId, ees, eeIndexMap );
geneTestStatusByteCache.put( queryGeneId, queryGeneEETestStatusBytes );
}
/*
* This is a potential bottleneck, because there are often >500 ees and >1000 cvos, and each EE tests >20000
* genes. Therefore we try hard not to iterate over all the CVOEEs more than we need to. So this is coded very
* carefully. Once the cache is warmed up, this still can take over 500ms to run (Feb 2010). The total number of
* loops _easily_ exceeds a million.
*/
int loopcount = 0; // for performance statistics
for ( CoexpressionValueObject cvo : coexpressionData ) {
Long coexGeneId = cvo.getGeneId();
if ( !queryGeneId.equals( cvo.getQueryGene().getId() ) ) {
throw new IllegalArgumentException( "All coexpression value objects must have the same query gene here" );
}
/*
* Get the target gene info, from the cache if possible.
*/
byte[] targetGeneEETestStatus;
if ( geneTestStatusByteCache.containsKey( coexGeneId ) ) {
targetGeneEETestStatus = geneTestStatusByteCache.get( coexGeneId );
} else {
targetGeneEETestStatus = computeTestedDatasetVector( coexGeneId, ees, eeIndexMap );
geneTestStatusByteCache.put( coexGeneId, targetGeneEETestStatus );
}
assert targetGeneEETestStatus.length == queryGeneEETestStatusBytes.length;
byte[] answer = new byte[targetGeneEETestStatus.length];
for ( int i = 0; i < answer.length; i++ ) {
answer[i] = ( byte ) ( targetGeneEETestStatus[i] & queryGeneEETestStatusBytes[i] );
loopcount++;
}
cvo.setDatasetsTestedInBytes( answer );
// That there is no easy way to avoid this inner loop - however, in this batch processing case where this is
// used, we end up with a bit vector later, so we could consider constructing that now instead.
// for ( BioAssaySet ee : ees ) {
// /*
// * Both the query and the target have to have been tested in the given experiment.
// */
// if ( queryGeneEETestStatus[i] && targetGeneEETestStatus[i] ) {
// Long eeid = ee.getId();
// cvo.getDatasetsTestedIn().add( eeid );
// }
// loopcount++;
// i++;
// }
// sanity check.
// assert cvo.getDatasetsTestedIn().size() > 0 : "No data sets tested in for : " + cvo;
}
if ( timer.getTime() > 100 ) {
log.info( "Compute EEs tested in (batch ): " + timer.getTime() + "ms; " + loopcount + " loops" );
}
}
/**
* Method for batch processing. Should not be used in a web application context.
*
* @param geneId
* @param ees
* @param eeIndexMap Map of EE IDs to index in the 'eesTestingIn' where that EE is.
* @return boolean array of same length as ees, where true means the given gene was tested in that dataset.
*/
private Boolean[] getEETestedForGeneVector( Long geneId, Collection<BioAssaySet> ees, Map<Long, Integer> eeIndexMap ) {
/*
* This condition is, pretty much only true once in practice. That's because the first time through populates
* genesTestedIn for all the genes tested in any of the data sets, which is essentially all genes.
*/
if ( !genesTestedIn.containsKey( geneId ) ) {
cacheEesGeneTestedIn( ees, eeIndexMap );
}
List<Boolean> eesTestingGene = genesTestedIn.get( geneId );
assert eesTestingGene != null;
Boolean[] queryGeneEETestStatus = new Boolean[ees.size()];
int i = 0;
// note: we assume that this collection does not change iteration order.
for ( BioAssaySet ee : ees ) {
Long eeid = ee.getId();
Integer index = eeIndexMap.get( eeid );
Boolean geneTested = eesTestingGene.get( index );
assert geneTested != null : "Null for index=" + index + ", EEID=" + eeid + ", GENEID=" + geneId;
queryGeneEETestStatus[i] = geneTested;
i++;
}
return queryGeneEETestStatus;
}
/**
* @param datasetsTestedIn
* @param eeIdOrder
* @return
*/
private byte[] computeTestedDatasetVector( Long geneId, Collection<BioAssaySet> ees, Map<Long, Integer> eeIdOrder ) {
/*
* This condition is, pretty much only true once in practice. That's because the first time through populates
* genesTestedIn for all the genes tested in any of the data sets.
*/
if ( !genesTestedIn.containsKey( geneId ) ) {
cacheEesGeneTestedIn( ees, eeIdOrder );
}
assert genesTestedIn.containsKey( geneId );
List<Boolean> eesTestingGene = genesTestedIn.get( geneId );
// initialize.
byte[] result = new byte[( int ) Math.ceil( eeIdOrder.size() / ( double ) Byte.SIZE )];
for ( int i = 0, j = result.length; i < j; i++ ) {
result[i] = 0x0;
}
int i = 0;
for ( BioAssaySet ee : ees ) {
Long eeid = ee.getId();
Integer index = eeIdOrder.get( eeid );
if ( eesTestingGene.get( index ) ) {
BitUtil.set( result, index );
}
i++;
}
return result;
}
/**
* For each experiment, get the genes it tested and populate a map. This is slow; but once we've seen a gene, we
* don't have to repeat it. We used to cache the ee->gene relationship, but doing it the other way around yields
* must faster code.
*
* @param ees
* @param eeIndexMap
*/
private void cacheEesGeneTestedIn( Collection<BioAssaySet> ees, Map<Long, Integer> eeIndexMap ) {
assert ees != null;
assert eeIndexMap != null;
assert !ees.isEmpty();
assert !eeIndexMap.isEmpty();
for ( BioAssaySet ee : ees ) {
Collection<Long> genes = probe2ProbeCoexpressionService.getGenesTestedBy( ee, false );
if ( genes.isEmpty() ) {
log.warn( "No genes were tested by " + ee );
continue;
}
// inverted map of gene -> ees tested in.
Integer indexOfEEInAr = eeIndexMap.get( ee.getId() );
for ( Long geneId : genes ) {
if ( !genesTestedIn.containsKey( geneId ) ) {
// initialize the boolean array for this gene.
genesTestedIn.put( geneId, new ArrayList<Boolean>() );
for ( int i = 0; i < ees.size(); i++ ) {
genesTestedIn.get( geneId ).add( Boolean.FALSE );
}
}
// flip to true since the gene was tested in the ee
genesTestedIn.get( geneId ).set( indexOfEEInAr, Boolean.TRUE );
}
}
}
/**
* For the genes that the query is coexpressed with. This is limited to the top MAX_GENES_TO_COMPUTE_EESTESTEDIN.
* This is not very fast if MAX_GENES_TO_COMPUTE_EESTESTEDIN is large. We use this version for on-line requests.
*
* @param eesQueryTestedIn, limited to the ees that the query gene is tested in.
* @param coexpressionData
* @see ProbeLinkCoexpressionAnalyzer.computeEesTestedInBatch for the version used when requests are going to be
* done for many genes, so cache is built first time.
*/
private void computeEesTestedIn( Collection<BioAssaySet> eesQueryTestedIn,
List<CoexpressionValueObject> coexpressionData ) {
Collection<Long> coexGeneIds = new HashSet<Long>();
StopWatch timer = new StopWatch();
timer.start();
int i = 0;
Map<Long, CoexpressionValueObject> gmap = new HashMap<Long, CoexpressionValueObject>();
for ( CoexpressionValueObject o : coexpressionData ) {
coexGeneIds.add( o.getGeneId() );
gmap.put( o.getGeneId(), o );
i++;
if ( i >= MAX_GENES_TO_COMPUTE_EESTESTEDIN ) break;
}
log.debug( "Computing EEs tested in for " + coexGeneIds.size() + " genes." );
Map<Long, Collection<BioAssaySet>> eesTestedIn = probe2ProbeCoexpressionService
.getExpressionExperimentsTestedIn( coexGeneIds, eesQueryTestedIn, false );
for ( Long g : eesTestedIn.keySet() ) {
CoexpressionValueObject cvo = gmap.get( g );
assert cvo != null;
assert eesTestedIn.get( g ).size() <= eesQueryTestedIn.size();
Collection<Long> ids = new HashSet<Long>();
for ( BioAssaySet ee : eesTestedIn.get( g ) ) {
Long eeid = ee.getId();
ids.add( eeid );
}
cvo.setDatasetsTestedIn( ids );
}
timer.stop();
if ( timer.getTime() > 1000 ) {
log.info( "computeEesTestedIn: " + timer.getTime() + "ms" );
}
}
/**
* @param geneOntologyService
*/
public void setGeneOntologyService( GeneOntologyService geneOntologyService ) {
this.geneOntologyService = geneOntologyService;
}
/**
* @param geneService
*/
public void setGeneService( GeneService geneService ) {
this.geneService = geneService;
}
/**
* @param probe2ProbeCoexpressionService
*/
public void setProbe2ProbeCoexpressionService( Probe2ProbeCoexpressionService probe2ProbeCoexpressionService ) {
this.probe2ProbeCoexpressionService = probe2ProbeCoexpressionService;
}
/**
* @param queryGene
* @param numQueryGeneGOTerms
* @param coexpressionData
*/
private void computeGoOverlap( Gene queryGene, int numQueryGeneGOTerms,
List<CoexpressionValueObject> coexpressionData ) {
Collection<Long> overlapIds = new HashSet<Long>();
int i = 0;
for ( CoexpressionValueObject cvo : coexpressionData ) {
overlapIds.add( cvo.getGeneId() );
cvo.setNumQueryGeneGOTerms( numQueryGeneGOTerms );
if ( i++ > MAX_GENES_TO_COMPUTE_GOOVERLAP ) break;
}
Map<Long, Collection<OntologyTerm>> overlap = geneOntologyService
.calculateGoTermOverlap( queryGene, overlapIds );
for ( CoexpressionValueObject cvo : coexpressionData ) {
cvo.setGoOverlap( overlap.get( cvo.getGeneId() ) );
}
}
/**
* @param coexpressions
*/
private void computeGoStats( CoexpressionCollectionValueObject coexpressions, int stringency ) {
// don't compute this if we aren't loading GO into memory.
if ( !geneOntologyService.isGeneOntologyLoaded() ) {
return;
}
log.debug( "Computing GO stats" );
Gene queryGene = coexpressions.getQueryGene();
int numQueryGeneGOTerms = geneOntologyService.getGOTerms( queryGene ).size();
coexpressions.setQueryGeneGoTermCount( numQueryGeneGOTerms );
if ( numQueryGeneGOTerms == 0 ) return;
if ( coexpressions.getAllGeneCoexpressionData( stringency ).size() == 0 ) return;
List<CoexpressionValueObject> knownGeneCoexpressionData = coexpressions
.getKnownGeneCoexpressionData( stringency );
computeGoOverlap( queryGene, numQueryGeneGOTerms, knownGeneCoexpressionData );
// Only known genes have GO terms, so we don't need to look at Predicted and PARs.
}
public void setExpressionExperimentService( ExpressionExperimentService expressionExperimentService ) {
this.expressionExperimentService = expressionExperimentService;
}
}
| hunting down bug 2180
| gemma-core/src/main/java/ubic/gemma/analysis/expression/coexpression/ProbeLinkCoexpressionAnalyzer.java | hunting down bug 2180 |
|
Java | apache-2.0 | e47744a543f20f6ca96bd67d5d625b30548bde7b | 0 | CMPUT301F17T23/routineKeen | package ca.ualberta.cs.routinekeen.Views;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import ca.ualberta.cs.routinekeen.Controllers.HabitHistoryController;
import ca.ualberta.cs.routinekeen.Controllers.HabitListController;
import ca.ualberta.cs.routinekeen.Helpers.PhotoHelpers;
import ca.ualberta.cs.routinekeen.Models.HabitEvent;
import ca.ualberta.cs.routinekeen.R;
public class ViewHabitEvent extends AppCompatActivity {
private Spinner spinner;
private EditText eventTitle;
private EditText eventComment;
private ImageButton photoImageButton;
private byte[] photoByteArray;
private String eventType;
private int index;
private ArrayList<String> typeList;
private ArrayAdapter<String> typeAdapter;
private Location location;
private LocationManager service;
private LocationManager locationManager;
private static final int REQUEST_LOCATION = 1;
protected static final int REQUEST_PERMISSION_READ_EXTERNAL_STORAGE = 2;
protected static final int REQUEST_SELECT_IMAGE = 3;
protected static final int IMAGE_MAX_BYTES = 65536;
protected static final int LENGTH = (int) Math.floor(Math.sqrt(IMAGE_MAX_BYTES))*2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_habit_event);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Grab data from previous activity
Intent intent = getIntent();
index = intent.getIntExtra("View Event", -1);
spinner = (Spinner) findViewById(R.id.typeSpinner);
// ActivityCompat.requestPermissions(this,
// new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
eventTitle = (EditText) findViewById(R.id.eventTitle);
eventComment = (EditText) findViewById(R.id.eventComment);
photoImageButton = (ImageButton) findViewById(R.id.imageButtonPhoto);
photoImageButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
}
@Override
protected void onStart(){
super.onStart();
typeList = HabitListController.getTypeList();
typeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
typeList);
typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(typeAdapter);
Intent intent = getIntent();
index = intent.getIntExtra("View Event", -1);
//Show respective values in view
TextView newEventTitle = (TextView) findViewById(R.id.eventTitle);
newEventTitle.setText(HabitHistoryController.getHabitEvent(index).getTitle());
TextView newEventComment = (TextView) findViewById(R.id.eventComment);
newEventComment.setText(HabitHistoryController.getHabitEvent(index).getComment());
photoByteArray = HabitHistoryController.getHabitEvent(index).getPhoto();
if (photoByteArray!=null) {
Bitmap oldImage = BitmapFactory.decodeByteArray(photoByteArray, 0, photoByteArray.length);
photoImageButton.setImageBitmap(oldImage);
}
}
public void saveEvent(View view)
{
if(validationSuccess()) {
String title = eventTitle.getText().toString().trim();
String comment = eventComment.getText().toString().trim();
String habitType = spinner.getSelectedItem().toString();
LatLng eventLocation = null;
try {
eventLocation = new LatLng(location.getLatitude(), location.getLongitude());
} catch(Exception e){
// no location attached OR location error
}
HabitHistoryController.updateHabitEvent(title, comment, habitType,
photoByteArray, eventLocation, index);
finish();
}
}
private boolean validationSuccess() {
if (eventTitle.getText().toString().isEmpty()) {
Toast.makeText(this, "Please enter a title for event.",
Toast.LENGTH_SHORT).show();
return false;
}
if (eventComment.getText().toString().length() > 20) {
Toast.makeText(this, "Habit event comment much be less than 20 characters.",
Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void delEvent(View view)
{
HabitEvent delEvent = HabitHistoryController.getHabitEvent(index);
HabitHistoryController.removeHabitEvent(delEvent);
finish();
}
public void attachUpdatedLocation(View view) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
try {
location = getDeviceLoc();
Toast.makeText(this,"Location Updated",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this,"Unable to trace your location",Toast.LENGTH_SHORT).show();
}
}
}
/**
* ref: https://chantisandroid.blogspot.ca/2017/06/get-current-location-example-in-android.html
* @return current location
*/
private Location getDeviceLoc() {
service = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(ViewHabitEvent.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(ViewHabitEvent.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ViewHabitEvent.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
}
else {
Location location = service.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location1 = service.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location2 = service.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);
if (location != null) {
return location;
}
else if (location1 != null) {
return location1;
}
else if (location2 != null) {
return location2;
}
}
return null;
}
protected void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please Turn ON your GPS Connection")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
public void selectImage() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION_READ_EXTERNAL_STORAGE);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == REQUEST_PERMISSION_READ_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_SELECT_IMAGE);
} else {
// permission denied, don't open gallery
Log.d("AHELog", "permission denied");
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SELECT_IMAGE && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
try {
InputStream image_stream = getContentResolver().openInputStream(imageUri);
Bitmap thumbImage = (new PhotoHelpers(this).convertImageStreamToThumbnail(image_stream, LENGTH, LENGTH));
if (thumbImage == null) {
Toast.makeText(this,"Image file too large.",Toast.LENGTH_SHORT).show();
}
photoImageButton.setImageBitmap(thumbImage); // reset the stream
photoByteArray = (new PhotoHelpers(this).compressImage(thumbImage));
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("AHELog", "FNF except");
} catch (Exception e) {
Log.d("AHELog", "Unknown except");
Log.e("AHELog", "unknown", e);
}
}
}
private void initListeners(){
photoImageButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
eventType = (String) parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
| RoutineKeen/app/src/main/java/ca/ualberta/cs/routinekeen/Views/ViewHabitEvent.java | package ca.ualberta.cs.routinekeen.Views;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import ca.ualberta.cs.routinekeen.Controllers.HabitHistoryController;
import ca.ualberta.cs.routinekeen.Controllers.HabitListController;
import ca.ualberta.cs.routinekeen.Helpers.PhotoHelpers;
import ca.ualberta.cs.routinekeen.Models.HabitEvent;
import ca.ualberta.cs.routinekeen.R;
public class ViewHabitEvent extends AppCompatActivity {
private Spinner spinner;
private EditText eventTitle;
private EditText eventComment;
private ImageButton photoImageButton;
private byte[] photoByteArray;
private String eventType;
private int index;
private ArrayList<String> typeList;
private ArrayAdapter<String> typeAdapter;
private Location location;
private LocationManager service;
private LocationManager locationManager;
private static final int REQUEST_LOCATION = 1;
protected static final int REQUEST_PERMISSION_READ_EXTERNAL_STORAGE = 2;
protected static final int REQUEST_SELECT_IMAGE = 3;
protected static final int IMAGE_MAX_BYTES = 65536;
protected static final int LENGTH = (int) Math.floor(Math.sqrt(IMAGE_MAX_BYTES))*2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_habit_event);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Grab data from previous activity
Intent intent = getIntent();
index = intent.getIntExtra("View Event", -1);
Spinner spinner = (Spinner) findViewById(R.id.typeSpinner);
// ActivityCompat.requestPermissions(this,
// new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
eventTitle = (EditText) findViewById(R.id.eventTitle);
eventComment = (EditText) findViewById(R.id.eventComment);
spinner = (Spinner) findViewById(R.id.typeSpinner);
photoImageButton = (ImageButton) findViewById(R.id.imageButtonPhoto);
photoImageButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
}
@Override
protected void onStart(){
super.onStart();
typeList = HabitListController.getTypeList();
typeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
typeList);
typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(typeAdapter);
Intent intent = getIntent();
index = intent.getIntExtra("View Event", -1);
//Show respective values in view
TextView newEventTitle = (TextView) findViewById(R.id.eventTitle);
newEventTitle.setText(HabitHistoryController.getHabitEvent(index).getTitle());
TextView newEventComment = (TextView) findViewById(R.id.eventComment);
newEventComment.setText(HabitHistoryController.getHabitEvent(index).getComment());
photoByteArray = HabitHistoryController.getHabitEvent(index).getPhoto();
if (photoByteArray!=null) {
Bitmap oldImage = BitmapFactory.decodeByteArray(photoByteArray, 0, photoByteArray.length);
photoImageButton.setImageBitmap(oldImage);
}
}
public void saveEvent(View view)
{
if(validationSuccess()) {
String title = eventTitle.getText().toString().trim();
String comment = eventComment.getText().toString().trim();
String habitType = spinner.getSelectedItem().toString();
LatLng eventLocation = null;
try {
eventLocation = new LatLng(location.getLatitude(), location.getLongitude());
} catch(Exception e){
// no location attached OR location error
}
HabitHistoryController.updateHabitEvent(title, comment, habitType,
photoByteArray, eventLocation, index);
finish();
}
}
private boolean validationSuccess() {
if (eventTitle.getText().toString().isEmpty()) {
Toast.makeText(this, "Please enter a title for event.",
Toast.LENGTH_SHORT).show();
return false;
}
if (eventComment.getText().toString().length() > 20) {
Toast.makeText(this, "Habit event comment much be less than 20 characters.",
Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void delEvent(View view)
{
HabitEvent delEvent = HabitHistoryController.getHabitEvent(index);
HabitHistoryController.removeHabitEvent(delEvent);
finish();
}
public void attachUpdatedLocation(View view) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
try {
location = getDeviceLoc();
Toast.makeText(this,"Location Updated",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this,"Unable to trace your location",Toast.LENGTH_SHORT).show();
}
}
}
/**
* ref: https://chantisandroid.blogspot.ca/2017/06/get-current-location-example-in-android.html
* @return current location
*/
private Location getDeviceLoc() {
service = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(ViewHabitEvent.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(ViewHabitEvent.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ViewHabitEvent.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
}
else {
Location location = service.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location1 = service.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location2 = service.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);
if (location != null) {
return location;
}
else if (location1 != null) {
return location1;
}
else if (location2 != null) {
return location2;
}
}
return null;
}
protected void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please Turn ON your GPS Connection")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
public void selectImage() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION_READ_EXTERNAL_STORAGE);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == REQUEST_PERMISSION_READ_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_SELECT_IMAGE);
} else {
// permission denied, don't open gallery
Log.d("AHELog", "permission denied");
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SELECT_IMAGE && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
try {
InputStream image_stream = getContentResolver().openInputStream(imageUri);
Bitmap thumbImage = (new PhotoHelpers(this).convertImageStreamToThumbnail(image_stream, LENGTH, LENGTH));
if (thumbImage == null) {
Toast.makeText(this,"Image file too large.",Toast.LENGTH_SHORT).show();
}
photoImageButton.setImageBitmap(thumbImage); // reset the stream
photoByteArray = (new PhotoHelpers(this).compressImage(thumbImage));
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("AHELog", "FNF except");
} catch (Exception e) {
Log.d("AHELog", "Unknown except");
Log.e("AHELog", "unknown", e);
}
}
}
private void initListeners(){
photoImageButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
eventType = (String) parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
| view habit event break fixed
| RoutineKeen/app/src/main/java/ca/ualberta/cs/routinekeen/Views/ViewHabitEvent.java | view habit event break fixed |
|
Java | apache-2.0 | 090ba9a20209fd63c8225c43ac77a16aa4247735 | 0 | gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas | /*
* Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.atlas.acceptance.selenium.tests.heatmaptable;
import org.junit.Test;
import uk.ac.ebi.atlas.acceptance.selenium.pages.HeatmapTablePage;
import uk.ac.ebi.atlas.acceptance.selenium.utils.SinglePageSeleniumFixture;
import java.util.List;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class SpecificAndOrganismPartIT extends SinglePageSeleniumFixture {
private static final String E_MTAB_599_ACCESSION = "E-MTAB-599";
private static final String HTTP_PARAMETERS = "exactMatch=false&specific=true&geneQuery=Cyp2d10+Tdo2+Serpina1d+Apoh+Albumin&queryFactorValues=liver&_queryFactorValues=1&cutoff=0.5";
private HeatmapTablePage subject;
public void getStartingPage() {
subject = new HeatmapTablePage(driver, E_MTAB_599_ACCESSION, HTTP_PARAMETERS);
subject.get();
}
@Test
public void verifySelectedGenes() {
List<String> selectedGenes = subject.getSelectedGenes();
assertThat(selectedGenes.size(), is(8));
assertThat(selectedGenes, contains("Afm", "Apoh", "Gc", "Cyp2d10", "Serpina1d", "Tdo2", "5830473C10Rik", "Ecm1"));
}
@Test
public void verifyFirstGeneProfile() {
subject.clickDisplayLevelsButton();
assertThat(subject.getFirstGeneProfile(), contains("", "", "270", "", "1", ""));
}
@Test
public void verifyLastGeneProfile() {
subject.clickDisplayLevelsButton();
assertThat(subject.getLastGeneProfile(), contains("25", "4", "112", "94", "23", "11"));
}
@Test
public void verifyGeneCount() {
assertThat(subject.getGeneCount().contains("8"), is(true));
}
}
| web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/heatmaptable/SpecificAndOrganismPartIT.java | /*
* Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.atlas.acceptance.selenium.tests.heatmaptable;
import org.junit.Test;
import uk.ac.ebi.atlas.acceptance.selenium.pages.HeatmapTablePage;
import uk.ac.ebi.atlas.acceptance.selenium.utils.SinglePageSeleniumFixture;
import java.util.List;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class SpecificAndOrganismPartIT extends SinglePageSeleniumFixture {
private static final String E_MTAB_599_ACCESSION = "E-MTAB-599";
private static final String HTTP_PARAMETERS = "specific=true&geneQuery=Cyp2d10+Tdo2+Serpina1d+Apoh+Albumin&queryFactorValues=liver&_queryFactorValues=1&cutoff=0.5";
private HeatmapTablePage subject;
public void getStartingPage() {
subject = new HeatmapTablePage(driver, E_MTAB_599_ACCESSION, HTTP_PARAMETERS);
subject.get();
}
@Test
public void verifySelectedGenes() {
List<String> selectedGenes = subject.getSelectedGenes();
assertThat(selectedGenes.size(), is(8));
assertThat(selectedGenes, contains("Afm", "Apoh", "Gc", "Cyp2d10", "Serpina1d", "Tdo2", "5830473C10Rik", "Ecm1"));
}
@Test
public void verifyFirstGeneProfile() {
subject.clickDisplayLevelsButton();
assertThat(subject.getFirstGeneProfile(), contains("", "", "270", "", "1", ""));
}
@Test
public void verifyLastGeneProfile() {
subject.clickDisplayLevelsButton();
assertThat(subject.getLastGeneProfile(), contains("25", "4", "112", "94", "23", "11"));
}
@Test
public void verifyGeneCount() {
assertThat(subject.getGeneCount().contains("8"), is(true));
}
}
| merging...
| web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/heatmaptable/SpecificAndOrganismPartIT.java | merging... |
|
Java | apache-2.0 | 48bd28fb584830d2224f8a8e9badec884b23fb73 | 0 | ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,DevStreet/FinanceAnalytics | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.model.option.definition;
import com.opengamma.analytics.financial.model.volatility.VolatilityModel;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.math.interpolation.Interpolator1DFactory;
import com.opengamma.analytics.math.interpolation.data.ArrayInterpolator1DDataBundle;
import com.opengamma.analytics.math.interpolation.data.Interpolator1DDataBundle;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.tuple.Triple;
import java.util.Arrays;
import org.apache.commons.lang.ObjectUtils;
/**
* Class describing the data required to describe a delta and expiration dependent smile from ATM, risk reversal and strangle as used in Forex market.
* The delta used is the delta with respect to forward.
*/
public class SmileDeltaTermStructureParameter implements VolatilityModel<Triple<Double, Double, Double>> {
/**
* The interpolator/extrapolator used in the strike dimension.
*/
private final Interpolator1D _interpolator;
/**
* The time to expiration in the term structure.
*/
private final double[] _timeToExpiration;
/**
* The smile description at the different time to expiration. All item should have the same deltas.
*/
private final SmileDeltaParameter[] _volatilityTerm;
/**
* The default interpolator: linear with flat extrapolation.
*/
private static final Interpolator1D DEFAULT_INTERPOLATOR = CombinedInterpolatorExtrapolatorFactory.getInterpolator(Interpolator1DFactory.LINEAR, Interpolator1DFactory.FLAT_EXTRAPOLATOR,
Interpolator1DFactory.FLAT_EXTRAPOLATOR);
/**
* Constructor from volatility term structure. The default interpolator is used to interpolate in the strike dimension. The default interpolator is linear with flat extrapolation.
* @param volatilityTerm The volatility description at the different expiration.
*/
public SmileDeltaTermStructureParameter(final SmileDeltaParameter[] volatilityTerm) {
this(volatilityTerm, DEFAULT_INTERPOLATOR);
}
/**
* Constructor from volatility term structure.
* @param volatilityTerm The volatility description at the different expiration.
* @param interpolator The interpolator used in the strike dimension.
*/
public SmileDeltaTermStructureParameter(final SmileDeltaParameter[] volatilityTerm, final Interpolator1D interpolator) {
ArgumentChecker.notNull(volatilityTerm, "Volatility term structure");
_volatilityTerm = volatilityTerm;
final int nbExp = volatilityTerm.length;
_timeToExpiration = new double[nbExp];
for (int loopexp = 0; loopexp < nbExp; loopexp++) {
_timeToExpiration[loopexp] = _volatilityTerm[loopexp].getTimeToExpiry();
}
_interpolator = interpolator;
}
/**
* Constructor from market data. The default interpolator is used to interpolate in the strike dimension. The default interpolator is linear with flat extrapolation.
* @param timeToExpiration The time to expiration of each volatility smile.
* @param delta The delta at which the volatilities are given. Must be positive and sorted in ascending order. The put will have as delta the opposite of the numbers.
* Common to all time to expiration.
* @param volatility The volatilities at each delta.
*/
public SmileDeltaTermStructureParameter(final double[] timeToExpiration, final double[] delta, final double[][] volatility) {
this(timeToExpiration, delta, volatility, DEFAULT_INTERPOLATOR);
}
/**
* Constructor from market data.
* @param timeToExpiration The time to expiration of each volatility smile.
* @param delta The delta at which the volatilities are given. Must be positive and sorted in ascending order. The put will have as delta the opposite of the numbers.
* Common to all time to expiration.
* @param volatility The volatilities at each delta.
* @param interpolator The interpolator used in the strike dimension.
*/
public SmileDeltaTermStructureParameter(final double[] timeToExpiration, final double[] delta, final double[][] volatility, final Interpolator1D interpolator) {
final int nbExp = timeToExpiration.length;
ArgumentChecker.isTrue(volatility.length == nbExp, "Volatility length should be coherent with time to expiration length");
ArgumentChecker.isTrue(volatility[0].length == 2 * delta.length + 1, "Risk volatility size should be coherent with time to delta length");
_timeToExpiration = timeToExpiration;
_volatilityTerm = new SmileDeltaParameter[nbExp];
for (int loopexp = 0; loopexp < nbExp; loopexp++) {
_volatilityTerm[loopexp] = new SmileDeltaParameter(timeToExpiration[loopexp], delta, volatility[loopexp]);
}
_interpolator = interpolator;
}
/**
* Constructor from market data. The default interpolator is used to interpolate in the strike dimension. The default interpolator is linear with flat extrapolation.
* @param timeToExpiration The time to expiration of each volatility smile.
* @param delta The delta at which the volatilities are given. Common to all time to expiration.
* @param atm The ATM volatilities for each time to expiration. The length should be equal to the length of timeToExpiration.
* @param riskReversal The risk reversal figures.
* @param strangle The strangle figures.
*/
public SmileDeltaTermStructureParameter(final double[] timeToExpiration, final double[] delta, final double[] atm, final double[][] riskReversal, final double[][] strangle) {
this(timeToExpiration, delta, atm, riskReversal, strangle, DEFAULT_INTERPOLATOR);
}
/**
* Constructor from market data.
* @param timeToExpiration The time to expiration of each volatility smile.
* @param delta The delta at which the volatilities are given. Common to all time to expiration.
* @param atm The ATM volatilities for each time to expiration. The length should be equal to the length of timeToExpiration.
* @param riskReversal The risk reversal figures.
* @param strangle The strangle figures.
* @param interpolator The interpolator used in the strike dimension.
*/
public SmileDeltaTermStructureParameter(final double[] timeToExpiration, final double[] delta, final double[] atm, final double[][] riskReversal, final double[][] strangle,
final Interpolator1D interpolator) {
final int nbExp = timeToExpiration.length;
ArgumentChecker.isTrue(atm.length == nbExp, "ATM length should be coherent with time to expiration length");
ArgumentChecker.isTrue(riskReversal.length == nbExp, "Risk reversal length should be coherent with time to expiration length");
ArgumentChecker.isTrue(strangle.length == nbExp, "Risk reversal length should be coherent with time to expiration length");
ArgumentChecker.isTrue(riskReversal[0].length == delta.length, "Risk reversal size should be coherent with time to delta length");
ArgumentChecker.isTrue(strangle[0].length == delta.length, "Risk reversal size should be coherent with time to delta length");
_timeToExpiration = timeToExpiration;
_volatilityTerm = new SmileDeltaParameter[nbExp];
for (int loopexp = 0; loopexp < nbExp; loopexp++) {
_volatilityTerm[loopexp] = new SmileDeltaParameter(timeToExpiration[loopexp], atm[loopexp], delta, riskReversal[loopexp], strangle[loopexp]);
}
_interpolator = interpolator;
}
/**
* Get the volatility at a given time/strike/forward from the term structure. The volatility at a given delta are interpolated linearly on the total variance (s^2*t) and extrapolated flat.
* The volatility are then linearly interpolated in the strike dimension and extrapolated flat.
* @param time The time to expiry.
* @param strike The strike.
* @param forward The forward.
* @return The volatility.
*/
public double getVolatility(final double time, final double strike, final double forward) {
ArgumentChecker.isTrue(time >= 0, "Positive time");
final int nbVol = _volatilityTerm[0].getVolatility().length;
ArgumentChecker.isTrue(nbVol > 1, "Need more than one volatility value to perform interpolation");
final int nbTime = _timeToExpiration.length;
ArgumentChecker.isTrue(nbTime > 1, "Need more than one time value to perform interpolation");
double[] volatilityT = new double[nbVol];
if (time <= _timeToExpiration[0]) {
volatilityT = _volatilityTerm[0].getVolatility();
} else {
if (time >= _timeToExpiration[nbTime - 1]) {
volatilityT = _volatilityTerm[nbTime - 1].getVolatility();
} else {
final ArrayInterpolator1DDataBundle interpData = new ArrayInterpolator1DDataBundle(_timeToExpiration, new double[nbTime]);
final int indexLower = interpData.getLowerBoundIndex(time);
final double[] variancePeriodT = new double[nbVol];
final double[] variancePeriod0 = new double[nbVol];
final double[] variancePeriod1 = new double[nbVol];
final double weight0 = (_timeToExpiration[indexLower + 1] - time) / (_timeToExpiration[indexLower + 1] - _timeToExpiration[indexLower]);
// Implementation note: Linear interpolation on variance over the period (s^2*t).
for (int loopvol = 0; loopvol < nbVol; loopvol++) {
variancePeriod0[loopvol] = _volatilityTerm[indexLower].getVolatility()[loopvol] * _volatilityTerm[indexLower].getVolatility()[loopvol] * _timeToExpiration[indexLower];
variancePeriod1[loopvol] = _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _timeToExpiration[indexLower + 1];
variancePeriodT[loopvol] = weight0 * variancePeriod0[loopvol] + (1 - weight0) * variancePeriod1[loopvol];
volatilityT[loopvol] = Math.sqrt(variancePeriodT[loopvol] / time);
}
}
}
final SmileDeltaParameter smile = new SmileDeltaParameter(time, _volatilityTerm[0].getDelta(), volatilityT);
final double[] strikes = smile.getStrike(forward);
final Interpolator1DDataBundle volatilityInterpolation = _interpolator.getDataBundle(strikes, volatilityT);
final double volatility = _interpolator.interpolate(volatilityInterpolation, strike);
return volatility;
}
/**
* Computes the volatility and the volatility sensitivity with respect to the volatility data points.
* @param time The time to expiration.
* @param strike The strike.
* @param forward The forward.
* @param bucketSensitivity The array is changed by the method. The array should have the correct size. After the methods, it contains the volatility sensitivity to the data points.
* Only the lines of impacted dates are changed. The input data on the other lines will not be changed.
* @return The volatility.
*/
public double getVolatility(final double time, final double strike, final double forward, final double[][] bucketSensitivity) {
final int nbVol = _volatilityTerm[0].getVolatility().length;
ArgumentChecker.isTrue(nbVol > 1, "Need more than one volatility value to perform interpolation");
final int nbTime = _timeToExpiration.length;
ArgumentChecker.isTrue(nbTime > 1, "Need more than one time value to perform interpolation");
final int indexLower;
final double weightLow;
// Long Expiry Extrapolation : Flat
if (time >= _timeToExpiration[nbTime - 1]) {
indexLower = nbTime - 2;
weightLow = 0.0;
// Short Expiry Extrapolation : Flat
} else if (time < _timeToExpiration[0]) {
indexLower = 0;;
weightLow = 1.0;
} else {
final ArrayInterpolator1DDataBundle interpData = new ArrayInterpolator1DDataBundle(_timeToExpiration, new double[nbTime]);
//TODO Do NOT use the interpolator to find the lower bound index
indexLower = interpData.getLowerBoundIndex(time);
weightLow = (_timeToExpiration[indexLower + 1] - time) / (_timeToExpiration[indexLower + 1] - _timeToExpiration[indexLower]);
}
final double weightHigh = 1.0 - weightLow;
// Forward sweep
final double[] variancePeriodT = new double[nbVol];
final double[] volatilityT = new double[nbVol];
final double[] variancePeriod0 = new double[nbVol];
final double[] variancePeriod1 = new double[nbVol];
// Implementation note: Linear interpolation on variance over the period (s^2*t).
for (int loopvol = 0; loopvol < nbVol; loopvol++) {
variancePeriod0[loopvol] = _volatilityTerm[indexLower].getVolatility()[loopvol] * _volatilityTerm[indexLower].getVolatility()[loopvol] * _timeToExpiration[indexLower];
variancePeriod1[loopvol] = _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _timeToExpiration[indexLower + 1];
variancePeriodT[loopvol] = weightLow * variancePeriod0[loopvol] + weightHigh * variancePeriod1[loopvol];
volatilityT[loopvol] = Math.sqrt(variancePeriodT[loopvol] / time);
}
final SmileDeltaParameter smile = new SmileDeltaParameter(time, _volatilityTerm[0].getDelta(), volatilityT);
final double[] strikes = smile.getStrike(forward);
final Interpolator1DDataBundle volatilityInterpolation = _interpolator.getDataBundle(strikes, volatilityT);
final double volatility = _interpolator.interpolate(volatilityInterpolation, strike);
// Backward sweep
final double volBar = 1.0;
// FIXME: the strike sensitivity to volatility is missing. The sensitivity to x data in interpolation is required [PLAT-1396]
final double[] volatilityTBar = _interpolator.getNodeSensitivitiesForValue(volatilityInterpolation, strike);
final double[] variancePeriodTBar = new double[nbVol];
final double[] variancePeriod0Bar = new double[nbVol];
final double[] variancePeriod1Bar = new double[nbVol];
for (int loopvol = 0; loopvol < nbVol; loopvol++) {
volatilityTBar[loopvol] *= volBar;
variancePeriodTBar[loopvol] = Math.pow(variancePeriodT[loopvol] / time, -0.5) / time / 2 * volatilityTBar[loopvol];
variancePeriod0Bar[loopvol] = variancePeriodTBar[loopvol] * weightLow;
variancePeriod1Bar[loopvol] = variancePeriodTBar[loopvol] * weightHigh;
bucketSensitivity[indexLower][loopvol] = 2.0 * _volatilityTerm[indexLower].getVolatility()[loopvol] * _timeToExpiration[indexLower] * variancePeriod0Bar[loopvol];
bucketSensitivity[indexLower + 1][loopvol] = 2.0 * _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _timeToExpiration[indexLower + 1] * variancePeriod1Bar[loopvol];
}
return volatility;
}
/**
* Get the volatility from a triple.
* @param tsf The Time, Strike, Forward triple.
* @return The volatility.
*/
@Override
public Double getVolatility(final Triple<Double, Double, Double> tsf) {
return getVolatility(tsf.getFirst(), tsf.getSecond(), tsf.getThird());
}
/**
* Gets the times to expiration.
* @return The times.
*/
public double[] getTimeToExpiration() {
return _timeToExpiration;
}
/**
* Gets the number of expirations.
* @return The number of expirations.
*/
public int getNumberExpiration() {
return _timeToExpiration.length;
}
/**
* Gets the volatility smiles from delta.
* @return The volatility smiles.
*/
public SmileDeltaParameter[] getVolatilityTerm() {
return _volatilityTerm;
}
/**
* Gets the number of strikes (common to all dates).
* @return The number of strikes.
*/
public int getNumberStrike() {
return _volatilityTerm[0].getVolatility().length;
}
/**
* Gets delta (common to all time to expiration).
* @return The delta.
*/
public double[] getDelta() {
return _volatilityTerm[0].getDelta();
}
/**
* Gets the interpolator
* @return The interpolator
*/
public Interpolator1D getInterpolator() {
return _interpolator;
}
/**
* Gets put delta absolute value for all strikes. The ATM is 0.50 delta and the x call are transformed in 1-x put.
* @return The delta.
*/
public double[] getDeltaFull() {
final int nbDelta = _volatilityTerm[0].getDelta().length;
final double[] result = new double[2 * nbDelta + 1];
for (int loopdelta = 0; loopdelta < nbDelta; loopdelta++) {
result[loopdelta] = _volatilityTerm[0].getDelta()[loopdelta];
result[nbDelta + 1 + loopdelta] = 1.0 - _volatilityTerm[0].getDelta()[nbDelta - 1 - loopdelta];
}
result[nbDelta] = 0.50;
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(_timeToExpiration);
result = prime * result + Arrays.hashCode(_volatilityTerm);
result = prime * result + _interpolator.hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final SmileDeltaTermStructureParameter other = (SmileDeltaTermStructureParameter) obj;
if (!Arrays.equals(_timeToExpiration, other._timeToExpiration)) {
return false;
}
if (!Arrays.equals(_volatilityTerm, other._volatilityTerm)) {
return false;
}
if (!ObjectUtils.equals(_interpolator, other._interpolator)) {
return false;
}
return true;
}
}
| projects/OG-Analytics/src/com/opengamma/analytics/financial/model/option/definition/SmileDeltaTermStructureParameter.java | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.model.option.definition;
import java.util.Arrays;
import org.apache.commons.lang.ObjectUtils;
import com.opengamma.analytics.financial.model.volatility.VolatilityModel;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.math.interpolation.Interpolator1DFactory;
import com.opengamma.analytics.math.interpolation.data.ArrayInterpolator1DDataBundle;
import com.opengamma.analytics.math.interpolation.data.Interpolator1DDataBundle;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.tuple.Triple;
/**
* Class describing the data required to describe a delta and expiration dependent smile from ATM, risk reversal and strangle as used in Forex market.
* The delta used is the delta with respect to forward.
*/
public class SmileDeltaTermStructureParameter implements VolatilityModel<Triple<Double, Double, Double>> {
/**
* The interpolator/extrapolator used in the strike dimension.
*/
private final Interpolator1D _interpolator;
/**
* The time to expiration in the term structure.
*/
private final double[] _timeToExpiration;
/**
* The smile description at the different time to expiration. All item should have the same deltas.
*/
private final SmileDeltaParameter[] _volatilityTerm;
/**
* The default interpolator: linear with flat extrapolation.
*/
private static final Interpolator1D DEFAULT_INTERPOLATOR = CombinedInterpolatorExtrapolatorFactory.getInterpolator(Interpolator1DFactory.LINEAR, Interpolator1DFactory.FLAT_EXTRAPOLATOR,
Interpolator1DFactory.FLAT_EXTRAPOLATOR);
/**
* Constructor from volatility term structure. The default interpolator is used to interpolate in the strike dimension. The default interpolator is linear with flat extrapolation.
* @param volatilityTerm The volatility description at the different expiration.
*/
public SmileDeltaTermStructureParameter(final SmileDeltaParameter[] volatilityTerm) {
this(volatilityTerm, DEFAULT_INTERPOLATOR);
}
/**
* Constructor from volatility term structure.
* @param volatilityTerm The volatility description at the different expiration.
* @param interpolator The interpolator used in the strike dimension.
*/
public SmileDeltaTermStructureParameter(final SmileDeltaParameter[] volatilityTerm, final Interpolator1D interpolator) {
ArgumentChecker.notNull(volatilityTerm, "Volatility term structure");
_volatilityTerm = volatilityTerm;
final int nbExp = volatilityTerm.length;
_timeToExpiration = new double[nbExp];
for (int loopexp = 0; loopexp < nbExp; loopexp++) {
_timeToExpiration[loopexp] = _volatilityTerm[loopexp].getTimeToExpiry();
}
_interpolator = interpolator;
}
/**
* Constructor from market data. The default interpolator is used to interpolate in the strike dimension. The default interpolator is linear with flat extrapolation.
* @param timeToExpiration The time to expiration of each volatility smile.
* @param delta The delta at which the volatilities are given. Must be positive and sorted in ascending order. The put will have as delta the opposite of the numbers.
* Common to all time to expiration.
* @param volatility The volatilities at each delta.
*/
public SmileDeltaTermStructureParameter(final double[] timeToExpiration, final double[] delta, final double[][] volatility) {
this(timeToExpiration, delta, volatility, DEFAULT_INTERPOLATOR);
}
/**
* Constructor from market data.
* @param timeToExpiration The time to expiration of each volatility smile.
* @param delta The delta at which the volatilities are given. Must be positive and sorted in ascending order. The put will have as delta the opposite of the numbers.
* Common to all time to expiration.
* @param volatility The volatilities at each delta.
* @param interpolator The interpolator used in the strike dimension.
*/
public SmileDeltaTermStructureParameter(final double[] timeToExpiration, final double[] delta, final double[][] volatility, final Interpolator1D interpolator) {
final int nbExp = timeToExpiration.length;
ArgumentChecker.isTrue(volatility.length == nbExp, "Volatility length should be coherent with time to expiration length");
ArgumentChecker.isTrue(volatility[0].length == 2 * delta.length + 1, "Risk volatility size should be coherent with time to delta length");
_timeToExpiration = timeToExpiration;
_volatilityTerm = new SmileDeltaParameter[nbExp];
for (int loopexp = 0; loopexp < nbExp; loopexp++) {
_volatilityTerm[loopexp] = new SmileDeltaParameter(timeToExpiration[loopexp], delta, volatility[loopexp]);
}
_interpolator = interpolator;
}
/**
* Constructor from market data. The default interpolator is used to interpolate in the strike dimension. The default interpolator is linear with flat extrapolation.
* @param timeToExpiration The time to expiration of each volatility smile.
* @param delta The delta at which the volatilities are given. Common to all time to expiration.
* @param atm The ATM volatilities for each time to expiration. The length should be equal to the length of timeToExpiration.
* @param riskReversal The risk reversal figures.
* @param strangle The strangle figures.
*/
public SmileDeltaTermStructureParameter(final double[] timeToExpiration, final double[] delta, final double[] atm, final double[][] riskReversal, final double[][] strangle) {
this(timeToExpiration, delta, atm, riskReversal, strangle, DEFAULT_INTERPOLATOR);
}
/**
* Constructor from market data.
* @param timeToExpiration The time to expiration of each volatility smile.
* @param delta The delta at which the volatilities are given. Common to all time to expiration.
* @param atm The ATM volatilities for each time to expiration. The length should be equal to the length of timeToExpiration.
* @param riskReversal The risk reversal figures.
* @param strangle The strangle figures.
* @param interpolator The interpolator used in the strike dimension.
*/
public SmileDeltaTermStructureParameter(final double[] timeToExpiration, final double[] delta, final double[] atm, final double[][] riskReversal, final double[][] strangle,
final Interpolator1D interpolator) {
final int nbExp = timeToExpiration.length;
ArgumentChecker.isTrue(atm.length == nbExp, "ATM length should be coherent with time to expiration length");
ArgumentChecker.isTrue(riskReversal.length == nbExp, "Risk reversal length should be coherent with time to expiration length");
ArgumentChecker.isTrue(strangle.length == nbExp, "Risk reversal length should be coherent with time to expiration length");
ArgumentChecker.isTrue(riskReversal[0].length == delta.length, "Risk reversal size should be coherent with time to delta length");
ArgumentChecker.isTrue(strangle[0].length == delta.length, "Risk reversal size should be coherent with time to delta length");
_timeToExpiration = timeToExpiration;
_volatilityTerm = new SmileDeltaParameter[nbExp];
for (int loopexp = 0; loopexp < nbExp; loopexp++) {
_volatilityTerm[loopexp] = new SmileDeltaParameter(timeToExpiration[loopexp], atm[loopexp], delta, riskReversal[loopexp], strangle[loopexp]);
}
_interpolator = interpolator;
}
/**
* Get the volatility at a given time/strike/forward from the term structure. The volatility at a given delta are interpolated linearly on the total variance (s^2*t) and extrapolated flat.
* The volatility are then linearly interpolated in the strike dimension and extrapolated flat.
* @param time The time to expiry.
* @param strike The strike.
* @param forward The forward.
* @return The volatility.
*/
public double getVolatility(final double time, final double strike, final double forward) {
ArgumentChecker.isTrue(time >= 0, "Positive time");
final int nbVol = _volatilityTerm[0].getVolatility().length;
ArgumentChecker.isTrue(nbVol > 1, "Need more than one volatility value to perform interpolation");
final int nbTime = _timeToExpiration.length;
ArgumentChecker.isTrue(nbTime > 1, "Need more than one time value to perform interpolation");
double[] volatilityT = new double[nbVol];
if (time <= _timeToExpiration[0]) {
volatilityT = _volatilityTerm[0].getVolatility();
} else {
if (time >= _timeToExpiration[nbTime - 1]) {
volatilityT = _volatilityTerm[nbTime - 1].getVolatility();
} else {
final ArrayInterpolator1DDataBundle interpData = new ArrayInterpolator1DDataBundle(_timeToExpiration, new double[nbTime]);
final int indexLower = interpData.getLowerBoundIndex(time);
final double[] variancePeriodT = new double[nbVol];
final double[] variancePeriod0 = new double[nbVol];
final double[] variancePeriod1 = new double[nbVol];
final double weight0 = (_timeToExpiration[indexLower + 1] - time) / (_timeToExpiration[indexLower + 1] - _timeToExpiration[indexLower]);
// Implementation note: Linear interpolation on variance over the period (s^2*t).
for (int loopvol = 0; loopvol < nbVol; loopvol++) {
variancePeriod0[loopvol] = _volatilityTerm[indexLower].getVolatility()[loopvol] * _volatilityTerm[indexLower].getVolatility()[loopvol] * _timeToExpiration[indexLower];
variancePeriod1[loopvol] = _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _timeToExpiration[indexLower + 1];
variancePeriodT[loopvol] = weight0 * variancePeriod0[loopvol] + (1 - weight0) * variancePeriod1[loopvol];
volatilityT[loopvol] = Math.sqrt(variancePeriodT[loopvol] / time);
}
}
}
final SmileDeltaParameter smile = new SmileDeltaParameter(time, _volatilityTerm[0].getDelta(), volatilityT);
final double[] strikes = smile.getStrike(forward);
final Interpolator1DDataBundle volatilityInterpolation = _interpolator.getDataBundle(strikes, volatilityT);
final double volatility = _interpolator.interpolate(volatilityInterpolation, strike);
return volatility;
}
/**
* Computes the volatility and the volatility sensitivity with respect to the volatility data points.
* @param time The time to expiration.
* @param strike The strike.
* @param forward The forward.
* @param bucketSensitivity The array is changed by the method. The array should have the correct size. After the methods, it contains the volatility sensitivity to the data points.
* Only the lines of impacted dates are changed. The input data on the other lines will not be changed.
* @return The volatility.
*/
public double getVolatility(final double time, final double strike, final double forward, final double[][] bucketSensitivity) {
final int nbVol = _volatilityTerm[0].getVolatility().length;
ArgumentChecker.isTrue(nbVol > 1, "Need more than one volatility value to perform interpolation");
final int nbTime = _timeToExpiration.length;
ArgumentChecker.isTrue(nbTime > 1, "Need more than one time value to perform interpolation");
final ArrayInterpolator1DDataBundle interpData = new ArrayInterpolator1DDataBundle(_timeToExpiration, new double[nbTime]);
final int indexLower = interpData.getLowerBoundIndex(time);
// Forward sweep
final double[] variancePeriodT = new double[nbVol];
final double[] volatilityT = new double[nbVol];
final double[] variancePeriod0 = new double[nbVol];
final double[] variancePeriod1 = new double[nbVol];
final double weight0 = (_timeToExpiration[indexLower + 1] - time) / (_timeToExpiration[indexLower + 1] - _timeToExpiration[indexLower]);
// Implementation note: Linear interpolation on variance over the period (s^2*t).
for (int loopvol = 0; loopvol < nbVol; loopvol++) {
variancePeriod0[loopvol] = _volatilityTerm[indexLower].getVolatility()[loopvol] * _volatilityTerm[indexLower].getVolatility()[loopvol] * _timeToExpiration[indexLower];
variancePeriod1[loopvol] = _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _timeToExpiration[indexLower + 1];
variancePeriodT[loopvol] = weight0 * variancePeriod0[loopvol] + (1 - weight0) * variancePeriod1[loopvol];
volatilityT[loopvol] = Math.sqrt(variancePeriodT[loopvol] / time);
}
final SmileDeltaParameter smile = new SmileDeltaParameter(time, _volatilityTerm[0].getDelta(), volatilityT);
final double[] strikes = smile.getStrike(forward);
final Interpolator1DDataBundle volatilityInterpolation = _interpolator.getDataBundle(strikes, volatilityT);
final double volatility = _interpolator.interpolate(volatilityInterpolation, strike);
// Backward sweep
final double volBar = 1.0;
// FIXME: the strike sensitivity to volatility is missing. The sensitivity to x data in interpolation is required [PLAT-1396]
final double[] volatilityTBar = _interpolator.getNodeSensitivitiesForValue(volatilityInterpolation, strike);
final double[] variancePeriodTBar = new double[nbVol];
final double[] variancePeriod0Bar = new double[nbVol];
final double[] variancePeriod1Bar = new double[nbVol];
for (int loopvol = 0; loopvol < nbVol; loopvol++) {
volatilityTBar[loopvol] *= volBar;
variancePeriodTBar[loopvol] = Math.pow(variancePeriodT[loopvol] / time, -0.5) / time / 2 * volatilityTBar[loopvol];
variancePeriod0Bar[loopvol] = variancePeriodTBar[loopvol] * weight0;
variancePeriod1Bar[loopvol] = variancePeriodTBar[loopvol] * (1 - weight0);
bucketSensitivity[indexLower][loopvol] = 2.0 * _volatilityTerm[indexLower].getVolatility()[loopvol] * _timeToExpiration[indexLower] * variancePeriod0Bar[loopvol];
bucketSensitivity[indexLower + 1][loopvol] = 2.0 * _volatilityTerm[indexLower + 1].getVolatility()[loopvol] * _timeToExpiration[indexLower + 1] * variancePeriod1Bar[loopvol];
}
return volatility;
}
/**
* Get the volatility from a triple.
* @param tsf The Time, Strike, Forward triple.
* @return The volatility.
*/
@Override
public Double getVolatility(final Triple<Double, Double, Double> tsf) {
return getVolatility(tsf.getFirst(), tsf.getSecond(), tsf.getThird());
}
/**
* Gets the times to expiration.
* @return The times.
*/
public double[] getTimeToExpiration() {
return _timeToExpiration;
}
/**
* Gets the number of expirations.
* @return The number of expirations.
*/
public int getNumberExpiration() {
return _timeToExpiration.length;
}
/**
* Gets the volatility smiles from delta.
* @return The volatility smiles.
*/
public SmileDeltaParameter[] getVolatilityTerm() {
return _volatilityTerm;
}
/**
* Gets the number of strikes (common to all dates).
* @return The number of strikes.
*/
public int getNumberStrike() {
return _volatilityTerm[0].getVolatility().length;
}
/**
* Gets delta (common to all time to expiration).
* @return The delta.
*/
public double[] getDelta() {
return _volatilityTerm[0].getDelta();
}
/**
* Gets the interpolator
* @return The interpolator
*/
public Interpolator1D getInterpolator() {
return _interpolator;
}
/**
* Gets put delta absolute value for all strikes. The ATM is 0.50 delta and the x call are transformed in 1-x put.
* @return The delta.
*/
public double[] getDeltaFull() {
final int nbDelta = _volatilityTerm[0].getDelta().length;
final double[] result = new double[2 * nbDelta + 1];
for (int loopdelta = 0; loopdelta < nbDelta; loopdelta++) {
result[loopdelta] = _volatilityTerm[0].getDelta()[loopdelta];
result[nbDelta + 1 + loopdelta] = 1.0 - _volatilityTerm[0].getDelta()[nbDelta - 1 - loopdelta];
}
result[nbDelta] = 0.50;
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(_timeToExpiration);
result = prime * result + Arrays.hashCode(_volatilityTerm);
result = prime * result + _interpolator.hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final SmileDeltaTermStructureParameter other = (SmileDeltaTermStructureParameter) obj;
if (!Arrays.equals(_timeToExpiration, other._timeToExpiration)) {
return false;
}
if (!Arrays.equals(_volatilityTerm, other._volatilityTerm)) {
return false;
}
if (!ObjectUtils.equals(_interpolator, other._interpolator)) {
return false;
}
return true;
}
}
| Added FLAT extrapolation of Black FX Smiles in Expiry direction
| projects/OG-Analytics/src/com/opengamma/analytics/financial/model/option/definition/SmileDeltaTermStructureParameter.java | Added FLAT extrapolation of Black FX Smiles in Expiry direction |
|
Java | apache-2.0 | 9cf9030e06e5ab5693e959c4cbe182540714d396 | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | package gcm2sbml.gui;
import gcm2sbml.parser.CompatibilityFixer;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.util.GlobalConstants;
import gcm2sbml.util.Utility;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Properties;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import biomodelsim.BioSim;
public class SpeciesPanel extends JPanel implements ActionListener {
public SpeciesPanel(String selected, PropertyList speciesList, PropertyList influencesList,
PropertyList conditionsList, GCMFile gcm, boolean paramsOnly, BioSim biosim) {
super(new GridLayout(6, 1));
this.selected = selected;
this.speciesList = speciesList;
this.influences = influencesList;
this.conditions = conditionsList;
this.gcm = gcm;
this.paramsOnly = paramsOnly;
this.biosim = biosim;
fields = new HashMap<String, PropertyField>();
// ID field
PropertyField field = new PropertyField(GlobalConstants.ID, "", null, null, Utility.IDstring,
paramsOnly);
if (paramsOnly) {
field.setEnabled(false);
}
fields.put(GlobalConstants.ID, field);
add(field);
// Name field
field = new PropertyField(GlobalConstants.NAME, "", null, null, Utility.NAMEstring, paramsOnly);
if (paramsOnly) {
field.setEnabled(false);
}
fields.put(GlobalConstants.NAME, field);
add(field);
// Type field
JPanel tempPanel = new JPanel();
JLabel tempLabel = new JLabel(GlobalConstants.TYPE);
typeBox = new JComboBox(types);
typeBox.setSelectedItem(types[1]);
typeBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(typeBox);
if (paramsOnly) {
tempLabel.setEnabled(false);
typeBox.setEnabled(false);
}
add(tempPanel);
// Initial field
if (paramsOnly) {
field = new PropertyField(GlobalConstants.INITIAL_STRING, gcm
.getParameter(GlobalConstants.INITIAL_STRING), PropertyField.paramStates[0], gcm
.getParameter(GlobalConstants.INITIAL_STRING), Utility.SWEEPstring, paramsOnly);
}
else {
field = new PropertyField(GlobalConstants.INITIAL_STRING, gcm
.getParameter(GlobalConstants.INITIAL_STRING), PropertyField.states[0], gcm
.getParameter(GlobalConstants.INITIAL_STRING), Utility.NUMstring, paramsOnly);
}
fields.put(GlobalConstants.INITIAL_STRING, field);
add(field);
// Max dimer field
// field = new PropertyField(GlobalConstants.MAX_DIMER_STRING, gcm
// .getParameter(GlobalConstants.MAX_DIMER_STRING),
// PropertyField.states[0], gcm
// .getParameter(GlobalConstants.MAX_DIMER_STRING),
// Utility.NUMstring);
// fields.put(GlobalConstants.MAX_DIMER_STRING, field);
// add(field);
// Dimerization field
if (paramsOnly) {
field = new PropertyField(GlobalConstants.KASSOCIATION_STRING, gcm
.getParameter(GlobalConstants.KASSOCIATION_STRING), PropertyField.paramStates[0], gcm
.getParameter(GlobalConstants.KASSOCIATION_STRING), Utility.SWEEPstring, paramsOnly);
}
else {
field = new PropertyField(GlobalConstants.KASSOCIATION_STRING, gcm
.getParameter(GlobalConstants.KASSOCIATION_STRING), PropertyField.states[0], gcm
.getParameter(GlobalConstants.KASSOCIATION_STRING), Utility.NUMstring, paramsOnly);
}
fields.put(GlobalConstants.KASSOCIATION_STRING, field);
add(field);
// Decay field
if (paramsOnly) {
field = new PropertyField(GlobalConstants.KDECAY_STRING, gcm
.getParameter(GlobalConstants.KDECAY_STRING), PropertyField.paramStates[0], gcm
.getParameter(GlobalConstants.KDECAY_STRING), Utility.SWEEPstring, paramsOnly);
}
else {
field = new PropertyField(GlobalConstants.KDECAY_STRING, gcm
.getParameter(GlobalConstants.KDECAY_STRING), PropertyField.states[0], gcm
.getParameter(GlobalConstants.KDECAY_STRING), Utility.NUMstring, paramsOnly);
}
fields.put(GlobalConstants.KDECAY_STRING, field);
add(field);
String oldName = null;
if (selected != null) {
oldName = selected;
Properties prop = gcm.getSpecies().get(selected);
fields.get(GlobalConstants.ID).setValue(selected);
typeBox.setSelectedItem(prop.getProperty(GlobalConstants.TYPE));
setType(prop.getProperty(GlobalConstants.TYPE));
loadProperties(prop);
}
else {
setType(types[1]);
}
boolean display = false;
while (!display) {
display = openGui(oldName);
}
}
private boolean checkValues() {
for (PropertyField f : fields.values()) {
if (!f.isValidValue()) {
return false;
}
}
return true;
}
private boolean openGui(String oldName) {
int value = JOptionPane.showOptionDialog(biosim.frame(), this, "Species Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (!checkValues()) {
Utility.createErrorMessage("Error", "Illegal values entered.");
return false;
}
if (oldName == null) {
if (gcm.getComponents().containsKey(fields.get(GlobalConstants.ID).getValue())
|| gcm.getSpecies().containsKey(fields.get(GlobalConstants.ID).getValue())) {
Utility.createErrorMessage("Error", "Species id already exists.");
return false;
}
}
else if (!oldName.equals(fields.get(GlobalConstants.ID).getValue())) {
if (gcm.getComponents().containsKey(fields.get(GlobalConstants.ID).getValue())
|| gcm.getSpecies().containsKey(fields.get(GlobalConstants.ID).getValue())) {
Utility.createErrorMessage("Error", "Species id already exists.");
return false;
}
}
if (oldName != null
&& !gcm.editSpeciesCheck(oldName, typeBox.getSelectedItem().toString())) {
Utility.createErrorMessage("Error", "Cannot change species type. "
+ "Species is used as a port in a component.");
return false;
}
String id = fields.get(GlobalConstants.ID).getValue();
// Check to see if we need to add or edit
Properties property = new Properties();
for (PropertyField f : fields.values()) {
if (f.getState() == null || f.getState().equals(PropertyField.states[1])) {
property.put(f.getKey(), f.getValue());
}
}
property.put(GlobalConstants.TYPE, typeBox.getSelectedItem().toString());
if (selected != null && !oldName.equals(id)) {
gcm.changeSpeciesName(oldName, id);
((DefaultListModel) influences.getModel()).clear();
influences.addAllItem(gcm.getInfluences().keySet());
((DefaultListModel) conditions.getModel()).clear();
conditions.addAllItem(gcm.getConditions());
}
gcm.addSpecies(id, property);
if (paramsOnly) {
if (fields.get(GlobalConstants.INITIAL_STRING).getState().equals(PropertyField.states[1])
|| fields.get(GlobalConstants.KASSOCIATION_STRING).getState().equals(
PropertyField.states[1])
|| fields.get(GlobalConstants.KDECAY_STRING).getState().equals(PropertyField.states[1])) {
id += " Modified";
}
}
speciesList.removeItem(oldName);
speciesList.removeItem(oldName + " Modified");
speciesList.addItem(id);
speciesList.setSelectedValue(id, true);
}
else if (value == JOptionPane.NO_OPTION) {
// System.out.println();
return true;
}
return true;
}
public String updates() {
String updates = "";
if (paramsOnly) {
if (fields.get(GlobalConstants.INITIAL_STRING).getState().equals(PropertyField.states[1])) {
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + " "
+ fields.get(GlobalConstants.INITIAL_STRING).getValue();
}
if (fields.get(GlobalConstants.KASSOCIATION_STRING).getState()
.equals(PropertyField.states[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + " "
+ fields.get(GlobalConstants.KASSOCIATION_STRING).getValue();
}
if (fields.get(GlobalConstants.KDECAY_STRING).getState().equals(PropertyField.states[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + " "
+ fields.get(GlobalConstants.KDECAY_STRING).getValue();
}
if (updates.equals("")) {
updates += fields.get(GlobalConstants.ID).getValue() + "/";
}
}
return updates;
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxChanged")) {
setType(typeBox.getSelectedItem().toString());
}
}
private void setType(String type) {
if (type.equals(types[0])) {
// fields.get(GlobalConstants.MAX_DIMER_STRING).setEnabled(true);
fields.get(GlobalConstants.KASSOCIATION_STRING).setEnabled(true);
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(false);
}
else if (type.equals(types[1])) {
// fields.get(GlobalConstants.MAX_DIMER_STRING).setEnabled(true);
fields.get(GlobalConstants.KASSOCIATION_STRING).setEnabled(true);
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
}
else if (type.equals(types[2])) {
// fields.get(GlobalConstants.MAX_DIMER_STRING).setEnabled(true);
fields.get(GlobalConstants.KASSOCIATION_STRING).setEnabled(true);
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
}
else {
// fields.get(GlobalConstants.MAX_DIMER_STRING).setEnabled(true);
fields.get(GlobalConstants.KASSOCIATION_STRING).setEnabled(true);
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
}
}
private void loadProperties(Properties property) {
for (Object o : property.keySet()) {
if (fields.containsKey(o.toString())) {
fields.get(o.toString()).setValue(property.getProperty(o.toString()));
fields.get(o.toString()).setCustom();
}
}
}
private String selected = "";
private PropertyList speciesList = null;
private PropertyList influences = null;
private PropertyList conditions = null;
private String[] options = { "Ok", "Cancel" };
private GCMFile gcm = null;
private JComboBox typeBox = null;
private static final String[] types = new String[] { "input", "internal", "output", "unconstrained" };
private HashMap<String, PropertyField> fields = null;
private boolean paramsOnly;
private BioSim biosim;
}
| gui/src/gcm2sbml/gui/SpeciesPanel.java | package gcm2sbml.gui;
import gcm2sbml.parser.CompatibilityFixer;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.util.GlobalConstants;
import gcm2sbml.util.Utility;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Properties;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import biomodelsim.BioSim;
public class SpeciesPanel extends JPanel implements ActionListener {
public SpeciesPanel(String selected, PropertyList speciesList, PropertyList influencesList,
PropertyList conditionsList, GCMFile gcm, boolean paramsOnly, BioSim biosim) {
super(new GridLayout(6, 1));
this.selected = selected;
this.speciesList = speciesList;
this.influences = influencesList;
this.conditions = conditionsList;
this.gcm = gcm;
this.paramsOnly = paramsOnly;
this.biosim = biosim;
fields = new HashMap<String, PropertyField>();
// ID field
PropertyField field = new PropertyField(GlobalConstants.ID, "", null, null, Utility.IDstring,
paramsOnly);
if (paramsOnly) {
field.setEnabled(false);
}
fields.put(GlobalConstants.ID, field);
add(field);
// Name field
field = new PropertyField(GlobalConstants.NAME, "", null, null, Utility.NAMEstring, paramsOnly);
if (paramsOnly) {
field.setEnabled(false);
}
fields.put(GlobalConstants.NAME, field);
add(field);
// Type field
JPanel tempPanel = new JPanel();
JLabel tempLabel = new JLabel(GlobalConstants.TYPE);
typeBox = new JComboBox(types);
typeBox.setSelectedItem(types[1]);
typeBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(typeBox);
if (paramsOnly) {
tempLabel.setEnabled(false);
typeBox.setEnabled(false);
}
add(tempPanel);
// Initial field
if (paramsOnly) {
field = new PropertyField(GlobalConstants.INITIAL_STRING, gcm
.getParameter(GlobalConstants.INITIAL_STRING), PropertyField.paramStates[0], gcm
.getParameter(GlobalConstants.INITIAL_STRING), Utility.SWEEPstring, paramsOnly);
}
else {
field = new PropertyField(GlobalConstants.INITIAL_STRING, gcm
.getParameter(GlobalConstants.INITIAL_STRING), PropertyField.states[0], gcm
.getParameter(GlobalConstants.INITIAL_STRING), Utility.NUMstring, paramsOnly);
}
fields.put(GlobalConstants.INITIAL_STRING, field);
add(field);
// Max dimer field
// field = new PropertyField(GlobalConstants.MAX_DIMER_STRING, gcm
// .getParameter(GlobalConstants.MAX_DIMER_STRING),
// PropertyField.states[0], gcm
// .getParameter(GlobalConstants.MAX_DIMER_STRING),
// Utility.NUMstring);
// fields.put(GlobalConstants.MAX_DIMER_STRING, field);
// add(field);
// Dimerization field
if (paramsOnly) {
field = new PropertyField(GlobalConstants.KASSOCIATION_STRING, gcm
.getParameter(GlobalConstants.KASSOCIATION_STRING), PropertyField.paramStates[0], gcm
.getParameter(GlobalConstants.KASSOCIATION_STRING), Utility.SWEEPstring, paramsOnly);
}
else {
field = new PropertyField(GlobalConstants.KASSOCIATION_STRING, gcm
.getParameter(GlobalConstants.KASSOCIATION_STRING), PropertyField.states[0], gcm
.getParameter(GlobalConstants.KASSOCIATION_STRING), Utility.NUMstring, paramsOnly);
}
fields.put(GlobalConstants.KASSOCIATION_STRING, field);
add(field);
// Decay field
if (paramsOnly) {
field = new PropertyField(GlobalConstants.KDECAY_STRING, gcm
.getParameter(GlobalConstants.KDECAY_STRING), PropertyField.paramStates[0], gcm
.getParameter(GlobalConstants.KDECAY_STRING), Utility.SWEEPstring, paramsOnly);
}
else {
field = new PropertyField(GlobalConstants.KDECAY_STRING, gcm
.getParameter(GlobalConstants.KDECAY_STRING), PropertyField.states[0], gcm
.getParameter(GlobalConstants.KDECAY_STRING), Utility.NUMstring, paramsOnly);
}
fields.put(GlobalConstants.KDECAY_STRING, field);
add(field);
String oldName = null;
if (selected != null) {
oldName = selected;
Properties prop = gcm.getSpecies().get(selected);
fields.get(GlobalConstants.ID).setValue(selected);
typeBox.setSelectedItem(prop.getProperty(GlobalConstants.TYPE));
setType(prop.getProperty(GlobalConstants.TYPE));
loadProperties(prop);
}
else {
setType(types[0]);
}
boolean display = false;
while (!display) {
display = openGui(oldName);
}
}
private boolean checkValues() {
for (PropertyField f : fields.values()) {
if (!f.isValidValue()) {
return false;
}
}
return true;
}
private boolean openGui(String oldName) {
int value = JOptionPane.showOptionDialog(biosim.frame(), this, "Species Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (!checkValues()) {
Utility.createErrorMessage("Error", "Illegal values entered.");
return false;
}
if (oldName == null) {
if (gcm.getComponents().containsKey(fields.get(GlobalConstants.ID).getValue())
|| gcm.getSpecies().containsKey(fields.get(GlobalConstants.ID).getValue())) {
Utility.createErrorMessage("Error", "Species id already exists.");
return false;
}
}
else if (!oldName.equals(fields.get(GlobalConstants.ID).getValue())) {
if (gcm.getComponents().containsKey(fields.get(GlobalConstants.ID).getValue())
|| gcm.getSpecies().containsKey(fields.get(GlobalConstants.ID).getValue())) {
Utility.createErrorMessage("Error", "Species id already exists.");
return false;
}
}
if (oldName != null
&& !gcm.editSpeciesCheck(oldName, typeBox.getSelectedItem().toString())) {
Utility.createErrorMessage("Error", "Cannot change species type. "
+ "Species is used as a port in a component.");
return false;
}
String id = fields.get(GlobalConstants.ID).getValue();
// Check to see if we need to add or edit
Properties property = new Properties();
for (PropertyField f : fields.values()) {
if (f.getState() == null || f.getState().equals(PropertyField.states[1])) {
property.put(f.getKey(), f.getValue());
}
}
property.put(GlobalConstants.TYPE, typeBox.getSelectedItem().toString());
if (selected != null && !oldName.equals(id)) {
gcm.changeSpeciesName(oldName, id);
((DefaultListModel) influences.getModel()).clear();
influences.addAllItem(gcm.getInfluences().keySet());
((DefaultListModel) conditions.getModel()).clear();
conditions.addAllItem(gcm.getConditions());
}
gcm.addSpecies(id, property);
if (paramsOnly) {
if (fields.get(GlobalConstants.INITIAL_STRING).getState().equals(PropertyField.states[1])
|| fields.get(GlobalConstants.KASSOCIATION_STRING).getState().equals(
PropertyField.states[1])
|| fields.get(GlobalConstants.KDECAY_STRING).getState().equals(PropertyField.states[1])) {
id += " Modified";
}
}
speciesList.removeItem(oldName);
speciesList.removeItem(oldName + " Modified");
speciesList.addItem(id);
speciesList.setSelectedValue(id, true);
}
else if (value == JOptionPane.NO_OPTION) {
// System.out.println();
return true;
}
return true;
}
public String updates() {
String updates = "";
if (paramsOnly) {
if (fields.get(GlobalConstants.INITIAL_STRING).getState().equals(PropertyField.states[1])) {
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + " "
+ fields.get(GlobalConstants.INITIAL_STRING).getValue();
}
if (fields.get(GlobalConstants.KASSOCIATION_STRING).getState()
.equals(PropertyField.states[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + " "
+ fields.get(GlobalConstants.KASSOCIATION_STRING).getValue();
}
if (fields.get(GlobalConstants.KDECAY_STRING).getState().equals(PropertyField.states[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + " "
+ fields.get(GlobalConstants.KDECAY_STRING).getValue();
}
if (updates.equals("")) {
updates += fields.get(GlobalConstants.ID).getValue() + "/";
}
}
return updates;
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxChanged")) {
setType(typeBox.getSelectedItem().toString());
}
}
private void setType(String type) {
if (type.equals(types[0])) {
// fields.get(GlobalConstants.MAX_DIMER_STRING).setEnabled(true);
fields.get(GlobalConstants.KASSOCIATION_STRING).setEnabled(true);
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(false);
}
else if (type.equals(types[1])) {
// fields.get(GlobalConstants.MAX_DIMER_STRING).setEnabled(true);
fields.get(GlobalConstants.KASSOCIATION_STRING).setEnabled(true);
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
}
else if (type.equals(types[2])) {
// fields.get(GlobalConstants.MAX_DIMER_STRING).setEnabled(true);
fields.get(GlobalConstants.KASSOCIATION_STRING).setEnabled(true);
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
}
else {
// fields.get(GlobalConstants.MAX_DIMER_STRING).setEnabled(true);
fields.get(GlobalConstants.KASSOCIATION_STRING).setEnabled(true);
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
}
}
private void loadProperties(Properties property) {
for (Object o : property.keySet()) {
if (fields.containsKey(o.toString())) {
fields.get(o.toString()).setValue(property.getProperty(o.toString()));
fields.get(o.toString()).setCustom();
}
}
}
private String selected = "";
private PropertyList speciesList = null;
private PropertyList influences = null;
private PropertyList conditions = null;
private String[] options = { "Ok", "Cancel" };
private GCMFile gcm = null;
private JComboBox typeBox = null;
private static final String[] types = new String[] { "input", "internal", "output", "unconstrained" };
private HashMap<String, PropertyField> fields = null;
private boolean paramsOnly;
private BioSim biosim;
}
| The new default for a species in the gcm editor is now internal.
| gui/src/gcm2sbml/gui/SpeciesPanel.java | The new default for a species in the gcm editor is now internal. |
|
Java | apache-2.0 | 80e8cd28db822675487c4ec51ce3f3c51af17437 | 0 | rjainqb/jets3t-rj,rjainqb/jets3t-rj | /*
* jets3t : Java Extra-Tasty S3 Toolkit (for Amazon S3 online storage service)
* This is a java.net project, see https://jets3t.dev.java.net/
*
* Copyright 2006 James Murty
*
* 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.jets3t.service.impl.rest.httpclient;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jets3t.service.io.InputStreamWrapper;
import org.jets3t.service.io.InterruptableInputStream;
/**
* Utility class to wrap InputStreams obtained from an HttpClient library's HttpMethod object, and
* ensure the stream and HTTP connection is cleaned up properly.
* <p>
* This input stream wrapper is used to ensure that input streams obtained through HttpClient
* connections are cleaned up correctly once the caller has read all the contents of the
* connection's input stream, or closed that input stream.
* </p>
* <p>
* <b>Important!</b> This input stream must be completely consumed or closed to ensure the necessary
* cleanup operations can be performed.
* </p>
*
* @author James Murty
*
*/
public class HttpMethodReleaseInputStream extends InputStream implements InputStreamWrapper {
private final Log log = LogFactory.getLog(HttpMethodReleaseInputStream.class);
private InputStream inputStream = null;
private HttpMethod httpMethod = null;
private boolean alreadyReleased = false;
private boolean underlyingStreamConsumed = false;
/**
* Constructs an input stream based on an {@link HttpMethod} object representing an HTTP connection.
* If a connection input stream is available, this constructor wraps the underlying input stream
* in an {@link InterruptableInputStream} and makes that stream available. If no underlying connection
* is available, an empty {@link ByteArrayInputStream} is made available.
*
* @param httpMethod
*/
public HttpMethodReleaseInputStream(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
try {
this.inputStream = new InterruptableInputStream(httpMethod.getResponseBodyAsStream());
} catch (IOException e) {
log.warn("Unable to obtain HttpMethod's response data stream", e);
httpMethod.releaseConnection();
this.inputStream = new ByteArrayInputStream(new byte[] {}); // Empty input stream;
}
}
/**
* Returns the underlying HttpMethod object that contains/manages the actual HTTP connection.
*
* @return
* the HTTPMethod object that provides the data input stream.
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Forces the release of an HttpMethod's connection in a way that will perform all the necessary
* cleanup through the correct use of HttpClient methods.
*
* @throws IOException
*/
protected void releaseConnection() throws IOException {
if (!alreadyReleased) {
if (!underlyingStreamConsumed) {
// Underlying input stream has not been consumed, abort method
// to force connection to be closed and cleaned-up.
httpMethod.abort();
}
httpMethod.releaseConnection();
alreadyReleased = true;
}
}
/**
* Standard input stream read method, except it calls {@link #releaseConnection} when the underlying
* input stream is consumed.
*/
public int read() throws IOException {
try {
int read = inputStream.read();
if (read == -1) {
underlyingStreamConsumed = true;
if (!alreadyReleased) {
releaseConnection();
log.debug("Released HttpMethod as its response data stream is fully consumed");
}
}
return read;
} catch (IOException e) {
releaseConnection();
log.debug("Released HttpMethod as its response data stream threw an exception", e);
throw e;
}
}
/**
* Standard input stream read method, except it calls {@link #releaseConnection} when the underlying
* input stream is consumed.
*/
public int read(byte[] b, int off, int len) throws IOException {
try {
int read = inputStream.read(b, off, len);
if (read == -1) {
underlyingStreamConsumed = true;
if (!alreadyReleased) {
releaseConnection();
log.debug("Released HttpMethod as its response data stream is fully consumed");
}
}
return read;
} catch (IOException e) {
releaseConnection();
log.debug("Released HttpMethod as its response data stream threw an exception", e);
throw e;
}
}
public int available() throws IOException {
try {
return inputStream.available();
} catch (IOException e) {
releaseConnection();
log.debug("Released HttpMethod as its response data stream threw an exception", e);
throw e;
}
}
/**
* Standard input stream close method, except it ensures that {@link #releaseConnection()} is called
* before the input stream is closed.
*/
public void close() throws IOException {
if (!alreadyReleased) {
releaseConnection();
log.debug("Released HttpMethod as its response data stream is closed");
}
inputStream.close();
}
/**
* Tries to ensure a connection is always cleaned-up correctly by calling {@link #releaseConnection()}
* on class destruction if the cleanup hasn't already been done.
* <p>
* This desperate cleanup act will only be necessary if the user of this class does not completely
* consume or close this input stream prior to object destruction. This method will log Warning
* messages if a forced cleanup is required, hopefully reminding the user to close their streams
* properly.
*/
protected void finalize() throws Throwable {
if (!alreadyReleased) {
log.warn("Attempting to release HttpMethod in finalize() as its response data stream has gone out of scope. "
+ "This attempt will not always succeed and cannot be relied upon! Please ensure S3 response data streams are "
+ "always fully consumed or closed to avoid HTTP connection starvation.");
releaseConnection();
log.warn("Successfully released HttpMethod in finalize(). You were lucky this time... "
+ "Please ensure S3 response data streams are always fully consumed or closed.");
}
super.finalize();
}
/**
* @return
* the underlying input stream wrapped by this class.
*/
public InputStream getWrappedInputStream() {
return inputStream;
}
}
| src/org/jets3t/service/impl/rest/httpclient/HttpMethodReleaseInputStream.java | /*
* jets3t : Java Extra-Tasty S3 Toolkit (for Amazon S3 online storage service)
* This is a java.net project, see https://jets3t.dev.java.net/
*
* Copyright 2006 James Murty
*
* 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.jets3t.service.impl.rest.httpclient;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jets3t.service.io.InputStreamWrapper;
import org.jets3t.service.io.InterruptableInputStream;
/**
* Utility class to wrap InputStreams obtained from an HttpClient library's HttpMethod object, and
* ensure the stream and HTTP connection is cleaned up properly.
* <p>
* This input stream wrapper is used to ensure that input streams obtained through HttpClient
* connections are cleaned up correctly once the caller has read all the contents of the
* connection's input stream, or closed that input stream.
* </p>
* <p>
* <b>Important!</b> This input stream must be completely consumed or closed to ensure the necessary
* cleanup operations can be performed.
* </p>
*
* @author James Murty
*
*/
public class HttpMethodReleaseInputStream extends InputStream implements InputStreamWrapper {
private final Log log = LogFactory.getLog(HttpMethodReleaseInputStream.class);
private InputStream inputStream = null;
private HttpMethod httpMethod = null;
private boolean alreadyReleased = false;
private boolean underlyingStreamConsumed = false;
/**
* Constructs an input stream based on an {@link HttpMethod} object representing an HTTP connection.
* If a connection input stream is available, this constructor wraps the underlying input stream
* in an {@link InterruptableInputStream} and makes that stream available. If no underlying connection
* is available, an empty {@link ByteArrayInputStream} is made available.
*
* @param httpMethod
*/
public HttpMethodReleaseInputStream(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
try {
this.inputStream = new InterruptableInputStream(httpMethod.getResponseBodyAsStream());
} catch (IOException e) {
log.warn("Unable to obtain HttpMethod's response data stream", e);
httpMethod.releaseConnection();
this.inputStream = new ByteArrayInputStream(new byte[] {}); // Empty input stream;
}
}
/**
* Returns the underlying HttpMethod object that contains/manages the actual HTTP connection.
*
* @return
* the HTTPMethod object that provides the data input stream.
*/
public HttpMethod getHttpMethod() {
return httpMethod;
}
/**
* Forces the release of an HttpMethod's connection in a way that will perform all the necessary
* cleanup through the correct use of HttpClient methods.
*
* @throws IOException
*/
protected void releaseConnection() throws IOException {
if (!alreadyReleased) {
if (!underlyingStreamConsumed) {
// Underlying input stream has not been consumed, abort method
// to force connection to be closed and cleaned-up.
httpMethod.abort();
}
httpMethod.releaseConnection();
alreadyReleased = true;
}
}
/**
* Standard input stream read method, except it calls {@link #releaseConnection} when the underlying
* input stream is consumed.
*/
public int read() throws IOException {
try {
int read = inputStream.read();
if (read == -1) {
underlyingStreamConsumed = true;
if (!alreadyReleased) {
releaseConnection();
log.debug("Released HttpMethod as its response data stream is fully consumed");
}
}
return read;
} catch (IOException e) {
httpMethod.releaseConnection();
log.debug("Released HttpMethod as its response data stream threw an exception", e);
throw e;
}
}
/**
* Standard input stream read method, except it calls {@link #releaseConnection} when the underlying
* input stream is consumed.
*/
public int read(byte[] b, int off, int len) throws IOException {
try {
int read = inputStream.read(b, off, len);
if (read == -1) {
underlyingStreamConsumed = true;
if (!alreadyReleased) {
releaseConnection();
log.debug("Released HttpMethod as its response data stream is fully consumed");
}
}
return read;
} catch (IOException e) {
httpMethod.releaseConnection();
log.debug("Released HttpMethod as its response data stream threw an exception", e);
throw e;
}
}
public int available() throws IOException {
try {
return inputStream.available();
} catch (IOException e) {
httpMethod.releaseConnection();
log.debug("Released HttpMethod as its response data stream threw an exception", e);
throw e;
}
}
/**
* Standard input stream close method, except it ensures that {@link #releaseConnection()} is called
* before the input stream is closed.
*/
public void close() throws IOException {
if (!alreadyReleased) {
releaseConnection();
log.debug("Released HttpMethod as its response data stream is closed");
}
inputStream.close();
}
/**
* Tries to ensure a connection is always cleaned-up correctly by calling {@link #releaseConnection()}
* on class destruction if the cleanup hasn't already been done.
* <p>
* This desperate cleanup act will only be necessary if the user of this class does not completely
* consume or close this input stream prior to object destruction. This method will log Warning
* messages if a forced cleanup is required, hopefully reminding the user to close their streams
* properly.
*/
protected void finalize() throws Throwable {
if (!alreadyReleased) {
log.warn("Attempting to release HttpMethod in finalize() as its response data stream has gone out of scope. "
+ "This attempt will not always succeed and cannot be relied upon! Please ensure S3 response data streams are "
+ "always fully consumed or closed to avoid HTTP connection starvation.");
releaseConnection();
log.warn("Successfully released HttpMethod in finalize(). You were lucky this time... "
+ "Please ensure S3 response data streams are always fully consumed or closed.");
}
super.finalize();
}
/**
* @return
* the underlying input stream wrapped by this class.
*/
public InputStream getWrappedInputStream() {
return inputStream;
}
}
| Slight clean-up, such that the general releaseConnection() method is called on IOExceptions instead of the httpMethod being released directly.
| src/org/jets3t/service/impl/rest/httpclient/HttpMethodReleaseInputStream.java | Slight clean-up, such that the general releaseConnection() method is called on IOExceptions instead of the httpMethod being released directly. |
|
Java | apache-2.0 | c0c2c1efeb6b5a9d6dca9802f13103a8d08aa523 | 0 | luj1985/dionysus,luj1985/dionysus,luj1985/dionysus | package com.huixinpn.dionysus.domain.psychtest.results.eval;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.huixinpn.dionysus.domain.psychtest.PsychTestQuestion;
import com.huixinpn.dionysus.domain.psychtest.PsychTestQuestionOption;
import com.huixinpn.dionysus.domain.psychtest.results.PsychTestEvaluationStrategy;
import com.huixinpn.dionysus.domain.psychtest.results.PsychTestResult;
public class PF16EvaluationStrategy implements PsychTestEvaluationStrategy {
// 卡特尔16PF测验计分健
private static final Map<String, String> RAW_ANSWERS = new HashMap<String, String>();
static {
RAW_ANSWERS.put("A" , "3ab,26bc,27bc,51bc,52ab,76bc,101ab,126ab,151bc,176ab");
RAW_ANSWERS.put("B" , "28b,53b,54b,77c,78b,102c,103b,127c,128b,152b,153c,177a,178a");
RAW_ANSWERS.put("C" , "4ab,5bc,29bc,30ab,55ab,79bc,80bc,104ab,105ab,129ab,130ab,154bc,179ab");
RAW_ANSWERS.put("E" , "6bc,7ab,31bc,32bc,56ab,57bc,81bc,106bc,131ab,155ab,156ab,180ab,181ab");
RAW_ANSWERS.put("F" , "8bc,33ab,58ab,82bc,83bc,107bc,108bc,132ab,133ab,157bc,158bc,182ab,183ab");
RAW_ANSWERS.put("G" , "9bc,34bc,59ab,84bc,109ab,134ab,159bc,160ab,184ab,185ab");
RAW_ANSWERS.put("H" , "10ab,35bc,36ab,60bc,61bc,85bc,86bc,110ab,111ab,135bc,136ab,161bc,186ab");
RAW_ANSWERS.put("I" , "11bc,12bc,37ab,62bc,87bc,112ab,137bc,138ab,162bc,163ab");
RAW_ANSWERS.put("L" , "13ab,38ab,63bc,64bc,88ab,89bc,113ab,114ab,139bc,164ab");
RAW_ANSWERS.put("M" , "14bc,15bc,39ab,40ab,65ab,90bc,91ab,115ab,116bc,140ab,141bc,165bc,166bc");
RAW_ANSWERS.put("N" , "16bc,17ab,41bc,42ab,66bc,67bc,92bc,117ab,142ab,167ab");
RAW_ANSWERS.put("O" , "18ab,19bc,43ab,44bc,68bc,69ab,93bc,94bc,118ab,119ab,143ab,144bc,168ab");
RAW_ANSWERS.put("Q1", "20ab,21ab,45bc,46ab,70ab,95bc,120bc,145ab,169ab,170bc");
RAW_ANSWERS.put("Q2", "22bc,47ab,71ab,72ab,96bc,97bc,121bc,122bc,146ab,171ab");
RAW_ANSWERS.put("Q3", "23bc,23bc,48ab,73ab,98ab,123bc,147ab,148ab,172bc,173ab");
RAW_ANSWERS.put("Q4", "25ab,49ab,50ab,74ab,75bc,99ab,100bc,124ab,125bc,149ab,150ab,174ab,175bc");
}
@Data
@AllArgsConstructor
@NoArgsConstructor
static class Answer {
private String factor;
private String values;
// 不是所有的题目均有计分
public static Answer nullObject = new Answer() {
@Override
public int calculateScore(String rawAnswer) {
return 0;
};
};
public int calculateScore(String rawAnswer) {
// 所有答案均为小写
String answer = rawAnswer.toLowerCase();
// 聪慧性(因素B)量表的题目有正确答案,每题答对1分,不对0分
if ("B".equals(this.factor)) {
return values.equals(answer) ? 1 : 0;
}
// 包含计分项目
if (values.contains(answer)) {
// 除B因素只计1分外,其他因素均为a、c计2分、b计1分
return "b".equals(answer) ? 1 : 2;
}
return 0;
}
}
public Answer requestAnswer(int index) {
Answer answer = answers.get(index);
return answer == null ? Answer.nullObject : answer;
}
private Map<Integer, Answer> answers = new HashMap<Integer, Answer>();
public PF16EvaluationStrategy() {
Pattern pattern = Pattern.compile("(\\d+)([abc]+)");
for(Map.Entry<String, String> entry : RAW_ANSWERS.entrySet()) {
String factor = entry.getKey();
String rawAnswer = entry.getValue();
Matcher matcher = pattern.matcher(rawAnswer);
while(matcher.find()) {
Integer num = Integer.parseInt(matcher.group(1));
String values = matcher.group(2);
answers.put(num, new Answer(factor, values));
}
}
}
class PF16Visitor extends PsychTestValueVisitorAdaptor {
private Map<String, Integer> scores = new HashMap<String, Integer>();
private PF16EvaluationStrategy strategy;
public PF16Visitor(PF16EvaluationStrategy strategy) {
this.strategy = strategy;
}
@Override
public void accept(PsychTestQuestion question, PsychTestQuestionOption option) {
Integer subid = question.getSubId();
Answer answer = strategy.requestAnswer(subid);
String factor = answer.getFactor();
if (factor != null) {
String identity = option.getIdentity();
int score = answer.calculateScore(identity);
if (scores.containsKey(factor)) {
scores.put(factor, scores.get(factor) + score);
} else {
scores.put(factor, score);
}
}
}
public Map<String, Integer> getScore() {
return this.scores;
}
public Map<String, Integer> getNormalizedScore(String[] mode) {
Map<String, Integer> scores = this.getScore();
// TODO: 判断用户身份,选择对应的常模
return PF16Normalization.normalize(scores, PF16Normalization.ADULT_MALE);
}
}
@Override
public void evaluate(PsychTestResult result) {
PF16Visitor visitor = new PF16Visitor(this);
result.accept(visitor);
}
}
| dionysus-core/src/main/java/com/huixinpn/dionysus/domain/psychtest/results/eval/PF16EvaluationStrategy.java | package com.huixinpn.dionysus.domain.psychtest.results.eval;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.huixinpn.dionysus.domain.psychtest.PsychTestQuestion;
import com.huixinpn.dionysus.domain.psychtest.PsychTestQuestionOption;
import com.huixinpn.dionysus.domain.psychtest.results.PsychTestEvaluationStrategy;
import com.huixinpn.dionysus.domain.psychtest.results.PsychTestResult;
public class PF16EvaluationStrategy implements PsychTestEvaluationStrategy {
// 卡特尔16PF测验计分健
private static final Map<String, String> RAW_ANSWERS = new HashMap<String, String>();
static {
RAW_ANSWERS.put("A" , "3ab,26bc,27bc,51bc,52ab,76bc,101ab,126ab,151bc,176ab");
RAW_ANSWERS.put("B" , "28b,53b,54b,77c,78b,102c,103b,127c,128b,152b,153c,177a,178a");
RAW_ANSWERS.put("C" , "4ab,5bc,29bc,30ab,55ab,79bc,80bc,104ab,105ab,129ab,130ab,154bc,179ab");
RAW_ANSWERS.put("E" , "6bc,7ab,31bc,32bc,56ab,57bc,81bc,106bc,131ab,155ab,156ab,180ab,181ab");
RAW_ANSWERS.put("F" , "8bc,33ab,58ab,82bc,83bc,107bc,108bc,132ab,133ab,157bc,158bc,182ab,183ab");
RAW_ANSWERS.put("G" , "9bc,34bc,59ab,84bc,109ab,134ab,159bc,160ab,184ab,185ab");
RAW_ANSWERS.put("H" , "10ab,35bc,36ab,60bc,61bc,85bc,86bc,110ab,111ab,135bc,136ab,161bc,186ab");
RAW_ANSWERS.put("I" , "11bc,12bc,37ab,62bc,87bc,112ab,137bc,138ab,162bc,163ab");
RAW_ANSWERS.put("L" , "13ab,38ab,63bc,64bc,88ab,89bc,113ab,114ab,139bc,164ab");
RAW_ANSWERS.put("M" , "14bc,15bc,39ab,40ab,65ab,90bc,91ab,115ab,116bc,140ab,141bc,165bc,166bc");
RAW_ANSWERS.put("N" , "16bc,17ab,41bc,42ab,66bc,67bc,92bc,117ab,142ab,167ab");
RAW_ANSWERS.put("O" , "18ab,19bc,43ab,44bc,68bc,69ab,93bc,94bc,118ab,119ab,143ab,144bc,168ab");
RAW_ANSWERS.put("Q1", "20ab,21ab,45bc,46ab,70ab,95bc,120bc,145ab,169ab,170bc");
RAW_ANSWERS.put("Q2", "22bc,47ab,71ab,72ab,96bc,97bc,121bc,122bc,146ab,171ab");
RAW_ANSWERS.put("Q3", "23bc,23bc,48ab,73ab,98ab,123bc,147ab,148ab,172bc,173ab");
RAW_ANSWERS.put("Q4", "25ab,49ab,50ab,74ab,75bc,99ab,100bc,124ab,125bc,149ab,150ab,174ab,175bc");
}
@Data
@AllArgsConstructor
@NoArgsConstructor
static class Answer {
private String factor;
private String values;
// 不是所有的题目均有计分
public static Answer nullObject = new Answer() {
@Override
public int calculateScore(String rawAnswer) {
return 0;
};
};
public int calculateScore(String rawAnswer) {
// 所有答案均为小写
String answer = rawAnswer.toLowerCase();
// 聪慧性(因素B)量表的题目有正确答案,每题答对1分,不对0分
if ("B".equals(this.factor)) {
return values.equals(answer) ? 1 : 0;
}
// 包含计分项目
if (values.contains(answer)) {
// 除B因素只计1分外,其他因素均为a、c计2分、b计1分
return "b".equals(answer) ? 1 : 2;
}
return 0;
}
}
public Answer requestAnswer(int index) {
Answer answer = answers.get(index);
return answer == null ? Answer.nullObject : answer;
}
private Map<Integer, Answer> answers = new HashMap<Integer, Answer>();
public PF16EvaluationStrategy() {
Pattern pattern = Pattern.compile("(\\d+)([abc]+)");
for(Map.Entry<String, String> entry : RAW_ANSWERS.entrySet()) {
String factor = entry.getKey();
String rawAnswer = entry.getValue();
Matcher matcher = pattern.matcher(rawAnswer);
while(matcher.find()) {
Integer num = Integer.parseInt(matcher.group(1));
String values = matcher.group(2);
answers.put(num, new Answer(factor, values));
}
}
}
class PF16Visitor extends PsychTestValueVisitorAdaptor {
private Map<String, Integer> scores = new HashMap<String, Integer>();
private PF16EvaluationStrategy strategy;
public PF16Visitor(PF16EvaluationStrategy strategy) {
this.strategy = strategy;
}
@Override
public void accept(PsychTestQuestion question, PsychTestQuestionOption option) {
Integer subid = question.getSubId();
Answer answer = strategy.requestAnswer(subid);
String factor = answer.getFactor();
if (factor != null) {
String identity = option.getIdentity();
int score = answer.calculateScore(identity);
if (scores.containsKey(factor)) {
scores.put(factor, scores.get(factor) + score);
} else {
scores.put(factor, score);
}
}
}
public Map<String, Integer> getScore() {
return this.scores;
}
}
@Override
public void evaluate(PsychTestResult result) {
PF16Visitor visitor = new PF16Visitor(this);
result.accept(visitor);
}
}
| add normalization code sample
| dionysus-core/src/main/java/com/huixinpn/dionysus/domain/psychtest/results/eval/PF16EvaluationStrategy.java | add normalization code sample |
|
Java | apache-2.0 | 54576065ddc6aba449a2b3bfd15d544f3b84842f | 0 | narry/score,CloudSlang/score,hprotem/score,natabeck/score,shajyhia/score,sekler/score,genadi-hp/score,CloudSlang/score,orius123/slite | package org.score.samples.openstack.actions;
import com.hp.score.lang.ExecutionRuntimeServices;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.apache.log4j.Logger;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* Date: 7/22/2014
*
* @author Bonczidai Levente
*/
public class OOActionRunner {
private final static Logger logger = Logger.getLogger(OOActionRunner.class);
public final static String ACTION_RUNTIME_EVENT_TYPE = "action_runtime_event";
public final static String ACTION_EXCEPTION_EVENT_TYPE = "action_exception_event";
private Class actionClass;
private Method actionMethod;
/**
* Wrapper method for running actions. A method is a valid action if it returns a Map<String, String>
* and its parameters are serializable.
*
* @param executionContext executionContext object populated by score
* @param executionRuntimeServices executionRuntimeServices object populated by score
* @param className full path of the actual action class
* @param methodName method name of the actual action
*/
public void run(
Map<String, Serializable> executionContext,
ExecutionRuntimeServices executionRuntimeServices,
String className,
String methodName) {
try {
logger.info("run method invocation");
Object[] actualParameters = extractMethodData(executionContext, executionRuntimeServices, className, methodName);
Map<String, String> results = invokeMethod(executionRuntimeServices, className, methodName, actualParameters);
mergeBackResults(executionContext, executionRuntimeServices, methodName, results);
} catch (Exception ex) {
executionRuntimeServices.addEvent(ACTION_EXCEPTION_EVENT_TYPE, ex);
}
}
private void mergeBackResults(Map<String, Serializable> executionContext, ExecutionRuntimeServices executionRuntimeServices, String methodName, Map<String, String> results) {
String resultString = results != null ? results.toString() : "";
executionRuntimeServices.addEvent(ACTION_RUNTIME_EVENT_TYPE, "Method \"" + methodName + "\" invoked.." +
" Attempting to merge back results: " + resultString);
//merge back the results of the action in the flow execution context
doMerge(executionContext, results);
executionRuntimeServices.addEvent(ACTION_RUNTIME_EVENT_TYPE, "Results merged back in the Execution Context");
}
private Map<String, String> invokeMethod(ExecutionRuntimeServices executionRuntimeServices, String className, String methodName, Object[] actualParameters) throws InvocationTargetException, IllegalAccessException, InstantiationException {
String invokeMessage = "Attempting to invoke action method \"" + methodName + "\"";
invokeMessage += " of class " + className;
// if the action method does not have any parameters then actualParameters is null
if (actualParameters != null) {
invokeMessage += " with parameters: ";
int limit = actualParameters.length - 1;
for (int i = 0; i < limit; i++) {
String parameter = actualParameters[i] == null ? "null" : actualParameters[i].toString();
invokeMessage += parameter + ",";
}
invokeMessage += actualParameters[actualParameters.length - 1];
}
executionRuntimeServices.addEvent(ACTION_RUNTIME_EVENT_TYPE, invokeMessage);
// invoke action method
return invokeActionMethod(actionMethod, actionClass.newInstance(), actualParameters);
}
private Object[] extractMethodData(Map<String, Serializable> executionContext, ExecutionRuntimeServices executionRuntimeServices, String className, String methodName) throws ClassNotFoundException {
executionRuntimeServices.addEvent(ACTION_RUNTIME_EVENT_TYPE, "Extracting action data");
//get the action class
actionClass = Class.forName(className);
//get the Method object
actionMethod = getMethodByName(actionClass, methodName);
//get the parameter names of the action method
ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
String[] parameterNames = parameterNameDiscoverer.getParameterNames(actionMethod);
//extract the parameters from execution context
return getParametersFromExecutionContext(executionContext, parameterNames);
}
/**
* Extracts the actual method of the action's class
*
* @param actionClass Class object that represents the actual action class
* @param methodName method name of the actual action
* @return actual method represented by Method object
* @throws ClassNotFoundException
*/
private Method getMethodByName(Class actionClass, String methodName) throws ClassNotFoundException {
Method[] methods = actionClass.getDeclaredMethods();
Method actionMethod = null;
for (Method m : methods) {
if (m.getName().equals(methodName)) {
actionMethod = m;
}
}
return actionMethod;
}
/**
* Retrieves a list of parameters from the execution context
*
* @param executionContext current Execution Context
* @param parameterNames list of parameter names to be retrieved
* @return parameters from the execution context represented as Object list
*/
private Object[] getParametersFromExecutionContext(Map<String, Serializable> executionContext, String[] parameterNames) {
int nrParameters = parameterNames.length;
Object[] actualParameters = null;
if (nrParameters > 0) {
actualParameters = new Object[nrParameters];
//actual parameter is passed from the execution context
//if not present will be null
for (int i = 0; i < nrParameters; i++) {
if (executionContext.containsKey(parameterNames[i])) {
actualParameters[i] = executionContext.get(parameterNames[i]);
} else {
actualParameters[i] = null;
}
}
}
return actualParameters;
}
/**
* Invokes the actual action method with the specified parameters
*
* @param actionMethod action method represented as Method object
* @param instance an instance of the invoker class
* @param parameters method parameters
* @return results if the action
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
@SuppressWarnings("unchecked")
private Map<String, String> invokeActionMethod(Method actionMethod, Object instance, Object... parameters)
throws InvocationTargetException, IllegalAccessException {
return (Map<String, String>) actionMethod.invoke(instance, parameters);
}
/**
* Merges back the results in the execution context
*
* @param executionContext current Execution Context
* @param results results to be merged back
*/
private void doMerge(Map<String, Serializable> executionContext, Map<String, String> results) {
if (results != null) {
executionContext.putAll(results);
}
}
public Long navigate(Map<String, Serializable> executionContext, List<NavigationMatcher> navigationMatchers, String defaultNextStepId) {
logger.info("navigate method invocation");
if (navigationMatchers == null) {
return null;
}
MatcherFactory matcherFactory = new MatcherFactory();
for (NavigationMatcher navigationMatcher : navigationMatchers) {
Serializable response = executionContext.get(navigationMatcher.getContextKey());
if (response != null) {
Integer intResponse = Integer.parseInt(response.toString());
if (matcherFactory.getMatcher(navigationMatcher.getMatchType(), navigationMatcher.getCompareArg()).matches(intResponse)) {
return Long.parseLong(navigationMatcher.getNextStepId());
}
}
}
return Long.parseLong(defaultNextStepId);
//return navigationMatcher.getDefaultNextStepId();
}
}
| score-samples/score-openstack-actions/src/main/java/org/score/samples/openstack/actions/OOActionRunner.java | package org.score.samples.openstack.actions;
import com.hp.score.lang.ExecutionRuntimeServices;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.apache.log4j.Logger;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* Date: 7/22/2014
*
* @author Bonczidai Levente
*/
public class OOActionRunner {
private final static Logger logger = Logger.getLogger(OOActionRunner.class);
public final static String ACTION_RUNTIME_EVENT_TYPE = "action_runtime_event";
public final static String ACTION_EXCEPTION_EVENT_TYPE = "action_exception_event";
private Class actionClass;
private Method actionMethod;
/**
* Wrapper method for running actions. A method is a valid action if it returns a Map<String, String>
* and its parameters are serializable.
*
* @param executionContext executionContext object populated by score
* @param executionRuntimeServices executionRuntimeServices object populated by score
* @param className full path of the actual action class
* @param methodName method name of the actual action
*/
public void run(
Map<String, Serializable> executionContext,
ExecutionRuntimeServices executionRuntimeServices,
String className,
String methodName) {
try {
logger.info("run method invocation");
Object[] actualParameters = extractMethodData(executionContext, executionRuntimeServices, className, methodName);
Map<String, String> results = invokeMethod(executionRuntimeServices, className, methodName, actualParameters);
mergeBackResults(executionContext, executionRuntimeServices, methodName, results);
} catch (Exception ex) {
executionRuntimeServices.addEvent(ACTION_EXCEPTION_EVENT_TYPE, ex);
}
}
private void mergeBackResults(Map<String, Serializable> executionContext, ExecutionRuntimeServices executionRuntimeServices, String methodName, Map<String, String> results) {
executionRuntimeServices.addEvent(ACTION_RUNTIME_EVENT_TYPE, "Method \"" + methodName + "\" invoked.." +
" Attempting to merge back results in the Execution Context");
//merge back the results of the action in the flow execution context
doMerge(executionContext, results);
executionRuntimeServices.addEvent(ACTION_RUNTIME_EVENT_TYPE, "Results merged back in the Execution Context");
}
private Map<String, String> invokeMethod(ExecutionRuntimeServices executionRuntimeServices, String className, String methodName, Object[] actualParameters) throws InvocationTargetException, IllegalAccessException, InstantiationException {
String invokeMessage = "Attempting to invoke action method \"" + methodName + "\"";
invokeMessage += " of class " + className;
// if the action method does not have any parameters then actualParameters is null
if (actualParameters != null) {
invokeMessage += " with parameters: ";
int limit = actualParameters.length - 1;
for (int i = 0; i < limit; i++) {
String parameter = actualParameters[i] == null ? "null" : actualParameters[i].toString();
invokeMessage += parameter + ",";
}
invokeMessage += actualParameters[actualParameters.length - 1];
}
executionRuntimeServices.addEvent(ACTION_RUNTIME_EVENT_TYPE, invokeMessage);
// invoke action method
return invokeActionMethod(actionMethod, actionClass.newInstance(), actualParameters);
}
private Object[] extractMethodData(Map<String, Serializable> executionContext, ExecutionRuntimeServices executionRuntimeServices, String className, String methodName) throws ClassNotFoundException {
executionRuntimeServices.addEvent(ACTION_RUNTIME_EVENT_TYPE, "Extracting action data");
//get the action class
actionClass = Class.forName(className);
//get the Method object
actionMethod = getMethodByName(actionClass, methodName);
//get the parameter names of the action method
ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
String[] parameterNames = parameterNameDiscoverer.getParameterNames(actionMethod);
//extract the parameters from execution context
return getParametersFromExecutionContext(executionContext, parameterNames);
}
/**
* Extracts the actual method of the action's class
*
* @param actionClass Class object that represents the actual action class
* @param methodName method name of the actual action
* @return actual method represented by Method object
* @throws ClassNotFoundException
*/
private Method getMethodByName(Class actionClass, String methodName) throws ClassNotFoundException {
Method[] methods = actionClass.getDeclaredMethods();
Method actionMethod = null;
for (Method m : methods) {
if (m.getName().equals(methodName)) {
actionMethod = m;
}
}
return actionMethod;
}
/**
* Retrieves a list of parameters from the execution context
*
* @param executionContext current Execution Context
* @param parameterNames list of parameter names to be retrieved
* @return parameters from the execution context represented as Object list
*/
private Object[] getParametersFromExecutionContext(Map<String, Serializable> executionContext, String[] parameterNames) {
int nrParameters = parameterNames.length;
Object[] actualParameters = null;
if (nrParameters > 0) {
actualParameters = new Object[nrParameters];
//actual parameter is passed from the execution context
//if not present will be null
for (int i = 0; i < nrParameters; i++) {
if (executionContext.containsKey(parameterNames[i])) {
actualParameters[i] = executionContext.get(parameterNames[i]);
} else {
actualParameters[i] = null;
}
}
}
return actualParameters;
}
/**
* Invokes the actual action method with the specified parameters
*
* @param actionMethod action method represented as Method object
* @param instance an instance of the invoker class
* @param parameters method parameters
* @return results if the action
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
@SuppressWarnings("unchecked")
private Map<String, String> invokeActionMethod(Method actionMethod, Object instance, Object... parameters)
throws InvocationTargetException, IllegalAccessException {
return (Map<String, String>) actionMethod.invoke(instance, parameters);
}
/**
* Merges back the results in the execution context
*
* @param executionContext current Execution Context
* @param results results to be merged back
*/
private void doMerge(Map<String, Serializable> executionContext, Map<String, String> results) {
if (results != null) {
executionContext.putAll(results);
}
}
public Long navigate(Map<String, Serializable> executionContext, List<NavigationMatcher> navigationMatchers, String defaultNextStepId) {
logger.info("navigate method invocation");
if (navigationMatchers == null) {
return null;
}
MatcherFactory matcherFactory = new MatcherFactory();
for (NavigationMatcher navigationMatcher : navigationMatchers) {
Serializable response = executionContext.get(navigationMatcher.getContextKey());
if (response != null) {
Integer intResponse = Integer.parseInt(response.toString());
if (matcherFactory.getMatcher(navigationMatcher.getMatchType(), navigationMatcher.getCompareArg()).matches(intResponse)) {
return Long.parseLong(navigationMatcher.getNextStepId());
}
}
}
return Long.parseLong(defaultNextStepId);
//return navigationMatcher.getDefaultNextStepId();
}
}
| added check results functionality through events
| score-samples/score-openstack-actions/src/main/java/org/score/samples/openstack/actions/OOActionRunner.java | added check results functionality through events |
|
Java | apache-2.0 | 5c6f6560c2a9d90ad1406733f0dee80b1f418804 | 0 | smashew/incubator-streams,smashew/incubator-streams,smashew/incubator-streams | package org.apache.streams.local.builders;
import org.apache.log4j.spi.LoggerFactory;
import org.apache.streams.core.*;
import org.apache.streams.local.tasks.LocalStreamProcessMonitorThread;
import org.apache.streams.local.tasks.StatusCounterMonitorThread;
import org.apache.streams.local.tasks.StreamsProviderTask;
import org.apache.streams.local.tasks.StreamsTask;
import org.apache.streams.util.SerializationUtil;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* {@link org.apache.streams.local.builders.LocalStreamBuilder} implementation to run a data processing stream in a single
* JVM across many threads. Depending on your data stream, the JVM heap may need to be set to a high value. Default
* implementation uses unbound {@link java.util.concurrent.ConcurrentLinkedQueue} to connect stream components.
*/
public class LocalStreamBuilder implements StreamBuilder {
private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(LocalStreamBuilder.class);
public static final String TIMEOUT_KEY = "TIMEOUT";
private Map<String, StreamComponent> providers;
private Map<String, StreamComponent> components;
private Queue<StreamsDatum> queue;
private Map<String, Object> streamConfig;
private ExecutorService executor;
private ExecutorService monitor;
private int totalTasks;
private int monitorTasks;
private LocalStreamProcessMonitorThread monitorThread;
private Map<String, List<StreamsTask>> tasks;
/**
*
*/
public LocalStreamBuilder(){
this(new ConcurrentLinkedQueue<StreamsDatum>(), null);
}
/**
*
* @param streamConfig
*/
public LocalStreamBuilder(Map<String, Object> streamConfig) {
this(new ConcurrentLinkedQueue<StreamsDatum>(), streamConfig);
}
/**
*
* @param queueType
*/
public LocalStreamBuilder(Queue<StreamsDatum> queueType) {
this(queueType, null);
}
/**
*
* @param queueType
* @param streamConfig
*/
public LocalStreamBuilder(Queue<StreamsDatum> queueType, Map<String, Object> streamConfig) {
this.queue = queueType;
this.providers = new HashMap<String, StreamComponent>();
this.components = new HashMap<String, StreamComponent>();
this.streamConfig = streamConfig;
this.totalTasks = 0;
this.monitorTasks = 0;
}
@Override
public StreamBuilder newPerpetualStream(String id, StreamsProvider provider) {
validateId(id);
this.providers.put(id, new StreamComponent(id, provider, true));
++this.totalTasks;
if( provider instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder newReadCurrentStream(String id, StreamsProvider provider) {
validateId(id);
this.providers.put(id, new StreamComponent(id, provider, false));
++this.totalTasks;
if( provider instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder newReadNewStream(String id, StreamsProvider provider, BigInteger sequence) {
validateId(id);
this.providers.put(id, new StreamComponent(id, provider, sequence));
++this.totalTasks;
if( provider instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder newReadRangeStream(String id, StreamsProvider provider, DateTime start, DateTime end) {
validateId(id);
this.providers.put(id, new StreamComponent(id, provider, start, end));
++this.totalTasks;
if( provider instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder addStreamsProcessor(String id, StreamsProcessor processor, int numTasks, String... inBoundIds) {
validateId(id);
StreamComponent comp = new StreamComponent(id, processor, cloneQueue(), numTasks);
this.components.put(id, comp);
connectToOtherComponents(inBoundIds, comp);
this.totalTasks += numTasks;
if( processor instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder addStreamsPersistWriter(String id, StreamsPersistWriter writer, int numTasks, String... inBoundIds) {
validateId(id);
StreamComponent comp = new StreamComponent(id, writer, cloneQueue(), numTasks);
this.components.put(id, comp);
connectToOtherComponents(inBoundIds, comp);
this.totalTasks += numTasks;
if( writer instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
/**
* Runs the data stream in the this JVM and blocks till completion.
*/
@Override
public void start() {
attachShutdownHandler();
boolean isRunning = true;
this.executor = Executors.newFixedThreadPool(this.totalTasks);
this.monitor = Executors.newFixedThreadPool(this.monitorTasks+1);
Map<String, StreamsProviderTask> provTasks = new HashMap<String, StreamsProviderTask>();
tasks = new HashMap<String, List<StreamsTask>>();
try {
monitorThread = new LocalStreamProcessMonitorThread(executor, 10);
this.monitor.submit(monitorThread);
setupComponentTasks(tasks);
setupProviderTasks(provTasks);
LOGGER.info("Started stream with {} components", tasks.size());
while(isRunning) {
isRunning = false;
for(StreamsProviderTask task : provTasks.values()) {
isRunning = isRunning || task.isRunning();
}
for(StreamComponent task: components.values()) {
isRunning = isRunning || task.getInBoundQueue().size() > 0;
}
if(isRunning) {
Thread.sleep(3000);
}
}
LOGGER.debug("Components are no longer running or timed out due to completion");
shutdown(tasks);
} catch (InterruptedException e){
forceShutdown(tasks);
}
}
private void attachShutdownHandler() {
final LocalStreamBuilder self = this;
LOGGER.debug("Attaching shutdown handler");
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
LOGGER.debug("Shutdown hook received. Beginning shutdown");
self.stop();
}
});
}
protected void forceShutdown(Map<String, List<StreamsTask>> streamsTasks) {
LOGGER.debug("Shutdown failed. Forcing shutdown");
//give the stream 30secs to try to shutdown gracefully, then force shutdown otherwise
for(List<StreamsTask> tasks : streamsTasks.values()) {
for(StreamsTask task : tasks) {
task.stopTask();
}
}
shutdownMonitor();
shutdownExecutor();
}
private void shutdownExecutor() {
// make sure that
try {
// tell the executor to shutdown.
this.executor.shutdown();
if(!this.executor.awaitTermination(3, TimeUnit.SECONDS)) {
this.executor.shutdownNow();
}
if(!this.monitor.awaitTermination(3, TimeUnit.SECONDS)) {
this.monitor.shutdownNow();
}
} catch (InterruptedException ie) {
this.executor.shutdownNow();
this.monitor.shutdownNow();
throw new RuntimeException(ie);
}
}
private void shutdownMonitor() {
try {
// turn off the monitor thread, then it's executor pool.
this.monitorThread.shutdown();
this.monitor.shutdown();
if (!this.monitor.awaitTermination(2, TimeUnit.SECONDS))
this.monitor.shutdownNow();
}
catch(InterruptedException ie) {
LOGGER.warn("There was a problem shutting down the monitor thread: {}", ie);
ie.printStackTrace(); // following the previous pattern
throw new RuntimeException(ie);
}
}
protected void shutdown(Map<String, List<StreamsTask>> streamsTasks) throws InterruptedException {
LOGGER.info("Shutting down LocalStreamsBuilder");
//complete stream shut down gracefully, ask them to shutdown
for(StreamComponent prov : this.providers.values())
shutDownTask(prov, streamsTasks);
shutdownMonitor();
shutdownExecutor();
}
protected void setupProviderTasks(Map<String, StreamsProviderTask> provTasks) {
for(StreamComponent prov : this.providers.values()) {
StreamsTask task = prov.createConnectedTask(getTimeout());
task.setStreamConfig(this.streamConfig);
this.executor.submit(task);
provTasks.put(prov.getId(), (StreamsProviderTask) task);
if( prov.isOperationCountable() ) {
this.monitor.submit(new StatusCounterMonitorThread((DatumStatusCountable) prov.getOperation(), 10));
this.monitor.submit(new StatusCounterMonitorThread((DatumStatusCountable) task, 10));
}
}
}
protected void setupComponentTasks(Map<String, List<StreamsTask>> streamsTasks) {
for(StreamComponent comp : this.components.values()) {
int tasks = comp.getNumTasks();
List<StreamsTask> compTasks = new LinkedList<StreamsTask>();
for(int i=0; i < tasks; ++i) {
StreamsTask task = comp.createConnectedTask(getTimeout());
task.setStreamConfig(this.streamConfig);
this.executor.submit(task);
compTasks.add(task);
if( comp.isOperationCountable() ) {
this.monitor.submit(new StatusCounterMonitorThread((DatumStatusCountable) comp.getOperation(), 10));
this.monitor.submit(new StatusCounterMonitorThread((DatumStatusCountable) task, 10));
}
}
streamsTasks.put(comp.getId(), compTasks);
}
}
/**
* Shutsdown the running tasks in sudo depth first search kind of way. Checks that the upstream components have
* finished running before shutting down. Waits till inbound queue is empty to shutdown.
* @param comp StreamComponent to shut down.
* @param streamTasks the list of non-StreamsProvider tasks for this stream.
* @throws InterruptedException
*/
private void shutDownTask(StreamComponent comp, Map<String, List<StreamsTask>> streamTasks) throws InterruptedException {
List<StreamsTask> tasks = streamTasks.get(comp.getId());
if(tasks != null) { //not a StreamProvider
boolean parentsShutDown = true;
for(StreamComponent parent : comp.getUpStreamComponents()) {
List<StreamsTask> parentTasks = streamTasks.get(parent.getId());
//if parentTask == null, its a provider and is not running anymore
if(parentTasks != null) {
for(StreamsTask task : parentTasks) {
parentsShutDown = parentsShutDown && !task.isRunning();
}
}
}
if(parentsShutDown) {
for(StreamsTask task : tasks) {
task.stopTask();
}
for(StreamsTask task : tasks) {
int count = 0;
while(count < 200 && task.isRunning()) {
Thread.sleep(50);
count++;
}
if(task.isRunning()) {
LOGGER.warn("Task {} failed to terminate in allotted timeframe", task.toString());
}
}
}
}
Collection<StreamComponent> children = comp.getDownStreamComponents();
if(children != null) {
for(StreamComponent child : comp.getDownStreamComponents()) {
shutDownTask(child, streamTasks);
}
}
}
/**
* NOT IMPLEMENTED.
*/
@Override
public void stop() {
try {
shutdown(tasks);
} catch (Exception e) {
forceShutdown(tasks);
}
}
private void connectToOtherComponents(String[] conntectToIds, StreamComponent toBeConnected) {
for(String id : conntectToIds) {
StreamComponent upStream = null;
if(this.providers.containsKey(id)) {
upStream = this.providers.get(id);
}
else if(this.components.containsKey(id)) {
upStream = this.components.get(id);
}
else {
throw new InvalidStreamException("Cannot connect to id, "+id+", because id does not exist.");
}
upStream.addOutBoundQueue(toBeConnected, toBeConnected.getInBoundQueue());
toBeConnected.addInboundQueue(upStream);
}
}
private void validateId(String id) {
if(this.providers.containsKey(id) || this.components.containsKey(id)) {
throw new InvalidStreamException("Duplicate id. "+id+" is already assigned to another component");
}
}
private Queue<StreamsDatum> cloneQueue() {
return (Queue<StreamsDatum>) SerializationUtil.cloneBySerialization(this.queue);
}
protected int getTimeout() {
return streamConfig != null && streamConfig.containsKey(TIMEOUT_KEY) ? (Integer)streamConfig.get(TIMEOUT_KEY) : 3000;
}
}
| streams-runtimes/streams-runtime-local/src/main/java/org/apache/streams/local/builders/LocalStreamBuilder.java | package org.apache.streams.local.builders;
import org.apache.log4j.spi.LoggerFactory;
import org.apache.streams.core.*;
import org.apache.streams.local.tasks.LocalStreamProcessMonitorThread;
import org.apache.streams.local.tasks.StatusCounterMonitorThread;
import org.apache.streams.local.tasks.StreamsProviderTask;
import org.apache.streams.local.tasks.StreamsTask;
import org.apache.streams.util.SerializationUtil;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* {@link org.apache.streams.local.builders.LocalStreamBuilder} implementation to run a data processing stream in a single
* JVM across many threads. Depending on your data stream, the JVM heap may need to be set to a high value. Default
* implementation uses unbound {@link java.util.concurrent.ConcurrentLinkedQueue} to connect stream components.
*/
public class LocalStreamBuilder implements StreamBuilder {
private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(LocalStreamBuilder.class);
public static final String TIMEOUT_KEY = "TIMEOUT";
private Map<String, StreamComponent> providers;
private Map<String, StreamComponent> components;
private Queue<StreamsDatum> queue;
private Map<String, Object> streamConfig;
private ExecutorService executor;
private ExecutorService monitor;
private int totalTasks;
private int monitorTasks;
private LocalStreamProcessMonitorThread monitorThread;
private Map<String, List<StreamsTask>> tasks;
/**
*
*/
public LocalStreamBuilder(){
this(new ConcurrentLinkedQueue<StreamsDatum>(), null);
}
/**
*
* @param streamConfig
*/
public LocalStreamBuilder(Map<String, Object> streamConfig) {
this(new ConcurrentLinkedQueue<StreamsDatum>(), streamConfig);
}
/**
*
* @param queueType
*/
public LocalStreamBuilder(Queue<StreamsDatum> queueType) {
this(queueType, null);
}
/**
*
* @param queueType
* @param streamConfig
*/
public LocalStreamBuilder(Queue<StreamsDatum> queueType, Map<String, Object> streamConfig) {
this.queue = queueType;
this.providers = new HashMap<String, StreamComponent>();
this.components = new HashMap<String, StreamComponent>();
this.streamConfig = streamConfig;
this.totalTasks = 0;
this.monitorTasks = 0;
}
@Override
public StreamBuilder newPerpetualStream(String id, StreamsProvider provider) {
validateId(id);
this.providers.put(id, new StreamComponent(id, provider, true));
++this.totalTasks;
if( provider instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder newReadCurrentStream(String id, StreamsProvider provider) {
validateId(id);
this.providers.put(id, new StreamComponent(id, provider, false));
++this.totalTasks;
if( provider instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder newReadNewStream(String id, StreamsProvider provider, BigInteger sequence) {
validateId(id);
this.providers.put(id, new StreamComponent(id, provider, sequence));
++this.totalTasks;
if( provider instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder newReadRangeStream(String id, StreamsProvider provider, DateTime start, DateTime end) {
validateId(id);
this.providers.put(id, new StreamComponent(id, provider, start, end));
++this.totalTasks;
if( provider instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder addStreamsProcessor(String id, StreamsProcessor processor, int numTasks, String... inBoundIds) {
validateId(id);
StreamComponent comp = new StreamComponent(id, processor, cloneQueue(), numTasks);
this.components.put(id, comp);
connectToOtherComponents(inBoundIds, comp);
this.totalTasks += numTasks;
if( processor instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
@Override
public StreamBuilder addStreamsPersistWriter(String id, StreamsPersistWriter writer, int numTasks, String... inBoundIds) {
validateId(id);
StreamComponent comp = new StreamComponent(id, writer, cloneQueue(), numTasks);
this.components.put(id, comp);
connectToOtherComponents(inBoundIds, comp);
this.totalTasks += numTasks;
if( writer instanceof DatumStatusCountable )
++this.monitorTasks;
return this;
}
/**
* Runs the data stream in the this JVM and blocks till completion.
*/
@Override
public void start() {
attachShutdownHandler();
boolean isRunning = true;
this.executor = Executors.newFixedThreadPool(this.totalTasks);
this.monitor = Executors.newFixedThreadPool(this.monitorTasks+1);
Map<String, StreamsProviderTask> provTasks = new HashMap<String, StreamsProviderTask>();
tasks = new HashMap<String, List<StreamsTask>>();
try {
monitorThread = new LocalStreamProcessMonitorThread(executor, 10);
this.monitor.submit(monitorThread);
setupComponentTasks(tasks);
setupProviderTasks(provTasks);
LOGGER.info("Started stream with {} components", tasks.size());
while(isRunning) {
isRunning = false;
for(StreamsProviderTask task : provTasks.values()) {
isRunning = isRunning || task.isRunning();
}
for(StreamComponent task: components.values()) {
isRunning = isRunning || task.getInBoundQueue().size() > 0;
}
if(isRunning) {
Thread.sleep(3000);
}
}
LOGGER.debug("Components are no longer running or timed out due to completion");
shutdown(tasks);
} catch (InterruptedException e){
forceShutdown(tasks);
}
}
private void attachShutdownHandler() {
final LocalStreamBuilder self = this;
LOGGER.debug("Attaching shutdown handler");
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
LOGGER.debug("Shutdown hook received. Beginning shutdown");
self.stop();
}
});
}
protected void forceShutdown(Map<String, List<StreamsTask>> streamsTasks) {
LOGGER.debug("Shutdown failed. Forcing shutdown");
//give the stream 30secs to try to shutdown gracefully, then force shutdown otherwise
for(List<StreamsTask> tasks : streamsTasks.values()) {
for(StreamsTask task : tasks) {
task.stopTask();
}
}
this.executor.shutdown();
this.monitor.shutdown();
try {
if(!this.executor.awaitTermination(3, TimeUnit.SECONDS)){
this.executor.shutdownNow();
}
if(!this.monitor.awaitTermination(3, TimeUnit.SECONDS)){
this.monitor.shutdownNow();
}
}catch (InterruptedException ie) {
this.executor.shutdownNow();
this.monitor.shutdownNow();
throw new RuntimeException(ie);
}
}
protected void shutdown(Map<String, List<StreamsTask>> streamsTasks) throws InterruptedException {
LOGGER.info("Attempting to shutdown tasks");
monitorThread.shutdown();
this.executor.shutdown();
//complete stream shut down gracfully
for(StreamComponent prov : this.providers.values()) {
shutDownTask(prov, streamsTasks);
}
//need to make this configurable
if(!this.executor.awaitTermination(10, TimeUnit.SECONDS)) { // all threads should have terminated already.
this.executor.shutdownNow();
this.executor.awaitTermination(10, TimeUnit.SECONDS);
}
if(!this.monitor.awaitTermination(5, TimeUnit.SECONDS)) { // all threads should have terminated already.
this.monitor.shutdownNow();
this.monitor.awaitTermination(5, TimeUnit.SECONDS);
}
}
protected void setupProviderTasks(Map<String, StreamsProviderTask> provTasks) {
for(StreamComponent prov : this.providers.values()) {
StreamsTask task = prov.createConnectedTask(getTimeout());
task.setStreamConfig(this.streamConfig);
this.executor.submit(task);
provTasks.put(prov.getId(), (StreamsProviderTask) task);
if( prov.isOperationCountable() ) {
this.monitor.submit(new StatusCounterMonitorThread((DatumStatusCountable) prov.getOperation(), 10));
this.monitor.submit(new StatusCounterMonitorThread((DatumStatusCountable) task, 10));
}
}
}
protected void setupComponentTasks(Map<String, List<StreamsTask>> streamsTasks) {
for(StreamComponent comp : this.components.values()) {
int tasks = comp.getNumTasks();
List<StreamsTask> compTasks = new LinkedList<StreamsTask>();
for(int i=0; i < tasks; ++i) {
StreamsTask task = comp.createConnectedTask(getTimeout());
task.setStreamConfig(this.streamConfig);
this.executor.submit(task);
compTasks.add(task);
if( comp.isOperationCountable() ) {
this.monitor.submit(new StatusCounterMonitorThread((DatumStatusCountable) comp.getOperation(), 10));
this.monitor.submit(new StatusCounterMonitorThread((DatumStatusCountable) task, 10));
}
}
streamsTasks.put(comp.getId(), compTasks);
}
}
/**
* Shutsdown the running tasks in sudo depth first search kind of way. Checks that the upstream components have
* finished running before shutting down. Waits till inbound queue is empty to shutdown.
* @param comp StreamComponent to shut down.
* @param streamTasks the list of non-StreamsProvider tasks for this stream.
* @throws InterruptedException
*/
private void shutDownTask(StreamComponent comp, Map<String, List<StreamsTask>> streamTasks) throws InterruptedException {
List<StreamsTask> tasks = streamTasks.get(comp.getId());
if(tasks != null) { //not a StreamProvider
boolean parentsShutDown = true;
for(StreamComponent parent : comp.getUpStreamComponents()) {
List<StreamsTask> parentTasks = streamTasks.get(parent.getId());
//if parentTask == null, its a provider and is not running anymore
if(parentTasks != null) {
for(StreamsTask task : parentTasks) {
parentsShutDown = parentsShutDown && !task.isRunning();
}
}
}
if(parentsShutDown) {
for(StreamsTask task : tasks) {
task.stopTask();
}
for(StreamsTask task : tasks) {
int count = 0;
while(count < 20 && task.isRunning()) {
Thread.sleep(500);
count++;
}
if(task.isRunning()) {
LOGGER.warn("Task {} failed to terminate in allotted timeframe", task.toString());
}
}
}
}
Collection<StreamComponent> children = comp.getDownStreamComponents();
if(children != null) {
for(StreamComponent child : comp.getDownStreamComponents()) {
shutDownTask(child, streamTasks);
}
}
}
/**
* NOT IMPLEMENTED.
*/
@Override
public void stop() {
try {
shutdown(tasks);
} catch (Exception e) {
forceShutdown(tasks);
}
}
private void connectToOtherComponents(String[] conntectToIds, StreamComponent toBeConnected) {
for(String id : conntectToIds) {
StreamComponent upStream = null;
if(this.providers.containsKey(id)) {
upStream = this.providers.get(id);
}
else if(this.components.containsKey(id)) {
upStream = this.components.get(id);
}
else {
throw new InvalidStreamException("Cannot connect to id, "+id+", because id does not exist.");
}
upStream.addOutBoundQueue(toBeConnected, toBeConnected.getInBoundQueue());
toBeConnected.addInboundQueue(upStream);
}
}
private void validateId(String id) {
if(this.providers.containsKey(id) || this.components.containsKey(id)) {
throw new InvalidStreamException("Duplicate id. "+id+" is already assigned to another component");
}
}
private Queue<StreamsDatum> cloneQueue() {
return (Queue<StreamsDatum>) SerializationUtil.cloneBySerialization(this.queue);
}
protected int getTimeout() {
return streamConfig != null && streamConfig.containsKey(TIMEOUT_KEY) ? (Integer)streamConfig.get(TIMEOUT_KEY) : 3000;
}
}
| STREAMS-81 - Fix for: There is an issue shutting down the local streambuilder, this is the fix.
| streams-runtimes/streams-runtime-local/src/main/java/org/apache/streams/local/builders/LocalStreamBuilder.java | STREAMS-81 - Fix for: There is an issue shutting down the local streambuilder, this is the fix. |
|
Java | apache-2.0 | f4fc13efeeb79e15e5bb27382621f73bfd662dd0 | 0 | christophd/camel,nikhilvibhav/camel,adessaigne/camel,nikhilvibhav/camel,tdiesler/camel,pax95/camel,apache/camel,apache/camel,adessaigne/camel,adessaigne/camel,tdiesler/camel,tadayosi/camel,adessaigne/camel,nikhilvibhav/camel,tdiesler/camel,apache/camel,nikhilvibhav/camel,pax95/camel,apache/camel,tadayosi/camel,christophd/camel,pax95/camel,tdiesler/camel,christophd/camel,cunningt/camel,cunningt/camel,tadayosi/camel,tadayosi/camel,pax95/camel,pax95/camel,christophd/camel,tadayosi/camel,cunningt/camel,apache/camel,christophd/camel,apache/camel,pax95/camel,cunningt/camel,tadayosi/camel,tdiesler/camel,adessaigne/camel,christophd/camel,cunningt/camel,adessaigne/camel,cunningt/camel,tdiesler/camel | /*
* 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.google.pubsub;
import java.util.concurrent.ExecutorService;
import org.apache.camel.Category;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.component.google.pubsub.serializer.DefaultGooglePubsubSerializer;
import org.apache.camel.component.google.pubsub.serializer.GooglePubsubSerializer;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Send and receive messages to/from Google Cloud Platform PubSub Service.
* <p/>
* Built on top of the Google Cloud Pub/Sub libraries.
*/
@UriEndpoint(firstVersion = "2.19.0", scheme = "google-pubsub", title = "Google Pubsub",
syntax = "google-pubsub:projectId:destinationName", category = { Category.CLOUD, Category.MESSAGING })
public class GooglePubsubEndpoint extends DefaultEndpoint {
private Logger log;
@UriPath(description = "Project Id")
@Metadata(required = true)
private String projectId;
@UriPath(description = "Destination Name")
@Metadata(required = true)
private String destinationName;
@UriParam(label = "common",
description = "The Service account key that can be used as credentials for the PubSub publisher/subscriber. It can be loaded by default from "
+ " classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems.")
private String serviceAccountKey;
@UriParam(name = "loggerId", description = "Logger ID to use when a match to the parent route required")
private String loggerId;
@UriParam(name = "concurrentConsumers", description = "The number of parallel streams consuming from the subscription",
defaultValue = "1")
private Integer concurrentConsumers = 1;
@UriParam(name = "maxMessagesPerPoll",
description = "The max number of messages to receive from the server in a single API call", defaultValue = "1")
private Integer maxMessagesPerPoll = 1;
@UriParam(name = "synchronousPull", description = "Synchronously pull batches of messages", defaultValue = "false")
private boolean synchronousPull;
@UriParam(defaultValue = "AUTO", enums = "AUTO,NONE",
description = "AUTO = exchange gets ack'ed/nack'ed on completion. NONE = downstream process has to ack/nack explicitly")
private GooglePubsubConstants.AckMode ackMode = GooglePubsubConstants.AckMode.AUTO;
@UriParam(defaultValue = "false",
description = "Should message ordering be enabled",
label = "producer,advanced")
private boolean messageOrderingEnabled;
@UriParam(description = "Pub/Sub endpoint to use. Required when using message ordering, and ensures that messages are received in order even when multiple publishers are used",
label = "producer,advanced")
private String pubsubEndpoint;
@UriParam(name = "serializer",
description = "A custom GooglePubsubSerializer to use for serializing message payloads in the producer",
label = "producer,advanced")
@Metadata(autowired = true)
private GooglePubsubSerializer serializer;
public GooglePubsubEndpoint(String uri, Component component, String remaining) {
super(uri, component);
if (!(component instanceof GooglePubsubComponent)) {
throw new IllegalArgumentException(
"The component provided is not GooglePubsubComponent : " + component.getClass().getName());
}
}
@Override
public GooglePubsubComponent getComponent() {
return (GooglePubsubComponent) super.getComponent();
}
public void afterPropertiesSet() throws Exception {
if (ObjectHelper.isEmpty(loggerId)) {
log = LoggerFactory.getLogger(this.getClass().getName());
} else {
log = LoggerFactory.getLogger(loggerId);
}
// Default pubsub connection.
// With the publisher endpoints - the main publisher
// with the consumer endpoints - the ack client
log.trace("Project ID: {}", this.projectId);
log.trace("Destination Name: {}", this.destinationName);
}
@Override
public Producer createProducer() throws Exception {
afterPropertiesSet();
if (ObjectHelper.isEmpty(serializer)) {
serializer = new DefaultGooglePubsubSerializer();
}
return new GooglePubsubProducer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
afterPropertiesSet();
setExchangePattern(ExchangePattern.InOnly);
GooglePubsubConsumer consumer = new GooglePubsubConsumer(this, processor);
configureConsumer(consumer);
return consumer;
}
public ExecutorService createExecutor() {
return getCamelContext().getExecutorServiceManager().newFixedThreadPool(this,
"GooglePubsubConsumer[" + getDestinationName() + "]", concurrentConsumers);
}
@Override
public boolean isSingleton() {
return false;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getLoggerId() {
return loggerId;
}
public void setLoggerId(String loggerId) {
this.loggerId = loggerId;
}
public String getServiceAccountKey() {
return serviceAccountKey;
}
public void setServiceAccountKey(String serviceAccountKey) {
this.serviceAccountKey = serviceAccountKey;
}
public String getDestinationName() {
return destinationName;
}
public void setDestinationName(String destinationName) {
this.destinationName = destinationName;
}
public Integer getConcurrentConsumers() {
return concurrentConsumers;
}
public void setConcurrentConsumers(Integer concurrentConsumers) {
this.concurrentConsumers = concurrentConsumers;
}
public Integer getMaxMessagesPerPoll() {
return maxMessagesPerPoll;
}
public void setMaxMessagesPerPoll(Integer maxMessagesPerPoll) {
this.maxMessagesPerPoll = maxMessagesPerPoll;
}
public boolean isSynchronousPull() {
return synchronousPull;
}
public void setSynchronousPull(Boolean synchronousPull) {
this.synchronousPull = synchronousPull;
}
public GooglePubsubConstants.AckMode getAckMode() {
return ackMode;
}
public void setAckMode(GooglePubsubConstants.AckMode ackMode) {
this.ackMode = ackMode;
}
public GooglePubsubSerializer getSerializer() {
return serializer;
}
public void setSerializer(GooglePubsubSerializer serializer) {
this.serializer = serializer;
}
public boolean isMessageOrderingEnabled() {
return this.messageOrderingEnabled;
}
public void setMessageOrderingEnabled(boolean messageOrderingEnabled) {
this.messageOrderingEnabled = messageOrderingEnabled;
}
public String getPubsubEndpoint() {
return this.pubsubEndpoint;
}
public void setPubsubEndpoint(String pubsubEndpoint) {
this.pubsubEndpoint = pubsubEndpoint;
}
}
| components/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubEndpoint.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.google.pubsub;
import java.util.concurrent.ExecutorService;
import org.apache.camel.Category;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.component.google.pubsub.serializer.DefaultGooglePubsubSerializer;
import org.apache.camel.component.google.pubsub.serializer.GooglePubsubSerializer;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Send and receive messages to/from Google Cloud Platform PubSub Service.
* <p/>
* Built on top of the Google Cloud Pub/Sub libraries.
*/
@UriEndpoint(firstVersion = "2.19.0", scheme = "google-pubsub", title = "Google Pubsub",
syntax = "google-pubsub:projectId:destinationName", category = { Category.CLOUD, Category.MESSAGING })
public class GooglePubsubEndpoint extends DefaultEndpoint {
private Logger log;
@UriPath(description = "Project Id")
@Metadata(required = true)
private String projectId;
@UriPath(description = "Destination Name")
@Metadata(required = true)
private String destinationName;
@UriParam(label = "common",
description = "The Service account key that can be used as credentials for the Storage client. It can be loaded by default from "
+ " classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems.")
private String serviceAccountKey;
@UriParam(name = "loggerId", description = "Logger ID to use when a match to the parent route required")
private String loggerId;
@UriParam(name = "concurrentConsumers", description = "The number of parallel streams consuming from the subscription",
defaultValue = "1")
private Integer concurrentConsumers = 1;
@UriParam(name = "maxMessagesPerPoll",
description = "The max number of messages to receive from the server in a single API call", defaultValue = "1")
private Integer maxMessagesPerPoll = 1;
@UriParam(name = "synchronousPull", description = "Synchronously pull batches of messages", defaultValue = "false")
private boolean synchronousPull;
@UriParam(defaultValue = "AUTO", enums = "AUTO,NONE",
description = "AUTO = exchange gets ack'ed/nack'ed on completion. NONE = downstream process has to ack/nack explicitly")
private GooglePubsubConstants.AckMode ackMode = GooglePubsubConstants.AckMode.AUTO;
@UriParam(defaultValue = "false",
description = "Should message ordering be enabled",
label = "producer,advanced")
private boolean messageOrderingEnabled;
@UriParam(description = "Pub/Sub endpoint to use. Required when using message ordering, and ensures that messages are received in order even when multiple publishers are used",
label = "producer,advanced")
private String pubsubEndpoint;
@UriParam(name = "serializer",
description = "A custom GooglePubsubSerializer to use for serializing message payloads in the producer",
label = "producer,advanced")
@Metadata(autowired = true)
private GooglePubsubSerializer serializer;
public GooglePubsubEndpoint(String uri, Component component, String remaining) {
super(uri, component);
if (!(component instanceof GooglePubsubComponent)) {
throw new IllegalArgumentException(
"The component provided is not GooglePubsubComponent : " + component.getClass().getName());
}
}
@Override
public GooglePubsubComponent getComponent() {
return (GooglePubsubComponent) super.getComponent();
}
public void afterPropertiesSet() throws Exception {
if (ObjectHelper.isEmpty(loggerId)) {
log = LoggerFactory.getLogger(this.getClass().getName());
} else {
log = LoggerFactory.getLogger(loggerId);
}
// Default pubsub connection.
// With the publisher endpoints - the main publisher
// with the consumer endpoints - the ack client
log.trace("Project ID: {}", this.projectId);
log.trace("Destination Name: {}", this.destinationName);
}
@Override
public Producer createProducer() throws Exception {
afterPropertiesSet();
if (ObjectHelper.isEmpty(serializer)) {
serializer = new DefaultGooglePubsubSerializer();
}
return new GooglePubsubProducer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
afterPropertiesSet();
setExchangePattern(ExchangePattern.InOnly);
GooglePubsubConsumer consumer = new GooglePubsubConsumer(this, processor);
configureConsumer(consumer);
return consumer;
}
public ExecutorService createExecutor() {
return getCamelContext().getExecutorServiceManager().newFixedThreadPool(this,
"GooglePubsubConsumer[" + getDestinationName() + "]", concurrentConsumers);
}
@Override
public boolean isSingleton() {
return false;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getLoggerId() {
return loggerId;
}
public void setLoggerId(String loggerId) {
this.loggerId = loggerId;
}
public String getServiceAccountKey() {
return serviceAccountKey;
}
public void setServiceAccountKey(String serviceAccountKey) {
this.serviceAccountKey = serviceAccountKey;
}
public String getDestinationName() {
return destinationName;
}
public void setDestinationName(String destinationName) {
this.destinationName = destinationName;
}
public Integer getConcurrentConsumers() {
return concurrentConsumers;
}
public void setConcurrentConsumers(Integer concurrentConsumers) {
this.concurrentConsumers = concurrentConsumers;
}
public Integer getMaxMessagesPerPoll() {
return maxMessagesPerPoll;
}
public void setMaxMessagesPerPoll(Integer maxMessagesPerPoll) {
this.maxMessagesPerPoll = maxMessagesPerPoll;
}
public boolean isSynchronousPull() {
return synchronousPull;
}
public void setSynchronousPull(Boolean synchronousPull) {
this.synchronousPull = synchronousPull;
}
public GooglePubsubConstants.AckMode getAckMode() {
return ackMode;
}
public void setAckMode(GooglePubsubConstants.AckMode ackMode) {
this.ackMode = ackMode;
}
public GooglePubsubSerializer getSerializer() {
return serializer;
}
public void setSerializer(GooglePubsubSerializer serializer) {
this.serializer = serializer;
}
public boolean isMessageOrderingEnabled() {
return this.messageOrderingEnabled;
}
public void setMessageOrderingEnabled(boolean messageOrderingEnabled) {
this.messageOrderingEnabled = messageOrderingEnabled;
}
public String getPubsubEndpoint() {
return this.pubsubEndpoint;
}
public void setPubsubEndpoint(String pubsubEndpoint) {
this.pubsubEndpoint = pubsubEndpoint;
}
}
| Google Pubsub: Added note about authentication in documentation
| components/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubEndpoint.java | Google Pubsub: Added note about authentication in documentation |
|
Java | apache-2.0 | 884a8dfcc1d9fdb64f578f42fd75c9aa22f03f46 | 0 | liuhu/Kaa,Dubland/kaa,abohomol/kaa,sashadidukh/kaa,aglne/kaa,Dubland/kaa,kallelzied/kaa,forGGe/kaa,Oleh-Kravchenko/kaa,aglne/kaa,Dubland/kaa,zofuthan/kaa,aglne/kaa,rasendubi/kaa,forGGe/kaa,sashadidukh/kaa,abohomol/kaa,rasendubi/kaa,Oleh-Kravchenko/kaa,vtkhir/kaa,Deepnekroz/kaa,Deepnekroz/kaa,rasendubi/kaa,sashadidukh/kaa,zofuthan/kaa,rasendubi/kaa,aglne/kaa,rasendubi/kaa,zofuthan/kaa,sashadidukh/kaa,Oleh-Kravchenko/kaa,Dubland/kaa,Oleh-Kravchenko/kaa,Oleh-Kravchenko/kaa,vtkhir/kaa,Dubland/kaa,zofuthan/kaa,sashadidukh/kaa,forGGe/kaa,abohomol/kaa,forGGe/kaa,vtkhir/kaa,zofuthan/kaa,Deepnekroz/kaa,Deepnekroz/kaa,aglne/kaa,abohomol/kaa,vtkhir/kaa,kallelzied/kaa,vtkhir/kaa,abohomol/kaa,forGGe/kaa,Deepnekroz/kaa,sashadidukh/kaa,kallelzied/kaa,liuhu/Kaa,forGGe/kaa,sashadidukh/kaa,liuhu/Kaa,Dubland/kaa,rasendubi/kaa,abohomol/kaa,aglne/kaa,Oleh-Kravchenko/kaa,kallelzied/kaa,forGGe/kaa,vtkhir/kaa,aglne/kaa,abohomol/kaa,Oleh-Kravchenko/kaa,liuhu/Kaa,Deepnekroz/kaa,Deepnekroz/kaa,vtkhir/kaa,rasendubi/kaa,Dubland/kaa,liuhu/Kaa,sashadidukh/kaa,liuhu/Kaa,vtkhir/kaa,zofuthan/kaa,liuhu/Kaa,kallelzied/kaa,kallelzied/kaa | /*
* Copyright 2014 CyberVision, 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.kaaproject.kaa.demo.smarthousedemo.data.persistent;
import java.util.ArrayList;
import java.util.List;
import org.kaaproject.kaa.demo.smarthousedemo.data.DeviceType;
import org.kaaproject.kaa.demo.smarthousedemo.data.SmartDeviceInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DeviceDataSource {
// Database fields.
private SQLiteDatabase database;
private DeviceSqlLiteHelper dbHelper;
private String[] allColumns = { DeviceSqlLiteHelper.COLUMN_ID,
DeviceSqlLiteHelper.COLUMN_ENDPOINT_KEY,
DeviceSqlLiteHelper.COLUMN_DEVICE_TYPE,
DeviceSqlLiteHelper.COLUMN_DEVICE_NAME};
public DeviceDataSource(Context context) {
dbHelper = new DeviceSqlLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public SmartDeviceInfo addDevice(SmartDeviceInfo device) {
ContentValues values = new ContentValues();
values.put(DeviceSqlLiteHelper.COLUMN_ENDPOINT_KEY, device.getEndpointKey());
values.put(DeviceSqlLiteHelper.COLUMN_DEVICE_TYPE, device.getDeviceType().name());
values.put(DeviceSqlLiteHelper.COLUMN_DEVICE_NAME, device.getDeviceName());
long insertId = database.insert(DeviceSqlLiteHelper.TABLE_DEVICES, null,
values);
Cursor cursor = database.query(DeviceSqlLiteHelper.TABLE_DEVICES,
allColumns, DeviceSqlLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
SmartDeviceInfo newDevice = cursorToDevice(cursor);
cursor.close();
return newDevice;
}
public void renameDevice(SmartDeviceInfo device, String newName) {
ContentValues values = new ContentValues();
values.put(DeviceSqlLiteHelper.COLUMN_DEVICE_NAME, newName);
long id = device.getId();
database.update(DeviceSqlLiteHelper.TABLE_DEVICES, values, DeviceSqlLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public void deleteDevice(SmartDeviceInfo device) {
long id = device.getId();
database.delete(DeviceSqlLiteHelper.TABLE_DEVICES, DeviceSqlLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public List<SmartDeviceInfo> getAllDevices() {
List<SmartDeviceInfo> devices = new ArrayList<SmartDeviceInfo>();
Cursor cursor = database.query(DeviceSqlLiteHelper.TABLE_DEVICES,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
SmartDeviceInfo device = cursorToDevice(cursor);
devices.add(device);
cursor.moveToNext();
}
// Close the cursor.
cursor.close();
return devices;
}
public void deleteAllDevices() {
database.delete(DeviceSqlLiteHelper.TABLE_DEVICES, null, null);
}
private SmartDeviceInfo cursorToDevice(Cursor cursor) {
SmartDeviceInfo device = SmartDeviceInfo.createDeviceInfo(cursor.getString(1), DeviceType.valueOf(cursor.getString(2)));
device.setId(cursor.getLong(0));
device.setDeviceName(cursor.getString(3));
return device;
}
}
| examples/smarthousedemo/source/src/org/kaaproject/kaa/demo/smarthousedemo/data/persistent/DeviceDataSource.java | /*
* Copyright 2014 CyberVision, 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.kaaproject.kaa.demo.smarthousedemo.data.persistent;
import java.util.ArrayList;
import java.util.List;
import org.kaaproject.kaa.demo.smarthousedemo.data.DeviceType;
import org.kaaproject.kaa.demo.smarthousedemo.data.SmartDeviceInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DeviceDataSource {
// Database fields
private SQLiteDatabase database;
private DeviceSqlLiteHelper dbHelper;
private String[] allColumns = { DeviceSqlLiteHelper.COLUMN_ID,
DeviceSqlLiteHelper.COLUMN_ENDPOINT_KEY,
DeviceSqlLiteHelper.COLUMN_DEVICE_TYPE,
DeviceSqlLiteHelper.COLUMN_DEVICE_NAME};
public DeviceDataSource(Context context) {
dbHelper = new DeviceSqlLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public SmartDeviceInfo addDevice(SmartDeviceInfo device) {
ContentValues values = new ContentValues();
values.put(DeviceSqlLiteHelper.COLUMN_ENDPOINT_KEY, device.getEndpointKey());
values.put(DeviceSqlLiteHelper.COLUMN_DEVICE_TYPE, device.getDeviceType().name());
values.put(DeviceSqlLiteHelper.COLUMN_DEVICE_NAME, device.getDeviceName());
long insertId = database.insert(DeviceSqlLiteHelper.TABLE_DEVICES, null,
values);
Cursor cursor = database.query(DeviceSqlLiteHelper.TABLE_DEVICES,
allColumns, DeviceSqlLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
SmartDeviceInfo newDevice = cursorToDevice(cursor);
cursor.close();
return newDevice;
}
public void renameDevice(SmartDeviceInfo device, String newName) {
ContentValues values = new ContentValues();
values.put(DeviceSqlLiteHelper.COLUMN_DEVICE_NAME, newName);
long id = device.getId();
database.update(DeviceSqlLiteHelper.TABLE_DEVICES, values, DeviceSqlLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public void deleteDevice(SmartDeviceInfo device) {
long id = device.getId();
database.delete(DeviceSqlLiteHelper.TABLE_DEVICES, DeviceSqlLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public List<SmartDeviceInfo> getAllDevices() {
List<SmartDeviceInfo> devices = new ArrayList<SmartDeviceInfo>();
Cursor cursor = database.query(DeviceSqlLiteHelper.TABLE_DEVICES,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
SmartDeviceInfo device = cursorToDevice(cursor);
devices.add(device);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return devices;
}
public void deleteAllDevices() {
database.delete(DeviceSqlLiteHelper.TABLE_DEVICES, null, null);
}
private SmartDeviceInfo cursorToDevice(Cursor cursor) {
SmartDeviceInfo device = SmartDeviceInfo.createDeviceInfo(cursor.getString(1), DeviceType.valueOf(cursor.getString(2)));
device.setId(cursor.getLong(0));
device.setDeviceName(cursor.getString(3));
return device;
}
}
| Reviewed comments | examples/smarthousedemo/source/src/org/kaaproject/kaa/demo/smarthousedemo/data/persistent/DeviceDataSource.java | Reviewed comments |
|
Java | apache-2.0 | 2e8d1bb8bc67d1c6a7625e9bf00b52acdf6939a1 | 0 | leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere | /*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingjdbc.core.parsing.integrate.engine;
import com.google.common.base.Optional;
import io.shardingjdbc.core.constant.DatabaseType;
import io.shardingjdbc.core.parsing.SQLParsingEngine;
import io.shardingjdbc.core.parsing.integrate.jaxb.condition.ConditionAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.condition.Value;
import io.shardingjdbc.core.parsing.integrate.jaxb.groupby.GroupByColumnAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.item.AggregationSelectItemAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.limit.LimitAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.orderby.OrderByColumnAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.root.ParserAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.table.TableAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.GeneratedKeyTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.IndexTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.ItemsTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.MultipleInsertValuesTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.OffsetTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.OrderByTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.RowCountTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.SQLTokenAsserts;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.TableTokenAssert;
import io.shardingjdbc.core.parsing.parser.context.OrderItem;
import io.shardingjdbc.core.parsing.parser.context.condition.Column;
import io.shardingjdbc.core.parsing.parser.context.condition.Condition;
import io.shardingjdbc.core.parsing.parser.context.condition.Conditions;
import io.shardingjdbc.core.parsing.parser.context.limit.Limit;
import io.shardingjdbc.core.parsing.parser.context.selectitem.AggregationSelectItem;
import io.shardingjdbc.core.parsing.parser.context.selectitem.SelectItem;
import io.shardingjdbc.core.parsing.parser.context.table.Table;
import io.shardingjdbc.core.parsing.parser.context.table.Tables;
import io.shardingjdbc.core.parsing.parser.sql.SQLStatement;
import io.shardingjdbc.core.parsing.parser.sql.dql.select.SelectStatement;
import io.shardingjdbc.core.parsing.parser.token.GeneratedKeyToken;
import io.shardingjdbc.core.parsing.parser.token.IndexToken;
import io.shardingjdbc.core.parsing.parser.token.ItemsToken;
import io.shardingjdbc.core.parsing.parser.token.MultipleInsertValuesToken;
import io.shardingjdbc.core.parsing.parser.token.OffsetToken;
import io.shardingjdbc.core.parsing.parser.token.OrderByToken;
import io.shardingjdbc.core.parsing.parser.token.RowCountToken;
import io.shardingjdbc.core.parsing.parser.token.SQLToken;
import io.shardingjdbc.core.parsing.parser.token.TableToken;
import io.shardingjdbc.test.sql.SQLCaseType;
import io.shardingjdbc.test.sql.SQLCasesLoader;
import lombok.RequiredArgsConstructor;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameters;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@RequiredArgsConstructor
public final class IntegrateSupportedSQLParsingTest extends AbstractBaseIntegrateSQLParsingTest {
private static SQLCasesLoader sqlCasesLoader = SQLCasesLoader.getInstance();
private static ParserAssertsLoader parserAssertsLoader = ParserAssertsLoader.getInstance();
private final String sqlCaseId;
private final DatabaseType databaseType;
private final SQLCaseType sqlCaseType;
@Parameters(name = "{0} ({2}) -> {1}")
public static Collection<Object[]> getTestParameters() {
return sqlCasesLoader.getSupportedSQLTestParameters(Arrays.<Enum>asList(DatabaseType.values()), DatabaseType.class);
}
@Test
public void assertSupportedSQL() throws NoSuchFieldException, IllegalAccessException {
String sql = sqlCasesLoader.getSupportedSQL(sqlCaseId, sqlCaseType, parserAssertsLoader.getParserAssert(sqlCaseId).getParameters());
assertSQLStatement(new SQLParsingEngine(databaseType, sql, getShardingRule()).parse());
}
private void assertSQLStatement(final SQLStatement actual) throws NoSuchFieldException, IllegalAccessException {
ParserAssert parserAssert = parserAssertsLoader.getParserAssert(sqlCaseId);
assertTables(actual.getTables(), parserAssert.getTables());
assertConditions(actual.getConditions(), parserAssert.getConditions());
assertSQLTokens(actual.getSqlTokens(), parserAssert.getTokens());
if (actual instanceof SelectStatement) {
SelectStatement selectStatement = (SelectStatement) actual;
assertItems(selectStatement.getItems(), parserAssert.getAggregationSelectItems());
assertGroupByItems(selectStatement.getGroupByItems(), parserAssert.getGroupByColumns());
assertOrderByItems(selectStatement.getOrderByItems(), parserAssert.getOrderByColumns());
assertLimit(selectStatement.getLimit(), parserAssert.getLimit());
}
// if (actual instanceof SelectStatement) {
// SelectStatement selectStatement = (SelectStatement) actual;
// SelectStatement expectedSqlStatement = ParserJAXBHelper.getSelectStatement(parserAssert);
// ParserAssertHelper.assertOrderBy(expectedSqlStatement.getOrderByItems(), selectStatement.getOrderByItems());
// ParserAssertHelper.assertGroupBy(expectedSqlStatement.getGroupByItems(), selectStatement.getGroupByItems());
// ParserAssertHelper.assertAggregationSelectItem(expectedSqlStatement.getAggregationSelectItems(), selectStatement.getAggregationSelectItems());
// ParserAssertHelper.assertLimit(parserAssert.getLimit(), selectStatement.getLimit(), withPlaceholder);
// }
}
private void assertTables(final Tables actual, final List<TableAssert> expected) {
assertThat(getFullAssertMessage("Tables size assertion error: "), actual.getTableNames().size(), is(expected.size()));
for (TableAssert each : expected) {
Optional<Table> table;
if (null != each.getAlias()) {
table = actual.find(each.getAlias());
} else {
table = actual.find(each.getName());
}
assertTrue(getFullAssertMessage("Table should exist: "), table.isPresent());
assertTable(table.get(), each);
}
}
private void assertTable(final Table actual, final TableAssert expected) {
assertThat(getFullAssertMessage("Table name assertion error: "), actual.getName(), is(expected.getName()));
assertThat(getFullAssertMessage("Table alias assertion error: "), actual.getAlias().orNull(), is(expected.getAlias()));
}
private void assertConditions(final Conditions actual, final List<ConditionAssert> expected) throws NoSuchFieldException, IllegalAccessException {
assertThat(getFullAssertMessage("Conditions size assertion error: "), actual.getConditions().size(), is(expected.size()));
for (ConditionAssert each : expected) {
Optional<Condition> condition = actual.find(new Column(each.getColumnName(), each.getTableName()));
assertTrue(getFullAssertMessage("Table should exist: "), condition.isPresent());
assertCondition(condition.get(), each);
}
}
@SuppressWarnings("unchecked")
private void assertCondition(final Condition actual, final ConditionAssert expected) throws NoSuchFieldException, IllegalAccessException {
assertThat(getFullAssertMessage("Condition column name assertion error: "), actual.getColumn().getName().toUpperCase(), is(expected.getColumnName().toUpperCase()));
assertThat(getFullAssertMessage("Condition table name assertion error: "), actual.getColumn().getTableName().toUpperCase(), is(expected.getTableName().toUpperCase()));
assertThat(getFullAssertMessage("Condition operator assertion error: "), actual.getOperator().name(), is(expected.getOperator()));
int count = 0;
for (Value each : expected.getValues()) {
Map<Integer, Comparable<?>> positionValueMap = (Map<Integer, Comparable<?>>) getField(actual, "positionValueMap");
Map<Integer, Integer> positionIndexMap = (Map<Integer, Integer>) getField(actual, "positionIndexMap");
if (!positionValueMap.isEmpty()) {
assertThat(getFullAssertMessage("Condition parameter value assertion error: "), positionValueMap.get(count), is((Comparable) each.getLiteralForAccurateType()));
} else if (!positionIndexMap.isEmpty()) {
assertThat(getFullAssertMessage("Condition parameter index assertion error: "), positionIndexMap.get(count), is(each.getIndex()));
}
count++;
}
}
private Object getField(final Object actual, final String fieldName) throws NoSuchFieldException, IllegalAccessException {
Field field = actual.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(actual);
}
private void assertSQLTokens(final List<SQLToken> actual, final SQLTokenAsserts expected) {
assertTableTokens(actual, expected);
assertIndexToken(actual, expected);
assertItemsToken(actual, expected);
assertGeneratedKeyToken(actual, expected);
assertMultipleInsertValuesToken(actual, expected);
assertOrderByToken(actual, expected);
assertOffsetToken(actual, expected);
assertRowCountToken(actual, expected);
}
private void assertTableTokens(final List<SQLToken> actual, final SQLTokenAsserts expected) {
List<TableToken> tableTokens = getTableTokens(actual);
assertThat(getFullAssertMessage("Table tokens size error: "), tableTokens.size(), is(expected.getTableTokens().size()));
int count = 0;
for (TableTokenAssert each : expected.getTableTokens()) {
assertTableToken(tableTokens.get(count), each);
count++;
}
}
private void assertTableToken(final TableToken actual, final TableTokenAssert expected) {
assertThat(getFullAssertMessage("Table tokens begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Table tokens original literals assertion error: "), actual.getOriginalLiterals(), is(expected.getOriginalLiterals()));
}
private List<TableToken> getTableTokens(final List<SQLToken> actual) {
List<TableToken> result = new ArrayList<>(actual.size());
for (SQLToken each : actual) {
if (each instanceof TableToken) {
result.add((TableToken) each);
}
}
return result;
}
private void assertIndexToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<IndexToken> indexToken = getIndexToken(actual);
if (indexToken.isPresent()) {
assertIndexToken(indexToken.get(), expected.getIndexToken());
} else {
assertNull(getFullAssertMessage("Index token should not exist: "), expected.getIndexToken());
}
}
private void assertIndexToken(final IndexToken actual, final IndexTokenAssert expected) {
assertThat(getFullAssertMessage("Index token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Index token original literals assertion error: "), actual.getOriginalLiterals(), is(expected.getOriginalLiterals()));
assertThat(getFullAssertMessage("Index token table name assertion error: "), actual.getTableName(), is(expected.getTableName()));
}
private Optional<IndexToken> getIndexToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof IndexToken) {
return Optional.of((IndexToken) each);
}
}
return Optional.absent();
}
private void assertItemsToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<ItemsToken> itemsToken = getItemsToken(actual);
if (itemsToken.isPresent()) {
assertItemsToken(itemsToken.get(), expected.getItemsToken());
} else {
assertNull(getFullAssertMessage("Items token should not exist: "), expected.getItemsToken());
}
}
private void assertItemsToken(final ItemsToken actual, final ItemsTokenAssert expected) {
assertThat(getFullAssertMessage("Items token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Items token items assertion error: "), actual.getItems(), is(expected.getItems()));
}
private Optional<ItemsToken> getItemsToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof ItemsToken) {
return Optional.of((ItemsToken) each);
}
}
return Optional.absent();
}
private void assertGeneratedKeyToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<GeneratedKeyToken> generatedKeyToken = getGeneratedKeyToken(actual);
if (generatedKeyToken.isPresent()) {
assertGeneratedKeyToken(generatedKeyToken.get(), expected.getGeneratedKeyToken());
} else {
assertNull(getFullAssertMessage("Generated key token should not exist: "), expected.getGeneratedKeyToken());
}
}
private void assertGeneratedKeyToken(final GeneratedKeyToken actual, final GeneratedKeyTokenAssert expected) {
if (SQLCaseType.Placeholder == sqlCaseType) {
assertThat(getFullAssertMessage("Generated key token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPositionWithPlaceholder()));
} else {
assertThat(getFullAssertMessage("Generated key token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPositionWithoutPlaceholder()));
}
}
private Optional<GeneratedKeyToken> getGeneratedKeyToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof GeneratedKeyToken) {
return Optional.of((GeneratedKeyToken) each);
}
}
return Optional.absent();
}
private void assertMultipleInsertValuesToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<MultipleInsertValuesToken> multipleInsertValuesToken = getMultipleInsertValuesToken(actual);
if (multipleInsertValuesToken.isPresent()) {
assertMultipleInsertValuesToken(multipleInsertValuesToken.get(), expected.getMultipleInsertValuesToken());
} else {
assertNull(getFullAssertMessage("Multiple insert values token should not exist: "), expected.getMultipleInsertValuesToken());
}
}
private void assertMultipleInsertValuesToken(final MultipleInsertValuesToken actual, final MultipleInsertValuesTokenAssert expected) {
assertThat(getFullAssertMessage("Multiple insert values token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Multiple insert values token values assertion error: "), actual.getValues(), is(expected.getValues()));
}
private Optional<MultipleInsertValuesToken> getMultipleInsertValuesToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof MultipleInsertValuesToken) {
return Optional.of((MultipleInsertValuesToken) each);
}
}
return Optional.absent();
}
private void assertOrderByToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<OrderByToken> orderByToken = getOrderByToken(actual);
if (orderByToken.isPresent()) {
assertOrderByToken(orderByToken.get(), expected.getOrderByToken());
} else {
assertNull(getFullAssertMessage("Order by token should not exist: "), expected.getOrderByToken());
}
}
private void assertOrderByToken(final OrderByToken actual, final OrderByTokenAssert expected) {
if (SQLCaseType.Placeholder == sqlCaseType) {
assertThat(getFullAssertMessage("Order by token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPositionWithPlaceholder()));
} else {
assertThat(getFullAssertMessage("Order by token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPositionWithoutPlaceholder()));
}
}
private Optional<OrderByToken> getOrderByToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof OrderByToken) {
return Optional.of((OrderByToken) each);
}
}
return Optional.absent();
}
private void assertOffsetToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<OffsetToken> offsetToken = getOffsetToken(actual);
if (SQLCaseType.Placeholder == sqlCaseType) {
assertFalse(getFullAssertMessage("Offset token should not exist: "), offsetToken.isPresent());
return;
}
if (offsetToken.isPresent()) {
assertOffsetToken(offsetToken.get(), expected.getOffsetToken());
} else {
assertNull(getFullAssertMessage("Offset token should not exist: "), expected.getOffsetToken());
}
}
private void assertOffsetToken(final OffsetToken actual, final OffsetTokenAssert expected) {
assertThat(getFullAssertMessage("Offset token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Offset token offset assertion error: "), actual.getOffset(), is(expected.getOffset()));
}
private Optional<OffsetToken> getOffsetToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof OffsetToken) {
return Optional.of((OffsetToken) each);
}
}
return Optional.absent();
}
private void assertRowCountToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<RowCountToken> rowCountToken = getRowCountToken(actual);
if (SQLCaseType.Placeholder == sqlCaseType) {
assertFalse(getFullAssertMessage("Row count token should not exist: "), rowCountToken.isPresent());
return;
}
if (rowCountToken.isPresent()) {
assertRowCountToken(rowCountToken.get(), expected.getRowCountToken());
} else {
assertNull(getFullAssertMessage("Row count token should not exist: "), expected.getRowCountToken());
}
}
private void assertRowCountToken(final RowCountToken actual, final RowCountTokenAssert expected) {
assertThat(getFullAssertMessage("Row count token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Row count token row count assertion error: "), actual.getRowCount(), is(expected.getRowCount()));
}
private Optional<RowCountToken> getRowCountToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof RowCountToken) {
return Optional.of((RowCountToken) each);
}
}
return Optional.absent();
}
private void assertItems(final Set<SelectItem> actual, final List<AggregationSelectItemAssert> expected) {
// TODO assert SelectItems total size
// TODO assert StarSelectItem
// TODO assert CommonSelectItem
assertAggregationSelectItems(actual, expected);
}
private void assertAggregationSelectItems(final Set<SelectItem> actual, final List<AggregationSelectItemAssert> expected) {
List<AggregationSelectItem> aggregationSelectItems = getAggregationSelectItems(actual);
assertThat(getFullAssertMessage("Table tokens size error: "), aggregationSelectItems.size(), is(expected.size()));
int count = 0;
for (AggregationSelectItem each : aggregationSelectItems) {
assertAggregationSelectItem(each, expected.get(count));
count++;
}
}
private void assertAggregationSelectItem(final AggregationSelectItem actual, final AggregationSelectItemAssert expected) {
assertThat(getFullAssertMessage("Aggregation select item aggregation type assertion error: "), actual.getType().name(), is(expected.getAggregationType()));
assertThat(getFullAssertMessage("Aggregation select item inner expression assertion error: "), actual.getInnerExpression(), is(expected.getInnerExpression()));
assertThat(getFullAssertMessage("Aggregation select item alias assertion error: "), actual.getAlias().orNull(), is(expected.getAlias()));
assertThat(getFullAssertMessage("Aggregation select item index assertion error: "), actual.getIndex(), is(expected.getIndex()));
assertThat(getFullAssertMessage("Aggregation select item derived aggregation select items assertion error: "),
actual.getDerivedAggregationSelectItems().size(), is(expected.getDerivedColumns().size()));
int count = 0;
for (AggregationSelectItem each : actual.getDerivedAggregationSelectItems()) {
assertAggregationSelectItem(each, expected.getDerivedColumns().get(count));
count++;
}
}
private List<AggregationSelectItem> getAggregationSelectItems(final Set<SelectItem> actual) {
List<AggregationSelectItem> result = new ArrayList<>(actual.size());
for (SelectItem each : actual) {
if (each instanceof AggregationSelectItem) {
result.add((AggregationSelectItem) each);
}
}
return result;
}
private void assertGroupByItems(final List<OrderItem> actual, final List<GroupByColumnAssert> expected) {
assertThat(getFullAssertMessage("Group by items size error: "), actual.size(), is(expected.size()));
int count = 0;
for (OrderItem each : actual) {
assertGroupByItem(each, expected.get(count));
count++;
}
}
private void assertGroupByItem(final OrderItem actual, final GroupByColumnAssert expected) {
assertThat(getFullAssertMessage("Group by item owner assertion error: "), actual.getOwner().orNull(), is(expected.getOwner()));
assertThat(getFullAssertMessage("Group by item name assertion error: "), actual.getName().orNull(), is(expected.getName()));
assertThat(getFullAssertMessage("Group by item order direction assertion error: "), actual.getOrderDirection().name(), is(expected.getOrderDirection()));
// TODO assert nullOrderDirection
assertThat(getFullAssertMessage("Group by item alias assertion error: "), actual.getAlias().orNull(), is(expected.getAlias()));
}
private void assertOrderByItems(final List<OrderItem> actual, final List<OrderByColumnAssert> expected) {
assertThat(getFullAssertMessage("Order by items size error: "), actual.size(), is(expected.size()));
int count = 0;
for (OrderItem each : actual) {
assertOrderByItem(each, expected.get(count));
count++;
}
}
private void assertOrderByItem(final OrderItem actual, final OrderByColumnAssert expected) {
assertThat(getFullAssertMessage("Order by item owner assertion error: "), actual.getOwner().orNull(), is(expected.getOwner()));
assertThat(getFullAssertMessage("Order by item name assertion error: "), actual.getName().orNull(), is(expected.getName()));
assertThat(getFullAssertMessage("Order by item order direction assertion error: "), actual.getOrderDirection().name(), is(expected.getOrderDirection()));
// TODO assert nullOrderDirection
assertThat(getFullAssertMessage("Order by item index assertion error: "), actual.getIndex(), is(expected.getIndex()));
assertThat(getFullAssertMessage("Order by item alias assertion error: "), actual.getAlias().orNull(), is(expected.getAlias()));
}
private void assertLimit(final Limit actual, final LimitAssert expected) {
if (null == actual) {
assertNull(getFullAssertMessage("Limit should not exist: "), expected);
return;
}
if (SQLCaseType.Placeholder == sqlCaseType) {
if (null != actual.getOffset()) {
assertThat(getFullAssertMessage("Limit offset index assertion error: "), actual.getOffset().getIndex(), is(expected.getOffsetParameterIndex()));
}
if (null != actual.getRowCount()) {
assertThat(getFullAssertMessage("Limit row count index assertion error: "), actual.getRowCount().getIndex(), is(expected.getRowCountParameterIndex()));
}
} else {
if (null != actual.getOffset()) {
assertThat(getFullAssertMessage("Limit offset value assertion error: "), actual.getOffset().getValue(), is(expected.getOffset()));
}
if (null != actual.getRowCount()) {
assertThat(getFullAssertMessage("Limit row count value assertion error: "), actual.getRowCount().getValue(), is(expected.getRowCount()));
}
}
}
private String getFullAssertMessage(final String assertMessage) {
StringBuilder result = new StringBuilder(System.getProperty("line.separator"));
result.append("SQL Case ID : ");
result.append(sqlCaseId);
result.append(System.getProperty("line.separator"));
result.append("SQL : ");
if (SQLCaseType.Placeholder == sqlCaseType) {
result.append(SQLCasesLoader.getInstance().getSupportedPlaceholderSQL(sqlCaseId));
result.append(System.getProperty("line.separator"));
result.append("SQL Params : ");
result.append(parserAssertsLoader.getParserAssert(sqlCaseId).getParameters());
result.append(System.getProperty("line.separator"));
} else {
result.append(SQLCasesLoader.getInstance().getSupportedLiteralSQL(sqlCaseId, parserAssertsLoader.getParserAssert(sqlCaseId).getParameters()));
}
result.append(System.getProperty("line.separator"));
result.append(assertMessage);
result.append(System.getProperty("line.separator"));
return result.toString();
}
}
| sharding-core/src/test/java/io/shardingjdbc/core/parsing/integrate/engine/IntegrateSupportedSQLParsingTest.java | /*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingjdbc.core.parsing.integrate.engine;
import com.google.common.base.Optional;
import io.shardingjdbc.core.constant.DatabaseType;
import io.shardingjdbc.core.parsing.SQLParsingEngine;
import io.shardingjdbc.core.parsing.integrate.jaxb.condition.ConditionAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.condition.Value;
import io.shardingjdbc.core.parsing.integrate.jaxb.groupby.GroupByColumnAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.item.AggregationSelectItemAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.orderby.OrderByColumnAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.root.ParserAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.table.TableAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.GeneratedKeyTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.IndexTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.ItemsTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.MultipleInsertValuesTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.OffsetTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.OrderByTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.RowCountTokenAssert;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.SQLTokenAsserts;
import io.shardingjdbc.core.parsing.integrate.jaxb.token.TableTokenAssert;
import io.shardingjdbc.core.parsing.parser.context.OrderItem;
import io.shardingjdbc.core.parsing.parser.context.condition.Column;
import io.shardingjdbc.core.parsing.parser.context.condition.Condition;
import io.shardingjdbc.core.parsing.parser.context.condition.Conditions;
import io.shardingjdbc.core.parsing.parser.context.selectitem.AggregationSelectItem;
import io.shardingjdbc.core.parsing.parser.context.selectitem.SelectItem;
import io.shardingjdbc.core.parsing.parser.context.table.Table;
import io.shardingjdbc.core.parsing.parser.context.table.Tables;
import io.shardingjdbc.core.parsing.parser.sql.SQLStatement;
import io.shardingjdbc.core.parsing.parser.sql.dql.select.SelectStatement;
import io.shardingjdbc.core.parsing.parser.token.GeneratedKeyToken;
import io.shardingjdbc.core.parsing.parser.token.IndexToken;
import io.shardingjdbc.core.parsing.parser.token.ItemsToken;
import io.shardingjdbc.core.parsing.parser.token.MultipleInsertValuesToken;
import io.shardingjdbc.core.parsing.parser.token.OffsetToken;
import io.shardingjdbc.core.parsing.parser.token.OrderByToken;
import io.shardingjdbc.core.parsing.parser.token.RowCountToken;
import io.shardingjdbc.core.parsing.parser.token.SQLToken;
import io.shardingjdbc.core.parsing.parser.token.TableToken;
import io.shardingjdbc.test.sql.SQLCaseType;
import io.shardingjdbc.test.sql.SQLCasesLoader;
import lombok.RequiredArgsConstructor;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameters;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@RequiredArgsConstructor
public final class IntegrateSupportedSQLParsingTest extends AbstractBaseIntegrateSQLParsingTest {
private static SQLCasesLoader sqlCasesLoader = SQLCasesLoader.getInstance();
private static ParserAssertsLoader parserAssertsLoader = ParserAssertsLoader.getInstance();
private final String sqlCaseId;
private final DatabaseType databaseType;
private final SQLCaseType sqlCaseType;
@Parameters(name = "{0} ({2}) -> {1}")
public static Collection<Object[]> getTestParameters() {
return sqlCasesLoader.getSupportedSQLTestParameters(Arrays.<Enum>asList(DatabaseType.values()), DatabaseType.class);
}
@Test
public void assertSupportedSQL() throws NoSuchFieldException, IllegalAccessException {
String sql = sqlCasesLoader.getSupportedSQL(sqlCaseId, sqlCaseType, parserAssertsLoader.getParserAssert(sqlCaseId).getParameters());
assertSQLStatement(new SQLParsingEngine(databaseType, sql, getShardingRule()).parse());
}
private void assertSQLStatement(final SQLStatement actual) throws NoSuchFieldException, IllegalAccessException {
ParserAssert parserAssert = parserAssertsLoader.getParserAssert(sqlCaseId);
assertTables(actual.getTables(), parserAssert.getTables());
assertConditions(actual.getConditions(), parserAssert.getConditions());
assertSQLTokens(actual.getSqlTokens(), parserAssert.getTokens());
if (actual instanceof SelectStatement) {
SelectStatement selectStatement = (SelectStatement) actual;
assertItems(selectStatement.getItems(), parserAssert.getAggregationSelectItems());
assertGroupByItems(selectStatement.getGroupByItems(), parserAssert.getGroupByColumns());
assertOrderByItems(selectStatement.getOrderByItems(), parserAssert.getOrderByColumns());
}
// if (actual instanceof SelectStatement) {
// SelectStatement selectStatement = (SelectStatement) actual;
// SelectStatement expectedSqlStatement = ParserJAXBHelper.getSelectStatement(parserAssert);
// ParserAssertHelper.assertOrderBy(expectedSqlStatement.getOrderByItems(), selectStatement.getOrderByItems());
// ParserAssertHelper.assertGroupBy(expectedSqlStatement.getGroupByItems(), selectStatement.getGroupByItems());
// ParserAssertHelper.assertAggregationSelectItem(expectedSqlStatement.getAggregationSelectItems(), selectStatement.getAggregationSelectItems());
// ParserAssertHelper.assertLimit(parserAssert.getLimit(), selectStatement.getLimit(), withPlaceholder);
// }
}
private void assertTables(final Tables actual, final List<TableAssert> expected) {
assertThat(getFullAssertMessage("Tables size assertion error: "), actual.getTableNames().size(), is(expected.size()));
for (TableAssert each : expected) {
Optional<Table> table;
if (null != each.getAlias()) {
table = actual.find(each.getAlias());
} else {
table = actual.find(each.getName());
}
assertTrue(getFullAssertMessage("Table should exist: "), table.isPresent());
assertTable(table.get(), each);
}
}
private void assertTable(final Table actual, final TableAssert expected) {
assertThat(getFullAssertMessage("Table name assertion error: "), actual.getName(), is(expected.getName()));
assertThat(getFullAssertMessage("Table alias assertion error: "), actual.getAlias().orNull(), is(expected.getAlias()));
}
private void assertConditions(final Conditions actual, final List<ConditionAssert> expected) throws NoSuchFieldException, IllegalAccessException {
assertThat(getFullAssertMessage("Conditions size assertion error: "), actual.getConditions().size(), is(expected.size()));
for (ConditionAssert each : expected) {
Optional<Condition> condition = actual.find(new Column(each.getColumnName(), each.getTableName()));
assertTrue(getFullAssertMessage("Table should exist: "), condition.isPresent());
assertCondition(condition.get(), each);
}
}
@SuppressWarnings("unchecked")
private void assertCondition(final Condition actual, final ConditionAssert expected) throws NoSuchFieldException, IllegalAccessException {
assertThat(getFullAssertMessage("Condition column name assertion error: "), actual.getColumn().getName().toUpperCase(), is(expected.getColumnName().toUpperCase()));
assertThat(getFullAssertMessage("Condition table name assertion error: "), actual.getColumn().getTableName().toUpperCase(), is(expected.getTableName().toUpperCase()));
assertThat(getFullAssertMessage("Condition operator assertion error: "), actual.getOperator().name(), is(expected.getOperator()));
int count = 0;
for (Value each : expected.getValues()) {
Map<Integer, Comparable<?>> positionValueMap = (Map<Integer, Comparable<?>>) getField(actual, "positionValueMap");
Map<Integer, Integer> positionIndexMap = (Map<Integer, Integer>) getField(actual, "positionIndexMap");
if (!positionValueMap.isEmpty()) {
assertThat(getFullAssertMessage("Condition parameter value assertion error: "), positionValueMap.get(count), is((Comparable) each.getLiteralForAccurateType()));
} else if (!positionIndexMap.isEmpty()) {
assertThat(getFullAssertMessage("Condition parameter index assertion error: "), positionIndexMap.get(count), is(each.getIndex()));
}
count++;
}
}
private Object getField(final Object actual, final String fieldName) throws NoSuchFieldException, IllegalAccessException {
Field field = actual.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(actual);
}
private void assertSQLTokens(final List<SQLToken> actual, final SQLTokenAsserts expected) {
assertTableTokens(actual, expected);
assertIndexToken(actual, expected);
assertItemsToken(actual, expected);
assertGeneratedKeyToken(actual, expected);
assertMultipleInsertValuesToken(actual, expected);
assertOrderByToken(actual, expected);
assertOffsetToken(actual, expected);
assertRowCountToken(actual, expected);
}
private void assertTableTokens(final List<SQLToken> actual, final SQLTokenAsserts expected) {
List<TableToken> tableTokens = getTableTokens(actual);
assertThat(getFullAssertMessage("Table tokens size error: "), tableTokens.size(), is(expected.getTableTokens().size()));
int count = 0;
for (TableTokenAssert each : expected.getTableTokens()) {
assertTableToken(tableTokens.get(count), each);
count++;
}
}
private void assertTableToken(final TableToken actual, final TableTokenAssert expected) {
assertThat(getFullAssertMessage("Table tokens begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Table tokens original literals assertion error: "), actual.getOriginalLiterals(), is(expected.getOriginalLiterals()));
}
private List<TableToken> getTableTokens(final List<SQLToken> actual) {
List<TableToken> result = new ArrayList<>(actual.size());
for (SQLToken each : actual) {
if (each instanceof TableToken) {
result.add((TableToken) each);
}
}
return result;
}
private void assertIndexToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<IndexToken> indexToken = getIndexToken(actual);
if (indexToken.isPresent()) {
assertIndexToken(indexToken.get(), expected.getIndexToken());
} else {
assertNull(getFullAssertMessage("Index token should not exist: "), expected.getIndexToken());
}
}
private void assertIndexToken(final IndexToken actual, final IndexTokenAssert expected) {
assertThat(getFullAssertMessage("Index token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Index token original literals assertion error: "), actual.getOriginalLiterals(), is(expected.getOriginalLiterals()));
assertThat(getFullAssertMessage("Index token table name assertion error: "), actual.getTableName(), is(expected.getTableName()));
}
private Optional<IndexToken> getIndexToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof IndexToken) {
return Optional.of((IndexToken) each);
}
}
return Optional.absent();
}
private void assertItemsToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<ItemsToken> itemsToken = getItemsToken(actual);
if (itemsToken.isPresent()) {
assertItemsToken(itemsToken.get(), expected.getItemsToken());
} else {
assertNull(getFullAssertMessage("Items token should not exist: "), expected.getItemsToken());
}
}
private void assertItemsToken(final ItemsToken actual, final ItemsTokenAssert expected) {
assertThat(getFullAssertMessage("Items token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Items token items assertion error: "), actual.getItems(), is(expected.getItems()));
}
private Optional<ItemsToken> getItemsToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof ItemsToken) {
return Optional.of((ItemsToken) each);
}
}
return Optional.absent();
}
private void assertGeneratedKeyToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<GeneratedKeyToken> generatedKeyToken = getGeneratedKeyToken(actual);
if (generatedKeyToken.isPresent()) {
assertGeneratedKeyToken(generatedKeyToken.get(), expected.getGeneratedKeyToken());
} else {
assertNull(getFullAssertMessage("Generated key token should not exist: "), expected.getGeneratedKeyToken());
}
}
private void assertGeneratedKeyToken(final GeneratedKeyToken actual, final GeneratedKeyTokenAssert expected) {
if (SQLCaseType.Placeholder == sqlCaseType) {
assertThat(getFullAssertMessage("Generated key token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPositionWithPlaceholder()));
} else {
assertThat(getFullAssertMessage("Generated key token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPositionWithoutPlaceholder()));
}
}
private Optional<GeneratedKeyToken> getGeneratedKeyToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof GeneratedKeyToken) {
return Optional.of((GeneratedKeyToken) each);
}
}
return Optional.absent();
}
private void assertMultipleInsertValuesToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<MultipleInsertValuesToken> multipleInsertValuesToken = getMultipleInsertValuesToken(actual);
if (multipleInsertValuesToken.isPresent()) {
assertMultipleInsertValuesToken(multipleInsertValuesToken.get(), expected.getMultipleInsertValuesToken());
} else {
assertNull(getFullAssertMessage("Multiple insert values token should not exist: "), expected.getMultipleInsertValuesToken());
}
}
private void assertMultipleInsertValuesToken(final MultipleInsertValuesToken actual, final MultipleInsertValuesTokenAssert expected) {
assertThat(getFullAssertMessage("Multiple insert values token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Multiple insert values token values assertion error: "), actual.getValues(), is(expected.getValues()));
}
private Optional<MultipleInsertValuesToken> getMultipleInsertValuesToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof MultipleInsertValuesToken) {
return Optional.of((MultipleInsertValuesToken) each);
}
}
return Optional.absent();
}
private void assertOrderByToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<OrderByToken> orderByToken = getOrderByToken(actual);
if (orderByToken.isPresent()) {
assertOrderByToken(orderByToken.get(), expected.getOrderByToken());
} else {
assertNull(getFullAssertMessage("Order by token should not exist: "), expected.getOrderByToken());
}
}
private void assertOrderByToken(final OrderByToken actual, final OrderByTokenAssert expected) {
if (SQLCaseType.Placeholder == sqlCaseType) {
assertThat(getFullAssertMessage("Order by token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPositionWithPlaceholder()));
} else {
assertThat(getFullAssertMessage("Order by token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPositionWithoutPlaceholder()));
}
}
private Optional<OrderByToken> getOrderByToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof OrderByToken) {
return Optional.of((OrderByToken) each);
}
}
return Optional.absent();
}
private void assertOffsetToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<OffsetToken> offsetToken = getOffsetToken(actual);
if (SQLCaseType.Placeholder == sqlCaseType) {
assertFalse(getFullAssertMessage("Offset token should not exist: "), offsetToken.isPresent());
return;
}
if (offsetToken.isPresent()) {
assertOffsetToken(offsetToken.get(), expected.getOffsetToken());
} else {
assertNull(getFullAssertMessage("Offset token should not exist: "), expected.getOffsetToken());
}
}
private void assertOffsetToken(final OffsetToken actual, final OffsetTokenAssert expected) {
assertThat(getFullAssertMessage("Offset token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Offset token offset assertion error: "), actual.getOffset(), is(expected.getOffset()));
}
private Optional<OffsetToken> getOffsetToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof OffsetToken) {
return Optional.of((OffsetToken) each);
}
}
return Optional.absent();
}
private void assertRowCountToken(final List<SQLToken> actual, final SQLTokenAsserts expected) {
Optional<RowCountToken> rowCountToken = getRowCountToken(actual);
if (SQLCaseType.Placeholder == sqlCaseType) {
assertFalse(getFullAssertMessage("Row count token should not exist: "), rowCountToken.isPresent());
return;
}
if (rowCountToken.isPresent()) {
assertRowCountToken(rowCountToken.get(), expected.getRowCountToken());
} else {
assertNull(getFullAssertMessage("Row count token should not exist: "), expected.getRowCountToken());
}
}
private void assertRowCountToken(final RowCountToken actual, final RowCountTokenAssert expected) {
assertThat(getFullAssertMessage("Row count token begin position assertion error: "), actual.getBeginPosition(), is(expected.getBeginPosition()));
assertThat(getFullAssertMessage("Row count token row count assertion error: "), actual.getRowCount(), is(expected.getRowCount()));
}
private Optional<RowCountToken> getRowCountToken(final List<SQLToken> actual) {
for (SQLToken each : actual) {
if (each instanceof RowCountToken) {
return Optional.of((RowCountToken) each);
}
}
return Optional.absent();
}
private void assertItems(final Set<SelectItem> actual, final List<AggregationSelectItemAssert> expected) {
// TODO assert SelectItems total size
// TODO assert StarSelectItem
// TODO assert CommonSelectItem
assertAggregationSelectItems(actual, expected);
}
private void assertAggregationSelectItems(final Set<SelectItem> actual, final List<AggregationSelectItemAssert> expected) {
List<AggregationSelectItem> aggregationSelectItems = getAggregationSelectItems(actual);
assertThat(getFullAssertMessage("Table tokens size error: "), aggregationSelectItems.size(), is(expected.size()));
int count = 0;
for (AggregationSelectItem each : aggregationSelectItems) {
assertAggregationSelectItem(each, expected.get(count));
count++;
}
}
private void assertAggregationSelectItem(final AggregationSelectItem actual, final AggregationSelectItemAssert expected) {
assertThat(getFullAssertMessage("Aggregation select item aggregation type assertion error: "), actual.getType().name(), is(expected.getAggregationType()));
assertThat(getFullAssertMessage("Aggregation select item inner expression assertion error: "), actual.getInnerExpression(), is(expected.getInnerExpression()));
assertThat(getFullAssertMessage("Aggregation select item alias assertion error: "), actual.getAlias().orNull(), is(expected.getAlias()));
assertThat(getFullAssertMessage("Aggregation select item index assertion error: "), actual.getIndex(), is(expected.getIndex()));
assertThat(getFullAssertMessage("Aggregation select item derived aggregation select items assertion error: "),
actual.getDerivedAggregationSelectItems().size(), is(expected.getDerivedColumns().size()));
int count = 0;
for (AggregationSelectItem each : actual.getDerivedAggregationSelectItems()) {
assertAggregationSelectItem(each, expected.getDerivedColumns().get(count));
count++;
}
}
private List<AggregationSelectItem> getAggregationSelectItems(final Set<SelectItem> actual) {
List<AggregationSelectItem> result = new ArrayList<>(actual.size());
for (SelectItem each : actual) {
if (each instanceof AggregationSelectItem) {
result.add((AggregationSelectItem) each);
}
}
return result;
}
private void assertGroupByItems(final List<OrderItem> actual, final List<GroupByColumnAssert> expected) {
assertThat(getFullAssertMessage("Group by items size error: "), actual.size(), is(expected.size()));
int count = 0;
for (OrderItem each : actual) {
assertGroupByItem(each, expected.get(count));
count++;
}
}
private void assertGroupByItem(final OrderItem actual, final GroupByColumnAssert expected) {
assertThat(actual.getOwner().orNull(), is(expected.getOwner()));
assertThat(actual.getName().orNull(), is(expected.getName()));
assertThat(actual.getOrderDirection().name(), is(expected.getOrderDirection()));
// TODO assert nullOrderDirection
assertThat(actual.getAlias().orNull(), is(expected.getAlias()));
}
private void assertOrderByItems(final List<OrderItem> actual, final List<OrderByColumnAssert> expected) {
assertThat(getFullAssertMessage("Order by items size error: "), actual.size(), is(expected.size()));
int count = 0;
for (OrderItem each : actual) {
assertOrderByItem(each, expected.get(count));
count++;
}
}
private void assertOrderByItem(final OrderItem actual, final OrderByColumnAssert expected) {
assertThat(actual.getOwner().orNull(), is(expected.getOwner()));
assertThat(actual.getName().orNull(), is(expected.getName()));
assertThat(actual.getOrderDirection().name(), is(expected.getOrderDirection()));
// TODO assert nullOrderDirection
assertThat(actual.getIndex(), is(expected.getIndex()));
assertThat(actual.getAlias().orNull(), is(expected.getAlias()));
}
private String getFullAssertMessage(final String assertMessage) {
StringBuilder result = new StringBuilder(System.getProperty("line.separator"));
result.append("SQL Case ID : ");
result.append(sqlCaseId);
result.append(System.getProperty("line.separator"));
result.append("SQL : ");
if (SQLCaseType.Placeholder == sqlCaseType) {
result.append(SQLCasesLoader.getInstance().getSupportedPlaceholderSQL(sqlCaseId));
result.append(System.getProperty("line.separator"));
result.append("SQL Params : ");
result.append(parserAssertsLoader.getParserAssert(sqlCaseId).getParameters());
result.append(System.getProperty("line.separator"));
} else {
result.append(SQLCasesLoader.getInstance().getSupportedLiteralSQL(sqlCaseId, parserAssertsLoader.getParserAssert(sqlCaseId).getParameters()));
}
result.append(System.getProperty("line.separator"));
result.append(assertMessage);
result.append(System.getProperty("line.separator"));
return result.toString();
}
}
| for #660: refactor assert Limit
| sharding-core/src/test/java/io/shardingjdbc/core/parsing/integrate/engine/IntegrateSupportedSQLParsingTest.java | for #660: refactor assert Limit |
|
Java | apache-2.0 | 4836b406a260f4c75402f1fc0f2925fd41ccc566 | 0 | subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base | package io.subutai.core.hubmanager.impl;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.http.HttpStatus;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import io.subutai.common.dao.DaoManager;
import io.subutai.common.peer.LocalPeer;
import io.subutai.common.util.CollectionUtil;
import io.subutai.common.util.RestUtil;
import io.subutai.core.environment.api.EnvironmentManager;
import io.subutai.core.executor.api.CommandExecutor;
import io.subutai.core.hubmanager.api.HubManager;
import io.subutai.core.hubmanager.api.StateLinkProcessor;
import io.subutai.core.hubmanager.api.dao.ConfigDataService;
import io.subutai.core.hubmanager.api.model.Config;
import io.subutai.core.hubmanager.impl.appscale.AppScaleManager;
import io.subutai.core.hubmanager.impl.appscale.AppScaleProcessor;
import io.subutai.core.hubmanager.impl.dao.ConfigDataServiceImpl;
import io.subutai.core.hubmanager.impl.environment.HubEnvironmentProcessor;
import io.subutai.core.hubmanager.impl.environment.state.Context;
import io.subutai.core.hubmanager.impl.http.HubRestClient;
import io.subutai.core.hubmanager.impl.processor.ContainerEventProcessor;
import io.subutai.core.hubmanager.impl.processor.EnvironmentUserHelper;
import io.subutai.core.hubmanager.impl.processor.HeartbeatProcessor;
import io.subutai.core.hubmanager.impl.processor.HubLoggerProcessor;
import io.subutai.core.hubmanager.impl.processor.ProductProcessor;
import io.subutai.core.hubmanager.impl.processor.ResourceHostDataProcessor;
import io.subutai.core.hubmanager.impl.processor.ResourceHostMonitorProcessor;
import io.subutai.core.hubmanager.impl.processor.SystemConfProcessor;
import io.subutai.core.hubmanager.impl.processor.VehsProcessor;
import io.subutai.core.hubmanager.impl.processor.VersionInfoProcessor;
import io.subutai.core.hubmanager.impl.tunnel.TunnelEventProcessor;
import io.subutai.core.hubmanager.impl.tunnel.TunnelProcessor;
import io.subutai.core.identity.api.IdentityManager;
import io.subutai.core.identity.api.model.User;
import io.subutai.core.metric.api.Monitor;
import io.subutai.core.peer.api.PeerManager;
import io.subutai.core.security.api.SecurityManager;
import io.subutai.hub.share.common.HubEventListener;
import io.subutai.hub.share.dto.PeerDto;
import io.subutai.hub.share.dto.PeerProductDataDto;
import io.subutai.hub.share.dto.SystemConfDto;
import io.subutai.hub.share.dto.UserDto;
import io.subutai.hub.share.dto.product.ProductsDto;
import io.subutai.hub.share.json.JsonUtil;
// TODO: Replace WebClient with HubRestClient.
public class HubManagerImpl implements HubManager
{
private static final long TIME_15_MINUTES = 900;
private final Logger log = LoggerFactory.getLogger( getClass() );
private final ScheduledExecutorService heartbeatExecutorService = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService resourceHostConfExecutorService =
Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService resourceHostMonitorExecutorService =
Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService hubLoggerExecutorService = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService containerEventExecutor = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService versionEventExecutor = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService tunnelEventService = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService sumChecker = Executors.newSingleThreadScheduledExecutor();
private final ExecutorService asyncHeartbeatExecutor = Executors.newFixedThreadPool( 3 );
private SecurityManager securityManager;
private EnvironmentManager envManager;
private PeerManager peerManager;
private ConfigManager configManager;
private CommandExecutor commandExecutor;
private DaoManager daoManager;
private ConfigDataService configDataService;
private Monitor monitor;
private IdentityManager identityManager;
private HeartbeatProcessor heartbeatProcessor;
private ResourceHostDataProcessor resourceHostDataProcessor;
private ContainerEventProcessor containerEventProcessor;
private VersionInfoProcessor versionInfoProcessor;
private final Set<HubEventListener> hubEventListeners = Sets.newConcurrentHashSet();
private String checksum = "";
private HubRestClient restClient;
private LocalPeer localPeer;
private EnvironmentUserHelper envUserHelper;
public HubManagerImpl( DaoManager daoManager )
{
this.daoManager = daoManager;
}
public void addListener( HubEventListener listener )
{
if ( listener != null )
{
hubEventListeners.add( listener );
}
}
public void removeListener( HubEventListener listener )
{
if ( listener != null )
{
hubEventListeners.remove( listener );
}
}
public void init()
{
try
{
localPeer = peerManager.getLocalPeer();
configDataService = new ConfigDataServiceImpl( daoManager );
configManager = new ConfigManager( securityManager, peerManager, identityManager );
restClient = new HubRestClient( configManager );
resourceHostDataProcessor = new ResourceHostDataProcessor( this, localPeer, monitor, restClient );
ResourceHostMonitorProcessor resourceHostMonitorProcessor =
new ResourceHostMonitorProcessor( this, peerManager, configManager, monitor );
resourceHostConfExecutorService
.scheduleWithFixedDelay( resourceHostDataProcessor, 20, TIME_15_MINUTES, TimeUnit.SECONDS );
resourceHostMonitorExecutorService
.scheduleWithFixedDelay( resourceHostMonitorProcessor, 30, 300, TimeUnit.SECONDS );
containerEventProcessor = new ContainerEventProcessor( this, configManager, peerManager );
containerEventExecutor.scheduleWithFixedDelay( containerEventProcessor, 30, 300, TimeUnit.SECONDS );
HubLoggerProcessor hubLoggerProcessor = new HubLoggerProcessor( configManager, this );
hubLoggerExecutorService.scheduleWithFixedDelay( hubLoggerProcessor, 40, 3600, TimeUnit.SECONDS );
TunnelEventProcessor tunnelEventProcessor = new TunnelEventProcessor( this, peerManager, configManager );
tunnelEventService.scheduleWithFixedDelay( tunnelEventProcessor, 20, 300, TimeUnit.SECONDS );
VersionInfoProcessor versionInfoProcessor = new VersionInfoProcessor( this, peerManager, configManager );
versionEventExecutor.scheduleWithFixedDelay( versionInfoProcessor, 20, 120, TimeUnit.SECONDS );
this.sumChecker.scheduleWithFixedDelay( new Runnable()
{
@Override
public void run()
{
log.info( "Starting sumchecker" );
generateChecksum();
}
}, 1, 600000, TimeUnit.MILLISECONDS );
envUserHelper = new EnvironmentUserHelper( identityManager, configDataService, envManager, restClient );
initHeartbeatProcessor();
}
catch ( Exception e )
{
log.error( e.getMessage() );
}
}
private void initHeartbeatProcessor()
{
StateLinkProcessor tunnelProcessor = new TunnelProcessor( peerManager, configManager );
Context ctx = new Context( identityManager, envManager, envUserHelper, localPeer, restClient );
StateLinkProcessor hubEnvironmentProcessor = new HubEnvironmentProcessor( ctx );
StateLinkProcessor systemConfProcessor = new SystemConfProcessor( configManager );
ProductProcessor productProcessor = new ProductProcessor( configManager, this.hubEventListeners );
StateLinkProcessor vehsProccessor = new VehsProcessor( configManager, peerManager );
AppScaleProcessor appScaleProcessor =
new AppScaleProcessor( configManager, new AppScaleManager( peerManager ) );
heartbeatProcessor =
new HeartbeatProcessor( this, restClient, localPeer.getId() ).addProcessor( tunnelProcessor )
.addProcessor( hubEnvironmentProcessor )
.addProcessor( systemConfProcessor )
.addProcessor( productProcessor )
.addProcessor( vehsProccessor )
.addProcessor( appScaleProcessor );
heartbeatExecutorService
.scheduleWithFixedDelay( heartbeatProcessor, 10, HeartbeatProcessor.SMALL_INTERVAL_SECONDS,
TimeUnit.SECONDS );
}
public void destroy()
{
heartbeatExecutorService.shutdown();
resourceHostConfExecutorService.shutdown();
resourceHostMonitorExecutorService.shutdown();
}
@Override
public void sendHeartbeat() throws Exception
{
resourceHostDataProcessor.process();
heartbeatProcessor.sendHeartbeat( true );
containerEventProcessor.process();
}
/**
* Called by Hub to trigger heartbeat on peer
*/
@Override
public void triggerHeartbeat()
{
asyncHeartbeatExecutor.execute( new Runnable()
{
public void run()
{
try
{
heartbeatProcessor.sendHeartbeat( true );
}
catch ( Exception e )
{
log.error( "Error on triggering heartbeat: ", e );
}
}
} );
}
@Override
public void sendResourceHostInfo() throws Exception
{
resourceHostDataProcessor.process();
}
@Override
public void registerPeer( String hupIp, String email, String password ) throws Exception
{
RegistrationManager registrationManager = new RegistrationManager( this, configManager, hupIp );
registrationManager.registerPeer( email, password );
generateChecksum();
notifyRegistrationListeners();
}
private void notifyRegistrationListeners()
{
if ( !CollectionUtil.isCollectionEmpty( hubEventListeners ) )
{
ExecutorService notifier = Executors.newFixedThreadPool( hubEventListeners.size() );
for ( final HubEventListener hubEventListener : hubEventListeners )
{
notifier.execute( new Runnable()
{
@Override
public void run()
{
try
{
hubEventListener.onRegistrationSucceeded();
}
catch ( Exception e )
{
//ignore
}
}
} );
}
notifier.shutdown();
}
}
@Override
public void unregisterPeer() throws Exception
{
RegistrationManager registrationManager = new RegistrationManager( this, configManager, null );
registrationManager.unregister();
}
@Override
public String getHubDns() throws Exception
{
Config config = getConfigDataService().getHubConfig( configManager.getPeerId() );
if ( config != null )
{
return config.getHubIp();
}
else
{
return null;
}
}
@Override
public String getProducts() throws Exception
{
try
{
WebClient client = configManager
.getTrustedWebClientWithAuth( "/rest/v1.2/marketplace/products/public", "hub.subut.ai" );
Response r = client.get();
if ( r.getStatus() == HttpStatus.SC_NO_CONTENT )
{
return null;
}
if ( r.getStatus() != HttpStatus.SC_OK )
{
log.error( r.readEntity( String.class ) );
return null;
}
String result = r.readEntity( String.class );
ProductsDto productsDto = new ProductsDto( result );
return JsonUtil.toJson( productsDto );
}
catch ( Exception e )
{
e.printStackTrace();
throw new Exception( "Could not retrieve product data", e );
}
}
@Override
public void installPlugin( String url, String name, String uid ) throws Exception
{
/*try
{
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager()
{
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType )
{
}
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType )
{
}
}
};
// Activate the new trust manager
try
{
SSLContext sc = SSLContext.getInstance( "SSL" );
sc.init( null, trustAllCerts, new java.security.SecureRandom() );
HttpsURLConnection.setDefaultSSLSocketFactory( sc.getSocketFactory() );
}
catch ( Exception e )
{
}
// And as before now you can use URL and URLConnection
File file =
new File( String.format( "%s/deploy", System.getProperty( "karaf.home" ) ) + "/" + name + ".kar" );
URL website = new URL( url );
URLConnection connection = website.openConnection();
InputStream in = connection.getInputStream();
OutputStream out = new FileOutputStream( file );
IOUtils.copy( in, out );
in.close();
out.close();
// FileUtils.copyURLToFile( website, file );
}
catch ( IOException e )
{
throw new Exception( "Could not install plugin", e );
}*/
WebClient webClient = RestUtil.createTrustedWebClient( url );
File product = webClient.get( File.class );
InputStream initialStream = FileUtils.openInputStream( product );
File targetFile =
new File( String.format( "%s/deploy", System.getProperty( "karaf.home" ) ) + "/" + name + ".kar" );
FileUtils.copyInputStreamToFile( initialStream, targetFile );
initialStream.close();
if ( isRegistered() )
{
ProductProcessor productProcessor = new ProductProcessor( this.configManager, this.hubEventListeners );
Set<String> links = new HashSet<>();
links.add( productProcessor.getProductProcessUrl( uid ) );
PeerProductDataDto peerProductDataDto = new PeerProductDataDto();
peerProductDataDto.setProductId( uid );
peerProductDataDto.setState( PeerProductDataDto.State.INSTALLED );
peerProductDataDto.setInstallDate( new Date() );
try
{
productProcessor.updatePeerProductData( peerProductDataDto );
}
catch ( Exception e )
{
log.error( "Failed to send plugin install command to Hub: {}", e.getMessage() );
}
}
log.debug( "Product installed successfully..." );
}
@Override
public void uninstallPlugin( final String name, final String uid )
{
File file = new File( String.format( "%s/deploy", System.getProperty( "karaf.home" ) ) + "/" + name + ".kar" );
log.info( file.getAbsolutePath() );
File repo = new File( "/opt/subutai-mng/system/io/subutai/" );
File[] dirs = repo.listFiles( new FileFilter()
{
@Override
public boolean accept( File pathname )
{
return pathname.getName().matches( ".*" + name.toLowerCase() + ".*" );
}
} );
if ( dirs != null )
{
for ( File f : dirs )
{
log.info( f.getAbsolutePath() );
try
{
FileUtils.deleteDirectory( f );
log.debug( f.getName() + " is removed." );
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
if ( file.delete() )
{
log.debug( file.getName() + " is removed." );
}
if ( isRegistered() )
{
ProductProcessor productProcessor = new ProductProcessor( this.configManager, this.hubEventListeners );
PeerProductDataDto peerProductDataDto = new PeerProductDataDto();
peerProductDataDto.setProductId( uid );
peerProductDataDto.setState( PeerProductDataDto.State.REMOVE );
try
{
productProcessor.deletePeerProductData( peerProductDataDto );
}
catch ( Exception e )
{
log.error( "Failed to send plugin remove command to Hub: {}", e.getMessage() );
}
}
log.debug( "Product uninstalled successfully..." );
}
@Override
public boolean isRegistered()
{
return configDataService.getHubConfig( configManager.getPeerId() ) != null;
}
@Override
public Map<String, String> getPeerInfo() throws Exception
{
Map<String, String> result = new HashMap<>();
try
{
String path = "/rest/v1/peers/" + configManager.getPeerId();
WebClient client = configManager.getTrustedWebClientWithAuth( path, configManager.getHubIp() );
Response r = client.get();
if ( r.getStatus() == HttpStatus.SC_OK )
{
byte[] encryptedContent = configManager.readContent( r );
byte[] plainContent = configManager.getMessenger().consume( encryptedContent );
PeerDto dto = JsonUtil.fromCbor( plainContent, PeerDto.class );
result.put( "OwnerId", dto.getOwnerId() );
log.debug( "PeerDto: " + result.toString() );
}
}
catch ( Exception e )
{
throw new Exception( "Could not retrieve Peer info", e );
}
return result;
}
public CommandExecutor getCommandExecutor()
{
return commandExecutor;
}
public void setCommandExecutor( final CommandExecutor commandExecutor )
{
this.commandExecutor = commandExecutor;
}
@Override
public Config getHubConfiguration()
{
return configDataService.getHubConfig( configManager.getPeerId() );
}
public void setEnvironmentManager( final EnvironmentManager environmentManager )
{
this.envManager = environmentManager;
}
public void setSecurityManager( final SecurityManager securityManager )
{
this.securityManager = securityManager;
}
public void setPeerManager( final PeerManager peerManager )
{
this.peerManager = peerManager;
}
public ConfigDataService getConfigDataService()
{
return configDataService;
}
public void setConfigDataService( final ConfigDataService configDataService )
{
this.configDataService = configDataService;
}
public void setMonitor( Monitor monitor )
{
this.monitor = monitor;
}
private static ObjectMapper createMapper( JsonFactory factory )
{
ObjectMapper mapper = new ObjectMapper( factory );
mapper.setVisibility( PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY );
return mapper;
}
public void setIdentityManager( final IdentityManager identityManager )
{
this.identityManager = identityManager;
}
private void generateChecksum()
{
try
{
log.info( "Generating plugins list md5 checksum" );
String productList = getProducts();
MessageDigest md = MessageDigest.getInstance( "MD5" );
byte[] bytes = md.digest( productList.getBytes( "UTF-8" ) );
StringBuilder hexString = new StringBuilder();
for ( int i = 0; i < bytes.length; i++ )
{
String hex = Integer.toHexString( 0xFF & bytes[i] );
if ( hex.length() == 1 )
{
hexString.append( '0' );
}
hexString.append( hex );
}
checksum = hexString.toString();
log.info( "Checksum generated: " + checksum );
}
catch ( Exception e )
{
log.error( e.getMessage() );
e.printStackTrace();
}
}
@Override
public String getChecksum()
{
return this.checksum;
}
@Override
public void sendSystemConfiguration( final SystemConfDto dto )
{
if ( isRegistered() )
{
try
{
String path = "/rest/v1/system-changes";
WebClient client = configManager.getTrustedWebClientWithAuth( path, configManager.getHubIp() );
byte[] cborData = JsonUtil.toCbor( dto );
byte[] encryptedData = configManager.getMessenger().produce( cborData );
log.info( "Sending Configuration of SS to Hub..." );
Response r = client.post( encryptedData );
if ( r.getStatus() == HttpStatus.SC_NO_CONTENT )
{
log.info( "SS configuration sent successfully." );
}
else
{
log.error( "Could not send SS configuration to Hub: ", r.readEntity( String.class ) );
}
}
catch ( Exception e )
{
log.error( "Could not send SS configuration to Hub", e );
}
}
}
@Override
public String getCurrentUserEmail()
{
User currentUser = identityManager.getActiveUser();
String email = currentUser.getEmail();
log.info( "currentUser: id={}, username={}, email={}", currentUser.getId(), currentUser.getUserName(), email );
if ( !email.contains( "@hub.subut.ai" ) )
{
return getHubConfiguration().getOwnerEmail();
}
UserDto userDto = envUserHelper.getUserDataFromHub( StringUtils.substringBefore( email, "@" ) );
return userDto.getEmail();
}
} | management/server/core/hub-manager/hub-manager-impl/src/main/java/io/subutai/core/hubmanager/impl/HubManagerImpl.java | package io.subutai.core.hubmanager.impl;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.http.HttpStatus;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import io.subutai.common.dao.DaoManager;
import io.subutai.common.peer.LocalPeer;
import io.subutai.common.util.CollectionUtil;
import io.subutai.common.util.RestUtil;
import io.subutai.core.environment.api.EnvironmentManager;
import io.subutai.core.executor.api.CommandExecutor;
import io.subutai.core.hubmanager.api.HubManager;
import io.subutai.core.hubmanager.api.StateLinkProcessor;
import io.subutai.core.hubmanager.api.dao.ConfigDataService;
import io.subutai.core.hubmanager.api.model.Config;
import io.subutai.core.hubmanager.impl.appscale.AppScaleManager;
import io.subutai.core.hubmanager.impl.appscale.AppScaleProcessor;
import io.subutai.core.hubmanager.impl.dao.ConfigDataServiceImpl;
import io.subutai.core.hubmanager.impl.environment.HubEnvironmentProcessor;
import io.subutai.core.hubmanager.impl.environment.state.Context;
import io.subutai.core.hubmanager.impl.http.HubRestClient;
import io.subutai.core.hubmanager.impl.processor.ContainerEventProcessor;
import io.subutai.core.hubmanager.impl.processor.EnvironmentUserHelper;
import io.subutai.core.hubmanager.impl.processor.HeartbeatProcessor;
import io.subutai.core.hubmanager.impl.processor.HubLoggerProcessor;
import io.subutai.core.hubmanager.impl.processor.ProductProcessor;
import io.subutai.core.hubmanager.impl.processor.ResourceHostDataProcessor;
import io.subutai.core.hubmanager.impl.processor.ResourceHostMonitorProcessor;
import io.subutai.core.hubmanager.impl.processor.SystemConfProcessor;
import io.subutai.core.hubmanager.impl.processor.VehsProcessor;
import io.subutai.core.hubmanager.impl.processor.VersionInfoProcessor;
import io.subutai.core.hubmanager.impl.tunnel.TunnelEventProcessor;
import io.subutai.core.hubmanager.impl.tunnel.TunnelProcessor;
import io.subutai.core.identity.api.IdentityManager;
import io.subutai.core.identity.api.model.User;
import io.subutai.core.metric.api.Monitor;
import io.subutai.core.peer.api.PeerManager;
import io.subutai.core.security.api.SecurityManager;
import io.subutai.hub.share.common.HubEventListener;
import io.subutai.hub.share.dto.PeerDto;
import io.subutai.hub.share.dto.PeerProductDataDto;
import io.subutai.hub.share.dto.SystemConfDto;
import io.subutai.hub.share.dto.UserDto;
import io.subutai.hub.share.dto.product.ProductsDto;
import io.subutai.hub.share.json.JsonUtil;
// TODO: Replace WebClient with HubRestClient.
public class HubManagerImpl implements HubManager
{
private static final long TIME_15_MINUTES = 900;
private final Logger log = LoggerFactory.getLogger( getClass() );
private final ScheduledExecutorService heartbeatExecutorService = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService resourceHostConfExecutorService =
Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService resourceHostMonitorExecutorService =
Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService hubLoggerExecutorService = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService containerEventExecutor = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService versionEventExecutor = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService tunnelEventService = Executors.newSingleThreadScheduledExecutor();
private final ScheduledExecutorService sumChecker = Executors.newSingleThreadScheduledExecutor();
private final ExecutorService asyncHeartbeatExecutor = Executors.newFixedThreadPool( 3 );
private SecurityManager securityManager;
private EnvironmentManager envManager;
private PeerManager peerManager;
private ConfigManager configManager;
private CommandExecutor commandExecutor;
private DaoManager daoManager;
private ConfigDataService configDataService;
private Monitor monitor;
private IdentityManager identityManager;
private HeartbeatProcessor heartbeatProcessor;
private ResourceHostDataProcessor resourceHostDataProcessor;
private ContainerEventProcessor containerEventProcessor;
private VersionInfoProcessor versionInfoProcessor;
private final Set<HubEventListener> hubEventListeners = Sets.newConcurrentHashSet();
private String checksum = "";
private HubRestClient restClient;
private LocalPeer localPeer;
private EnvironmentUserHelper envUserHelper;
public HubManagerImpl( DaoManager daoManager )
{
this.daoManager = daoManager;
}
public void addListener( HubEventListener listener )
{
if ( listener != null )
{
hubEventListeners.add( listener );
}
}
public void removeListener( HubEventListener listener )
{
if ( listener != null )
{
hubEventListeners.remove( listener );
}
}
public void init()
{
try
{
localPeer = peerManager.getLocalPeer();
configDataService = new ConfigDataServiceImpl( daoManager );
configManager = new ConfigManager( securityManager, peerManager, identityManager );
restClient = new HubRestClient( configManager );
resourceHostDataProcessor = new ResourceHostDataProcessor( this, localPeer, monitor, restClient );
ResourceHostMonitorProcessor resourceHostMonitorProcessor =
new ResourceHostMonitorProcessor( this, peerManager, configManager, monitor );
resourceHostConfExecutorService
.scheduleWithFixedDelay( resourceHostDataProcessor, 20, /*TIME_15_MINUTES*/30, TimeUnit.SECONDS );
resourceHostMonitorExecutorService
.scheduleWithFixedDelay( resourceHostMonitorProcessor, 30, 300, TimeUnit.SECONDS );
containerEventProcessor = new ContainerEventProcessor( this, configManager, peerManager );
containerEventExecutor.scheduleWithFixedDelay( containerEventProcessor, 30, 300, TimeUnit.SECONDS );
HubLoggerProcessor hubLoggerProcessor = new HubLoggerProcessor( configManager, this );
hubLoggerExecutorService.scheduleWithFixedDelay( hubLoggerProcessor, 40, 3600, TimeUnit.SECONDS );
TunnelEventProcessor tunnelEventProcessor = new TunnelEventProcessor( this, peerManager, configManager );
tunnelEventService.scheduleWithFixedDelay( tunnelEventProcessor, 20, 300, TimeUnit.SECONDS );
VersionInfoProcessor versionInfoProcessor = new VersionInfoProcessor( this, peerManager, configManager );
versionEventExecutor.scheduleWithFixedDelay( versionInfoProcessor, 20, 120, TimeUnit.SECONDS );
this.sumChecker.scheduleWithFixedDelay( new Runnable()
{
@Override
public void run()
{
log.info( "Starting sumchecker" );
generateChecksum();
}
}, 1, 600000, TimeUnit.MILLISECONDS );
envUserHelper = new EnvironmentUserHelper( identityManager, configDataService, envManager, restClient );
initHeartbeatProcessor();
}
catch ( Exception e )
{
log.error( e.getMessage() );
}
}
private void initHeartbeatProcessor()
{
StateLinkProcessor tunnelProcessor = new TunnelProcessor( peerManager, configManager );
Context ctx = new Context( identityManager, envManager, envUserHelper, localPeer, restClient );
StateLinkProcessor hubEnvironmentProcessor = new HubEnvironmentProcessor( ctx );
StateLinkProcessor systemConfProcessor = new SystemConfProcessor( configManager );
ProductProcessor productProcessor = new ProductProcessor( configManager, this.hubEventListeners );
StateLinkProcessor vehsProccessor = new VehsProcessor( configManager, peerManager );
AppScaleProcessor appScaleProcessor =
new AppScaleProcessor( configManager, new AppScaleManager( peerManager ) );
heartbeatProcessor =
new HeartbeatProcessor( this, restClient, localPeer.getId() ).addProcessor( tunnelProcessor )
.addProcessor( hubEnvironmentProcessor )
.addProcessor( systemConfProcessor )
.addProcessor( productProcessor )
.addProcessor( vehsProccessor )
.addProcessor( appScaleProcessor );
heartbeatExecutorService
.scheduleWithFixedDelay( heartbeatProcessor, 10, HeartbeatProcessor.SMALL_INTERVAL_SECONDS,
TimeUnit.SECONDS );
}
public void destroy()
{
heartbeatExecutorService.shutdown();
resourceHostConfExecutorService.shutdown();
resourceHostMonitorExecutorService.shutdown();
}
@Override
public void sendHeartbeat() throws Exception
{
resourceHostDataProcessor.process();
heartbeatProcessor.sendHeartbeat( true );
containerEventProcessor.process();
}
/**
* Called by Hub to trigger heartbeat on peer
*/
@Override
public void triggerHeartbeat()
{
asyncHeartbeatExecutor.execute( new Runnable()
{
public void run()
{
try
{
heartbeatProcessor.sendHeartbeat( true );
}
catch ( Exception e )
{
log.error( "Error on triggering heartbeat: ", e );
}
}
} );
}
@Override
public void sendResourceHostInfo() throws Exception
{
resourceHostDataProcessor.process();
}
@Override
public void registerPeer( String hupIp, String email, String password ) throws Exception
{
RegistrationManager registrationManager = new RegistrationManager( this, configManager, hupIp );
registrationManager.registerPeer( email, password );
generateChecksum();
notifyRegistrationListeners();
}
private void notifyRegistrationListeners()
{
if ( !CollectionUtil.isCollectionEmpty( hubEventListeners ) )
{
ExecutorService notifier = Executors.newFixedThreadPool( hubEventListeners.size() );
for ( final HubEventListener hubEventListener : hubEventListeners )
{
notifier.execute( new Runnable()
{
@Override
public void run()
{
try
{
hubEventListener.onRegistrationSucceeded();
}
catch ( Exception e )
{
//ignore
}
}
} );
}
notifier.shutdown();
}
}
@Override
public void unregisterPeer() throws Exception
{
RegistrationManager registrationManager = new RegistrationManager( this, configManager, null );
registrationManager.unregister();
}
@Override
public String getHubDns() throws Exception
{
Config config = getConfigDataService().getHubConfig( configManager.getPeerId() );
if ( config != null )
{
return config.getHubIp();
}
else
{
return null;
}
}
@Override
public String getProducts() throws Exception
{
try
{
WebClient client = configManager
.getTrustedWebClientWithAuth( "/rest/v1.2/marketplace/products/public", "hub.subut.ai" );
Response r = client.get();
if ( r.getStatus() == HttpStatus.SC_NO_CONTENT )
{
return null;
}
if ( r.getStatus() != HttpStatus.SC_OK )
{
log.error( r.readEntity( String.class ) );
return null;
}
String result = r.readEntity( String.class );
ProductsDto productsDto = new ProductsDto( result );
return JsonUtil.toJson( productsDto );
}
catch ( Exception e )
{
e.printStackTrace();
throw new Exception( "Could not retrieve product data", e );
}
}
@Override
public void installPlugin( String url, String name, String uid ) throws Exception
{
/*try
{
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager()
{
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType )
{
}
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType )
{
}
}
};
// Activate the new trust manager
try
{
SSLContext sc = SSLContext.getInstance( "SSL" );
sc.init( null, trustAllCerts, new java.security.SecureRandom() );
HttpsURLConnection.setDefaultSSLSocketFactory( sc.getSocketFactory() );
}
catch ( Exception e )
{
}
// And as before now you can use URL and URLConnection
File file =
new File( String.format( "%s/deploy", System.getProperty( "karaf.home" ) ) + "/" + name + ".kar" );
URL website = new URL( url );
URLConnection connection = website.openConnection();
InputStream in = connection.getInputStream();
OutputStream out = new FileOutputStream( file );
IOUtils.copy( in, out );
in.close();
out.close();
// FileUtils.copyURLToFile( website, file );
}
catch ( IOException e )
{
throw new Exception( "Could not install plugin", e );
}*/
WebClient webClient = RestUtil.createTrustedWebClient( url );
File product = webClient.get( File.class );
InputStream initialStream = FileUtils.openInputStream( product );
File targetFile =
new File( String.format( "%s/deploy", System.getProperty( "karaf.home" ) ) + "/" + name + ".kar" );
FileUtils.copyInputStreamToFile( initialStream, targetFile );
initialStream.close();
if ( isRegistered() )
{
ProductProcessor productProcessor = new ProductProcessor( this.configManager, this.hubEventListeners );
Set<String> links = new HashSet<>();
links.add( productProcessor.getProductProcessUrl( uid ) );
PeerProductDataDto peerProductDataDto = new PeerProductDataDto();
peerProductDataDto.setProductId( uid );
peerProductDataDto.setState( PeerProductDataDto.State.INSTALLED );
peerProductDataDto.setInstallDate( new Date() );
try
{
productProcessor.updatePeerProductData( peerProductDataDto );
}
catch ( Exception e )
{
log.error( "Failed to send plugin install command to Hub: {}", e.getMessage() );
}
}
log.debug( "Product installed successfully..." );
}
@Override
public void uninstallPlugin( final String name, final String uid )
{
File file = new File( String.format( "%s/deploy", System.getProperty( "karaf.home" ) ) + "/" + name + ".kar" );
log.info( file.getAbsolutePath() );
File repo = new File( "/opt/subutai-mng/system/io/subutai/" );
File[] dirs = repo.listFiles( new FileFilter()
{
@Override
public boolean accept( File pathname )
{
return pathname.getName().matches( ".*" + name.toLowerCase() + ".*" );
}
} );
if ( dirs != null )
{
for ( File f : dirs )
{
log.info( f.getAbsolutePath() );
try
{
FileUtils.deleteDirectory( f );
log.debug( f.getName() + " is removed." );
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
if ( file.delete() )
{
log.debug( file.getName() + " is removed." );
}
if ( isRegistered() )
{
ProductProcessor productProcessor = new ProductProcessor( this.configManager, this.hubEventListeners );
PeerProductDataDto peerProductDataDto = new PeerProductDataDto();
peerProductDataDto.setProductId( uid );
peerProductDataDto.setState( PeerProductDataDto.State.REMOVE );
try
{
productProcessor.deletePeerProductData( peerProductDataDto );
}
catch ( Exception e )
{
log.error( "Failed to send plugin remove command to Hub: {}", e.getMessage() );
}
}
log.debug( "Product uninstalled successfully..." );
}
@Override
public boolean isRegistered()
{
return configDataService.getHubConfig( configManager.getPeerId() ) != null;
}
@Override
public Map<String, String> getPeerInfo() throws Exception
{
Map<String, String> result = new HashMap<>();
try
{
String path = "/rest/v1/peers/" + configManager.getPeerId();
WebClient client = configManager.getTrustedWebClientWithAuth( path, configManager.getHubIp() );
Response r = client.get();
if ( r.getStatus() == HttpStatus.SC_OK )
{
byte[] encryptedContent = configManager.readContent( r );
byte[] plainContent = configManager.getMessenger().consume( encryptedContent );
PeerDto dto = JsonUtil.fromCbor( plainContent, PeerDto.class );
result.put( "OwnerId", dto.getOwnerId() );
log.debug( "PeerDto: " + result.toString() );
}
}
catch ( Exception e )
{
throw new Exception( "Could not retrieve Peer info", e );
}
return result;
}
public CommandExecutor getCommandExecutor()
{
return commandExecutor;
}
public void setCommandExecutor( final CommandExecutor commandExecutor )
{
this.commandExecutor = commandExecutor;
}
@Override
public Config getHubConfiguration()
{
return configDataService.getHubConfig( configManager.getPeerId() );
}
public void setEnvironmentManager( final EnvironmentManager environmentManager )
{
this.envManager = environmentManager;
}
public void setSecurityManager( final SecurityManager securityManager )
{
this.securityManager = securityManager;
}
public void setPeerManager( final PeerManager peerManager )
{
this.peerManager = peerManager;
}
public ConfigDataService getConfigDataService()
{
return configDataService;
}
public void setConfigDataService( final ConfigDataService configDataService )
{
this.configDataService = configDataService;
}
public void setMonitor( Monitor monitor )
{
this.monitor = monitor;
}
private static ObjectMapper createMapper( JsonFactory factory )
{
ObjectMapper mapper = new ObjectMapper( factory );
mapper.setVisibility( PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY );
return mapper;
}
public void setIdentityManager( final IdentityManager identityManager )
{
this.identityManager = identityManager;
}
private void generateChecksum()
{
try
{
log.info( "Generating plugins list md5 checksum" );
String productList = getProducts();
MessageDigest md = MessageDigest.getInstance( "MD5" );
byte[] bytes = md.digest( productList.getBytes( "UTF-8" ) );
StringBuilder hexString = new StringBuilder();
for ( int i = 0; i < bytes.length; i++ )
{
String hex = Integer.toHexString( 0xFF & bytes[i] );
if ( hex.length() == 1 )
{
hexString.append( '0' );
}
hexString.append( hex );
}
checksum = hexString.toString();
log.info( "Checksum generated: " + checksum );
}
catch ( Exception e )
{
log.error( e.getMessage() );
e.printStackTrace();
}
}
@Override
public String getChecksum()
{
return this.checksum;
}
@Override
public void sendSystemConfiguration( final SystemConfDto dto )
{
if ( isRegistered() )
{
try
{
String path = "/rest/v1/system-changes";
WebClient client = configManager.getTrustedWebClientWithAuth( path, configManager.getHubIp() );
byte[] cborData = JsonUtil.toCbor( dto );
byte[] encryptedData = configManager.getMessenger().produce( cborData );
log.info( "Sending Configuration of SS to Hub..." );
Response r = client.post( encryptedData );
if ( r.getStatus() == HttpStatus.SC_NO_CONTENT )
{
log.info( "SS configuration sent successfully." );
}
else
{
log.error( "Could not send SS configuration to Hub: ", r.readEntity( String.class ) );
}
}
catch ( Exception e )
{
log.error( "Could not send SS configuration to Hub", e );
}
}
}
@Override
public String getCurrentUserEmail()
{
User currentUser = identityManager.getActiveUser();
String email = currentUser.getEmail();
log.info( "currentUser: id={}, username={}, email={}", currentUser.getId(), currentUser.getUserName(), email );
if ( !email.contains( "@hub.subut.ai" ) )
{
return getHubConfiguration().getOwnerEmail();
}
UserDto userDto = envUserHelper.getUserDataFromHub( StringUtils.substringBefore( email, "@" ) );
return userDto.getEmail();
}
} | Reverted sending p2p logs and status to 15 min.
| management/server/core/hub-manager/hub-manager-impl/src/main/java/io/subutai/core/hubmanager/impl/HubManagerImpl.java | Reverted sending p2p logs and status to 15 min. |
|
Java | apache-2.0 | 6d3da25a46fc190204a858e2c84afccbb98d9903 | 0 | jeorme/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,McLeodMoores/starling,jerome79/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.core.historicaltimeseries.impl;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.AssertJUnit.assertEquals;
import javax.time.calendar.LocalDate;
import net.sf.ehcache.CacheManager;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesSource;
import com.opengamma.id.UniqueId;
import com.opengamma.util.ehcache.EHCacheUtils;
import com.opengamma.util.timeseries.localdate.ArrayLocalDateDoubleTimeSeries;
/**
* Test {@link EHCachingHistoricalTimeSeriesSource}.
*/
@Test
public class EHCachingHistoricalTimeSeriesSourceTest {
private HistoricalTimeSeriesSource _underlyingSource;
private EHCachingHistoricalTimeSeriesSource _cachingSource;
private static final UniqueId UID = UniqueId.of("A", "B");
@BeforeMethod
public void setUp() throws Exception {
EHCacheUtils.clearAll();
_underlyingSource = mock(HistoricalTimeSeriesSource.class);
CacheManager cm = EHCacheUtils.createCacheManager();
_cachingSource = new EHCachingHistoricalTimeSeriesSource(_underlyingSource, cm);
}
//-------------------------------------------------------------------------
public void getHistoricalTimeSeries_UniqueId() {
LocalDate[] dates = {LocalDate.of(2011, 6, 30)};
double[] values = {12.34d};
ArrayLocalDateDoubleTimeSeries timeSeries = new ArrayLocalDateDoubleTimeSeries(dates, values);
HistoricalTimeSeries series = new SimpleHistoricalTimeSeries(UID, timeSeries);
when(_underlyingSource.getHistoricalTimeSeries(UID)).thenReturn(series);
// Fetching same series twice should return same result
HistoricalTimeSeries series1 = _cachingSource.getHistoricalTimeSeries(UID);
HistoricalTimeSeries series2 = _cachingSource.getHistoricalTimeSeries(UID);
assertEquals(series, series1);
assertEquals(series, series2);
assertEquals(series1, series2);
// underlying source should only have been called once if cache worked as expected
verify(_underlyingSource, times(1)).getHistoricalTimeSeries(UID);
}
}
| projects/OG-Core/tests/unit/com/opengamma/core/historicaltimeseries/impl/EHCachingHistoricalTimeSeriesSourceTest.java | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.core.historicaltimeseries.impl;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.AssertJUnit.assertEquals;
import javax.time.calendar.LocalDate;
import net.sf.ehcache.CacheManager;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesSource;
import com.opengamma.id.UniqueId;
import com.opengamma.util.ehcache.EHCacheUtils;
import com.opengamma.util.timeseries.localdate.ArrayLocalDateDoubleTimeSeries;
/**
* Test {@link EHCachingHistoricalTimeSeriesSource}.
*/
@Test
public class EHCachingHistoricalTimeSeriesSourceTest {
private HistoricalTimeSeriesSource _underlyingSource;
private EHCachingHistoricalTimeSeriesSource _cachingSource;
private static final UniqueId UID = UniqueId.of("A", "B");
@BeforeMethod
public void setUp() throws Exception {
EHCacheUtils.clearAll();
_underlyingSource = mock(HistoricalTimeSeriesSource.class);
CacheManager cm = EHCacheUtils.createCacheManager();
_cachingSource = new EHCachingHistoricalTimeSeriesSource(_underlyingSource, cm);
}
//-------------------------------------------------------------------------
public void getHistoricalTimeSeries_UniqueId() {
LocalDate[] dates = {LocalDate.of(2011, 6, 30)};
double[] values = {12.34d};
ArrayLocalDateDoubleTimeSeries timeSeries = new ArrayLocalDateDoubleTimeSeries(dates, values);
HistoricalTimeSeries series = new SimpleHistoricalTimeSeries(UID, timeSeries);
when(_underlyingSource.getHistoricalTimeSeries(UID)).thenReturn(series);
HistoricalTimeSeries series1 = _cachingSource.getHistoricalTimeSeries(UID);
HistoricalTimeSeries series2 = _cachingSource.getHistoricalTimeSeries(UID);
assertEquals(series, series1);
assertEquals(series, series2);
assertEquals(series1, series2);
verify(_underlyingSource, times(1)).getHistoricalTimeSeries(UID);
}
}
| Added comments.
| projects/OG-Core/tests/unit/com/opengamma/core/historicaltimeseries/impl/EHCachingHistoricalTimeSeriesSourceTest.java | Added comments. |
|
Java | apache-2.0 | b718d7f171e7cbf93232be9f7dc4af789be2f66a | 0 | dmmiller612/deeplearning4j,huitseeker/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,kinbod/deeplearning4j,dmmiller612/deeplearning4j,dmmiller612/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,dmmiller612/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,dmmiller612/deeplearning4j,huitseeker/deeplearning4j,dmmiller612/deeplearning4j,kinbod/deeplearning4j | package org.deeplearning4j.iterativereduce.actor.deepautoencoder;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.PoisonPill;
import akka.actor.Props;
import akka.contrib.pattern.ClusterSingletonManager;
import akka.contrib.pattern.DistributedPubSubMediator;
import akka.routing.RoundRobinPool;
import org.deeplearning4j.models.featuredetectors.autoencoder.SemanticHashing;
import org.deeplearning4j.iterativereduce.actor.core.*;
import org.deeplearning4j.iterativereduce.actor.core.actor.BatchActor;
import org.deeplearning4j.iterativereduce.tracker.statetracker.StateTracker;
import org.deeplearning4j.iterativereduce.tracker.statetracker.hazelcast.deepautoencoder.DeepAutoEncoderAccumulatorIterateAndUpdate;
import org.nd4j.linalg.dataset.DataSet;
import org.deeplearning4j.nn.BaseMultiLayerNetwork;
import org.deeplearning4j.scaleout.conf.Conf;
import org.deeplearning4j.scaleout.iterativereduce.deepautoencoder.UpdateableEncoderImpl;
import java.io.DataOutputStream;
import java.util.Collection;
/**
* Handles a applyTransformToDestination of workers and acts as a
* parameter server for iterative reduce
* @author Adam Gibson
*
*/
public class MasterActor extends org.deeplearning4j.iterativereduce.actor.core.actor.MasterActor<UpdateableEncoderImpl> {
//start with this network as a baseline
protected SemanticHashing network;
protected BaseMultiLayerNetwork encoder;
/**
* Creates the master and the workers with this given conf
* @param conf the neural net config to use
* @param batchActor the batch actor that handles data applyTransformToDestination dispersion
*/
public MasterActor(Conf conf,ActorRef batchActor, StateTracker<UpdateableEncoderImpl> stateTracker) {
super(conf,batchActor,stateTracker);
setup(conf);
}
/**
* Creates the master and the workers with this given conf
* @param conf the neural net config to use
* @param batchActor the batch actor for the cluster, this
* will manage dataset dispersion
* @param network the neural network to use
*/
public MasterActor(Conf conf,ActorRef batchActor,BaseMultiLayerNetwork network,StateTracker<UpdateableEncoderImpl> stateTracker) {
super(conf,batchActor,stateTracker);
this.encoder = network;
setup(conf);
}
/**
* Creates the master and the workers with this given conf
* @param conf the neural net config to use
* @param batchActor the batch actor for the cluster, this
* will manage dataset dispersion
* @param network the neural network to use
*/
public MasterActor(Conf conf,ActorRef batchActor,SemanticHashing network,StateTracker<UpdateableEncoderImpl> stateTracker) {
super(conf,batchActor,stateTracker);
this.network = network;
setup(conf);
}
@Override
public UpdateableEncoderImpl compute() {
DeepAutoEncoderAccumulatorIterateAndUpdate update = (DeepAutoEncoderAccumulatorIterateAndUpdate) stateTracker.updates();
if(stateTracker.workerUpdates().isEmpty())
return null;
try {
update.accumulate();
}catch(Exception e) {
log.debug("Unable to accumulate results",e);
return null;
}
UpdateableEncoderImpl masterResults = getResults();
if(masterResults == null)
masterResults = update.accumulated();
else
masterResults.set(update.accumulated().get());
try {
stateTracker.setCurrent(masterResults);
} catch (Exception e) {
throw new RuntimeException(e);
}
return masterResults;
}
@Override
public void setup(Conf conf) {
log.info("Starting workers");
ActorSystem system = context().system();
RoundRobinPool pool = new RoundRobinPool(Runtime.getRuntime().availableProcessors());
//start local workers
Props p = pool.props(WorkerActor.propsFor(conf, (StateTracker<UpdateableEncoderImpl>) stateTracker));
p = ClusterSingletonManager.defaultProps(p, "master", PoisonPill.getInstance(), "master");
system.actorOf(p, "worker");
log.info("Broadcasting initial master network");
SemanticHashing network;
if(this.network == null) {
if(encoder != null) {
network = new SemanticHashing.Builder().withEncoder(this.network).build();
this.network = network;
}
else {
network = new SemanticHashing.Builder().withEncoder(conf.init()).build();
this.network = network;
}
}
else
network = this.network;
UpdateableEncoderImpl masterResults = new UpdateableEncoderImpl(network);
/**
* Note that at this point we are storing an uninitialized network.
*
*
*/
try {
this.stateTracker.setCurrent(masterResults);
UpdateableEncoderImpl u2 = this.stateTracker.getCurrent();
log.info("Stored " + u2.get());
} catch (Exception e1) {
throw new RuntimeException(e1);
}
stateTracker.setMiniBatchSize(conf.getSplit());
}
@SuppressWarnings({ "unchecked" })
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof DistributedPubSubMediator.SubscribeAck || message instanceof DistributedPubSubMediator.UnsubscribeAck) {
DistributedPubSubMediator.SubscribeAck ack = (DistributedPubSubMediator.SubscribeAck) message;
//reply
mediator.tell(new DistributedPubSubMediator.Publish(ClusterListener.TOPICS,
message), getSelf());
log.info("Subscribed " + ack.toString());
}
else if(message instanceof DoneMessage) {
log.info("Received done message");
doDoneOrNextPhase();
}
else if(message instanceof String) {
getSender().tell(Ack.getInstance(),getSelf());
}
else if(message instanceof MoreWorkMessage) {
log.info("Prompted for more work, starting pipeline");
mediator.tell(new DistributedPubSubMediator.Publish(BatchActor.BATCH,
MoreWorkMessage.getInstance() ), getSelf());
}
//list of examples
else if(message instanceof Collection) {
if(message instanceof Collection) {
Collection<String> list = (Collection<String>) message;
//workers to send job to
for(String worker : list) {
DataSet data = stateTracker.loadForWorker(worker);
int numRetries = 0;
while(data == null && numRetries < 3) {
data = stateTracker.loadForWorker(worker);
numRetries++;
if(data == null) {
Thread.sleep(10000);
log.info("Data still not found....sleeping for 10 seconds and trying again");
}
}
if(data == null && numRetries >= 3) {
log.info("No data found for worker..." + worker + " returning");
return;
}
Job j2 = new Job(worker,data.copy());
//replicate the job to hazelcast
stateTracker.addJobToCurrent(j2);
//clear data immediately afterwards
data = null;
log.info("Job delegated for " + worker);
}
}
}
else
unhandled(message);
}
@Override
public void complete(DataOutputStream ds) {
this.getMasterResults().write(ds);
}
}
| deeplearning4j-scaleout/deeplearning4j-scaleout-akka/src/main/java/org/deeplearning4j/iterativereduce/actor/deepautoencoder/MasterActor.java | package org.deeplearning4j.iterativereduce.actor.deepautoencoder;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.PoisonPill;
import akka.actor.Props;
import akka.contrib.pattern.ClusterSingletonManager;
import akka.contrib.pattern.DistributedPubSubMediator;
import akka.routing.RoundRobinPool;
import org.deeplearning4j.models.featuredetectors.autoencoder.SemanticHashing;
import org.deeplearning4j.iterativereduce.actor.core.*;
import org.deeplearning4j.iterativereduce.actor.core.actor.BatchActor;
import org.deeplearning4j.iterativereduce.tracker.statetracker.StateTracker;
import org.deeplearning4j.iterativereduce.tracker.statetracker.hazelcast.deepautoencoder.DeepAutoEncoderAccumulatorIterateAndUpdate;
import org.nd4j.linalg.dataset.DataSet;
import org.deeplearning4j.nn.BaseMultiLayerNetwork;
import org.deeplearning4j.scaleout.conf.Conf;
import org.deeplearning4j.scaleout.iterativereduce.deepautoencoder.UpdateableEncoderImpl;
import java.io.DataOutputStream;
import java.util.Collection;
/**
* Handles a applyTransformToDestination of workers and acts as a
* parameter server for iterative reduce
* @author Adam Gibson
*
*/
public class MasterActor extends org.deeplearning4j.iterativereduce.actor.core.actor.MasterActor<UpdateableEncoderImpl> {
//start with this network as a baseline
protected SemanticHashing network;
protected BaseMultiLayerNetwork encoder;
/**
* Creates the master and the workers with this given conf
* @param conf the neural net config to use
* @param batchActor the batch actor that handles data applyTransformToDestination dispersion
*/
public MasterActor(Conf conf,ActorRef batchActor, StateTracker<UpdateableEncoderImpl> stateTracker) {
super(conf,batchActor,stateTracker);
setup(conf);
}
/**
* Creates the master and the workers with this given conf
* @param conf the neural net config to use
* @param batchActor the batch actor for the cluster, this
* will manage dataset dispersion
* @param network the neural network to use
*/
public MasterActor(Conf conf,ActorRef batchActor,BaseMultiLayerNetwork network,StateTracker<UpdateableEncoderImpl> stateTracker) {
super(conf,batchActor,stateTracker);
this.encoder = network;
setup(conf);
}
/**
* Creates the master and the workers with this given conf
* @param conf the neural net config to use
* @param batchActor the batch actor for the cluster, this
* will manage dataset dispersion
* @param network the neural network to use
*/
public MasterActor(Conf conf,ActorRef batchActor,SemanticHashing network,StateTracker<UpdateableEncoderImpl> stateTracker) {
super(conf,batchActor,stateTracker);
this.network = network;
setup(conf);
}
@Override
public UpdateableEncoderImpl compute() {
DeepAutoEncoderAccumulatorIterateAndUpdate update = (DeepAutoEncoderAccumulatorIterateAndUpdate) stateTracker.updates();
if(stateTracker.workerUpdates().isEmpty())
return null;
try {
update.accumulate();
}catch(Exception e) {
log.debug("Unable to accumulate results",e);
return null;
}
UpdateableEncoderImpl masterResults = getResults();
if(masterResults == null)
masterResults = update.accumulated();
else
masterResults.set(update.accumulated().get());
try {
stateTracker.setCurrent(masterResults);
} catch (Exception e) {
throw new RuntimeException(e);
}
return masterResults;
}
@Override
public void setup(Conf conf) {
log.info("Starting workers");
ActorSystem system = context().system();
RoundRobinPool pool = new RoundRobinPool(Runtime.getRuntime().availableProcessors());
//start local workers
Props p = pool.props(WorkerActor.propsFor(conf, (StateTracker<UpdateableEncoderImpl>) stateTracker));
p = ClusterSingletonManager.defaultProps(p, "master", PoisonPill.getInstance(), "master");
system.actorOf(p, "worker");
log.info("Broadcasting initial master network");
SemanticHashing network;
if(this.network == null) {
if(encoder != null) {
network = new SemanticHashing.Builder().withEncoder(this.network).build();
this.network = network;
}
else {
network = new SemanticHashing.Builder().withEncoder(conf.init()).build();
this.network = network;
}
}
else
network = this.network;
network.setOutputLayerActivation(conf.getOutputActivationFunction());
network.setRoundCodeLayerInput(conf.isRoundCodeLayer());
network.setNormalizeCodeLayerOutput(conf.isNormalizeCodeLayer());
UpdateableEncoderImpl masterResults = new UpdateableEncoderImpl(network);
/**
* Note that at this point we are storing an uninitialized network.
*
*
*/
try {
this.stateTracker.setCurrent(masterResults);
UpdateableEncoderImpl u2 = this.stateTracker.getCurrent();
log.info("Stored " + u2.get());
} catch (Exception e1) {
throw new RuntimeException(e1);
}
stateTracker.setMiniBatchSize(conf.getSplit());
}
@SuppressWarnings({ "unchecked" })
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof DistributedPubSubMediator.SubscribeAck || message instanceof DistributedPubSubMediator.UnsubscribeAck) {
DistributedPubSubMediator.SubscribeAck ack = (DistributedPubSubMediator.SubscribeAck) message;
//reply
mediator.tell(new DistributedPubSubMediator.Publish(ClusterListener.TOPICS,
message), getSelf());
log.info("Subscribed " + ack.toString());
}
else if(message instanceof DoneMessage) {
log.info("Received done message");
doDoneOrNextPhase();
}
else if(message instanceof String) {
getSender().tell(Ack.getInstance(),getSelf());
}
else if(message instanceof MoreWorkMessage) {
log.info("Prompted for more work, starting pipeline");
mediator.tell(new DistributedPubSubMediator.Publish(BatchActor.BATCH,
MoreWorkMessage.getInstance() ), getSelf());
}
//list of examples
else if(message instanceof Collection) {
if(message instanceof Collection) {
Collection<String> list = (Collection<String>) message;
//workers to send job to
for(String worker : list) {
DataSet data = stateTracker.loadForWorker(worker);
int numRetries = 0;
while(data == null && numRetries < 3) {
data = stateTracker.loadForWorker(worker);
numRetries++;
if(data == null) {
Thread.sleep(10000);
log.info("Data still not found....sleeping for 10 seconds and trying again");
}
}
if(data == null && numRetries >= 3) {
log.info("No data found for worker..." + worker + " returning");
return;
}
Job j2 = new Job(worker,data.copy());
//replicate the job to hazelcast
stateTracker.addJobToCurrent(j2);
//clear data immediately afterwards
data = null;
log.info("Job delegated for " + worker);
}
}
}
else
unhandled(message);
}
@Override
public void complete(DataOutputStream ds) {
this.getMasterResults().write(ds);
}
}
| semantic hashing renamed; now builds with new api
Former-commit-id: 329359b634718c2e1c89eef319046355ebf61968 | deeplearning4j-scaleout/deeplearning4j-scaleout-akka/src/main/java/org/deeplearning4j/iterativereduce/actor/deepautoencoder/MasterActor.java | semantic hashing renamed; now builds with new api |
|
Java | apache-2.0 | a72e3a36df6a89aeae655b60573bf7e364817773 | 0 | omindu/carbon-identity-framework,omindu/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework | /*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.application.authentication.framework.model;
/**
* Represents a session of a federated user
*/
public class FederatedUserSession {
private String idpSessionId;
private String sessionId;
private String idpName;
private String authenticatorName;
private String protocolType;
public FederatedUserSession() {
}
public FederatedUserSession(String idpSessionId, String sessionId, String idpName, String authenticatorName,
String protocolType) {
this.idpSessionId = idpSessionId;
this.sessionId = sessionId;
this.idpName = idpName;
this.authenticatorName = authenticatorName;
this.protocolType = protocolType;
}
public String getIdpSessionId() {
return idpSessionId;
}
public void setIdpSessionId(String idpSessionId) {
this.idpSessionId = idpSessionId;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getIdpName() {
return idpName;
}
public void setIdpName(String idpName) {
this.idpName = idpName;
}
public String getAuthenticatorName() {
return authenticatorName;
}
public void setAuthenticatorName(String authenticatorName) {
this.authenticatorName = authenticatorName;
}
public String getProtocolType() {
return protocolType;
}
public void setProtocolType(String protocolType) {
this.protocolType = protocolType;
}
}
| components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/model/FederatedUserSession.java | /*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.application.authentication.framework.model;
/**
* Represents a session of a federated user
*/
public class FederatedUserSession {
private String idPSessionId;
private String sessionId;
private String idPName;
private String authenticatorName;
private String protocolType;
public FederatedUserSession() {
}
public FederatedUserSession(String idPSessionId, String sessionId, String idPName, String authenticatorName,
String protocolType) {
this.idPSessionId = idPSessionId;
this.sessionId = sessionId;
this.idPName = idPName;
this.authenticatorName = authenticatorName;
this.protocolType = protocolType;
}
public String getIdPSessionId() {
return idPSessionId;
}
public void setIdPSessionId(String idPSessionId) {
this.idPSessionId = idPSessionId;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getIdPName() {
return idPName;
}
public void setIdPName(String idPName) {
this.idPName = idPName;
}
public String getAuthenticatorName() {
return authenticatorName;
}
public void setAuthenticatorName(String authenticatorName) {
this.authenticatorName = authenticatorName;
}
public String getProtocolType() {
return protocolType;
}
public void setProtocolType(String protocolType) {
this.protocolType = protocolType;
}
}
| change var names
| components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/model/FederatedUserSession.java | change var names |
|
Java | apache-2.0 | 6feaa727cfc6a4dcdce5714d21160ba03f3e584b | 0 | tsammons/SMART-GH,seeebiii/graphhopper,kalvish/graphhopper,kod3r/graphhopper,cloudbearings/SMART-GH,tlatt/graphhopper,joh12041/graphhopper,zzottel/graphhopper,bendavidson/graphhopper,hguerrero/graphhopper,ammagamma/graphhopper,nside/graphhopper,bendavidson/graphhopper,tlatt/graphhopper,komoot/graphhopper,DIVERSIFY-project/SMART-GH,CEPFU/graphhopper,graphhopper/graphhopper,mmalfertheiner/graphhopper,DIVERSIFY-project/SMART-GH,engaric/graphhopper,joh12041/graphhopper,joh12041/graphhopper,routexl/graphhopper,graphhopper/graphhopper,nside/graphhopper,Ranjan101/graphhopper,devemux86/graphhopper,HelgeKrueger/graphhopper,fbonzon/graphhopper,tsammons/SMART-GH,don-philipe/graphhopper,ratrun/graphhopper,boldtrn/graphhopper,jansoe/graphhopper,piemapping/graphhopper,Ranjan101/graphhopper,PGWelch/graphhopper,tsammons/SMART-GH,tsammons/SMART-GH,zhiqiangZHAO/graphhopper,boldtrn/graphhopper,engaric/graphhopper,kalvish/graphhopper,hguerrero/graphhopper,seeebiii/graphhopper,cloudbearings/SMART-GH,routexl/graphhopper,don-philipe/graphhopper,kalvish/graphhopper,CEPFU/graphhopper,jansoe/graphhopper,seeebiii/graphhopper,engaric/graphhopper,cecemel/graphhopper,hguerrero/graphhopper,routexl/graphhopper,CEPFU/graphhopper,tobias74/graphhopper,zhiqiangZHAO/graphhopper,Ranjan101/graphhopper,DIVERSIFY-project/SMART-GH,mmalfertheiner/graphhopper,tlatt/graphhopper,mmalfertheiner/graphhopper,msoftware/graphhopper,jansoe/graphhopper,PGWelch/graphhopper,hguerrero/graphhopper,heisenpai/GraphHopper,HelgeKrueger/graphhopper,nside/graphhopper,zhiqiangZHAO/graphhopper,prembasumatary/graphhopper,devemux86/graphhopper,ratrun/graphhopper,don-philipe/graphhopper,don-philipe/graphhopper,prembasumatary/graphhopper,piemapping/graphhopper,DIVERSIFY-project/SMART-GH,graphhopper/graphhopper,cecemel/graphhopper,fbonzon/graphhopper,tsammons/SMART-GH,komoot/graphhopper,fbonzon/graphhopper,nside/graphhopper,zhiqiangZHAO/graphhopper,mmalfertheiner/graphhopper,devemux86/graphhopper,joh12041/graphhopper,ammagamma/graphhopper,HelgeKrueger/graphhopper,cecemel/graphhopper,DIVERSIFY-project/SMART-GH,ammagamma/graphhopper,msoftware/graphhopper,PGWelch/graphhopper,zhiqiangZHAO/graphhopper,kod3r/graphhopper,tobias74/graphhopper,piemapping/graphhopper,fbonzon/graphhopper,SamSix/graphhopper,Kwangseob/graphhopper,cecemel/graphhopper,bendavidson/graphhopper,nside/graphhopper,cloudbearings/SMART-GH,prembasumatary/graphhopper,ratrun/graphhopper,SamSix/graphhopper,boldtrn/graphhopper,heisenpai/GraphHopper,graphhopper/graphhopper,SamSix/graphhopper,boldtrn/graphhopper,engaric/graphhopper,komoot/graphhopper,Ranjan101/graphhopper,PGWelch/graphhopper,msoftware/graphhopper,kod3r/graphhopper,heisenpai/GraphHopper,Kwangseob/graphhopper,zzottel/graphhopper,tlatt/graphhopper,piemapping/graphhopper,HelgeKrueger/graphhopper,prembasumatary/graphhopper,cloudbearings/SMART-GH,CEPFU/graphhopper,devemux86/graphhopper,tobias74/graphhopper,SamSix/graphhopper,Kwangseob/graphhopper,kalvish/graphhopper,tobias74/graphhopper,jansoe/graphhopper,zzottel/graphhopper,zzottel/graphhopper,seeebiii/graphhopper,kod3r/graphhopper,ratrun/graphhopper,routexl/graphhopper,cloudbearings/SMART-GH,Kwangseob/graphhopper,SamSix/graphhopper,msoftware/graphhopper,ammagamma/graphhopper,bendavidson/graphhopper,komoot/graphhopper,heisenpai/GraphHopper | /*
* Copyright 2012 Peter Karich [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.jetsli.graph.routing;
import de.jetsli.graph.coll.MyOpenBitSet;
import de.jetsli.graph.reader.CarFlags;
import de.jetsli.graph.storage.EdgeEntry;
import de.jetsli.graph.storage.Graph;
import de.jetsli.graph.util.ApproxCalcDistance;
import de.jetsli.graph.util.CalcDistance;
import de.jetsli.graph.util.EdgeIdIterator;
import de.jetsli.graph.util.GraphUtility;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import java.util.PriorityQueue;
/**
* @author Peter Karich
*/
public class AStar extends AbstractRoutingAlgorithm {
private CalcDistance dist = new ApproxCalcDistance();
public AStar(Graph g) {
super(g);
}
/**
* @param fast if true it enables approximative distance calculation from lat,lon values
*/
public AStar setFast(boolean fast) {
if (fast)
dist = new ApproxCalcDistance();
else
dist = new CalcDistance();
return this;
}
@Override public Path calcPath(int from, int to) {
MyOpenBitSet closedSet = new MyOpenBitSet(graph.getNodes());
TIntObjectMap<AStarEdge> map = new TIntObjectHashMap<AStarEdge>();
PriorityQueue<AStarEdge> prioQueueOpenSet = new PriorityQueue<AStarEdge>();
double toLat = graph.getLatitude(to);
double toLon = graph.getLongitude(to);
double tmpLat = graph.getLatitude(from);
double tmpLon = graph.getLongitude(from);
double currWeightToGoal = dist.calcDistKm(toLat, toLon, tmpLat, tmpLon);
currWeightToGoal = applyWeight(currWeightToGoal);
double distEstimation = 0 + currWeightToGoal;
AStarEdge fromEntry = new AStarEdge(from, distEstimation, 0);
AStarEdge currEdge = fromEntry;
while (true) {
int currVertex = currEdge.node;
EdgeIdIterator iter = graph.getOutgoing(currVertex);
while (iter.next()) {
int neighborNode = iter.nodeId();
if (closedSet.contains(neighborNode))
continue;
float alreadyVisitedWeight = (float) getWeight(iter) + currEdge.weightToCompare;
AStarEdge nEdge = map.get(neighborNode);
if (nEdge == null || nEdge.weightToCompare > alreadyVisitedWeight) {
tmpLat = graph.getLatitude(neighborNode);
tmpLon = graph.getLongitude(neighborNode);
currWeightToGoal = dist.calcDistKm(toLat, toLon, tmpLat, tmpLon);
currWeightToGoal = applyWeight(currWeightToGoal);
distEstimation = alreadyVisitedWeight + currWeightToGoal;
if (nEdge == null) {
nEdge = new AStarEdge(neighborNode, distEstimation, alreadyVisitedWeight);
map.put(neighborNode, nEdge);
} else {
prioQueueOpenSet.remove(nEdge);
nEdge.weightToCompare = alreadyVisitedWeight;
nEdge.weight = distEstimation;
}
nEdge.prevEntry = currEdge;
prioQueueOpenSet.add(nEdge);
updateShortest(nEdge, neighborNode);
}
}
if (to == currVertex)
break;
closedSet.add(currVertex);
currEdge = prioQueueOpenSet.poll();
if (currEdge == null)
return null;
}
// extract path from shortest-path-tree
Path path = new Path();
while (currEdge.prevEntry != null) {
int tmpFrom = currEdge.node;
path.add(tmpFrom);
currEdge = (AStarEdge) currEdge.prevEntry;
path.updateProperties(graph.getIncoming(tmpFrom), currEdge.node);
}
path.add(fromEntry.node);
path.reverseOrder();
return path;
}
private double applyWeight(double currDistToGoal) {
if (AlgoType.FASTEST.equals(type))
return currDistToGoal / CarFlags.MAX_SPEED;
return currDistToGoal;
}
private static class AStarEdge extends EdgeEntry {
// the variable 'weight' is used to let heap select smallest *full* distance.
// but to compare distance we need it only from start:
float weightToCompare;
public AStarEdge(int loc, double weightForHeap, float weightToCompare) {
super(loc, weightForHeap);
// round makes distance smaller => heuristic should underestimate the distance!
this.weightToCompare = (float) weightToCompare;
}
}
}
| core/src/main/java/de/jetsli/graph/routing/AStar.java | /*
* Copyright 2012 Peter Karich [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.jetsli.graph.routing;
import de.jetsli.graph.coll.MyOpenBitSet;
import de.jetsli.graph.reader.CarFlags;
import de.jetsli.graph.storage.EdgeEntry;
import de.jetsli.graph.storage.Graph;
import de.jetsli.graph.util.ApproxCalcDistance;
import de.jetsli.graph.util.CalcDistance;
import de.jetsli.graph.util.EdgeIdIterator;
import de.jetsli.graph.util.GraphUtility;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import java.util.PriorityQueue;
/**
* @author Peter Karich
*/
public class AStar extends AbstractRoutingAlgorithm {
private CalcDistance dist = new ApproxCalcDistance();
public AStar(Graph g) {
super(g);
}
/**
* @param fast if true it enables approximative distance calculation from lat,lon values
*/
public AStar setFast(boolean fast) {
if (fast)
dist = new ApproxCalcDistance();
else
dist = new CalcDistance();
return this;
}
@Override public Path calcPath(int from, int to) {
MyOpenBitSet closedSet = new MyOpenBitSet(graph.getNodes());
TIntObjectMap<AStarEdge> map = new TIntObjectHashMap<AStarEdge>();
PriorityQueue<AStarEdge> prioQueueOpenSet = new PriorityQueue<AStarEdge>();
double toLat = graph.getLatitude(to);
double toLon = graph.getLongitude(to);
double tmpLat = graph.getLatitude(from);
double tmpLon = graph.getLongitude(from);
double currWeightToGoal = dist.calcDistKm(toLat, toLon, tmpLat, tmpLon);
currWeightToGoal = applyWeight(currWeightToGoal);
double distEstimation = 0 + currWeightToGoal;
AStarEdge fromEntry = new AStarEdge(from, distEstimation, 0);
AStarEdge currEdge = fromEntry;
while (true) {
int currVertex = currEdge.node;
EdgeIdIterator iter = graph.getOutgoing(currVertex);
while (iter.next()) {
int neighborNode = iter.nodeId();
if (closedSet.contains(neighborNode))
continue;
float alreadyVisitedWeight = (float) getWeight(iter) + currEdge.weightToCompare;
AStarEdge nEdge = map.get(neighborNode);
if (nEdge == null || nEdge.weightToCompare > alreadyVisitedWeight) {
tmpLat = graph.getLatitude(neighborNode);
tmpLon = graph.getLongitude(neighborNode);
currWeightToGoal = dist.calcDistKm(toLat, toLon, tmpLat, tmpLon);
currWeightToGoal = applyWeight(currWeightToGoal);
distEstimation = alreadyVisitedWeight + currWeightToGoal;
if (nEdge == null) {
nEdge = new AStarEdge(neighborNode, distEstimation, alreadyVisitedWeight);
map.put(neighborNode, nEdge);
} else {
prioQueueOpenSet.remove(nEdge);
nEdge.weightToCompare = alreadyVisitedWeight;
nEdge.weight = distEstimation;
}
nEdge.prevEntry = currEdge;
prioQueueOpenSet.add(nEdge);
}
// TODO optimize: call only if necessary
updateShortest(nEdge, neighborNode);
}
if (to == currVertex)
break;
closedSet.add(currVertex);
currEdge = prioQueueOpenSet.poll();
if (currEdge == null)
return null;
}
// extract path from shortest-path-tree
Path path = new Path();
while (currEdge.prevEntry != null) {
int tmpFrom = currEdge.node;
path.add(tmpFrom);
currEdge = (AStarEdge) currEdge.prevEntry;
path.updateProperties(graph.getIncoming(tmpFrom), currEdge.node);
}
path.add(fromEntry.node);
path.reverseOrder();
return path;
}
private double applyWeight(double currDistToGoal) {
if (AlgoType.FASTEST.equals(type))
return currDistToGoal / CarFlags.MAX_SPEED;
return currDistToGoal;
}
private static class AStarEdge extends EdgeEntry {
// the variable 'weight' is used to let heap select smallest *full* distance.
// but to compare distance we need it only from start:
float weightToCompare;
public AStarEdge(int loc, double weightForHeap, float weightToCompare) {
super(loc, weightForHeap);
// round makes distance smaller => heuristic should underestimate the distance!
this.weightToCompare = (float) weightToCompare;
}
}
}
| minor perf improvement for astar
| core/src/main/java/de/jetsli/graph/routing/AStar.java | minor perf improvement for astar |
|
Java | apache-2.0 | 1004a88942a18f3f91fed116b24bfe3e43f5e617 | 0 | leftouterjoin/jackrabbit-oak,kwin/jackrabbit-oak,alexkli/jackrabbit-oak,leftouterjoin/jackrabbit-oak,yesil/jackrabbit-oak,kwin/jackrabbit-oak,tripodsan/jackrabbit-oak,alexparvulescu/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,joansmith/jackrabbit-oak,catholicon/jackrabbit-oak,davidegiannella/jackrabbit-oak,francescomari/jackrabbit-oak,leftouterjoin/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,code-distillery/jackrabbit-oak,stillalex/jackrabbit-oak,davidegiannella/jackrabbit-oak,stillalex/jackrabbit-oak,bdelacretaz/jackrabbit-oak,code-distillery/jackrabbit-oak,anchela/jackrabbit-oak,rombert/jackrabbit-oak,ieb/jackrabbit-oak,alexkli/jackrabbit-oak,kwin/jackrabbit-oak,kwin/jackrabbit-oak,chetanmeh/jackrabbit-oak,kwin/jackrabbit-oak,rombert/jackrabbit-oak,mduerig/jackrabbit-oak,afilimonov/jackrabbit-oak,tripodsan/jackrabbit-oak,catholicon/jackrabbit-oak,francescomari/jackrabbit-oak,mduerig/jackrabbit-oak,chetanmeh/jackrabbit-oak,mduerig/jackrabbit-oak,anchela/jackrabbit-oak,alexparvulescu/jackrabbit-oak,anchela/jackrabbit-oak,meggermo/jackrabbit-oak,code-distillery/jackrabbit-oak,alexparvulescu/jackrabbit-oak,yesil/jackrabbit-oak,joansmith/jackrabbit-oak,chetanmeh/jackrabbit-oak,leftouterjoin/jackrabbit-oak,stillalex/jackrabbit-oak,francescomari/jackrabbit-oak,meggermo/jackrabbit-oak,chetanmeh/jackrabbit-oak,mduerig/jackrabbit-oak,meggermo/jackrabbit-oak,code-distillery/jackrabbit-oak,bdelacretaz/jackrabbit-oak,chetanmeh/jackrabbit-oak,yesil/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,alexkli/jackrabbit-oak,francescomari/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,joansmith/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,afilimonov/jackrabbit-oak,anchela/jackrabbit-oak,catholicon/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,alexkli/jackrabbit-oak,davidegiannella/jackrabbit-oak,catholicon/jackrabbit-oak,tripodsan/jackrabbit-oak,davidegiannella/jackrabbit-oak,afilimonov/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,ieb/jackrabbit-oak,rombert/jackrabbit-oak,stillalex/jackrabbit-oak,code-distillery/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,bdelacretaz/jackrabbit-oak,alexparvulescu/jackrabbit-oak,meggermo/jackrabbit-oak,rombert/jackrabbit-oak,joansmith/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,bdelacretaz/jackrabbit-oak,ieb/jackrabbit-oak,tripodsan/jackrabbit-oak,anchela/jackrabbit-oak,meggermo/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,alexparvulescu/jackrabbit-oak,davidegiannella/jackrabbit-oak,mduerig/jackrabbit-oak,ieb/jackrabbit-oak,yesil/jackrabbit-oak,afilimonov/jackrabbit-oak,stillalex/jackrabbit-oak,alexkli/jackrabbit-oak,joansmith/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.mongomk.prototype;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nonnull;
import org.apache.jackrabbit.mk.api.MicroKernel;
import org.apache.jackrabbit.mk.api.MicroKernelException;
import org.apache.jackrabbit.mk.blobs.BlobStore;
import org.apache.jackrabbit.mk.blobs.MemoryBlobStore;
import org.apache.jackrabbit.mk.json.JsopReader;
import org.apache.jackrabbit.mk.json.JsopStream;
import org.apache.jackrabbit.mk.json.JsopTokenizer;
import org.apache.jackrabbit.mongomk.impl.blob.MongoBlobStore;
import org.apache.jackrabbit.mongomk.prototype.Node.Children;
import org.apache.jackrabbit.oak.commons.PathUtils;
import com.mongodb.DB;
/**
* A MicroKernel implementation that stores the data in a MongoDB.
*/
public class MongoMK implements MicroKernel {
/**
* The delay for asynchronous operations (delayed commit propagation and
* cache update).
*/
protected static final long ASYNC_DELAY = 1000;
/**
* For revisions that are older than this many seconds, the MongoMK will
* assume the revision is valid. For more recent changes, the MongoMK needs
* to verify it first (by reading the revision root). The default is
* Integer.MAX_VALUE, meaning no revisions are trusted. Once the garbage
* collector removes old revisions, this value is changed.
*/
private static final int trustedRevisionAge = Integer.MAX_VALUE;
AtomicBoolean isDisposed = new AtomicBoolean();
/**
* The MongoDB store (might be used by multiple MongoMKs).
*/
private final DocumentStore store;
/**
* The MongoDB blob store.
*/
private final BlobStore blobStore;
/**
* The unique cluster id, similar to the unique machine id in MongoDB.
*/
private final int clusterId;
/**
* The node cache.
*
* Key: path@rev
* Value: node
*/
// TODO: should be path@id
private final Map<String, Node> nodeCache = new Cache<String, Node>(1024);
/**
* The unsaved write count increments.
*/
private final Map<String, Long> writeCountIncrements = new HashMap<String, Long>();
/**
* The set of known valid revision.
* The key is the revision id, the value is 1 (because a cache can't be a set).
*/
private final Map<String, Long> revCache = new Cache<String, Long>(1024);
/**
* The last known head revision. This is the last-known revision.
*/
private Revision headRevision;
private Thread backgroundThread;
private final Map<String, String> branchCommits = new HashMap<String, String>();
private Cache<String, Node.Children> nodeChildrenCache =
new Cache<String, Node.Children>(1024);
/**
* Create a new in-memory MongoMK used for testing.
*/
public MongoMK() {
this(new MemoryDocumentStore(), new MemoryBlobStore(), 0);
}
/**
* Create a new MongoMK.
*
* @param db the MongoDB connection (null for in-memory)
* @param clusterId the cluster id (must be unique)
*/
public MongoMK(DB db, int clusterId) {
this(db == null ? new MemoryDocumentStore() : new MongoDocumentStore(db),
db == null ? new MemoryBlobStore() : new MongoBlobStore(db),
clusterId);
}
/**
* Create a new MongoMK.
*
* @param store the store (might be shared)
* @param blobStore the blob store to use
* @param clusterId the cluster id (must be unique)
*/
public MongoMK(DocumentStore store, BlobStore blobStore, int clusterId) {
this.store = store;
this.blobStore = blobStore;
this.clusterId = clusterId;
backgroundThread = new Thread(
new BackgroundOperation(this, isDisposed),
"MongoMK background thread");
backgroundThread.setDaemon(true);
backgroundThread.start();
headRevision = Revision.newRevision(clusterId);
Node n = readNode("/", headRevision);
if (n == null) {
// root node is missing: repository is not initialized
Commit commit = new Commit(headRevision);
n = new Node("/", headRevision);
commit.addNode(n);
commit.apply(store);
}
}
Revision newRevision() {
return Revision.newRevision(clusterId);
}
void runBackgroundOperations() {
// to be implemented
}
public void dispose() {
if (!isDisposed.getAndSet(true)) {
synchronized (isDisposed) {
isDisposed.notifyAll();
}
try {
backgroundThread.join();
} catch (InterruptedException e) {
// ignore
}
store.dispose();
}
}
/**
* Get the node for the given path and revision. The returned object might
* not be modified directly.
*
* @param path
* @param rev
* @return the node
*/
Node getNode(String path, Revision rev) {
String key = path + "@" + rev;
Node node = nodeCache.get(key);
if (node == null) {
node = readNode(path, rev);
if (node != null) {
nodeCache.put(key, node);
}
}
return node;
}
private boolean includeRevision(Revision x, Revision requestRevision) {
if (x.getClusterId() == this.clusterId &&
requestRevision.getClusterId() == this.clusterId) {
// both revisions were created by this cluster node:
// compare timestamps only
return requestRevision.compareRevisionTime(x) >= 0;
}
// TODO currently we only compare the timestamps
return x.compareRevisionTime(requestRevision) >= 0;
}
private boolean isRevisionNewer(Revision x, Revision previous) {
// TODO currently we only compare the timestamps
return x.compareRevisionTime(previous) >= 0;
}
public Node.Children readChildren(String path, String nodeId, Revision rev, int limit) {
Node.Children c;
c = nodeChildrenCache.get(nodeId);
if (c != null) {
return c;
}
String from = PathUtils.concat(path, "a");
from = Node.convertPathToDocumentId(from);
from = from.substring(0, from.length() - 1);
String to = PathUtils.concat(path, "z");
to = Node.convertPathToDocumentId(to);
to = to.substring(0, to.length() - 2) + "0";
List<Map<String, Object>> list = store.query(DocumentStore.Collection.NODES, from, to, limit);
c = new Node.Children(path, nodeId, rev);
for (Map<String, Object> e : list) {
// Filter out deleted children
if (isDeleted(e, rev)) {
continue;
}
// TODO put the whole node in the cache
String id = e.get("_id").toString();
String p = id.substring(2);
c.children.add(p);
}
nodeChildrenCache.put(nodeId, c);
return c;
}
private Node readNode(String path, Revision rev) {
String id = Node.convertPathToDocumentId(path);
Map<String, Object> map = store.find(DocumentStore.Collection.NODES, id);
if (map == null) {
return null;
}
if (isDeleted(map, rev)) {
return null;
}
Node n = new Node(path, rev);
Long w = writeCountIncrements.get(path);
long writeCount = w == null ? 0 : w;
for (String key : map.keySet()) {
if (key.equals("_writeCount")) {
writeCount += (Long) map.get(key);
}
if (key.startsWith("_")) {
// TODO property name escaping
continue;
}
Object v = map.get(key);
@SuppressWarnings("unchecked")
Map<String, String> valueMap = (Map<String, String>) v;
if (valueMap != null) {
Revision latestRev = null;
for (String r : valueMap.keySet()) {
Revision propRev = Revision.fromString(r);
if (includeRevision(propRev, rev)) {
if (latestRev == null || isRevisionNewer(propRev, latestRev)) {
latestRev = propRev;
n.setProperty(key, valueMap.get(r));
}
}
}
}
}
n.setWriteCount(writeCount);
return n;
}
@Override
public String getHeadRevision() throws MicroKernelException {
return headRevision.toString();
}
@Override
public String getRevisionHistory(long since, int maxEntries, String path)
throws MicroKernelException {
// not currently called by oak-core
throw new MicroKernelException("Not implemented");
}
@Override
public String waitForCommit(String oldHeadRevisionId, long timeout)
throws MicroKernelException, InterruptedException {
// not currently called by oak-core
throw new MicroKernelException("Not implemented");
}
@Override
public String getJournal(String fromRevisionId, String toRevisionId,
String path) throws MicroKernelException {
// not currently called by oak-core
throw new MicroKernelException("Not implemented");
}
@Override
public String diff(String fromRevisionId, String toRevisionId, String path,
int depth) throws MicroKernelException {
if (fromRevisionId.equals(toRevisionId)) {
return "";
}
// TODO implement if needed
return "{}";
}
@Override
public boolean nodeExists(String path, String revisionId)
throws MicroKernelException {
Revision rev = Revision.fromString(revisionId);
Node n = getNode(path, rev);
return n != null;
}
@Override
public long getChildNodeCount(String path, String revisionId)
throws MicroKernelException {
// not currently called by oak-core
throw new MicroKernelException("Not implemented");
}
@Override
public String getNodes(String path, String revisionId, int depth,
long offset, int maxChildNodes, String filter)
throws MicroKernelException {
if (depth != 0) {
throw new MicroKernelException("Only depth 0 is supported, depth is " + depth);
}
if (revisionId.startsWith("b")) {
// reading from the branch is reading from the trunk currently
revisionId = revisionId.substring(1).replace('+', ' ').trim();
}
Revision rev = Revision.fromString(revisionId);
Node n = getNode(path, rev);
if (n == null) {
return null;
// throw new MicroKernelException("Node not found at path " + path);
}
JsopStream json = new JsopStream();
boolean includeId = filter != null && filter.contains(":id");
includeId = filter != null && filter.contains(":hash");
json.object();
n.append(json, includeId);
Children c = readChildren(path, n.getId(), rev, maxChildNodes);
for (String s : c.children) {
String name = PathUtils.getName(s);
json.key(name).object().endObject();
}
json.key(":childNodeCount").value(c.children.size());
json.endObject();
String result = json.toString();
// if (filter != null && filter.contains(":hash")) {
// result = result.replaceAll("\":id\"", "\":hash\"");
// }
return result;
}
@Override
public String commit(String rootPath, String json, String revisionId,
String message) throws MicroKernelException {
revisionId = revisionId == null ? headRevision.toString() : revisionId;
JsopReader t = new JsopTokenizer(json);
Revision rev = Revision.newRevision(clusterId);
Commit commit = new Commit(rev);
while (true) {
int r = t.read();
if (r == JsopReader.END) {
break;
}
String path = PathUtils.concat(rootPath, t.readString());
switch (r) {
case '+':
t.read(':');
t.read('{');
parseAddNode(commit, t, path);
break;
case '-':
commit.removeNode(path);
markAsDeleted(path, commit,true);
break;
case '^':
t.read(':');
String value;
if (t.matches(JsopReader.NULL)) {
value = null;
commit.getDiff().tag('^').key(path).value(null);
} else {
value = t.readRawValue().trim();
commit.getDiff().tag('^').key(path).value(null);
}
String p = PathUtils.getParentPath(path);
String propertyName = PathUtils.getName(path);
UpdateOp op = commit.getUpdateOperationForNode(p);
op.addMapEntry(propertyName, rev.toString(), value);
op.increment("_writeCount", 1);
break;
case '>': {
t.read(':');
String sourcePath = path;
String targetPath = t.readString();
if (!PathUtils.isAbsolute(targetPath)) {
targetPath = PathUtils.concat(path, targetPath);
}
commit.moveNode(sourcePath, targetPath);
moveNode(sourcePath, targetPath, commit);
break;
}
case '*': {
// TODO possibly support target position notation
t.read(':');
String target = t.readString();
if (!PathUtils.isAbsolute(target)) {
target = PathUtils.concat(rootPath, target);
}
String to = PathUtils.relativize("/", target);
// TODO support copy operations
break;
}
default:
throw new MicroKernelException("token: " + (char) t.getTokenType());
}
}
if (revisionId.startsWith("b")) {
// just commit to head currently
applyCommit(commit);
return "b" + rev.toString();
// String jsonBranch = branchCommits.remove(revisionId);
// jsonBranch += commit.getDiff().toString();
// String branchRev = revisionId + "+";
// branchCommits.put(branchRev, jsonBranch);
// return branchRev;
}
applyCommit(commit);
return rev.toString();
}
private void moveNode(String sourcePath, String targetPath, Commit commit) {
//TODO Optimize - Move logic would not work well with very move of very large subtrees
//At minimum we can optimize by traversing breadth wise and collect node id
//and fetch them via '$in' queries
//TODO Transient Node - Current logic does not account for operations which are part
//of this commit i.e. transient nodes. If its required it would need to be looked
//into
Node n = getNode(sourcePath, commit.getRevision());
//Node might be deleted already
if(n == null){
return;
}
Node newNode = new Node(targetPath,commit.getRevision());
n.copyTo(newNode);
commit.addNode(newNode);
markAsDeleted(sourcePath,commit,false);
Node.Children c = readChildren(sourcePath, n.getId(),
commit.getRevision(), Integer.MAX_VALUE);
for (String srcChildPath : c.children) {
String childName = PathUtils.getName(srcChildPath);
String destChildPath = PathUtils.concat(targetPath, childName);
moveNode(srcChildPath,destChildPath,commit);
}
}
private void markAsDeleted(String path, Commit commit, boolean subTreeAlso) {
Revision rev = commit.getRevision();
UpdateOp op = commit.getUpdateOperationForNode(path);
op.addMapEntry("_deleted", rev.toString(), "true");
op.increment("_writeCount", 1);
if(subTreeAlso){
// TODO Would cause issue with large number of children.
// Need to be changed
Node n = getNode(path, rev);
Node.Children c = readChildren(path, n.getId(), rev, Integer.MAX_VALUE);
for (String childPath : c.children) {
markAsDeleted(childPath, commit,true);
}
}
//Remove the node from the cache
nodeCache.remove(path + "@" + rev);
}
private boolean isDeleted(Map<String, Object> nodeProps, Revision rev) {
@SuppressWarnings("unchecked")
Map<String, String> valueMap = (Map<String, String>) nodeProps
.get("_deleted");
if (valueMap != null) {
for (Map.Entry<String, String> e : valueMap.entrySet()) {
// TODO What if multiple revisions are there?. Should we sort
// them and then
// determine include revision based on that
Revision propRev = Revision.fromString(e.getKey());
if (includeRevision(propRev, rev)) {
if ("true".equals(e.getValue())) {
return true;
}
}
}
}
return false;
}
private void applyCommit(Commit commit) {
headRevision = commit.getRevision();
if (commit.isEmpty()) {
return;
}
commit.apply(store);
commit.apply(this);
}
public static void parseAddNode(Commit commit, JsopReader t, String path) {
Node n = new Node(path, commit.getRevision());
if (!t.matches('}')) {
do {
String key = t.readString();
t.read(':');
if (t.matches('{')) {
String childPath = PathUtils.concat(path, key);
parseAddNode(commit, t, childPath);
} else {
String value = t.readRawValue().trim();
n.setProperty(key, value);
}
} while (t.matches(','));
t.read('}');
}
commit.addNodeWithDiff(n);
}
@Override
public String branch(String trunkRevisionId) throws MicroKernelException {
// TODO improve implementation if needed
String branchId = "b" + trunkRevisionId;
// branchCommits.put(branchId, "");
return branchId;
}
@Override
public String merge(String branchRevisionId, String message)
throws MicroKernelException {
// reading from the branch is reading from the trunk currently
String revisionId = branchRevisionId.substring(1).replace('+', ' ').trim();
return revisionId;
// TODO improve implementation if needed
// if (!branchRevisionId.startsWith("b")) {
// throw new MicroKernelException("Not a branch: " + branchRevisionId);
// }
//
// String commit = branchCommits.remove(branchRevisionId);
// return commit("", commit, null, null);
}
@Override
@Nonnull
public String rebase(String branchRevisionId, String newBaseRevisionId)
throws MicroKernelException {
// TODO improve implementation if needed
return branchRevisionId;
}
@Override
public long getLength(String blobId) throws MicroKernelException {
try {
return blobStore.getBlobLength(blobId);
} catch (Exception e) {
throw new MicroKernelException(e);
}
}
@Override
public int read(String blobId, long pos, byte[] buff, int off, int length)
throws MicroKernelException {
try {
return blobStore.readBlob(blobId, pos, buff, off, length);
} catch (Exception e) {
throw new MicroKernelException(e);
}
}
@Override
public String write(InputStream in) throws MicroKernelException {
try {
return blobStore.writeBlob(in);
} catch (Exception e) {
throw new MicroKernelException(e);
}
}
public DocumentStore getDocumentStore() {
return store;
}
/**
* A simple cache.
*
* @param <K> the key type
* @param <V> the value type
*/
static class Cache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private int size;
Cache(int size) {
super(size, (float) 0.75, true);
this.size = size;
}
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > size;
}
}
/**
* A background thread.
*/
static class BackgroundOperation implements Runnable {
final WeakReference<MongoMK> ref;
private final AtomicBoolean isDisposed;
BackgroundOperation(MongoMK mk, AtomicBoolean isDisposed) {
ref = new WeakReference<MongoMK>(mk);
this.isDisposed = isDisposed;
}
public void run() {
while (!isDisposed.get()) {
synchronized (isDisposed) {
try {
isDisposed.wait(ASYNC_DELAY);
} catch (InterruptedException e) {
// ignore
}
}
MongoMK mk = ref.get();
if (mk != null) {
mk.runBackgroundOperations();
}
}
}
}
public void incrementWriteCount(String path) {
Long value = writeCountIncrements.get(path);
value = value == null ? 1 : value + 1;
writeCountIncrements.put(path, value);
}
}
| oak-mongomk/src/main/java/org/apache/jackrabbit/mongomk/prototype/MongoMK.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.mongomk.prototype;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nonnull;
import org.apache.jackrabbit.mk.api.MicroKernel;
import org.apache.jackrabbit.mk.api.MicroKernelException;
import org.apache.jackrabbit.mk.blobs.BlobStore;
import org.apache.jackrabbit.mk.blobs.MemoryBlobStore;
import org.apache.jackrabbit.mk.json.JsopReader;
import org.apache.jackrabbit.mk.json.JsopStream;
import org.apache.jackrabbit.mk.json.JsopTokenizer;
import org.apache.jackrabbit.mongomk.impl.blob.MongoBlobStore;
import org.apache.jackrabbit.mongomk.prototype.Node.Children;
import org.apache.jackrabbit.oak.commons.PathUtils;
import com.mongodb.DB;
/**
* A MicroKernel implementation that stores the data in a MongoDB.
*/
public class MongoMK implements MicroKernel {
/**
* The delay for asynchronous operations (delayed commit propagation and
* cache update).
*/
protected static final long ASYNC_DELAY = 1000;
/**
* For revisions that are older than this many seconds, the MongoMK will
* assume the revision is valid. For more recent changes, the MongoMK needs
* to verify it first (by reading the revision root). The default is
* Integer.MAX_VALUE, meaning no revisions are trusted. Once the garbage
* collector removes old revisions, this value is changed.
*/
private static final int trustedRevisionAge = Integer.MAX_VALUE;
AtomicBoolean isDisposed = new AtomicBoolean();
/**
* The MongoDB store (might be used by multiple MongoMKs).
*/
private final DocumentStore store;
/**
* The MongoDB blob store.
*/
private final BlobStore blobStore;
/**
* The unique cluster id, similar to the unique machine id in MongoDB.
*/
private final int clusterId;
/**
* The node cache.
*
* Key: path@rev
* Value: node
*/
// TODO: should be path@id
private final Map<String, Node> nodeCache = new Cache<String, Node>(1024);
/**
* The unsaved write count increments.
*/
private final Map<String, Long> writeCountIncrements = new HashMap<String, Long>();
/**
* The set of known valid revision.
* The key is the revision id, the value is 1 (because a cache can't be a set).
*/
private final Map<String, Long> revCache = new Cache<String, Long>(1024);
/**
* The last known head revision. This is the last-known revision.
*/
private Revision headRevision;
private Thread backgroundThread;
private final Map<String, String> branchCommits = new HashMap<String, String>();
private Cache<String, Node.Children> nodeChildrenCache =
new Cache<String, Node.Children>(1024);
/**
* Create a new in-memory MongoMK used for testing.
*/
public MongoMK() {
this(new MemoryDocumentStore(), new MemoryBlobStore(), 0);
}
/**
* Create a new MongoMK.
*
* @param db the MongoDB connection (null for in-memory)
* @param clusterId the cluster id (must be unique)
*/
public MongoMK(DB db, int clusterId) {
this(db == null ? new MemoryDocumentStore() : new MongoDocumentStore(db),
db == null ? new MemoryBlobStore() : new MongoBlobStore(db),
clusterId);
}
/**
* Create a new MongoMK.
*
* @param store the store (might be shared)
* @param blobStore the blob store to use
* @param clusterId the cluster id (must be unique)
*/
public MongoMK(DocumentStore store, BlobStore blobStore, int clusterId) {
this.store = store;
this.blobStore = blobStore;
this.clusterId = clusterId;
backgroundThread = new Thread(
new BackgroundOperation(this, isDisposed),
"MongoMK background thread");
backgroundThread.setDaemon(true);
backgroundThread.start();
headRevision = Revision.newRevision(clusterId);
Node n = readNode("/", headRevision);
if (n == null) {
// root node is missing: repository is not initialized
Commit commit = new Commit(headRevision);
n = new Node("/", headRevision);
commit.addNode(n);
commit.apply(store);
}
}
Revision newRevision() {
return Revision.newRevision(clusterId);
}
void runBackgroundOperations() {
// to be implemented
}
public void dispose() {
if (!isDisposed.getAndSet(true)) {
synchronized (isDisposed) {
isDisposed.notifyAll();
}
try {
backgroundThread.join();
} catch (InterruptedException e) {
// ignore
}
store.dispose();
}
}
/**
* Get the node for the given path and revision. The returned object might
* not be modified directly.
*
* @param path
* @param rev
* @return the node
*/
Node getNode(String path, Revision rev) {
String key = path + "@" + rev;
Node node = nodeCache.get(key);
if (node == null) {
node = readNode(path, rev);
if (node != null) {
nodeCache.put(key, node);
}
}
return node;
}
private boolean includeRevision(Revision x, Revision requestRevision) {
if (x.getClusterId() == this.clusterId &&
requestRevision.getClusterId() == this.clusterId) {
// both revisions were created by this cluster node:
// compare timestamps only
return requestRevision.compareRevisionTime(x) >= 0;
}
// TODO currently we only compare the timestamps
return x.compareRevisionTime(requestRevision) >= 0;
}
private boolean isRevisionNewer(Revision x, Revision previous) {
// TODO currently we only compare the timestamps
return x.compareRevisionTime(previous) >= 0;
}
public Node.Children readChildren(String path, String nodeId, Revision rev, int limit) {
Node.Children c;
c = nodeChildrenCache.get(nodeId);
if (c != null) {
return c;
}
String from = PathUtils.concat(path, "a");
from = Node.convertPathToDocumentId(from);
from = from.substring(0, from.length() - 1);
String to = PathUtils.concat(path, "z");
to = Node.convertPathToDocumentId(to);
to = to.substring(0, to.length() - 2) + "0";
List<Map<String, Object>> list = store.query(DocumentStore.Collection.NODES, from, to, limit);
c = new Node.Children(path, nodeId, rev);
for (Map<String, Object> e : list) {
// Filter out deleted children
if (isDeleted(e, rev)) {
continue;
}
// TODO put the whole node in the cache
String id = e.get("_id").toString();
String p = id.substring(2);
c.children.add(p);
}
nodeChildrenCache.put(nodeId, c);
return c;
}
private Node readNode(String path, Revision rev) {
String id = Node.convertPathToDocumentId(path);
Map<String, Object> map = store.find(DocumentStore.Collection.NODES, id);
if (map == null) {
return null;
}
if (isDeleted(map, rev)) {
return null;
}
Node n = new Node(path, rev);
Long w = writeCountIncrements.get(path);
long writeCount = w == null ? 0 : w;
for (String key : map.keySet()) {
if (key.equals("_writeCount")) {
writeCount += (Long) map.get(key);
}
if (key.startsWith("_")) {
// TODO property name escaping
continue;
}
Object v = map.get(key);
@SuppressWarnings("unchecked")
Map<String, String> valueMap = (Map<String, String>) v;
if (valueMap != null) {
Revision latestRev = null;
for (String r : valueMap.keySet()) {
Revision propRev = Revision.fromString(r);
if (includeRevision(propRev, rev)) {
if (latestRev == null || isRevisionNewer(propRev, latestRev)) {
latestRev = propRev;
n.setProperty(key, valueMap.get(r));
}
}
}
}
}
n.setWriteCount(writeCount);
return n;
}
@Override
public String getHeadRevision() throws MicroKernelException {
return headRevision.toString();
}
@Override
public String getRevisionHistory(long since, int maxEntries, String path)
throws MicroKernelException {
// not currently called by oak-core
throw new MicroKernelException("Not implemented");
}
@Override
public String waitForCommit(String oldHeadRevisionId, long timeout)
throws MicroKernelException, InterruptedException {
// not currently called by oak-core
throw new MicroKernelException("Not implemented");
}
@Override
public String getJournal(String fromRevisionId, String toRevisionId,
String path) throws MicroKernelException {
// not currently called by oak-core
throw new MicroKernelException("Not implemented");
}
@Override
public String diff(String fromRevisionId, String toRevisionId, String path,
int depth) throws MicroKernelException {
if (fromRevisionId.equals(toRevisionId)) {
return "";
}
// TODO implement if needed
return "{}";
}
@Override
public boolean nodeExists(String path, String revisionId)
throws MicroKernelException {
Revision rev = Revision.fromString(revisionId);
Node n = getNode(path, rev);
return n != null;
}
@Override
public long getChildNodeCount(String path, String revisionId)
throws MicroKernelException {
// not currently called by oak-core
throw new MicroKernelException("Not implemented");
}
@Override
public String getNodes(String path, String revisionId, int depth,
long offset, int maxChildNodes, String filter)
throws MicroKernelException {
if (depth != 0) {
throw new MicroKernelException("Only depth 0 is supported, depth is " + depth);
}
if (revisionId.startsWith("b")) {
// reading from the branch is reading from the trunk currently
revisionId = revisionId.substring(1).replace('+', ' ').trim();
}
Revision rev = Revision.fromString(revisionId);
Node n = getNode(path, rev);
if (n == null) {
return null;
// throw new MicroKernelException("Node not found at path " + path);
}
JsopStream json = new JsopStream();
boolean includeId = filter != null && filter.contains(":id");
includeId = filter != null && filter.contains(":hash");
json.object();
n.append(json, includeId);
Children c = readChildren(path, n.getId(), rev, maxChildNodes);
for (String s : c.children) {
String name = PathUtils.getName(s);
json.key(name).object().endObject();
}
json.key(":childNodeCount").value(c.children.size());
json.endObject();
String result = json.toString();
// if (filter != null && filter.contains(":hash")) {
// result = result.replaceAll("\":id\"", "\":hash\"");
// }
return result;
}
@Override
public String commit(String rootPath, String json, String revisionId,
String message) throws MicroKernelException {
revisionId = revisionId == null ? headRevision.toString() : revisionId;
JsopReader t = new JsopTokenizer(json);
Revision rev = Revision.newRevision(clusterId);
Commit commit = new Commit(rev);
while (true) {
int r = t.read();
if (r == JsopReader.END) {
break;
}
String path = PathUtils.concat(rootPath, t.readString());
switch (r) {
case '+':
t.read(':');
t.read('{');
parseAddNode(commit, t, path);
break;
case '-':
commit.removeNode(path);
markAsDeleted(path, commit,true);
break;
case '^':
t.read(':');
String value;
if (t.matches(JsopReader.NULL)) {
value = null;
commit.getDiff().tag('^').key(path).value(null);
} else {
value = t.readRawValue().trim();
commit.getDiff().tag('^').key(path).value(null);
}
String p = PathUtils.getParentPath(path);
String propertyName = PathUtils.getName(path);
UpdateOp op = commit.getUpdateOperationForNode(p);
op.addMapEntry(propertyName, rev.toString(), value);
op.increment("_writeCount", 1);
break;
case '>': {
t.read(':');
String sourcePath = path;
String targetPath = t.readString();
if (!PathUtils.isAbsolute(targetPath)) {
targetPath = PathUtils.concat(path, targetPath);
}
commit.moveNode(sourcePath, targetPath);
moveNode(sourcePath, targetPath, commit);
break;
}
case '*': {
// TODO possibly support target position notation
t.read(':');
String target = t.readString();
if (!PathUtils.isAbsolute(target)) {
target = PathUtils.concat(rootPath, target);
}
String to = PathUtils.relativize("/", target);
// TODO support copy operations
break;
}
default:
throw new MicroKernelException("token: " + (char) t.getTokenType());
}
}
if (revisionId.startsWith("b")) {
// just commit to head currently
applyCommit(commit);
return "b" + rev.toString();
// String jsonBranch = branchCommits.remove(revisionId);
// jsonBranch += commit.getDiff().toString();
// String branchRev = revisionId + "+";
// branchCommits.put(branchRev, jsonBranch);
// return branchRev;
}
applyCommit(commit);
return rev.toString();
}
private void moveNode(String sourcePath, String targetPath, Commit commit) {
//TODO Optimize - Move logic would not work well with very move of very large subtrees
//At minimum we can optimize by traversing breadth wise and collect node id
//and fetch them via '$in' queries
//TODO Transient Node - Current logic does not account for operations which are part
//of this commit i.e. transient nodes. If its required it would need to be looked
//into
Node n = getNode(sourcePath, commit.getRevision());
//Node might be deleted already
if(n == null){
return;
}
Node newNode = new Node(targetPath,commit.getRevision());
n.copyTo(newNode);
commit.addNode(newNode);
markAsDeleted(sourcePath,commit,false);
Node.Children c = readChildren(sourcePath, n.getId(),
commit.getRevision(), Integer.MAX_VALUE);
for (String srcChildPath : c.children) {
String childName = PathUtils.getName(srcChildPath);
String destChildPath = PathUtils.concat(targetPath, childName);
moveNode(srcChildPath,destChildPath,commit);
}
}
private void markAsDeleted(String path, Commit commit, boolean subTreeAlso) {
Revision rev = commit.getRevision();
UpdateOp op = commit.getUpdateOperationForNode(path);
op.addMapEntry("_deleted", rev.toString(), "true");
op.increment("_writeCount", 1);
nodeCache.remove(path + "@" + rev);
if(subTreeAlso){
// TODO Would cause issue with large number of children.
// Need to be changed
Node n = getNode(path, rev);
Node.Children c = readChildren(path, n.getId(), rev, Integer.MAX_VALUE);
for (String childPath : c.children) {
markAsDeleted(childPath, commit,true);
}
}
}
private boolean isDeleted(Map<String, Object> nodeProps, Revision rev) {
@SuppressWarnings("unchecked")
Map<String, String> valueMap = (Map<String, String>) nodeProps
.get("_deleted");
if (valueMap != null) {
for (Map.Entry<String, String> e : valueMap.entrySet()) {
// TODO What if multiple revisions are there?. Should we sort
// them and then
// determine include revision based on that
Revision propRev = Revision.fromString(e.getKey());
if (includeRevision(propRev, rev)) {
if ("true".equals(e.getValue())) {
return true;
}
}
}
}
return false;
}
private void applyCommit(Commit commit) {
headRevision = commit.getRevision();
if (commit.isEmpty()) {
return;
}
commit.apply(store);
commit.apply(this);
}
public static void parseAddNode(Commit commit, JsopReader t, String path) {
Node n = new Node(path, commit.getRevision());
if (!t.matches('}')) {
do {
String key = t.readString();
t.read(':');
if (t.matches('{')) {
String childPath = PathUtils.concat(path, key);
parseAddNode(commit, t, childPath);
} else {
String value = t.readRawValue().trim();
n.setProperty(key, value);
}
} while (t.matches(','));
t.read('}');
}
commit.addNodeWithDiff(n);
}
@Override
public String branch(String trunkRevisionId) throws MicroKernelException {
// TODO improve implementation if needed
String branchId = "b" + trunkRevisionId;
// branchCommits.put(branchId, "");
return branchId;
}
@Override
public String merge(String branchRevisionId, String message)
throws MicroKernelException {
// reading from the branch is reading from the trunk currently
String revisionId = branchRevisionId.substring(1).replace('+', ' ').trim();
return revisionId;
// TODO improve implementation if needed
// if (!branchRevisionId.startsWith("b")) {
// throw new MicroKernelException("Not a branch: " + branchRevisionId);
// }
//
// String commit = branchCommits.remove(branchRevisionId);
// return commit("", commit, null, null);
}
@Override
@Nonnull
public String rebase(String branchRevisionId, String newBaseRevisionId)
throws MicroKernelException {
// TODO improve implementation if needed
return branchRevisionId;
}
@Override
public long getLength(String blobId) throws MicroKernelException {
try {
return blobStore.getBlobLength(blobId);
} catch (Exception e) {
throw new MicroKernelException(e);
}
}
@Override
public int read(String blobId, long pos, byte[] buff, int off, int length)
throws MicroKernelException {
try {
return blobStore.readBlob(blobId, pos, buff, off, length);
} catch (Exception e) {
throw new MicroKernelException(e);
}
}
@Override
public String write(InputStream in) throws MicroKernelException {
try {
return blobStore.writeBlob(in);
} catch (Exception e) {
throw new MicroKernelException(e);
}
}
public DocumentStore getDocumentStore() {
return store;
}
/**
* A simple cache.
*
* @param <K> the key type
* @param <V> the value type
*/
static class Cache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private int size;
Cache(int size) {
super(size, (float) 0.75, true);
this.size = size;
}
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > size;
}
}
/**
* A background thread.
*/
static class BackgroundOperation implements Runnable {
final WeakReference<MongoMK> ref;
private final AtomicBoolean isDisposed;
BackgroundOperation(MongoMK mk, AtomicBoolean isDisposed) {
ref = new WeakReference<MongoMK>(mk);
this.isDisposed = isDisposed;
}
public void run() {
while (!isDisposed.get()) {
synchronized (isDisposed) {
try {
isDisposed.wait(ASYNC_DELAY);
} catch (InterruptedException e) {
// ignore
}
}
MongoMK mk = ref.get();
if (mk != null) {
mk.runBackgroundOperations();
}
}
}
}
public void incrementWriteCount(String path) {
Long value = writeCountIncrements.get(path);
value = value == null ? 1 : value + 1;
writeCountIncrements.put(path, value);
}
}
| OAK-619 - Lock-free MongoMK implementation
Moving the remove from cache step to the later part.
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1449805 13f79535-47bb-0310-9956-ffa450edef68
| oak-mongomk/src/main/java/org/apache/jackrabbit/mongomk/prototype/MongoMK.java | OAK-619 - Lock-free MongoMK implementation |
|
Java | apache-2.0 | 0aa7429c1ebf63b6762daeca4cb93daf8ca080c5 | 0 | pkhokhlov/OptimalCombinations | package optimalcombinations;
import java.util.ArrayList;
/**
* @author Pavel Khokhlov
*/
public class DecreasingUnitPoolMethod
{
// TODO: include static methods for calculation
Group best_;
int groupSize_;
int iterations_ = 0;
ArrayList<Unit> pool_;
public DecreasingUnitPoolMethod(ArrayList<Unit> pool)
{
pool_ = pool;
groupSize_ = 3; //TODO change for all group sizes
}
/**
* precondition: the pool is evenly divisible by the groupSize
* @return
*/
public void findHappiestGroup()
{
int highestScore = 0;
for(int a = 0; a < pool_.size() - 2; a++)
{
for(int b = a + 1; b < pool_.size() - 1; b++)
{
for(int c = b + 1; c < pool_.size(); c++)
{
Group temp = new Group(pool_.get(a), pool_.get(b), pool_.get(c)); // only works for groups of size 3
int gScore = temp.getGroupScore();
if(gScore > highestScore)
{
highestScore = gScore;
best_ = temp;
}
}
}
}
}
/**
* pool_.remove(...) works because the pool_ is partly made of the units within best_
*/
public void removeFromPool()
{
for(int i = 0; i < best_.getMembers().size(); i++)
{
pool_.remove(best_.getMembers().get(i));
}
}
public ArrayList<Group> findHappiestGroups()
{
ArrayList<Group> happiest = new ArrayList<Group>();
while(pool_.size() > 0)
{
findHappiestGroup();
happiest.add(best_);
removeFromPool();
}
return happiest;
}
}
/* WORKING */ | src/optimalcombinations/DecreasingUnitPoolMethod.java | package optimalcombinations;
import java.util.ArrayList;
/**
* @author Pavel Khokhlov
*/
public class DecreasingUnitPoolMethod
{
// TODO: include static methods for calculation
Group best_;
int groupSize_;
int iterations_ = 0;
ArrayList<Unit> pool_;
public DecreasingUnitPoolMethod(ArrayList<Unit> pool)
{
pool_ = pool;
groupSize_ = 3; //TODO change for all groupsizes
}
/**
* precondition: the pool is evenly divisible by the groupSize
* @return
*/
public void findHappiestGroup()
{
int highestScore = 0;
for(int a = 0; a < pool_.size() - 2; a++)
{
for(int b = a + 1; b < pool_.size() - 1; b++)
{
for(int c = b + 1; c < pool_.size(); c++)
{
Group temp = new Group(pool_.get(a), pool_.get(b), pool_.get(c)); // only works for groups of size 3
int gScore = temp.getGroupScore();
if(gScore > highestScore)
{
highestScore = gScore;
best_ = temp;
}
}
}
}
}
/**
* pool_.remove(...) works because the pool_ is partly made of the units within best_
*/
public void removeFromPool()
{
for(int i = 0; i < best_.getMembers().size(); i++)
{
pool_.remove(best_.getMembers().get(i));
}
}
public ArrayList<Group> findHappiestGroups()
{
ArrayList<Group> happiest = new ArrayList<Group>();
while(pool_.size() > 0)
{
findHappiestGroup();
happiest.add(best_);
removeFromPool();
}
return happiest;
}
} | TESTING | src/optimalcombinations/DecreasingUnitPoolMethod.java | TESTING |
|
Java | apache-2.0 | 0bcbc52fe4f04a092736c557ad201c60b2c768d5 | 0 | QuickBlox/q-municate-android | package com.quickblox.q_municate.ui.chats;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.quickblox.internal.core.exception.QBResponseException;
import com.quickblox.module.chat.model.QBDialog;
import com.quickblox.module.content.model.QBFile;
import com.quickblox.q_municate.R;
import com.quickblox.q_municate.caching.DatabaseManager;
import com.quickblox.q_municate.caching.tables.MessageTable;
import com.quickblox.q_municate.model.Friend;
import com.quickblox.q_municate.qb.commands.QBUpdateDialogCommand;
import com.quickblox.q_municate.qb.helpers.QBMultiChatHelper;
import com.quickblox.q_municate.service.QBService;
import com.quickblox.q_municate.service.QBServiceConsts;
import com.quickblox.q_municate.utils.Consts;
import com.quickblox.q_municate.utils.ErrorUtils;
import com.quickblox.q_municate.utils.ReceiveFileListener;
import com.quickblox.q_municate.utils.ReceiveImageFileTask;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class GroupDialogActivity extends BaseDialogActivity implements ReceiveFileListener {
private String groupName;
public GroupDialogActivity() {
super(R.layout.activity_dialog, QBService.MULTI_CHAT_HELPER);
}
public static void start(Context context, ArrayList<Friend> friends) {
Intent intent = new Intent(context, GroupDialogActivity.class);
intent.putExtra(QBServiceConsts.EXTRA_FRIENDS, friends);
context.startActivity(intent);
}
public static void start(Context context, QBDialog qbDialog) {
Intent intent = new Intent(context, GroupDialogActivity.class);
intent.putExtra(QBServiceConsts.EXTRA_ROOM_JID, qbDialog.getDialogId());
intent.putExtra(QBServiceConsts.EXTRA_DIALOG, qbDialog);
context.startActivity(intent);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().hasExtra(QBServiceConsts.EXTRA_ROOM_JID)) {
dialogId = getIntent().getStringExtra(QBServiceConsts.EXTRA_ROOM_JID);
}
dialog = (QBDialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
initListView();
startLoadDialogMessages();
registerForContextMenu(messagesListView);
}
@Override
protected void onUpdateChatDialog() {
if (messagesAdapter != null && !messagesAdapter.isEmpty()) {
startUpdateChatDialog();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
removeActions();
}
protected void removeActions() {
removeAction(QBServiceConsts.LOAD_ATTACH_FILE_SUCCESS_ACTION);
removeAction(QBServiceConsts.LOAD_ATTACH_FILE_FAIL_ACTION);
}
@Override
protected void onFileSelected(Uri originalUri) {
try {
ParcelFileDescriptor descriptor = getContentResolver().openFileDescriptor(originalUri, "r");
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(descriptor.getFileDescriptor(), null, bitmapOptions);
new ReceiveImageFileTask(GroupDialogActivity.this).execute(imageHelper, bitmap, true);
} catch (FileNotFoundException e) {
ErrorUtils.showError(this, e.getMessage());
}
}
@Override
protected void onFileLoaded(QBFile file) {
try {
((QBMultiChatHelper) chatHelper).sendGroupMessageWithAttachImage(dialog.getRoomJid(), file);
} catch (QBResponseException e) {
ErrorUtils.showError(this, e);
}
}
@Override
protected Bundle generateBundleToInitDialog() {
return null;
}
private void startUpdateChatDialog() {
QBDialog dialog = getQBDialog();
if (dialog != null) {
QBUpdateDialogCommand.start(this, dialog);
}
}
private QBDialog getQBDialog() {
Cursor cursor = (Cursor) messagesAdapter.getItem(messagesAdapter.getCount() - 1);
String lastMessage = cursor.getString(cursor.getColumnIndex(MessageTable.Cols.BODY));
long dateSent = cursor.getLong(cursor.getColumnIndex(MessageTable.Cols.TIME));
dialog.setLastMessage(lastMessage);
dialog.setLastMessageDateSent(dateSent);
dialog.setUnreadMessageCount(Consts.ZERO_INT_VALUE);
return dialog;
}
private void updateChatData() {
dialog = DatabaseManager.getDialogByDialogId(this, dialogId);
if (dialog != null) {
groupName = dialog.getName();
updateActionBar();
}
}
private void initListView() {
messagesAdapter = new GroupDialogMessagesAdapter(this, getAllDialogMessagesByDialogId(), this, dialog);
messagesListView.setAdapter(messagesAdapter);
}
private void updateActionBar() {
actionBar.setTitle(groupName);
actionBar.setSubtitle(getString(R.string.gdd_participants, dialog.getOccupants().size()));
actionBar.setLogo(R.drawable.placeholder_group);
if(!TextUtils.isEmpty(dialog.getPhotoUrl())) {
loadLogoActionBar(dialog.getPhotoUrl());
}
}
@Override
public void onCachedImageFileReceived(File file) {
startLoadAttachFile(file);
}
@Override
public void onAbsolutePathExtFileReceived(String absolutePath) {
}
public void sendMessageOnClick(View view) {
try {
((QBMultiChatHelper) chatHelper).sendGroupMessage(dialog.getRoomJid(),
messageEditText.getText().toString());
} catch (QBResponseException e) {
ErrorUtils.showError(this, e);
}
messageEditText.setText(Consts.EMPTY_STRING);
scrollListView();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.group_dialog_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
navigateToParent();
return true;
case R.id.action_attach:
attachButtonOnClick();
return true;
case R.id.action_group_details:
GroupDialogDetailsActivity.start(this, dialog.getDialogId());
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater m = getMenuInflater();
m.inflate(R.menu.group_dialog_ctx_menu, menu);
}
@Override
protected void onResume() {
super.onResume();
updateChatData();
scrollListView();
}
} | Q-municate/src/main/java/com/quickblox/q_municate/ui/chats/GroupDialogActivity.java | package com.quickblox.q_municate.ui.chats;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.quickblox.internal.core.exception.QBResponseException;
import com.quickblox.module.chat.model.QBDialog;
import com.quickblox.module.content.model.QBFile;
import com.quickblox.q_municate.R;
import com.quickblox.q_municate.caching.DatabaseManager;
import com.quickblox.q_municate.caching.tables.MessageTable;
import com.quickblox.q_municate.model.Friend;
import com.quickblox.q_municate.qb.commands.QBUpdateDialogCommand;
import com.quickblox.q_municate.qb.helpers.QBMultiChatHelper;
import com.quickblox.q_municate.service.QBService;
import com.quickblox.q_municate.service.QBServiceConsts;
import com.quickblox.q_municate.utils.Consts;
import com.quickblox.q_municate.utils.ErrorUtils;
import com.quickblox.q_municate.utils.ReceiveFileListener;
import com.quickblox.q_municate.utils.ReceiveImageFileTask;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class GroupDialogActivity extends BaseDialogActivity implements ReceiveFileListener {
private String groupName;
public GroupDialogActivity() {
super(R.layout.activity_dialog, QBService.MULTI_CHAT_HELPER);
}
public static void start(Context context, ArrayList<Friend> friends) {
Intent intent = new Intent(context, GroupDialogActivity.class);
intent.putExtra(QBServiceConsts.EXTRA_FRIENDS, friends);
context.startActivity(intent);
}
public static void start(Context context, QBDialog qbDialog) {
Intent intent = new Intent(context, GroupDialogActivity.class);
intent.putExtra(QBServiceConsts.EXTRA_ROOM_JID, qbDialog.getDialogId());
intent.putExtra(QBServiceConsts.EXTRA_DIALOG, qbDialog);
context.startActivity(intent);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().hasExtra(QBServiceConsts.EXTRA_ROOM_JID)) {
dialogId = getIntent().getStringExtra(QBServiceConsts.EXTRA_ROOM_JID);
}
dialog = (QBDialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
initListView();
startLoadDialogMessages();
registerForContextMenu(messagesListView);
}
@Override
protected void onUpdateChatDialog() {
if (messagesAdapter != null && !messagesAdapter.isEmpty()) {
startUpdateChatDialog();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
removeActions();
}
protected void removeActions() {
removeAction(QBServiceConsts.LOAD_ATTACH_FILE_SUCCESS_ACTION);
removeAction(QBServiceConsts.LOAD_ATTACH_FILE_FAIL_ACTION);
}
@Override
protected void onFileSelected(Uri originalUri) {
try {
ParcelFileDescriptor descriptor = getContentResolver().openFileDescriptor(originalUri, "r");
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(descriptor.getFileDescriptor(), null, bitmapOptions);
new ReceiveImageFileTask(GroupDialogActivity.this).execute(imageHelper, bitmap, true);
} catch (FileNotFoundException e) {
ErrorUtils.showError(this, e.getMessage());
}
}
@Override
protected void onFileLoaded(QBFile file) {
try {
((QBMultiChatHelper) chatHelper).sendGroupMessageWithAttachImage(dialog.getRoomJid(), file);
} catch (QBResponseException e) {
ErrorUtils.showError(this, e);
}
}
@Override
protected Bundle generateBundleToInitDialog() {
return null;
}
private void startUpdateChatDialog() {
QBDialog dialog = getQBDialog();
if (dialog != null) {
QBUpdateDialogCommand.start(this, dialog);
}
}
private QBDialog getQBDialog() {
Cursor cursor = (Cursor) messagesAdapter.getItem(messagesAdapter.getCount() - 1);
String lastMessage = cursor.getString(cursor.getColumnIndex(MessageTable.Cols.BODY));
long dateSent = cursor.getLong(cursor.getColumnIndex(MessageTable.Cols.TIME));
dialog.setLastMessage(lastMessage);
dialog.setLastMessageDateSent(dateSent);
dialog.setUnreadMessageCount(Consts.ZERO_INT_VALUE);
return dialog;
}
private void updateChatData() {
dialog = DatabaseManager.getDialogByDialogId(this, dialogId);
if ( dialog != null) {
groupName = dialog.getName();
updateActionBar();
}
}
private void initListView() {
messagesAdapter = new GroupDialogMessagesAdapter(this, getAllDialogMessagesByDialogId(), this, dialog);
messagesListView.setAdapter(messagesAdapter);
}
private void updateActionBar() {
actionBar.setTitle(groupName);
actionBar.setSubtitle(getString(R.string.gdd_participants, dialog.getOccupants().size()));
actionBar.setLogo(R.drawable.placeholder_group);
}
@Override
public void onCachedImageFileReceived(File file) {
startLoadAttachFile(file);
}
@Override
public void onAbsolutePathExtFileReceived(String absolutePath) {
}
public void sendMessageOnClick(View view) {
try {
((QBMultiChatHelper) chatHelper).sendGroupMessage(dialog.getRoomJid(),
messageEditText.getText().toString());
} catch (QBResponseException e) {
ErrorUtils.showError(this, e);
}
messageEditText.setText(Consts.EMPTY_STRING);
scrollListView();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.group_dialog_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
navigateToParent();
return true;
case R.id.action_attach:
attachButtonOnClick();
return true;
case R.id.action_group_details:
GroupDialogDetailsActivity.start(this, dialog.getDialogId());
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater m = getMenuInflater();
m.inflate(R.menu.group_dialog_ctx_menu, menu);
}
@Override
protected void onResume() {
super.onResume();
updateChatData();
scrollListView();
}
} | Loading of group photo was added.
| Q-municate/src/main/java/com/quickblox/q_municate/ui/chats/GroupDialogActivity.java | Loading of group photo was added. |
|
Java | apache-2.0 | 19a3b0646e3db7bc15be035aa23d436230740f2c | 0 | SpineEventEngine/gae-java,SpineEventEngine/gae-java | /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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 io.spine.server.storage.datastore;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.StructuredQuery;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.Any;
import io.spine.core.TenantId;
import io.spine.net.EmailAddress;
import io.spine.net.InternetDomain;
import io.spine.server.storage.datastore.given.TestDatastores;
import io.spine.server.tenant.TenantAwareFunction0;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import static com.google.cloud.datastore.Query.newEntityQueryBuilder;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.truth.Truth.assertThat;
import static io.spine.server.storage.datastore.DatastoreWrapper.wrap;
import static io.spine.server.storage.datastore.TestDatastoreWrapper.wrap;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.GENERIC_ENTITY_KIND;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.NAMESPACE_HOLDER_KIND;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.checkTenantIdInKey;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.ensureNamespace;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.testDatastore;
import static io.spine.server.storage.datastore.given.TestDatastores.projectId;
import static io.spine.server.storage.datastore.tenant.TestNamespaceSuppliers.multitenant;
import static io.spine.server.storage.datastore.tenant.TestNamespaceSuppliers.singleTenant;
import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@DisplayName("DatastoreWrapper should")
class DatastoreWrapperTest {
@AfterAll
static void tearDown() {
DatastoreWrapper wrapper = wrap(testDatastore(), singleTenant());
wrapper.dropTable(NAMESPACE_HOLDER_KIND);
}
@Nested
class SingleTenant {
private DatastoreWrapper wrapper;
@BeforeEach
void setUp() {
wrapper = wrap(testDatastore(), singleTenant());
wrapper.startTransaction();
}
@Test
@DisplayName("work with transactions if necessary")
void testExecuteTransactions() {
assertTrue(wrapper.isTransactionActive());
wrapper.commitTransaction();
assertFalse(wrapper.isTransactionActive());
}
@Test
@DisplayName("rollback transactions")
void testRollback() {
assertTrue(wrapper.isTransactionActive());
wrapper.rollbackTransaction();
assertFalse(wrapper.isTransactionActive());
}
@Test
@DisplayName("fail to start transaction if one is active")
void testFailToRestartTransactions() {
try {
assertTrue(wrapper.isTransactionActive());
assertThrows(IllegalStateException.class, wrapper::startTransaction);
} finally {
wrapper.rollbackTransaction();
}
}
@Test
@DisplayName("fail to finish non active transaction")
void testFailToFinishNonActiveTransaction() {
assertTrue(wrapper.isTransactionActive());
wrapper.commitTransaction();
assertFalse(wrapper.isTransactionActive());
assertThrows(IllegalStateException.class, wrapper::rollbackTransaction);
}
}
@Nested
class NotWaiting {
private TestDatastoreWrapper wrapper;
@BeforeEach
void setUp() {
wrapper = wrap(testDatastore(), false);
}
@AfterEach
void tearDown() {
wrapper.dropAllTables();
}
@Test
@DisplayName("support bulk reads")
void testBulkRead() throws InterruptedException {
int bulkSize = 1001;
Map<Key, Entity> entities = newTestEntities(bulkSize, wrapper);
Collection<Entity> expectedEntities = entities.values();
wrapper.createOrUpdate(expectedEntities);
// Wait for some time to make sure the writing is complete
Thread.sleep(bulkSize * 5L);
Collection<Entity> readEntities = newArrayList(wrapper.read(entities.keySet()));
assertEquals(entities.size(), readEntities.size());
assertTrue(expectedEntities.containsAll(readEntities));
}
@Disabled("This test rarely passes on Travis CI due to eventual consistency.")
@Test
@DisplayName("support big bulk reads")
void testBigBulkRead() throws InterruptedException {
int bulkSize = 2001;
Map<Key, Entity> entities = newTestEntities(bulkSize, wrapper);
Collection<Entity> expectedEntities = entities.values();
wrapper.createOrUpdate(expectedEntities);
// Wait for some time to make sure the writing is complete
Thread.sleep(bulkSize * 3L);
StructuredQuery<Entity> query = newEntityQueryBuilder()
.setKind(GENERIC_ENTITY_KIND.getValue())
.build();
Collection<Entity> readEntities = newArrayList(wrapper.read(query));
assertEquals(entities.size(), readEntities.size());
assertTrue(expectedEntities.containsAll(readEntities));
}
}
@Nested
@DisplayName("read entities by keys")
class ReadByKeys {
private TestDatastoreWrapper wrapper;
@BeforeEach
void setUp() {
wrapper = wrap(testDatastore(), false);
}
@AfterEach
void tearDown() {
wrapper.dropAllTables();
}
@Test
@DisplayName("replacing missing entities with null")
void testMissingAreNull() throws InterruptedException {
int bulkSize = 3;
Map<Key, Entity> entities = createAndStoreTestEntities(bulkSize);
// Wait for some time to make sure the writing is complete
Thread.sleep(bulkSize * 5L);
List<Key> presentKeys = newArrayList(entities.keySet());
List<Key> queryKeys = new ImmutableList.Builder<Key>()
.add(newKey("missing-key-1", wrapper))
.add(presentKeys.get(0))
.add(presentKeys.get(1))
.add(newKey("missing-key-2", wrapper))
.add(presentKeys.get(2))
.build();
Iterator<Entity> actualEntities = wrapper.read(queryKeys);
assertNull(actualEntities.next());
assertEquals(entities.get(presentKeys.get(0)), actualEntities.next());
assertEquals(entities.get(presentKeys.get(1)), actualEntities.next());
assertNull(actualEntities.next());
assertEquals(entities.get(presentKeys.get(2)), actualEntities.next());
assertFalse(actualEntities.hasNext());
}
@Test
@DisplayName("preserving order")
void test() throws InterruptedException {
int bulkSize = 3;
Map<Key, Entity> entities = createAndStoreTestEntities(bulkSize);
// Wait for some time to make sure the writing is complete
Thread.sleep(bulkSize * 5L);
List<Key> presentKeys = newArrayList(entities.keySet());
List<Key> queryKeys = new ImmutableList.Builder<Key>()
.add(presentKeys.get(2))
.add(presentKeys.get(0))
.add(presentKeys.get(1))
.build();
Iterator<Entity> actualEntities = wrapper.read(queryKeys);
assertEquals(entities.get(queryKeys.get(0)), actualEntities.next());
assertEquals(entities.get(queryKeys.get(1)), actualEntities.next());
assertEquals(entities.get(queryKeys.get(2)), actualEntities.next());
assertFalse(actualEntities.hasNext());
}
private Map<Key, Entity> createAndStoreTestEntities(int bulkSize) {
Map<Key, Entity> entities = newTestEntities(bulkSize, wrapper);
Collection<Entity> expectedEntities = entities.values();
wrapper.createOrUpdate(expectedEntities);
return entities;
}
}
@Nested
@DisplayName("read with structured query")
class ReadWithStructuredQuery {
private TestDatastoreWrapper wrapper;
@BeforeEach
void setUp() {
wrapper = wrap(testDatastore(), false);
}
@AfterEach
void tearDown() {
wrapper.dropAllTables();
}
@Test
@DisplayName("throws IAE during batch read with limit")
void testIaeOnBatchReadWithLimit() {
assertThrows(IllegalArgumentException.class,
() -> wrapper.readAll(newEntityQueryBuilder()
.setLimit(5)
.build(), 1));
}
@Test
@DisplayName("throws IAE during batch read of 0 size")
void testIaeOnBatchReadWithZeroSize() {
assertThrows(IllegalArgumentException.class,
() -> wrapper.readAll(newEntityQueryBuilder().build(), 0));
}
}
@Test
@DisplayName("generate key factories aware of tenancy")
void testGenerateKeyFactory() {
ProjectId projectId = TestDatastores.projectId();
DatastoreWrapper wrapper = wrap(testDatastore(), multitenant(projectId));
String tenantId1 = "first-tenant-ID";
String tenantId1Prefixed = "Vfirst-tenant-ID";
String tenantId2 = "[email protected]";
String tenantId2Prefixed = "Esecond-at-tenant.id";
String tenantId3 = "third.id";
String tenantId3Prefixed = "Dthird.id";
Datastore datastore = wrapper.getDatastore();
ensureNamespace(tenantId1Prefixed, datastore);
ensureNamespace(tenantId2Prefixed, datastore);
ensureNamespace(tenantId3Prefixed, datastore);
TenantId id1 = TenantId.newBuilder()
.setValue(tenantId1)
.build();
TenantId id2 = TenantId.newBuilder()
.setEmail(EmailAddress.newBuilder()
.setValue(tenantId2))
.build();
TenantId id3 = TenantId.newBuilder()
.setDomain(InternetDomain.newBuilder()
.setValue(tenantId3))
.build();
checkTenantIdInKey(tenantId1Prefixed, id1, wrapper);
checkTenantIdInKey(tenantId2Prefixed, id2, wrapper);
checkTenantIdInKey(tenantId3Prefixed, id3, wrapper);
}
@Test
@DisplayName("produce lazy iterator on query read")
void testLazyIterator() {
DatastoreWrapper wrapper = wrap(testDatastore(), singleTenant());
int count = 2;
Map<?, Entity> entities = newTestEntities(count, wrapper);
Collection<Entity> expctedEntities = entities.values();
wrapper.createOrUpdate(expctedEntities);
StructuredQuery<Entity> query = newEntityQueryBuilder()
.setKind(GENERIC_ENTITY_KIND.getValue())
.build();
Iterator<Entity> result = wrapper.read(query);
assertTrue(result.hasNext());
Entity first = result.next();
assertTrue(result.hasNext());
Entity second = result.next();
assertThat(expctedEntities).contains(first);
assertThat(expctedEntities).contains(second);
assertFalse(result.hasNext());
assertFalse(result.hasNext());
assertFalse(result.hasNext());
try {
result.next();
fail();
} catch (NoSuchElementException ignored) {
}
}
@Test
@DisplayName("allow to add new namespaces 'on the go'")
void testNewNamespaces() {
DatastoreWrapper wrapper = wrap(testDatastore(), multitenant(projectId()));
TenantId tenantId = TenantId.newBuilder()
.setValue("Luke_I_am_your_tenant.")
.build();
String key = "noooooo";
Key entityKey = new TenantAwareFunction0<Key>(tenantId) {
@Override
public Key apply() {
Key entityKey = wrapper.getKeyFactory(Kind.of(NAMESPACE_HOLDER_KIND))
.newKey(key);
Entity entity = Entity.newBuilder(entityKey)
.build();
wrapper.create(entity);
return entityKey;
}
}.execute();
// Clean up the namespace.
wrapper.delete(entityKey);
}
/**
* Cannot be moved to test environment because it uses package-local
* {@link Entities#fromMessage(com.google.protobuf.Message, Key) fromMessage()}.
*/
private static Map<Key, Entity> newTestEntities(int n, DatastoreWrapper wrapper) {
Map<Key, Entity> result = new HashMap<>(n);
for (int i = 0; i < n; i++) {
Any message = Any.getDefaultInstance();
Key key = newKey(format("record-%s", i), wrapper);
Entity entity = Entities.fromMessage(message, key);
result.put(key, entity);
}
return result;
}
/**
* Cannot be moved to test environment because it uses package-local {@link RecordId}.
*/
private static Key newKey(String id, DatastoreWrapper wrapper) {
RecordId recordId = new RecordId(id);
return wrapper.keyFor(GENERIC_ENTITY_KIND, recordId);
}
}
| datastore/src/test/java/io/spine/server/storage/datastore/DatastoreWrapperTest.java | /*
* Copyright 2018, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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 io.spine.server.storage.datastore;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.StructuredQuery;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.Any;
import io.spine.core.TenantId;
import io.spine.net.EmailAddress;
import io.spine.net.InternetDomain;
import io.spine.server.storage.datastore.given.TestDatastores;
import io.spine.server.tenant.TenantAwareFunction0;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.truth.Truth.assertThat;
import static io.spine.server.storage.datastore.DatastoreWrapper.wrap;
import static io.spine.server.storage.datastore.TestDatastoreWrapper.wrap;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.GENERIC_ENTITY_KIND;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.NAMESPACE_HOLDER_KIND;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.checkTenantIdInKey;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.ensureNamespace;
import static io.spine.server.storage.datastore.given.DatastoreWrapperTestEnv.testDatastore;
import static io.spine.server.storage.datastore.given.TestDatastores.projectId;
import static io.spine.server.storage.datastore.tenant.TestNamespaceSuppliers.multitenant;
import static io.spine.server.storage.datastore.tenant.TestNamespaceSuppliers.singleTenant;
import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@DisplayName("DatastoreWrapper should")
class DatastoreWrapperTest {
@AfterAll
static void tearDown() {
DatastoreWrapper wrapper = wrap(testDatastore(), singleTenant());
wrapper.dropTable(NAMESPACE_HOLDER_KIND);
}
@Nested
class SingleTenant {
private DatastoreWrapper wrapper;
@BeforeEach
void setUp() {
wrapper = wrap(testDatastore(), singleTenant());
wrapper.startTransaction();
}
@Test
@DisplayName("work with transactions if necessary")
void testExecuteTransactions() {
assertTrue(wrapper.isTransactionActive());
wrapper.commitTransaction();
assertFalse(wrapper.isTransactionActive());
}
@Test
@DisplayName("rollback transactions")
void testRollback() {
assertTrue(wrapper.isTransactionActive());
wrapper.rollbackTransaction();
assertFalse(wrapper.isTransactionActive());
}
@Test
@DisplayName("fail to start transaction if one is active")
void testFailToRestartTransactions() {
try {
assertTrue(wrapper.isTransactionActive());
assertThrows(IllegalStateException.class, wrapper::startTransaction);
} finally {
wrapper.rollbackTransaction();
}
}
@Test
@DisplayName("fail to finish non active transaction")
void testFailToFinishNonActiveTransaction() {
assertTrue(wrapper.isTransactionActive());
wrapper.commitTransaction();
assertFalse(wrapper.isTransactionActive());
assertThrows(IllegalStateException.class, wrapper::rollbackTransaction);
}
}
@Nested
class NotWaiting {
private TestDatastoreWrapper wrapper;
@BeforeEach
void setUp() {
wrapper = wrap(testDatastore(), false);
}
@AfterEach
void tearDown() {
wrapper.dropAllTables();
}
@Test
@DisplayName("support bulk reads")
void testBulkRead() throws InterruptedException {
int bulkSize = 1001;
Map<Key, Entity> entities = newTestEntities(bulkSize, wrapper);
Collection<Entity> expectedEntities = entities.values();
wrapper.createOrUpdate(expectedEntities);
// Wait for some time to make sure the writing is complete
Thread.sleep(bulkSize * 5L);
Collection<Entity> readEntities = newArrayList(wrapper.read(entities.keySet()));
assertEquals(entities.size(), readEntities.size());
assertTrue(expectedEntities.containsAll(readEntities));
}
@Disabled("This test rarely passes on Travis CI due to eventual consistency.")
@Test
@DisplayName("support big bulk reads")
void testBigBulkRead() throws InterruptedException {
int bulkSize = 2001;
Map<Key, Entity> entities = newTestEntities(bulkSize, wrapper);
Collection<Entity> expectedEntities = entities.values();
wrapper.createOrUpdate(expectedEntities);
// Wait for some time to make sure the writing is complete
Thread.sleep(bulkSize * 3L);
StructuredQuery<Entity> query = Query.newEntityQueryBuilder()
.setKind(GENERIC_ENTITY_KIND.getValue())
.build();
Collection<Entity> readEntities = newArrayList(wrapper.read(query));
assertEquals(entities.size(), readEntities.size());
assertTrue(expectedEntities.containsAll(readEntities));
}
}
@Nested
@DisplayName("read entities by keys")
class ReadByKeys {
private TestDatastoreWrapper wrapper;
@BeforeEach
void setUp() {
wrapper = wrap(testDatastore(), false);
}
@AfterEach
void tearDown() {
wrapper.dropAllTables();
}
@Test
@DisplayName("replacing missing entities with null")
void testMissingAreNull() throws InterruptedException {
int bulkSize = 3;
Map<Key, Entity> entities = createAndStoreTestEntities(bulkSize);
// Wait for some time to make sure the writing is complete
Thread.sleep(bulkSize * 5L);
List<Key> presentKeys = newArrayList(entities.keySet());
List<Key> queryKeys = new ImmutableList.Builder<Key>()
.add(newKey("missing-key-1", wrapper))
.add(presentKeys.get(0))
.add(presentKeys.get(1))
.add(newKey("missing-key-2", wrapper))
.add(presentKeys.get(2))
.build();
Iterator<Entity> actualEntities = wrapper.read(queryKeys);
assertNull(actualEntities.next());
assertEquals(entities.get(presentKeys.get(0)), actualEntities.next());
assertEquals(entities.get(presentKeys.get(1)), actualEntities.next());
assertNull(actualEntities.next());
assertEquals(entities.get(presentKeys.get(2)), actualEntities.next());
assertFalse(actualEntities.hasNext());
}
@Test
@DisplayName("preserving order")
void test() throws InterruptedException {
int bulkSize = 3;
Map<Key, Entity> entities = createAndStoreTestEntities(bulkSize);
// Wait for some time to make sure the writing is complete
Thread.sleep(bulkSize * 5L);
List<Key> presentKeys = newArrayList(entities.keySet());
List<Key> queryKeys = new ImmutableList.Builder<Key>()
.add(presentKeys.get(2))
.add(presentKeys.get(0))
.add(presentKeys.get(1))
.build();
Iterator<Entity> actualEntities = wrapper.read(queryKeys);
assertEquals(entities.get(queryKeys.get(0)), actualEntities.next());
assertEquals(entities.get(queryKeys.get(1)), actualEntities.next());
assertEquals(entities.get(queryKeys.get(2)), actualEntities.next());
assertFalse(actualEntities.hasNext());
}
private Map<Key, Entity> createAndStoreTestEntities(int bulkSize) {
Map<Key, Entity> entities = newTestEntities(bulkSize, wrapper);
Collection<Entity> expectedEntities = entities.values();
wrapper.createOrUpdate(expectedEntities);
return entities;
}
}
@Test
@DisplayName("generate key factories aware of tenancy")
void testGenerateKeyFactory() {
ProjectId projectId = TestDatastores.projectId();
DatastoreWrapper wrapper = wrap(testDatastore(), multitenant(projectId));
String tenantId1 = "first-tenant-ID";
String tenantId1Prefixed = "Vfirst-tenant-ID";
String tenantId2 = "[email protected]";
String tenantId2Prefixed = "Esecond-at-tenant.id";
String tenantId3 = "third.id";
String tenantId3Prefixed = "Dthird.id";
Datastore datastore = wrapper.getDatastore();
ensureNamespace(tenantId1Prefixed, datastore);
ensureNamespace(tenantId2Prefixed, datastore);
ensureNamespace(tenantId3Prefixed, datastore);
TenantId id1 = TenantId.newBuilder()
.setValue(tenantId1)
.build();
TenantId id2 = TenantId.newBuilder()
.setEmail(EmailAddress.newBuilder()
.setValue(tenantId2))
.build();
TenantId id3 = TenantId.newBuilder()
.setDomain(InternetDomain.newBuilder()
.setValue(tenantId3))
.build();
checkTenantIdInKey(tenantId1Prefixed, id1, wrapper);
checkTenantIdInKey(tenantId2Prefixed, id2, wrapper);
checkTenantIdInKey(tenantId3Prefixed, id3, wrapper);
}
@Test
@DisplayName("produce lazy iterator on query read")
void testLazyIterator() {
DatastoreWrapper wrapper = wrap(testDatastore(), singleTenant());
int count = 2;
Map<?, Entity> entities = newTestEntities(count, wrapper);
Collection<Entity> expctedEntities = entities.values();
wrapper.createOrUpdate(expctedEntities);
StructuredQuery<Entity> query = Query.newEntityQueryBuilder()
.setKind(GENERIC_ENTITY_KIND.getValue())
.build();
Iterator<Entity> result = wrapper.read(query);
assertTrue(result.hasNext());
Entity first = result.next();
assertTrue(result.hasNext());
Entity second = result.next();
assertThat(expctedEntities).contains(first);
assertThat(expctedEntities).contains(second);
assertFalse(result.hasNext());
assertFalse(result.hasNext());
assertFalse(result.hasNext());
try {
result.next();
fail();
} catch (NoSuchElementException ignored) {
}
}
@Test
@DisplayName("allow to add new namespaces 'on the go'")
void testNewNamespaces() {
DatastoreWrapper wrapper = wrap(testDatastore(), multitenant(projectId()));
TenantId tenantId = TenantId.newBuilder()
.setValue("Luke_I_am_your_tenant.")
.build();
String key = "noooooo";
Key entityKey = new TenantAwareFunction0<Key>(tenantId) {
@Override
public Key apply() {
Key entityKey = wrapper.getKeyFactory(Kind.of(NAMESPACE_HOLDER_KIND))
.newKey(key);
Entity entity = Entity.newBuilder(entityKey)
.build();
wrapper.create(entity);
return entityKey;
}
}.execute();
// Clean up the namespace.
wrapper.delete(entityKey);
}
/**
* Cannot be moved to test environment because it uses package-local
* {@link Entities#fromMessage(com.google.protobuf.Message, Key) fromMessage()}.
*/
private static Map<Key, Entity> newTestEntities(int n, DatastoreWrapper wrapper) {
Map<Key, Entity> result = new HashMap<>(n);
for (int i = 0; i < n; i++) {
Any message = Any.getDefaultInstance();
Key key = newKey(format("record-%s", i), wrapper);
Entity entity = Entities.fromMessage(message, key);
result.put(key, entity);
}
return result;
}
/**
* Cannot be moved to test environment because it uses package-local {@link RecordId}.
*/
private static Key newKey(String id, DatastoreWrapper wrapper) {
RecordId recordId = new RecordId(id);
return wrapper.keyFor(GENERIC_ENTITY_KIND, recordId);
}
}
| Add batch size tests.
| datastore/src/test/java/io/spine/server/storage/datastore/DatastoreWrapperTest.java | Add batch size tests. |
|
Java | bsd-3-clause | e5cba4af621350a5c77ac0daecec209d0b86d3c6 | 0 | koraktor/steam-condenser-java,JamesGames/steam-condenser-for-rust | /**
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2008-2012, Sebastian Staudt
* 2012, Sam Kinard
*/
package com.github.koraktor.steamcondenser.steam.community;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.github.koraktor.steamcondenser.exceptions.SteamCondenserException;
/**
* The SteamGroup class represents a group in the Steam Community
*
* @author Sebastian Staudt
*/
public class SteamGroup {
private static Map<Object, SteamGroup> steamGroups = new HashMap<Object, SteamGroup>();
private String customUrl;
private long fetchTime;
private long groupId64;
private Integer memberCount;
private ArrayList<SteamId> members;
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The 64bit Steam ID of the group
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(long id) throws SteamCondenserException {
return SteamGroup.create((Object) id, true, false);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The custom URL of the group specified by the group admin
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(String id) throws SteamCondenserException {
return SteamGroup.create((Object) id, true, false);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The 64bit Steam ID of the group
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(long id, boolean fetch)
throws SteamCondenserException {
return SteamGroup.create((Object) id, fetch, false);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The custom URL of the group specified by the group admin
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(String id, boolean fetch)
throws SteamCondenserException {
return SteamGroup.create((Object) id, fetch, false);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The 64bit Steam ID of the group
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @param bypassCache If <code>true</code> an already cached instance for
* this group will be ignored and a new one will be created
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(long id, boolean fetch, boolean bypassCache)
throws SteamCondenserException {
return SteamGroup.create((Object) id, fetch, bypassCache);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The custom URL of the group specified by the group admin
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @param bypassCache If <code>true</code> an already cached instance for
* this group will be ignored and a new one will be created
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(String id, boolean fetch, boolean bypassCache)
throws SteamCondenserException {
return SteamGroup.create((Object) id, fetch, bypassCache);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The custom URL of the group specified by the group admin or
* the 64bit group ID
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @param bypassCache If <code>true</code> an already cached instance for
* this group will be ignored and a new one will be created
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
private static SteamGroup create(Object id, boolean fetch, boolean bypassCache)
throws SteamCondenserException {
if(SteamGroup.isCached(id) && !bypassCache) {
SteamGroup group = SteamGroup.steamGroups.get(id);
if(fetch && !group.isFetched()) {
group.fetchMembers();
}
return group;
} else {
return new SteamGroup(id, fetch);
}
}
/**
* Returns whether the requested group is already cached
*
* @param id The custom URL of the group specified by the group admin or
* the 64bit group ID
* @return <code>true</code> if this group is already cached
*/
public static boolean isCached(Object id) {
return SteamGroup.steamGroups.containsKey(id);
}
/**
* Creates a new <code>SteamGroup</code> instance for the group with the
* given ID
*
* @param id The custom URL of the group specified by the group admin or
* the 64bit group ID
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
private SteamGroup(Object id, boolean fetch)
throws SteamCondenserException {
if(id instanceof String) {
this.customUrl = (String) id;
} else {
this.groupId64 = (Long) id;
}
this.members = new ArrayList<SteamId>();
if(fetch) {
this.fetchMembers();
}
this.cache();
}
/**
* Saves this <code>SteamGroup</code> instance in the cache
*
* @return <code>false</code> if this group is already cached
*/
public boolean cache() {
if(!SteamGroup.steamGroups.containsKey(this.groupId64)) {
SteamGroup.steamGroups.put(this.groupId64, this);
if(this.customUrl != null && !SteamGroup.steamGroups.containsKey(this.customUrl)) {
SteamGroup.steamGroups.put(this.customUrl, this);
}
return true;
}
return false;
}
/**
* Loads the members of this group
* <p>
* This might take several HTTP requests as the Steam Community splits this
* data over several XML documents if the group has lots of members.
*
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public void fetchMembers() throws SteamCondenserException {
int page = 0;
int totalPages;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
do {
totalPages = fetchPage(++page);
} while(page < totalPages);
} catch(Exception e) {
throw new SteamCondenserException("XML data could not be parsed.", e);
}
this.fetchTime = new Date().getTime();
}
/**
* Returns the custom URL of this group
* <p>
* The custom URL is a admin specified unique string that can be used
* instead of the 64bit SteamID as an identifier for a group.
*
* @return The custom URL of this group
*/
public String getCustomUrl() {
return this.customUrl;
}
/**
* Returns this group's 64bit SteamID
*
* @return This group's 64bit SteamID
*/
public long getGroupId64() {
return this.groupId64;
}
/**
* Returns the base URL for this group's page
* <p>
* This URL is different for groups having a custom URL.
*
* @return The base URL for this group
*/
public String getBaseUrl() {
if(this.customUrl == null) {
return "http://steamcommunity.com/gid/" + this.groupId64;
} else {
return "http://steamcommunity.com/groups/" + this.customUrl;
}
}
/**
* Returns the time this group has been fetched
*
* @return The timestamp of the last fetch time
*/
public long getFetchTime() {
return this.fetchTime;
}
/**
* Returns this group's 64bit SteamID
*
* @return This group's 64bit SteamID
*/
public long getId() {
return this.groupId64;
}
/**
* Returns the number of members this group has
* <p>
* If the members have already been fetched the size of the member array is
* returned. Otherwise the the first page of the member listing is fetched
* and the member count and the first batch of members is stored.
*
* @return The number of this group's members
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public int getMemberCount() throws SteamCondenserException {
try {
if(this.memberCount == null) {
int totalPages = fetchPage(1);
if(totalPages == 1) {
this.fetchTime = new Date().getTime();
}
}
return memberCount;
} catch(Exception e) {
throw new SteamCondenserException(e.getMessage(), e);
}
}
/**
* Fetches a specific page of the member listing of this group
*
* @param page The member page to fetch
* @return The total number of pages of this group's member listing
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
private int fetchPage(int page) throws SteamCondenserException {
int totalPages;
String url;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
url = this.getBaseUrl() + "/memberslistxml?p=" + page;
Element memberData = parser.parse(url).getDocumentElement();
this.memberCount = Integer.parseInt(memberData.getElementsByTagName("memberCount").item(0).getTextContent());
totalPages = Integer.parseInt(memberData.getElementsByTagName("totalPages").item(0).getTextContent());
NodeList membersList = ((Element) memberData.getElementsByTagName("members").item(0)).getElementsByTagName("steamID64");
for(int i = 0; i < membersList.getLength(); i++) {
Element member = (Element) membersList.item(i);
this.members.add(SteamId.create(Long.parseLong(member.getTextContent()), false));
}
} catch(Exception e) {
throw new SteamCondenserException("XML data could not be parsed.", e);
}
return totalPages;
}
/**
* Returns the members of this group
* <p>
* If the members haven't been fetched yet, this is done now.
*
* @return The Steam ID's of the members of this group
* @see #fetchMembers
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public ArrayList<SteamId> getMembers() throws SteamCondenserException {
if(Integer.valueOf(this.members.size()) != this.memberCount) {
this.fetchMembers();
}
return this.members;
}
/**
* Returns whether the data for this group has already been fetched
*
* @return <code>true</code> if the group's members have been
* fetched
*/
public boolean isFetched() {
return this.fetchTime != 0;
}
}
| src/main/java/com/github/koraktor/steamcondenser/steam/community/SteamGroup.java | /**
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2008-2011, Sebastian Staudt
*/
package com.github.koraktor.steamcondenser.steam.community;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.github.koraktor.steamcondenser.exceptions.SteamCondenserException;
/**
* The SteamGroup class represents a group in the Steam Community
*
* @author Sebastian Staudt
*/
public class SteamGroup {
private static Map<Object, SteamGroup> steamGroups = new HashMap<Object, SteamGroup>();
private String customUrl;
private long fetchTime;
private long groupId64;
private int memberCount;
private ArrayList<SteamId> members;
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The 64bit Steam ID of the group
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(long id) throws SteamCondenserException {
return SteamGroup.create((Object) id, true, false);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The custom URL of the group specified by the group admin
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(String id) throws SteamCondenserException {
return SteamGroup.create((Object) id, true, false);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The 64bit Steam ID of the group
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(long id, boolean fetch)
throws SteamCondenserException {
return SteamGroup.create((Object) id, fetch, false);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The custom URL of the group specified by the group admin
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(String id, boolean fetch)
throws SteamCondenserException {
return SteamGroup.create((Object) id, fetch, false);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The 64bit Steam ID of the group
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @param bypassCache If <code>true</code> an already cached instance for
* this group will be ignored and a new one will be created
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(long id, boolean fetch, boolean bypassCache)
throws SteamCondenserException {
return SteamGroup.create((Object) id, fetch, bypassCache);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The custom URL of the group specified by the group admin
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @param bypassCache If <code>true</code> an already cached instance for
* this group will be ignored and a new one will be created
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public static SteamGroup create(String id, boolean fetch, boolean bypassCache)
throws SteamCondenserException {
return SteamGroup.create((Object) id, fetch, bypassCache);
}
/**
* Creates a new <code>SteamGroup</code> instance or gets an existing one
* from the cache for the group with the given ID
*
* @param id The custom URL of the group specified by the group admin or
* the 64bit group ID
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @param bypassCache If <code>true</code> an already cached instance for
* this group will be ignored and a new one will be created
* @return The <code>SteamGroup</code> instance of the requested group
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
private static SteamGroup create(Object id, boolean fetch, boolean bypassCache)
throws SteamCondenserException {
if(SteamGroup.isCached(id) && !bypassCache) {
SteamGroup group = SteamGroup.steamGroups.get(id);
if(fetch && !group.isFetched()) {
group.fetchMembers();
}
return group;
} else {
return new SteamGroup(id, fetch);
}
}
/**
* Returns whether the requested group is already cached
*
* @param id The custom URL of the group specified by the group admin or
* the 64bit group ID
* @return <code>true</code> if this group is already cached
*/
public static boolean isCached(Object id) {
return SteamGroup.steamGroups.containsKey(id);
}
/**
* Creates a new <code>SteamGroup</code> instance for the group with the
* given ID
*
* @param id The custom URL of the group specified by the group admin or
* the 64bit group ID
* @param fetch if <code>true</code> the groups's data is loaded into the
* object
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
private SteamGroup(Object id, boolean fetch)
throws SteamCondenserException {
if(id instanceof String) {
this.customUrl = (String) id;
} else {
this.groupId64 = (Long) id;
}
this.members = new ArrayList<SteamId>();
if(fetch) {
this.fetchMembers();
}
this.cache();
}
/**
* Saves this <code>SteamGroup</code> instance in the cache
*
* @return <code>false</code> if this group is already cached
*/
public boolean cache() {
if(!SteamGroup.steamGroups.containsKey(this.groupId64)) {
SteamGroup.steamGroups.put(this.groupId64, this);
if(this.customUrl != null && !SteamGroup.steamGroups.containsKey(this.customUrl)) {
SteamGroup.steamGroups.put(this.customUrl, this);
}
return true;
}
return false;
}
/**
* Loads the members of this group
* <p>
* This might take several HTTP requests as the Steam Community splits this
* data over several XML documents if the group has lots of members.
*
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public void fetchMembers() throws SteamCondenserException {
int page = 0;
int totalPages;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
do {
totalPages = fetchPage(++page);
} while(page < totalPages);
} catch(Exception e) {
throw new SteamCondenserException("XML data could not be parsed.", e);
}
this.fetchTime = new Date().getTime();
}
/**
* Returns the custom URL of this group
* <p>
* The custom URL is a admin specified unique string that can be used
* instead of the 64bit SteamID as an identifier for a group.
*
* @return The custom URL of this group
*/
public String getCustomUrl() {
return this.customUrl;
}
/**
* Returns this group's 64bit SteamID
*
* @return This group's 64bit SteamID
*/
public long getGroupId64() {
return this.groupId64;
}
/**
* Returns the base URL for this group's page
* <p>
* This URL is different for groups having a custom URL.
*
* @return The base URL for this group
*/
public String getBaseUrl() {
if(this.customUrl == null) {
return "http://steamcommunity.com/gid/" + this.groupId64;
} else {
return "http://steamcommunity.com/groups/" + this.customUrl;
}
}
/**
* Returns the time this group has been fetched
*
* @return The timestamp of the last fetch time
*/
public long getFetchTime() {
return this.fetchTime;
}
/**
* Returns this group's 64bit SteamID
*
* @return This group's 64bit SteamID
*/
public long getId() {
return this.groupId64;
}
/**
* Returns the number of members this group has
* <p>
* If the members have not already been fetched the first page is
* fetched and memberCount is set and returned. Otherwise memberCount
* has already been set and is returned.
*
* @return The number of this group's members
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public int getMemberCount() throws SteamCondenserException {
try {
if(this.members.size() == 0) {
members = new ArrayList<SteamId>();
fetchPage(1);
if (members.size() == memberCount) {
this.fetchTime = new Date().getTime();
}
}
return memberCount;
} catch(Exception e) {
throw new SteamCondenserException(e.getMessage(), e);
}
}
/**
* Fetches a specific page of the member listing of this group
*
* @param page desired page to be fetched
* @return The total number of pages of this group's member listing
* @throws SteamCondenserException if error occurs while parsing the
* data
*/
private int fetchPage(int page) throws SteamCondenserException {
int totalPages;
String url;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
url = this.getBaseUrl() + "/memberslistxml?p=" + page;
Element memberData = parser.parse(url).getDocumentElement();
if (page == 1) {
if (members.size() == 0) {
memberCount = Integer.parseInt(memberData.getElementsByTagName("memberCount").item(0).getTextContent());
storeMembers(memberData);
}
} else {
storeMembers(memberData);
}
totalPages = Integer.parseInt(memberData.getElementsByTagName("totalPages").item(0).getTextContent());
} catch(Exception e) {
throw new SteamCondenserException("XML data could not be parsed.", e);
}
return totalPages;
}
/**
* Stores member information in internal ArrayList storage.
*
* @param memberData member data parsed from XML
* @throws SteamCondenserException if error occurs while creating a SteamId
*/
private void storeMembers(Element memberData) throws SteamCondenserException {
NodeList membersList = ((Element) memberData.getElementsByTagName("members").item(0)).getElementsByTagName("steamID64");
for(int i = 0; i < membersList.getLength(); i++) {
Element member = (Element) membersList.item(i);
this.members.add(SteamId.create(Long.parseLong(member.getTextContent()), false));
}
}
/**
* Returns the members of this group
* <p>
* If the members haven't been fetched yet, this is done now.
*
* @return The Steam ID's of the members of this group
* @see #fetchMembers
* @throws SteamCondenserException if an error occurs while parsing the
* data
*/
public ArrayList<SteamId> getMembers() throws SteamCondenserException {
if (members.size() != memberCount) {
this.fetchMembers();
}
return this.members;
}
/**
* Returns whether the data for this group has already been fetched
*
* @return <code>true</code> if the group's members have been
* fetched
*/
public boolean isFetched() {
return this.fetchTime != 0;
}
}
| Cleanup SteamGroup fetching
| src/main/java/com/github/koraktor/steamcondenser/steam/community/SteamGroup.java | Cleanup SteamGroup fetching |
|
Java | mit | 8ee3119f02770172caef7a8b3df02bc350f39228 | 0 | demo-cards-trading-game/game | package demo;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.border.LineBorder;
import data.LoadData;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import demo.deck;
import extra.Rlabel;
import extra.RoundButton;
import extra.RoundedPanel;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.IOException;
import javax.swing.JTextPane;
import javax.swing.border.CompoundBorder;
import javax.swing.border.MatteBorder;
public class DeckGui extends JPanel {
public JTextField textField;
public deck Deck;
private JTextField txtHero;
private JTextField txtCharacter;
private JTextField txtSection;
public JLabel btnNewButton;
public JLabel btnNewButton_1;
public JLabel btnNewButton_2;
public JLabel lblTheFallen;
public JLayeredPane panel;
public JLabel lblDeck;
public JLabel lblForgotten ;
public JInternalFrame menu;
public SmallCard Hero;
public JButton Play, Preview;
public DeckGui(int x,int y) {
this.Deck=new deck();
try {
Deck.Load("resources/siren.in");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setBackground(new Color(255, 165, 0));
setBounds(x, y, 250, 340);
setOpaque(false);
setLayout(null);
btnNewButton = new JLabel("");
//btnNewButton.setBackground(new Color(139, 69, 19));
//btnNewButton.setOpaque(false);
btnNewButton.setIcon(new ImageIcon("draw1.png"));
btnNewButton.setBounds(175, 269, 46, 40);
add(btnNewButton);
textField = new JTextField();
textField.setEditable(false);
textField.setForeground(new Color(255, 255, 255));
textField.setFont(new Font("Comic Sans MS", Font.BOLD, 11));
textField.setText("CARDS LEFT "+ Deck.cardsLeft());
textField.setBackground(Color.BLACK);
textField.setBounds(160, 320, 80, 20);
add(textField);
textField.setColumns(10);
lblDeck = new JLabel("Deck");
lblDeck.setHorizontalAlignment(SwingConstants.CENTER);
lblDeck.setForeground(new Color(50, 205, 50));
lblDeck.setFont(new Font("Elephant", Font.BOLD | Font.ITALIC, 15));
lblDeck.setBounds(168, 244, 53, 14);
add(lblDeck);
btnNewButton_1 = new JLabel();
btnNewButton_1.setIcon(new ImageIcon("fallen1.png"));
btnNewButton_1.setBounds(175, 193, 46, 40);
add(btnNewButton_1);
lblTheFallen = new JLabel("The Fallen");
lblTheFallen.setHorizontalAlignment(SwingConstants.CENTER);
lblTheFallen.setForeground(new Color(30, 144, 255));
lblTheFallen.setFont(new Font("Elephant", Font.BOLD | Font.ITALIC, 15));
lblTheFallen.setBounds(140, 168, 100, 14);
add(lblTheFallen);
btnNewButton_2 = new JLabel();
btnNewButton_2.setIcon(new ImageIcon("forgotten1.png"));
btnNewButton_2.setBounds(175, 117, 46, 40);
add(btnNewButton_2);
lblForgotten = new JLabel("Forgotten");
lblForgotten.setForeground(new Color(0x8888ff));
lblForgotten.setFont(new Font("Elephant", Font.BOLD | Font.ITALIC, 15));
lblForgotten.setForeground(new Color(153, 102, 255));
lblForgotten.setBounds(149, 92, 117, 14);
add(lblForgotten);
panel= new JLayeredPane();
panel.add(new RoundedPanel());
panel.setLayout(null);
panel.setBackground(new Color(204, 153, 0));
panel.setBounds(39, 195, 100, 145);
add(panel);
}
public void addhero(Card x) throws IOException
{
Hero=new SmallCard(false,x);
panel.add(Hero);
menu = new JInternalFrame();
menu.getContentPane().setLayout(null);
repaint();
Play = new JButton("Play");
Play.setBounds(5, 11, 80, 23);
Play.setFont(new Font("Comic Sans MS", Font.BOLD | Font.ITALIC, 9));
menu.getContentPane().add(Play);
Preview = new JButton("Preview");
Preview.setBounds(5, 59, 80, 23);
menu.getContentPane().add(Preview);
Preview.setFont(new Font("Comic Sans MS", Font.BOLD | Font.ITALIC, 10));
menu.setClosable(true);
menu.setBounds(0,0,100,145);
menu.setBackground(Color.ORANGE);
menu.setVisible(false);
panel.add(menu);
menu.setOpaque(true);
}
}
| src/demo/DeckGui.java | package demo;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.border.LineBorder;
import data.LoadData;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import demo.deck;
import extra.Rlabel;
import extra.RoundButton;
import extra.RoundedPanel;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.IOException;
import javax.swing.JTextPane;
import javax.swing.border.CompoundBorder;
import javax.swing.border.MatteBorder;
public class DeckGui extends JPanel {
public JTextField textField;
public deck Deck;
private JTextField txtHero;
private JTextField txtCharacter;
private JTextField txtSection;
public JLabel btnNewButton;
public JLabel btnNewButton_1;
public JLabel btnNewButton_2;
public JLabel lblTheFallen;
public JLayeredPane panel;
public JLabel lblDeck;
public Rlabel lblForgotten ;
public JInternalFrame menu;
public SmallCard Hero;
public JButton Play, Preview;
public DeckGui(int x,int y) {
this.Deck=new deck();
try {
Deck.Load("resources/siren.in");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setBackground(new Color(255, 165, 0));
setBounds(x, y, 250, 340);
setOpaque(false);
setLayout(null);
btnNewButton = new JLabel("");
//btnNewButton.setBackground(new Color(139, 69, 19));
//btnNewButton.setOpaque(false);
btnNewButton.setIcon(new ImageIcon("draw1.png"));
btnNewButton.setBounds(175, 269, 46, 40);
add(btnNewButton);
textField = new JTextField();
textField.setEditable(false);
textField.setForeground(new Color(255, 255, 255));
textField.setFont(new Font("Comic Sans MS", Font.BOLD, 11));
textField.setText("CARDS LEFT "+ Deck.cardsLeft());
textField.setBackground(Color.BLACK);
textField.setBounds(160, 320, 80, 20);
add(textField);
textField.setColumns(10);
lblDeck = new JLabel("DECK");
lblDeck.setHorizontalAlignment(SwingConstants.CENTER);
lblDeck.setForeground(new Color(50, 205, 50));
lblDeck.setFont(new Font("Showcard Gothic", Font.BOLD | Font.ITALIC, 12));
lblDeck.setBounds(168, 244, 53, 14);
add(lblDeck);
btnNewButton_1 = new JLabel();
btnNewButton_1.setIcon(new ImageIcon("fallen1.png"));
btnNewButton_1.setBounds(175, 193, 46, 40);
add(btnNewButton_1);
lblTheFallen = new JLabel("The Fallen");
lblTheFallen.setHorizontalAlignment(SwingConstants.CENTER);
lblTheFallen.setForeground(new Color(30, 144, 255));
lblTheFallen.setFont(new Font("Showcard Gothic", Font.BOLD | Font.ITALIC, 12));
lblTheFallen.setBounds(160, 168, 80, 14);
add(lblTheFallen);
btnNewButton_2 = new JLabel();
btnNewButton_2.setIcon(new ImageIcon("forgotten1.png"));
btnNewButton_2.setBounds(175, 117, 46, 40);
add(btnNewButton_2);
lblForgotten = new Rlabel("Forgotten",0);
lblForgotten.setText("FORGOTTEN");
lblForgotten.setRightShadow(1,1,Color.black);
lblForgotten.setLeftShadow(-1,-1, new Color(0xccccff));
lblForgotten.setForeground(new Color(0x8888ff));
lblForgotten.setFont(lblForgotten.getFont().deriveFont(140f));
lblForgotten.setHorizontalAlignment(SwingConstants.RIGHT);
lblForgotten.setBorder(null);
lblForgotten.setForeground(new Color(153, 102, 255));
lblForgotten.setFont(new Font("Showcard Gothic", Font.BOLD | Font.ITALIC, 12));
lblForgotten.setBounds(160, 100, 117, 14);
add(lblForgotten);
panel= new JLayeredPane();
panel.add(new RoundedPanel());
panel.setLayout(null);
panel.setBackground(new Color(204, 153, 0));
panel.setBounds(39, 195, 100, 145);
add(panel);
}
public void addhero(Card x) throws IOException
{
Hero=new SmallCard(false,x);
panel.add(Hero);
menu = new JInternalFrame();
menu.getContentPane().setLayout(null);
repaint();
Play = new JButton("Play");
Play.setBounds(5, 11, 80, 23);
Play.setFont(new Font("Comic Sans MS", Font.BOLD | Font.ITALIC, 9));
menu.getContentPane().add(Play);
Preview = new JButton("Preview");
Preview.setBounds(5, 59, 80, 23);
menu.getContentPane().add(Preview);
Preview.setFont(new Font("Comic Sans MS", Font.BOLD | Font.ITALIC, 10));
menu.setClosable(true);
menu.setBounds(0,0,100,145);
menu.setBackground(Color.ORANGE);
menu.setVisible(false);
panel.add(menu);
menu.setOpaque(true);
}
}
| cambios a fonts | src/demo/DeckGui.java | cambios a fonts |
|
Java | mit | 6cfda8916342d9025d7935bdeaa4f95880b86b25 | 0 | amruthsoft9/Jenkis,svanoort/jenkins,yonglehou/jenkins,protazy/jenkins,intelchen/jenkins,batmat/jenkins,ns163/jenkins,NehemiahMi/jenkins,github-api-test-org/jenkins,olivergondza/jenkins,FarmGeek4Life/jenkins,292388900/jenkins,rashmikanta-1984/jenkins,chbiel/jenkins,tfennelly/jenkins,paulmillar/jenkins,jpbriend/jenkins,elkingtonmcb/jenkins,Wilfred/jenkins,jtnord/jenkins,Ykus/jenkins,kohsuke/hudson,tastatur/jenkins,daspilker/jenkins,mrooney/jenkins,elkingtonmcb/jenkins,ndeloof/jenkins,tastatur/jenkins,aduprat/jenkins,synopsys-arc-oss/jenkins,AustinKwang/jenkins,CodeShane/jenkins,morficus/jenkins,MadsNielsen/jtemp,rashmikanta-1984/jenkins,viqueen/jenkins,jk47/jenkins,tfennelly/jenkins,mdonohue/jenkins,samatdav/jenkins,gorcz/jenkins,jcarrothers-sap/jenkins,daspilker/jenkins,damianszczepanik/jenkins,Krasnyanskiy/jenkins,arcivanov/jenkins,mdonohue/jenkins,recena/jenkins,mdonohue/jenkins,liupugong/jenkins,github-api-test-org/jenkins,Wilfred/jenkins,paulmillar/jenkins,intelchen/jenkins,aheritier/jenkins,FTG-003/jenkins,csimons/jenkins,tfennelly/jenkins,viqueen/jenkins,varmenise/jenkins,github-api-test-org/jenkins,viqueen/jenkins,Jimilian/jenkins,my7seven/jenkins,soenter/jenkins,Wilfred/jenkins,csimons/jenkins,jenkinsci/jenkins,azweb76/jenkins,ndeloof/jenkins,FTG-003/jenkins,protazy/jenkins,SenolOzer/jenkins,fbelzunc/jenkins,mcanthony/jenkins,ErikVerheul/jenkins,luoqii/jenkins,aquarellian/jenkins,mrobinet/jenkins,sathiya-mit/jenkins,MichaelPranovich/jenkins_sc,dbroady1/jenkins,stefanbrausch/hudson-main,jk47/jenkins,petermarcoen/jenkins,pselle/jenkins,nandan4/Jenkins,github-api-test-org/jenkins,SebastienGllmt/jenkins,soenter/jenkins,goldchang/jenkins,petermarcoen/jenkins,Wilfred/jenkins,pjanouse/jenkins,christ66/jenkins,gitaccountforprashant/gittest,fbelzunc/jenkins,6WIND/jenkins,Jochen-A-Fuerbacher/jenkins,DoctorQ/jenkins,dbroady1/jenkins,morficus/jenkins,jpederzolli/jenkins-1,everyonce/jenkins,patbos/jenkins,seanlin816/jenkins,jk47/jenkins,liupugong/jenkins,yonglehou/jenkins,ChrisA89/jenkins,pselle/jenkins,Vlatombe/jenkins,evernat/jenkins,SenolOzer/jenkins,gusreiber/jenkins,DanielWeber/jenkins,my7seven/jenkins,seanlin816/jenkins,olivergondza/jenkins,dbroady1/jenkins,chbiel/jenkins,MichaelPranovich/jenkins_sc,stefanbrausch/hudson-main,jhoblitt/jenkins,SebastienGllmt/jenkins,yonglehou/jenkins,FarmGeek4Life/jenkins,guoxu0514/jenkins,samatdav/jenkins,vjuranek/jenkins,ydubreuil/jenkins,pantheon-systems/jenkins,luoqii/jenkins,chbiel/jenkins,CodeShane/jenkins,synopsys-arc-oss/jenkins,dennisjlee/jenkins,wuwen5/jenkins,msrb/jenkins,jtnord/jenkins,arunsingh/jenkins,6WIND/jenkins,vvv444/jenkins,tfennelly/jenkins,lvotypko/jenkins3,nandan4/Jenkins,ikedam/jenkins,vlajos/jenkins,Jimilian/jenkins,noikiy/jenkins,github-api-test-org/jenkins,verbitan/jenkins,abayer/jenkins,pjanouse/jenkins,vivek/hudson,lvotypko/jenkins,bkmeneguello/jenkins,lilyJi/jenkins,rashmikanta-1984/jenkins,brunocvcunha/jenkins,rsandell/jenkins,jenkinsci/jenkins,oleg-nenashev/jenkins,brunocvcunha/jenkins,protazy/jenkins,NehemiahMi/jenkins,h4ck3rm1k3/jenkins,escoem/jenkins,everyonce/jenkins,dariver/jenkins,hashar/jenkins,vvv444/jenkins,292388900/jenkins,MichaelPranovich/jenkins_sc,vijayto/jenkins,FarmGeek4Life/jenkins,aquarellian/jenkins,keyurpatankar/hudson,chbiel/jenkins,patbos/jenkins,rsandell/jenkins,stephenc/jenkins,shahharsh/jenkins,tfennelly/jenkins,hplatou/jenkins,wuwen5/jenkins,chbiel/jenkins,1and1/jenkins,lilyJi/jenkins,ydubreuil/jenkins,escoem/jenkins,wuwen5/jenkins,ikedam/jenkins,hudson/hudson-2.x,SenolOzer/jenkins,scoheb/jenkins,sathiya-mit/jenkins,amuniz/jenkins,aldaris/jenkins,lordofthejars/jenkins,vlajos/jenkins,liorhson/jenkins,DoctorQ/jenkins,keyurpatankar/hudson,christ66/jenkins,hashar/jenkins,rsandell/jenkins,lvotypko/jenkins,huybrechts/hudson,gusreiber/jenkins,jpbriend/jenkins,stefanbrausch/hudson-main,msrb/jenkins,scoheb/jenkins,scoheb/jenkins,aduprat/jenkins,albers/jenkins,thomassuckow/jenkins,godfath3r/jenkins,jpederzolli/jenkins-1,DoctorQ/jenkins,samatdav/jenkins,ns163/jenkins,my7seven/jenkins,varmenise/jenkins,jcarrothers-sap/jenkins,shahharsh/jenkins,singh88/jenkins,godfath3r/jenkins,thomassuckow/jenkins,everyonce/jenkins,csimons/jenkins,nandan4/Jenkins,pantheon-systems/jenkins,damianszczepanik/jenkins,thomassuckow/jenkins,aheritier/jenkins,chbiel/jenkins,tangkun75/jenkins,dbroady1/jenkins,intelchen/jenkins,samatdav/jenkins,bkmeneguello/jenkins,CodeShane/jenkins,vijayto/jenkins,mcanthony/jenkins,kohsuke/hudson,tangkun75/jenkins,MarkEWaite/jenkins,daspilker/jenkins,Vlatombe/jenkins,mrobinet/jenkins,hemantojhaa/jenkins,mcanthony/jenkins,gitaccountforprashant/gittest,my7seven/jenkins,vijayto/jenkins,DoctorQ/jenkins,SenolOzer/jenkins,jpbriend/jenkins,christ66/jenkins,github-api-test-org/jenkins,varmenise/jenkins,luoqii/jenkins,h4ck3rm1k3/jenkins,keyurpatankar/hudson,jglick/jenkins,vlajos/jenkins,gorcz/jenkins,khmarbaise/jenkins,lvotypko/jenkins,wuwen5/jenkins,alvarolobato/jenkins,arcivanov/jenkins,guoxu0514/jenkins,evernat/jenkins,elkingtonmcb/jenkins,hemantojhaa/jenkins,khmarbaise/jenkins,lindzh/jenkins,synopsys-arc-oss/jenkins,lvotypko/jenkins2,liorhson/jenkins,liupugong/jenkins,azweb76/jenkins,vlajos/jenkins,mrobinet/jenkins,my7seven/jenkins,MichaelPranovich/jenkins_sc,pantheon-systems/jenkins,bkmeneguello/jenkins,jcarrothers-sap/jenkins,gusreiber/jenkins,paulwellnerbou/jenkins,soenter/jenkins,paulmillar/jenkins,pjanouse/jenkins,bkmeneguello/jenkins,mrobinet/jenkins,ikedam/jenkins,jzjzjzj/jenkins,singh88/jenkins,thomassuckow/jenkins,hudson/hudson-2.x,wangyikai/jenkins,scoheb/jenkins,vjuranek/jenkins,goldchang/jenkins,godfath3r/jenkins,gitaccountforprashant/gittest,hudson/hudson-2.x,morficus/jenkins,seanlin816/jenkins,duzifang/my-jenkins,rsandell/jenkins,viqueen/jenkins,vjuranek/jenkins,jenkinsci/jenkins,damianszczepanik/jenkins,github-api-test-org/jenkins,maikeffi/hudson,noikiy/jenkins,msrb/jenkins,sathiya-mit/jenkins,godfath3r/jenkins,andresrc/jenkins,amruthsoft9/Jenkis,jglick/jenkins,dariver/jenkins,stephenc/jenkins,MarkEWaite/jenkins,MarkEWaite/jenkins,gitaccountforprashant/gittest,6WIND/jenkins,292388900/jenkins,ndeloof/jenkins,FTG-003/jenkins,daspilker/jenkins,evernat/jenkins,huybrechts/hudson,iterate/coding-dojo,hemantojhaa/jenkins,bpzhang/jenkins,v1v/jenkins,ErikVerheul/jenkins,amuniz/jenkins,andresrc/jenkins,vjuranek/jenkins,mcanthony/jenkins,gitaccountforprashant/gittest,my7seven/jenkins,maikeffi/hudson,SebastienGllmt/jenkins,akshayabd/jenkins,ChrisA89/jenkins,pantheon-systems/jenkins,albers/jenkins,aduprat/jenkins,daspilker/jenkins,dennisjlee/jenkins,iterate/coding-dojo,abayer/jenkins,msrb/jenkins,amruthsoft9/Jenkis,lindzh/jenkins,olivergondza/jenkins,pselle/jenkins,AustinKwang/jenkins,MarkEWaite/jenkins,tfennelly/jenkins,singh88/jenkins,AustinKwang/jenkins,yonglehou/jenkins,pselle/jenkins,dariver/jenkins,mrooney/jenkins,1and1/jenkins,paulwellnerbou/jenkins,FarmGeek4Life/jenkins,samatdav/jenkins,mdonohue/jenkins,h4ck3rm1k3/jenkins,rsandell/jenkins,SenolOzer/jenkins,aldaris/jenkins,SebastienGllmt/jenkins,rlugojr/jenkins,jpederzolli/jenkins-1,batmat/jenkins,msrb/jenkins,FarmGeek4Life/jenkins,daniel-beck/jenkins,alvarolobato/jenkins,rsandell/jenkins,gitaccountforprashant/gittest,Krasnyanskiy/jenkins,andresrc/jenkins,luoqii/jenkins,patbos/jenkins,amruthsoft9/Jenkis,arunsingh/jenkins,goldchang/jenkins,lvotypko/jenkins2,tastatur/jenkins,aquarellian/jenkins,daniel-beck/jenkins,kzantow/jenkins,FarmGeek4Life/jenkins,Vlatombe/jenkins,yonglehou/jenkins,vivek/hudson,dariver/jenkins,azweb76/jenkins,guoxu0514/jenkins,alvarolobato/jenkins,guoxu0514/jenkins,olivergondza/jenkins,Jochen-A-Fuerbacher/jenkins,brunocvcunha/jenkins,jtnord/jenkins,scoheb/jenkins,CodeShane/jenkins,gusreiber/jenkins,hplatou/jenkins,noikiy/jenkins,dennisjlee/jenkins,vlajos/jenkins,aheritier/jenkins,1and1/jenkins,lvotypko/jenkins,lvotypko/jenkins2,hudson/hudson-2.x,morficus/jenkins,h4ck3rm1k3/jenkins,deadmoose/jenkins,viqueen/jenkins,wangyikai/jenkins,batmat/jenkins,shahharsh/jenkins,kzantow/jenkins,jpederzolli/jenkins-1,ns163/jenkins,escoem/jenkins,ns163/jenkins,christ66/jenkins,jpederzolli/jenkins-1,lvotypko/jenkins3,hplatou/jenkins,DanielWeber/jenkins,lvotypko/jenkins3,arcivanov/jenkins,maikeffi/hudson,goldchang/jenkins,Wilfred/jenkins,paulmillar/jenkins,stefanbrausch/hudson-main,patbos/jenkins,wuwen5/jenkins,aheritier/jenkins,kohsuke/hudson,nandan4/Jenkins,jhoblitt/jenkins,damianszczepanik/jenkins,maikeffi/hudson,deadmoose/jenkins,hemantojhaa/jenkins,arunsingh/jenkins,Ykus/jenkins,MarkEWaite/jenkins,dariver/jenkins,liorhson/jenkins,pselle/jenkins,liupugong/jenkins,h4ck3rm1k3/jenkins,samatdav/jenkins,soenter/jenkins,azweb76/jenkins,kzantow/jenkins,bpzhang/jenkins,gorcz/jenkins,v1v/jenkins,maikeffi/hudson,lilyJi/jenkins,arcivanov/jenkins,nandan4/Jenkins,svanoort/jenkins,iterate/coding-dojo,svanoort/jenkins,jglick/jenkins,hashar/jenkins,iqstack/jenkins,mpeltonen/jenkins,shahharsh/jenkins,albers/jenkins,maikeffi/hudson,evernat/jenkins,MadsNielsen/jtemp,iqstack/jenkins,goldchang/jenkins,dennisjlee/jenkins,vivek/hudson,keyurpatankar/hudson,aheritier/jenkins,pselle/jenkins,arunsingh/jenkins,vvv444/jenkins,tangkun75/jenkins,Krasnyanskiy/jenkins,jenkinsci/jenkins,albers/jenkins,NehemiahMi/jenkins,lindzh/jenkins,vijayto/jenkins,damianszczepanik/jenkins,khmarbaise/jenkins,MadsNielsen/jtemp,vjuranek/jenkins,albers/jenkins,jk47/jenkins,liorhson/jenkins,DanielWeber/jenkins,noikiy/jenkins,daniel-beck/jenkins,huybrechts/hudson,jhoblitt/jenkins,mcanthony/jenkins,Ykus/jenkins,mdonohue/jenkins,petermarcoen/jenkins,rashmikanta-1984/jenkins,6WIND/jenkins,mdonohue/jenkins,escoem/jenkins,lvotypko/jenkins2,ChrisA89/jenkins,DoctorQ/jenkins,huybrechts/hudson,ajshastri/jenkins,elkingtonmcb/jenkins,fbelzunc/jenkins,keyurpatankar/hudson,ikedam/jenkins,jzjzjzj/jenkins,evernat/jenkins,brunocvcunha/jenkins,luoqii/jenkins,kzantow/jenkins,Ykus/jenkins,mpeltonen/jenkins,stefanbrausch/hudson-main,ikedam/jenkins,daspilker/jenkins,deadmoose/jenkins,Krasnyanskiy/jenkins,ydubreuil/jenkins,kohsuke/hudson,arunsingh/jenkins,hemantojhaa/jenkins,DoctorQ/jenkins,vjuranek/jenkins,jcsirot/jenkins,sathiya-mit/jenkins,thomassuckow/jenkins,kzantow/jenkins,jzjzjzj/jenkins,KostyaSha/jenkins,noikiy/jenkins,dariver/jenkins,olivergondza/jenkins,lvotypko/jenkins3,tangkun75/jenkins,aquarellian/jenkins,viqueen/jenkins,evernat/jenkins,bkmeneguello/jenkins,svanoort/jenkins,aduprat/jenkins,shahharsh/jenkins,SebastienGllmt/jenkins,vvv444/jenkins,github-api-test-org/jenkins,csimons/jenkins,aheritier/jenkins,jcsirot/jenkins,Jimilian/jenkins,kohsuke/hudson,godfath3r/jenkins,lordofthejars/jenkins,DoctorQ/jenkins,daniel-beck/jenkins,hplatou/jenkins,rashmikanta-1984/jenkins,jtnord/jenkins,lilyJi/jenkins,arcivanov/jenkins,jglick/jenkins,aduprat/jenkins,ajshastri/jenkins,MadsNielsen/jtemp,aduprat/jenkins,jzjzjzj/jenkins,kohsuke/hudson,ns163/jenkins,paulwellnerbou/jenkins,oleg-nenashev/jenkins,abayer/jenkins,fbelzunc/jenkins,lvotypko/jenkins2,deadmoose/jenkins,evernat/jenkins,MadsNielsen/jtemp,keyurpatankar/hudson,mcanthony/jenkins,lordofthejars/jenkins,keyurpatankar/hudson,wangyikai/jenkins,andresrc/jenkins,jcsirot/jenkins,noikiy/jenkins,FTG-003/jenkins,azweb76/jenkins,dbroady1/jenkins,SebastienGllmt/jenkins,verbitan/jenkins,ChrisA89/jenkins,intelchen/jenkins,akshayabd/jenkins,aquarellian/jenkins,Ykus/jenkins,batmat/jenkins,mattclark/jenkins,tastatur/jenkins,bpzhang/jenkins,MadsNielsen/jtemp,verbitan/jenkins,morficus/jenkins,tangkun75/jenkins,jcarrothers-sap/jenkins,brunocvcunha/jenkins,AustinKwang/jenkins,godfath3r/jenkins,azweb76/jenkins,amuniz/jenkins,jglick/jenkins,vlajos/jenkins,stephenc/jenkins,jk47/jenkins,lvotypko/jenkins,jenkinsci/jenkins,lordofthejars/jenkins,escoem/jenkins,fbelzunc/jenkins,patbos/jenkins,rlugojr/jenkins,rlugojr/jenkins,ndeloof/jenkins,tastatur/jenkins,ajshastri/jenkins,KostyaSha/jenkins,jtnord/jenkins,khmarbaise/jenkins,paulwellnerbou/jenkins,seanlin816/jenkins,vjuranek/jenkins,paulmillar/jenkins,vivek/hudson,1and1/jenkins,hplatou/jenkins,damianszczepanik/jenkins,292388900/jenkins,Jochen-A-Fuerbacher/jenkins,hudson/hudson-2.x,mdonohue/jenkins,jenkinsci/jenkins,gorcz/jenkins,hplatou/jenkins,ns163/jenkins,ErikVerheul/jenkins,seanlin816/jenkins,verbitan/jenkins,chbiel/jenkins,hplatou/jenkins,albers/jenkins,jpbriend/jenkins,h4ck3rm1k3/jenkins,jenkinsci/jenkins,ydubreuil/jenkins,ydubreuil/jenkins,mrobinet/jenkins,Vlatombe/jenkins,christ66/jenkins,oleg-nenashev/jenkins,mpeltonen/jenkins,daniel-beck/jenkins,arcivanov/jenkins,keyurpatankar/hudson,maikeffi/hudson,hashar/jenkins,v1v/jenkins,wuwen5/jenkins,pantheon-systems/jenkins,morficus/jenkins,synopsys-arc-oss/jenkins,vivek/hudson,rlugojr/jenkins,mrobinet/jenkins,ajshastri/jenkins,duzifang/my-jenkins,oleg-nenashev/jenkins,thomassuckow/jenkins,batmat/jenkins,lindzh/jenkins,intelchen/jenkins,kohsuke/hudson,soenter/jenkins,singh88/jenkins,Krasnyanskiy/jenkins,stephenc/jenkins,liorhson/jenkins,MadsNielsen/jtemp,deadmoose/jenkins,jenkinsci/jenkins,deadmoose/jenkins,jcarrothers-sap/jenkins,AustinKwang/jenkins,jzjzjzj/jenkins,huybrechts/hudson,intelchen/jenkins,lvotypko/jenkins3,stefanbrausch/hudson-main,jpederzolli/jenkins-1,yonglehou/jenkins,jglick/jenkins,ajshastri/jenkins,mrooney/jenkins,aquarellian/jenkins,dbroady1/jenkins,mattclark/jenkins,daniel-beck/jenkins,aduprat/jenkins,varmenise/jenkins,maikeffi/hudson,goldchang/jenkins,Jimilian/jenkins,oleg-nenashev/jenkins,jhoblitt/jenkins,gorcz/jenkins,DanielWeber/jenkins,ChrisA89/jenkins,stefanbrausch/hudson-main,mattclark/jenkins,jpbriend/jenkins,svanoort/jenkins,petermarcoen/jenkins,6WIND/jenkins,wangyikai/jenkins,mpeltonen/jenkins,rsandell/jenkins,protazy/jenkins,varmenise/jenkins,FarmGeek4Life/jenkins,lvotypko/jenkins3,jcarrothers-sap/jenkins,vijayto/jenkins,ydubreuil/jenkins,SenolOzer/jenkins,jzjzjzj/jenkins,dennisjlee/jenkins,iterate/coding-dojo,svanoort/jenkins,pjanouse/jenkins,khmarbaise/jenkins,lilyJi/jenkins,akshayabd/jenkins,bpzhang/jenkins,Jochen-A-Fuerbacher/jenkins,hemantojhaa/jenkins,aquarellian/jenkins,h4ck3rm1k3/jenkins,amuniz/jenkins,iterate/coding-dojo,jk47/jenkins,godfath3r/jenkins,KostyaSha/jenkins,daspilker/jenkins,shahharsh/jenkins,Krasnyanskiy/jenkins,goldchang/jenkins,jtnord/jenkins,ns163/jenkins,paulwellnerbou/jenkins,escoem/jenkins,jhoblitt/jenkins,bkmeneguello/jenkins,ndeloof/jenkins,alvarolobato/jenkins,noikiy/jenkins,gusreiber/jenkins,mrooney/jenkins,FTG-003/jenkins,everyonce/jenkins,synopsys-arc-oss/jenkins,gitaccountforprashant/gittest,mrooney/jenkins,arcivanov/jenkins,petermarcoen/jenkins,msrb/jenkins,mattclark/jenkins,mattclark/jenkins,recena/jenkins,vvv444/jenkins,stephenc/jenkins,stephenc/jenkins,alvarolobato/jenkins,recena/jenkins,mpeltonen/jenkins,iterate/coding-dojo,Jochen-A-Fuerbacher/jenkins,KostyaSha/jenkins,olivergondza/jenkins,Jimilian/jenkins,KostyaSha/jenkins,DanielWeber/jenkins,vivek/hudson,amruthsoft9/Jenkis,arunsingh/jenkins,duzifang/my-jenkins,rlugojr/jenkins,DanielWeber/jenkins,csimons/jenkins,luoqii/jenkins,brunocvcunha/jenkins,6WIND/jenkins,wangyikai/jenkins,morficus/jenkins,lvotypko/jenkins2,verbitan/jenkins,svanoort/jenkins,jk47/jenkins,gusreiber/jenkins,v1v/jenkins,goldchang/jenkins,bpzhang/jenkins,ChrisA89/jenkins,abayer/jenkins,MichaelPranovich/jenkins_sc,duzifang/my-jenkins,tangkun75/jenkins,1and1/jenkins,rlugojr/jenkins,everyonce/jenkins,1and1/jenkins,jcsirot/jenkins,hashar/jenkins,christ66/jenkins,bpzhang/jenkins,paulmillar/jenkins,gorcz/jenkins,dennisjlee/jenkins,lordofthejars/jenkins,protazy/jenkins,duzifang/my-jenkins,elkingtonmcb/jenkins,mattclark/jenkins,amruthsoft9/Jenkis,sathiya-mit/jenkins,varmenise/jenkins,seanlin816/jenkins,Jimilian/jenkins,mattclark/jenkins,paulwellnerbou/jenkins,Wilfred/jenkins,CodeShane/jenkins,recena/jenkins,jcsirot/jenkins,ndeloof/jenkins,azweb76/jenkins,292388900/jenkins,292388900/jenkins,thomassuckow/jenkins,intelchen/jenkins,liorhson/jenkins,MichaelPranovich/jenkins_sc,aldaris/jenkins,liorhson/jenkins,Vlatombe/jenkins,singh88/jenkins,albers/jenkins,wangyikai/jenkins,NehemiahMi/jenkins,CodeShane/jenkins,escoem/jenkins,KostyaSha/jenkins,vivek/hudson,msrb/jenkins,akshayabd/jenkins,guoxu0514/jenkins,mpeltonen/jenkins,tastatur/jenkins,samatdav/jenkins,ErikVerheul/jenkins,iqstack/jenkins,alvarolobato/jenkins,MarkEWaite/jenkins,stephenc/jenkins,jcsirot/jenkins,andresrc/jenkins,vijayto/jenkins,abayer/jenkins,6WIND/jenkins,pselle/jenkins,KostyaSha/jenkins,jpbriend/jenkins,iqstack/jenkins,jcsirot/jenkins,aldaris/jenkins,viqueen/jenkins,scoheb/jenkins,ndeloof/jenkins,verbitan/jenkins,rlugojr/jenkins,fbelzunc/jenkins,damianszczepanik/jenkins,patbos/jenkins,iqstack/jenkins,liupugong/jenkins,hashar/jenkins,daniel-beck/jenkins,FTG-003/jenkins,abayer/jenkins,jzjzjzj/jenkins,jhoblitt/jenkins,lordofthejars/jenkins,Krasnyanskiy/jenkins,hashar/jenkins,sathiya-mit/jenkins,NehemiahMi/jenkins,lvotypko/jenkins2,andresrc/jenkins,1and1/jenkins,DoctorQ/jenkins,everyonce/jenkins,ErikVerheul/jenkins,bpzhang/jenkins,protazy/jenkins,recena/jenkins,amuniz/jenkins,Wilfred/jenkins,huybrechts/hudson,csimons/jenkins,olivergondza/jenkins,shahharsh/jenkins,MarkEWaite/jenkins,vvv444/jenkins,aldaris/jenkins,CodeShane/jenkins,ikedam/jenkins,rashmikanta-1984/jenkins,soenter/jenkins,huybrechts/hudson,dbroady1/jenkins,jcarrothers-sap/jenkins,liupugong/jenkins,tangkun75/jenkins,lilyJi/jenkins,tfennelly/jenkins,lindzh/jenkins,singh88/jenkins,jpederzolli/jenkins-1,damianszczepanik/jenkins,kohsuke/hudson,rashmikanta-1984/jenkins,soenter/jenkins,everyonce/jenkins,duzifang/my-jenkins,oleg-nenashev/jenkins,pjanouse/jenkins,jtnord/jenkins,v1v/jenkins,duzifang/my-jenkins,christ66/jenkins,ikedam/jenkins,vivek/hudson,AustinKwang/jenkins,seanlin816/jenkins,SebastienGllmt/jenkins,jhoblitt/jenkins,nandan4/Jenkins,ydubreuil/jenkins,aldaris/jenkins,Vlatombe/jenkins,mrooney/jenkins,NehemiahMi/jenkins,pantheon-systems/jenkins,brunocvcunha/jenkins,vlajos/jenkins,aheritier/jenkins,jzjzjzj/jenkins,gusreiber/jenkins,daniel-beck/jenkins,lilyJi/jenkins,pantheon-systems/jenkins,nandan4/Jenkins,recena/jenkins,paulmillar/jenkins,lvotypko/jenkins,mpeltonen/jenkins,shahharsh/jenkins,andresrc/jenkins,vijayto/jenkins,arunsingh/jenkins,amuniz/jenkins,iqstack/jenkins,dennisjlee/jenkins,khmarbaise/jenkins,Ykus/jenkins,batmat/jenkins,Jochen-A-Fuerbacher/jenkins,lvotypko/jenkins,recena/jenkins,wuwen5/jenkins,Jimilian/jenkins,fbelzunc/jenkins,ErikVerheul/jenkins,batmat/jenkins,varmenise/jenkins,jglick/jenkins,alvarolobato/jenkins,iqstack/jenkins,AustinKwang/jenkins,gorcz/jenkins,pjanouse/jenkins,liupugong/jenkins,lordofthejars/jenkins,amuniz/jenkins,luoqii/jenkins,SenolOzer/jenkins,dariver/jenkins,patbos/jenkins,lvotypko/jenkins3,ajshastri/jenkins,protazy/jenkins,akshayabd/jenkins,Ykus/jenkins,ikedam/jenkins,pjanouse/jenkins,ErikVerheul/jenkins,wangyikai/jenkins,paulwellnerbou/jenkins,kzantow/jenkins,tastatur/jenkins,v1v/jenkins,292388900/jenkins,DanielWeber/jenkins,ajshastri/jenkins,vvv444/jenkins,hemantojhaa/jenkins,elkingtonmcb/jenkins,ChrisA89/jenkins,kzantow/jenkins,elkingtonmcb/jenkins,yonglehou/jenkins,singh88/jenkins,akshayabd/jenkins,akshayabd/jenkins,gorcz/jenkins,petermarcoen/jenkins,csimons/jenkins,bkmeneguello/jenkins,KostyaSha/jenkins,jcarrothers-sap/jenkins,mrooney/jenkins,MichaelPranovich/jenkins_sc,khmarbaise/jenkins,my7seven/jenkins,mrobinet/jenkins,rsandell/jenkins,deadmoose/jenkins,lindzh/jenkins,amruthsoft9/Jenkis,iterate/coding-dojo,petermarcoen/jenkins,sathiya-mit/jenkins,hudson/hudson-2.x,FTG-003/jenkins,NehemiahMi/jenkins,verbitan/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,Vlatombe/jenkins,abayer/jenkins,guoxu0514/jenkins,aldaris/jenkins,guoxu0514/jenkins,lindzh/jenkins,scoheb/jenkins,Jochen-A-Fuerbacher/jenkins,synopsys-arc-oss/jenkins,jpbriend/jenkins,v1v/jenkins,synopsys-arc-oss/jenkins,mcanthony/jenkins | package hudson;
import hudson.model.Hudson;
import hudson.model.TaskListener;
import hudson.model.Computer;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Channel;
import hudson.Proc.LocalProc;
import hudson.util.StreamCopyThread;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Starts a process.
*
* <p>
* This hides the difference between running programs locally vs remotely.
*
*
* <h2>'env' parameter</h2>
* <p>
* To allow important environment variables to be copied over to the remote machine,
* the 'env' parameter shouldn't contain default inherited environment variables
* (which often contains machine-specific information, like PATH, TIMEZONE, etc.)
*
* <p>
* {@link Launcher} is responsible for inheriting environment variables.
*
*
* @author Kohsuke Kawaguchi
*/
public abstract class Launcher {
protected final TaskListener listener;
protected final VirtualChannel channel;
public Launcher(TaskListener listener, VirtualChannel channel) {
this.listener = listener;
this.channel = channel;
}
/**
* Gets the channel that can be used to run a program remotely.
*
* @return
* null if the target node is not configured to support this.
* this is a transitional measure.
* Note that a launcher for the master is always non-null.
*/
public VirtualChannel getChannel() {
return channel;
}
public final Proc launch(String cmd, Map<String,String> env, OutputStream out, FilePath workDir) throws IOException {
return launch(cmd,Util.mapToEnv(env),out,workDir);
}
public final Proc launch(String[] cmd, Map<String,String> env, OutputStream out, FilePath workDir) throws IOException {
return launch(cmd,Util.mapToEnv(env),out,workDir);
}
public final Proc launch(String[] cmd, Map<String,String> env, InputStream in, OutputStream out) throws IOException {
return launch(cmd,Util.mapToEnv(env),in,out);
}
public final Proc launch(String cmd,String[] env,OutputStream out, FilePath workDir) throws IOException {
return launch(Util.tokenize(cmd),env,out,workDir);
}
public final Proc launch(String[] cmd,String[] env,OutputStream out, FilePath workDir) throws IOException {
return launch(cmd,env,null,out,workDir);
}
public final Proc launch(String[] cmd,String[] env,InputStream in,OutputStream out) throws IOException {
return launch(cmd,env,in,out,null);
}
/**
* @param in
* null if there's no input.
* @param workDir
* null if the working directory could be anything.
* @param out
* stdout and stderr of the process will be sent to this stream.
* the stream won't be closed.
*/
public abstract Proc launch(String[] cmd,String[] env,InputStream in,OutputStream out, FilePath workDir) throws IOException;
/**
* Launches a specified process and connects its input/output to a {@link Channel}, then
* return it.
*
* @param out
* Where the stderr from the launched process will be sent.
*/
public abstract Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir) throws IOException, InterruptedException;
/**
* Returns true if this {@link Launcher} is going to launch on Unix.
*/
public boolean isUnix() {
return File.pathSeparatorChar==':';
}
/**
* Prints out the command line to the listener so that users know what we are doing.
*/
protected final void printCommandLine(String[] cmd, FilePath workDir) {
StringBuffer buf = new StringBuffer();
if (workDir != null) {
buf.append('[');
if(showFullPath)
buf.append(workDir.getRemote());
else
buf.append(workDir.getRemote().replaceFirst("^.+[/\\\\]", ""));
buf.append("] ");
}
buf.append('$');
for (String c : cmd) {
buf.append(' ');
if(c.indexOf(' ')>=0) {
if(c.indexOf('"')>=0)
buf.append('\'').append(c).append('\'');
else
buf.append('"').append(c).append('"');
} else
buf.append(c);
}
listener.getLogger().println(buf.toString());
}
public static class LocalLauncher extends Launcher {
public LocalLauncher(TaskListener listener) {
this(listener,Hudson.MasterComputer.localChannel);
}
public LocalLauncher(TaskListener listener, VirtualChannel channel) {
super(listener, channel);
}
public Proc launch(String[] cmd,String[] env,InputStream in,OutputStream out, FilePath workDir) throws IOException {
printCommandLine(cmd, workDir);
return new LocalProc(cmd,Util.mapToEnv(inherit(env)),in,out, toFile(workDir));
}
private File toFile(FilePath f) {
return f==null ? null : new File(f.getRemote());
}
public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir) throws IOException {
printCommandLine(cmd, workDir);
Process proc = Runtime.getRuntime().exec(cmd, null, toFile(workDir));
// TODO: don't we need the equivalent of 'Proc' here? to abort it
Thread t2 = new StreamCopyThread(cmd+": stderr copier", proc.getErrorStream(), out);
t2.start();
return new Channel("locally launched channel on "+cmd,
Computer.threadPoolForRemoting, proc.getInputStream(), proc.getOutputStream(), out);
}
/**
* Expands the list of environment variables by inheriting current env variables.
*/
private Map<String,String> inherit(String[] env) {
Map<String,String> m = new HashMap<String,String>(EnvVars.masterEnvVars);
for (String e : env) {
int index = e.indexOf('=');
String key = e.substring(0,index);
String value = e.substring(index+1);
if(value.length()==0)
m.remove(key);
else
m.put(key,value);
}
return m;
}
}
/**
* Debug option to display full current path instead of just the last token.
*/
public static boolean showFullPath = false;
}
| core/src/main/java/hudson/Launcher.java | package hudson;
import hudson.model.Hudson;
import hudson.model.TaskListener;
import hudson.model.Computer;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Channel;
import hudson.Proc.LocalProc;
import hudson.util.StreamCopyThread;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Starts a process.
*
* <p>
* This hides the difference between running programs locally vs remotely.
*
*
* <h2>'env' parameter</h2>
* <p>
* To allow important environment variables to be copied over to the remote machine,
* the 'env' parameter shouldn't contain default inherited environment variables
* (which often contains machine-specific information, like PATH, TIMEZONE, etc.)
*
* <p>
* {@link Launcher} is responsible for inheriting environment variables.
*
*
* @author Kohsuke Kawaguchi
*/
public abstract class Launcher {
protected final TaskListener listener;
protected final VirtualChannel channel;
public Launcher(TaskListener listener, VirtualChannel channel) {
this.listener = listener;
this.channel = channel;
}
/**
* Gets the channel that can be used to run a program remotely.
*
* @return
* null if the target node is not configured to support this.
* this is a transitional measure.
* Note that a launcher for the master is always non-null.
*/
public VirtualChannel getChannel() {
return channel;
}
public final Proc launch(String cmd, Map<String,String> env, OutputStream out, FilePath workDir) throws IOException {
return launch(cmd,Util.mapToEnv(env),out,workDir);
}
public final Proc launch(String[] cmd, Map<String,String> env, OutputStream out, FilePath workDir) throws IOException {
return launch(cmd,Util.mapToEnv(env),out,workDir);
}
public final Proc launch(String[] cmd, Map<String,String> env, InputStream in, OutputStream out) throws IOException {
return launch(cmd,Util.mapToEnv(env),in,out);
}
public final Proc launch(String cmd,String[] env,OutputStream out, FilePath workDir) throws IOException {
return launch(Util.tokenize(cmd),env,out,workDir);
}
public final Proc launch(String[] cmd,String[] env,OutputStream out, FilePath workDir) throws IOException {
return launch(cmd,env,null,out,workDir);
}
public final Proc launch(String[] cmd,String[] env,InputStream in,OutputStream out) throws IOException {
return launch(cmd,env,in,out,null);
}
/**
* @param in
* null if there's no input.
* @param workDir
* null if the working directory could be anything.
* @param out
* stdout and stderr of the process will be sent to this stream.
* the stream won't be closed.
*/
public abstract Proc launch(String[] cmd,String[] env,InputStream in,OutputStream out, FilePath workDir) throws IOException;
/**
* Launches a specified process and connects its input/output to a {@link Channel}, then
* return it.
*
* @param out
* Where the stderr from the launched process will be sent.
*/
public abstract Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir) throws IOException, InterruptedException;
/**
* Returns true if this {@link Launcher} is going to launch on Unix.
*/
public boolean isUnix() {
return File.pathSeparatorChar==':';
}
/**
* Prints out the command line to the listener so that users know what we are doing.
*/
protected final void printCommandLine(String[] cmd, FilePath workDir) {
StringBuffer buf = new StringBuffer();
if (workDir != null) {
buf.append('[');
if(showFullPath)
buf.append(workDir.getRemote());
else
buf.append(workDir.getRemote().replaceFirst("^.+[/\\\\]", ""));
buf.append("] ");
}
buf.append('$');
for (String c : cmd) {
buf.append(' ').append(c);
}
listener.getLogger().println(buf.toString());
}
public static class LocalLauncher extends Launcher {
public LocalLauncher(TaskListener listener) {
this(listener,Hudson.MasterComputer.localChannel);
}
public LocalLauncher(TaskListener listener, VirtualChannel channel) {
super(listener, channel);
}
public Proc launch(String[] cmd,String[] env,InputStream in,OutputStream out, FilePath workDir) throws IOException {
printCommandLine(cmd, workDir);
return new LocalProc(cmd,Util.mapToEnv(inherit(env)),in,out, toFile(workDir));
}
private File toFile(FilePath f) {
return f==null ? null : new File(f.getRemote());
}
public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir) throws IOException {
printCommandLine(cmd, workDir);
Process proc = Runtime.getRuntime().exec(cmd, null, toFile(workDir));
// TODO: don't we need the equivalent of 'Proc' here? to abort it
Thread t2 = new StreamCopyThread(cmd+": stderr copier", proc.getErrorStream(), out);
t2.start();
return new Channel("locally launched channel on "+cmd,
Computer.threadPoolForRemoting, proc.getInputStream(), proc.getOutputStream(), out);
}
/**
* Expands the list of environment variables by inheriting current env variables.
*/
private Map<String,String> inherit(String[] env) {
Map<String,String> m = new HashMap<String,String>(EnvVars.masterEnvVars);
for (String e : env) {
int index = e.indexOf('=');
String key = e.substring(0,index);
String value = e.substring(index+1);
if(value.length()==0)
m.remove(key);
else
m.put(key,value);
}
return m;
}
}
/**
* Debug option to display full current path instead of just the last token.
*/
public static boolean showFullPath = false;
}
| properly quote tokens when it needs to be quoted.
git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@2335 71c3de6d-444a-0410-be80-ed276b4c234a
| core/src/main/java/hudson/Launcher.java | properly quote tokens when it needs to be quoted. |
|
Java | mit | 820dbe0c2cf1aa5d8a3dda3d31232518bbcafae2 | 0 | dhaunac/fictional-spoon,GlassWispInteractive/fictional-spoon | package game;
import dungeon.Generator;
import dungeon.Map;
import entities.Entity;
import entities.EntityFactory;
import entities.Player;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Paint;
public class World {
/** SINGELTON */
private static World singleton;
// class components
private Generator gen;
private Map map;
private EntityFactory fac;
private State state = State.VIEW;
// variables
private int size = 5;
private int offsetX, offsetY, viewSizeX, viewSizeY;
private Paint[] color = { Paint.valueOf("#454545"), Paint.valueOf("#A1D490"), Paint.valueOf("#D4B790"),
Paint.valueOf("#B39B7B"), Paint.valueOf("#801B1B"), Paint.valueOf("#000000") };
public static World getWorld() {
if (singleton == null) {
singleton = new World();
}
return singleton;
}
private World() {
gen = new Generator(280, 180);
map = gen.newLevel();
fac = EntityFactory.getFactory();
// player = fac.makePlayer(15, 15);
changeState(state);
Player player = fac.makePlayer(80, 70);
setCurrentView(player.getX(), player.getY());
}
// we should delete this function - change the map would need effects in any
// other state as well!
public void updateMap(Map newMap) {
this.map = newMap;
}
public Map getMap() {
return this.map;
}
public void setSize(int size) {
this.size = size;
}
public void changeState(State state){
this.state = state;
switch (this.state) {
case MAP:
viewSizeX = map.getN();
viewSizeY = map.getM();
size = 5;
break;
case VIEW:
size = 20; //10
viewSizeX = 1400/size; //140
viewSizeY = 900/size; //90
break;
default:
break;
}
}
public void setCurrentView(int centerX, int centerY){
this.offsetX = centerX - viewSizeX/2;
this.offsetY = centerY - viewSizeY/2;
checkOffset();
}
public void changeCurrentView(int centerX, int centerY) {
int viewPaddingX = viewSizeX / 5; //20%
int viewPaddingY = viewSizeY / 5;
if(centerX - viewPaddingX < offsetX ){
offsetX = centerX - viewPaddingX;
}
if(centerX + viewPaddingX - viewSizeX > offsetX){
offsetX = centerX + viewPaddingX - viewSizeX;
}
if(centerY - viewPaddingY < offsetY ){
offsetY = centerY - viewPaddingY;
}
if(centerY + viewPaddingY - viewSizeY > offsetY){
offsetY = centerY + viewPaddingY - viewSizeY;
}
checkOffset();
}
private void checkOffset(){
if (offsetX < 0) {
offsetX = 0;
}
if (offsetY < 0) {
offsetY = 0;
}
if (offsetX >= map.getN() - viewSizeX) {
offsetX = map.getN() - viewSizeX;
}
if (offsetY >= map.getM() - viewSizeY) {
offsetY = map.getM() - viewSizeY;
}
}
public void tick(double el) {
for (Entity mob : fac.getMobs()) {
mob.tick(el);
}
}
public void render(GraphicsContext gc) {
// set color and render ground tile
for (int x = 0; x < viewSizeX; x++) {
for (int y = 0; y < viewSizeY; y++) {
gc.setFill(color[map.getGround(x + offsetX, y + offsetY).ordinal()]);
gc.fillRect(x * size, y * size, size, size);
}
}
for (Entity mob : fac.getMobs()) {
mob.render(gc, size, offsetX, offsetY);
}
}
}
| src/game/World.java | package game;
import dungeon.Generator;
import dungeon.Map;
import entities.Entity;
import entities.EntityFactory;
import entities.Player;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Paint;
public class World {
/** SINGELTON */
private static World singleton;
// class components
private Generator gen;
private Map map;
private EntityFactory fac;
private State state = State.VIEW;
// variables
private int size = 5;
private int offsetX, offsetY, viewSizeX, viewSizeY;
private Paint[] color = { Paint.valueOf("#454545"), Paint.valueOf("#A1D490"), Paint.valueOf("#D4B790"),
Paint.valueOf("#B39B7B"), Paint.valueOf("#801B1B"), Paint.valueOf("#000000") };
public static World getWorld() {
if (singleton == null) {
singleton = new World();
}
return singleton;
}
private World() {
gen = new Generator(280, 180);
map = gen.newLevel();
fac = EntityFactory.getFactory();
// player = fac.makePlayer(15, 15);
changeState(state);
Player player = fac.makePlayer(80, 70);
setCurrentView(player.getX(), player.getY());
}
// we should delete this function - change the map would need effects in any
// other state as well!
public void updateMap(Map newMap) {
this.map = newMap;
}
public Map getMap() {
return this.map;
}
public void setSize(int size) {
this.size = size;
}
public void changeState(State state){
this.state = state;
switch (this.state) {
case MAP:
viewSizeX = map.getN();
viewSizeY = map.getM();
size = 5;
break;
case VIEW:
viewSizeX = 70; //140
viewSizeY = 45; //90
size = 20; //10
break;
default:
break;
}
}
public void setCurrentView(int centerX, int centerY){
this.offsetX = centerX - viewSizeX/2;
this.offsetY = centerY - viewSizeY/2;
checkOffset();
}
public void changeCurrentView(int centerX, int centerY) {
int viewPaddingX = viewSizeX / 5; //20%
int viewPaddingY = viewSizeY / 5;
if(centerX - viewPaddingX < offsetX ){
offsetX = centerX - viewPaddingX;
}
if(centerX + viewPaddingX - viewSizeX > offsetX){
offsetX = centerX + viewPaddingX - viewSizeX;
}
if(centerY - viewPaddingY < offsetY ){
offsetY = centerY - viewPaddingY;
}
if(centerY + viewPaddingY - viewSizeY > offsetY){
offsetY = centerY + viewPaddingY - viewSizeY;
}
checkOffset();
}
private void checkOffset(){
if (offsetX < 0) {
offsetX = 0;
}
if (offsetY < 0) {
offsetY = 0;
}
if (offsetX >= map.getN() - viewSizeX) {
offsetX = map.getN() - viewSizeX;
}
if (offsetY >= map.getM() - viewSizeY) {
offsetY = map.getM() - viewSizeY;
}
}
public void tick(double el) {
for (Entity mob : fac.getMobs()) {
mob.tick(el);
}
}
public void render(GraphicsContext gc) {
// set color and render ground tile
for (int x = 0; x < viewSizeX; x++) {
for (int y = 0; y < viewSizeY; y++) {
gc.setFill(color[map.getGround(x + offsetX, y + offsetY).ordinal()]);
gc.fillRect(x * size, y * size, size, size);
}
}
for (Entity mob : fac.getMobs()) {
mob.render(gc, size, offsetX, offsetY);
}
}
}
| small change
| src/game/World.java | small change |
|
Java | mit | 74be00a147cb5cd6897082e7fde3b291c47b912d | 0 | timmolter/XChange,stachon/XChange,andre77/XChange,bitrich-info/xchange-stream,douggie/XChange | package info.bitrich.xchangestream.bitfinex.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade;
import java.math.BigDecimal;
/**
* Created by Lukas Zaoralek on 7.11.17.
*/
@JsonFormat(shape= JsonFormat.Shape.ARRAY)
public class BitfinexWebSocketTrade {
public long tradeId;
public long timestamp;
public BigDecimal amount;
public BigDecimal price;
public BitfinexWebSocketTrade() { }
public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) {
this.tradeId = tradeId;
this.timestamp = timestamp;
this.amount = amount;
this.price = price;
}
public long getTradeId() {
return tradeId;
}
public long getTimestamp() {
return timestamp;
}
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getPrice() {
return price;
}
public BitfinexTrade toBitfinexTrade() {
String type;
BigDecimal zero = new BigDecimal(0);
if (amount.compareTo(zero) < 0) {
type = "sell";
} else {
type = "buy";
}
return new BitfinexTrade(price, amount, timestamp / 1000,"bitfinex", tradeId, type);
}
}
| xchange-bitfinex/src/main/java/info/bitrich/xchangestream/bitfinex/dto/BitfinexWebSocketTrade.java | package info.bitrich.xchangestream.bitfinex.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade;
import java.math.BigDecimal;
/**
* Created by Lukas Zaoralek on 7.11.17.
*/
@JsonFormat(shape= JsonFormat.Shape.ARRAY)
public class BitfinexWebSocketTrade {
public long tradeId;
public long timestamp;
public BigDecimal amount;
public BigDecimal price;
public BitfinexWebSocketTrade() { }
public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) {
this.tradeId = tradeId;
this.timestamp = timestamp;
this.amount = amount;
this.price = price;
}
public long getTradeId() {
return tradeId;
}
public long getTimestamp() {
return timestamp;
}
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getPrice() {
return price;
}
public BitfinexTrade toBitfinexTrade() {
String type;
BigDecimal zero = new BigDecimal(0);
if (amount.compareTo(zero) < 0) {
type = "sell";
} else {
type = "buy";
}
return new BitfinexTrade(price, amount, timestamp,"bitfinex", tradeId, type);
}
}
| Convert v2 timestamp (msec) to v1 timestamp (sec). (#36)
| xchange-bitfinex/src/main/java/info/bitrich/xchangestream/bitfinex/dto/BitfinexWebSocketTrade.java | Convert v2 timestamp (msec) to v1 timestamp (sec). (#36) |
|
Java | mit | 271c1f888acbde55388d515b467d006da02aadce | 0 | graywolf336/TrailingPerspective | package com.graywolf336.trailingperspective.listeners;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import com.graywolf336.trailingperspective.TrailingPerspectiveMain;
import net.ess3.api.IUser;
import net.ess3.api.events.AfkStatusChangeEvent;
public class TrailingPerspectiveEssentialsListener implements Listener {
private TrailingPerspectiveMain pl;
public TrailingPerspectiveEssentialsListener(TrailingPerspectiveMain plugin) {
this.pl = plugin;
}
@EventHandler
public void playerHasGoneAfk(AfkStatusChangeEvent event) {
IUser user = event.getAffected();
if(user.isAfk() && this.pl.getTrailerManager().isBeingTrailed(user.getBase().getUniqueId())) {
pl.getTrailerManager().getTrailersTrailingPlayer(user.getBase().getUniqueId()).forEach(t -> t.setNoLongerTrailingAnyone());
}
}
}
| src/main/java/com/graywolf336/trailingperspective/listeners/TrailingPerspectiveEssentialsListener.java | package com.graywolf336.trailingperspective.listeners;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import com.graywolf336.trailingperspective.TrailingPerspectiveMain;
import net.ess3.api.IUser;
import net.ess3.api.events.AfkStatusChangeEvent;
public class TrailingPerspectiveEssentialsListener implements Listener {
private TrailingPerspectiveMain pl;
public TrailingPerspectiveEssentialsListener(TrailingPerspectiveMain plugin) {
this.pl = plugin;
}
@EventHandler
public void playerHasGoneAfk(AfkStatusChangeEvent event) {
IUser user = event.getAffected();
if(user.isAfk() && this.pl.getTrailerManager().isBeingTrailed(user.getBase().getUniqueId())) {
pl.getTrailerManager().getTrailersTrailingPlayer(user.getBase().getUniqueId()).forEach(t -> t.setNoLongerTrailingAnyone());
}
}
}
| Codacy style fix | src/main/java/com/graywolf336/trailingperspective/listeners/TrailingPerspectiveEssentialsListener.java | Codacy style fix |
|
Java | agpl-3.0 | ba4b33fe4a01c8400d53976f70eddec24ded23b9 | 0 | headsupdev/agile,headsupdev/agile,headsupdev/agile,headsupdev/agile | /*
* HeadsUp Agile
* Copyright 2009-2014 Heads Up Development Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.headsupdev.agile.app.issues;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.headsupdev.agile.api.User;
import org.headsupdev.agile.storage.Attachment;
import org.headsupdev.agile.storage.HibernateStorage;
import org.headsupdev.agile.storage.StoredProject;
import org.headsupdev.agile.storage.issues.Duration;
import org.headsupdev.agile.storage.issues.Issue;
import org.headsupdev.agile.storage.issues.Milestone;
import org.headsupdev.agile.storage.resource.DurationWorked;
import org.headsupdev.agile.web.HeadsUpPage;
import org.headsupdev.agile.web.HeadsUpSession;
import org.headsupdev.agile.web.components.*;
import org.headsupdev.agile.web.components.issues.IssueListPanel;
import org.headsupdev.agile.web.components.issues.IssueUtils;
import org.headsupdev.agile.web.components.milestones.MilestoneDropDownChoice;
import java.util.Date;
import java.util.LinkedList;
/**
* The form used when editing / creating an issue
*
* @author Andrew Williams
* @version $Id$
* @since 1.0
*/
public class EditIssueForm
extends Panel
{
public EditIssueForm( String id, final Issue issue, boolean creating, HeadsUpPage owner )
{
super( id );
add( CSSPackageResource.getHeaderContribution( IssueListPanel.class, "issue.css" ) );
add( new IssueForm( "edit", issue, creating, owner, this ) );
}
public void onSubmit( Issue issue )
{
// allow others to override
}
}
class IssueForm
extends Form<Issue>
{
private Issue issue;
private User oldAssignee;
private Duration oldTimeRequired;
private HeadsUpPage owner;
private EditIssueForm parent;
private boolean creating;
private AttachmentPanel attachmentPanel;
private CheckBox toggleWatchers;
private User currentUser;
public IssueForm( String id, final Issue issue, final boolean creating, final HeadsUpPage owner, EditIssueForm parent )
{
super( id );
this.issue = issue;
this.owner = owner;
this.parent = parent;
this.creating = creating;
this.oldAssignee = issue.getAssignee();
currentUser = ( (HeadsUpSession) getSession() ).getUser();
if ( issue.getTimeRequired() != null )
{
this.oldTimeRequired = new Duration( issue.getTimeRequired() );
}
setModel( new CompoundPropertyModel<Issue>( issue ) );
add( new Label( "project", issue.getProject().getAlias() ) );
add( new IssueTypeDropDownChoice( "type", IssueUtils.getTypes() ) );
add( new DropDownChoice<Integer>( "priority", IssueUtils.getPriorities() )
{
public boolean isNullValid()
{
return false;
}
}.setChoiceRenderer( new IChoiceRenderer<Integer>()
{
public Object getDisplayValue( Integer i )
{
return IssueUtils.getPriorityName( i );
}
public String getIdValue( Integer o, int i )
{
return o.toString();
}
} ) );
add( new TextField( "version" ) );
add( new MilestoneDropDownChoice( "milestone", issue.getProject(), issue.getMilestone() ).setNullValid( true ) );
Label status = new Label( "status", new Model<String>()
{
@Override
public String getObject()
{
return IssueUtils.getStatusName( issue.getStatus() );
}
} );
add( status );
add( new Label( "reporter", issue.getReporter().getFullnameOrUsername() ) );
final DropDownChoice<User> assignees = new UserDropDownChoice( "assignee", issue.getAssignee() );
assignees.setNullValid( true );
add( assignees );
toggleWatchers = new CheckBox( "toggleWatchers", new Model<Boolean>()
{
@Override
public void setObject( Boolean object )
{
currentUser.setPreference( "issue.automaticallyWatch", object );
}
@Override
public Boolean getObject()
{
return currentUser.getPreference( "issue.automaticallyWatch", true );
}
} );
toggleWatchers.setVisible( creating );
add( toggleWatchers );
Button assignToMe = new Button( "assignToMe" )
{
@Override
public void onSubmit()
{
issue.setAssignee( currentUser );
issue.getWatchers().add( currentUser );
assignees.setChoices( new LinkedList<User>( owner.getSecurityManager().getRealUsers() ) );
assignees.setModelObject( currentUser );
assignees.modelChanged();
super.onSubmit();
}
};
assignToMe.setVisible( issue.getStatus() < Issue.STATUS_RESOLVED &&
!( currentUser.equals( issue.getAssignee() ) ) );
add( assignToMe.setDefaultFormProcessing( false ) );
if ( creating )
{
add( new WebMarkupContainer( "created" ).setVisible( false ) );
add( new WebMarkupContainer( "updated" ).setVisible( false ) );
}
else
{
add( new Label( "created", new FormattedDateModel( issue.getCreated(),
( (HeadsUpSession) getSession() ).getTimeZone() ) ) );
add( new Label( "updated", new FormattedDateModel( issue.getUpdated(),
( (HeadsUpSession) getSession() ).getTimeZone() ) ) );
}
add( new TextField( "order" ).setRequired( false ) );
add( new Label( "watchers", new Model<String>()
{
@Override
public String getObject()
{
return IssueUtils.getWatchersDescription( issue, currentUser );
}
} ).setVisible( !creating ) );
add( new TextField( "summary" ).setRequired( true ) );
add( new TextField( "environment" ) );
boolean useTime = Boolean.parseBoolean( issue.getProject().getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_ENABLED ) );
boolean required = useTime && Boolean.parseBoolean( issue.getProject().getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_REQUIRED ) );
Duration timeEstimated = issue.getTimeEstimate();
if ( timeEstimated == null )
{
timeEstimated = new Duration( 0, Duration.UNIT_HOURS );
issue.setTimeEstimate( timeEstimated );
}
add( new DurationEditPanel( "timeEstimated", new Model<Duration>( issue.getTimeEstimate() ) ).setRequired( required ).setVisible( useTime ) );
boolean showRemain = !creating &&
Boolean.parseBoolean( issue.getProject().getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_BURNDOWN ) );
boolean resolved = issue.getStatus() >= Issue.STATUS_RESOLVED;
Duration timeRequired = issue.getTimeRequired();
if ( timeRequired == null )
{
timeRequired = new Duration( 0, Duration.UNIT_HOURS );
issue.setTimeRequired( timeRequired );
}
add( new DurationEditPanel( "timeRequired", new Model<Duration>( timeRequired ) )
.setRequired( required )
.setVisible( useTime && ( resolved || showRemain ) ) );
add( new CheckBox( "includeInInitialEstimates" ).setVisible( useTime ) );
add( new TextArea( "body" ) );
add( new TextArea( "testNotes" ) );
// if we're creating allow adding of new attachments
if ( creating )
{
add( attachmentPanel = new AttachmentPanel( "attachment", owner ) );
}
else
{
add( new WebMarkupContainer( "attachment" ).setVisible( false ) );
}
}
public void onSubmit()
{
if ( attachmentPanel != null )
{
for ( Attachment attachment : attachmentPanel.getAttachments() )
{
if ( attachment != null )
{
issue.getAttachments().add( attachment );
}
}
}
if ( !creating )
{
issue = (Issue) ( (HibernateStorage) owner.getStorage() ).getHibernateSession().merge( issue );
// if we are updating our total required then log the change
if ( issue.getTimeRequired() != null && !issue.getTimeRequired().equals( oldTimeRequired ) )
{
DurationWorked simulate = new DurationWorked();
simulate.setUpdatedRequired( issue.getTimeRequired() );
simulate.setDay( new Date() );
simulate.setIssue( issue );
simulate.setUser( currentUser );
( (HibernateStorage) owner.getStorage() ).save( simulate );
issue.getTimeWorked().add( simulate );
}
}
else if ( Boolean.parseBoolean( issue.getProject().getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_BURNDOWN ) ) )
{
issue.setTimeRequired( issue.getTimeEstimate() );
}
if ( creating )
{
if ( toggleWatchers.getModelObject() )
{
issue.getWatchers().add( currentUser );
}
}
issue.setUpdated( new Date() );
if ( issue.getMilestone() != null )
{
Milestone milestone = issue.getMilestone();
if ( creating )
{
milestone = (Milestone) ( (HibernateStorage) owner.getStorage() ).getHibernateSession().merge( milestone );
}
if ( !milestone.getIssues().contains( issue ) )
{
milestone.getIssues().add( issue );
}
}
// if we have an assignee that is not watching then add them to the watchers - assuming they have not just opted out :)
if ( issue.getAssignee() != null && !issue.getWatchers().contains( issue.getAssignee() ) )
{
if ( oldAssignee == null || !issue.getAssignee().equals( oldAssignee ) )
{
issue.getWatchers().add( issue.getAssignee() );
}
}
parent.onSubmit( issue );
PageParameters params = new PageParameters();
params.add( "project", issue.getProject().getId() );
params.add( "id", String.valueOf( issue.getId() ) );
setResponsePage( owner.getPageClass( "issues/view" ), params );
}
}
| agile-apps/agile-app-issues/src/main/java/org/headsupdev/agile/app/issues/EditIssueForm.java | /*
* HeadsUp Agile
* Copyright 2009-2014 Heads Up Development Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.headsupdev.agile.app.issues;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.headsupdev.agile.api.User;
import org.headsupdev.agile.storage.Attachment;
import org.headsupdev.agile.storage.HibernateStorage;
import org.headsupdev.agile.storage.StoredProject;
import org.headsupdev.agile.storage.issues.Duration;
import org.headsupdev.agile.storage.issues.Issue;
import org.headsupdev.agile.storage.issues.Milestone;
import org.headsupdev.agile.storage.resource.DurationWorked;
import org.headsupdev.agile.web.HeadsUpPage;
import org.headsupdev.agile.web.HeadsUpSession;
import org.headsupdev.agile.web.components.*;
import org.headsupdev.agile.web.components.issues.IssueListPanel;
import org.headsupdev.agile.web.components.issues.IssueUtils;
import org.headsupdev.agile.web.components.milestones.MilestoneDropDownChoice;
import java.util.Date;
import java.util.LinkedList;
/**
* The form used when editing / creating an issue
*
* @author Andrew Williams
* @version $Id$
* @since 1.0
*/
public class EditIssueForm
extends Panel
{
public EditIssueForm( String id, final Issue issue, boolean creating, HeadsUpPage owner )
{
super( id );
add( CSSPackageResource.getHeaderContribution( IssueListPanel.class, "issue.css" ) );
add( new IssueForm( "edit", issue, creating, owner, this ) );
}
public void onSubmit( Issue issue )
{
// allow others to override
}
}
class IssueForm
extends Form<Issue>
{
private Issue issue;
private User oldAssignee;
private Duration oldTimeRequired;
private HeadsUpPage owner;
private EditIssueForm parent;
private boolean creating;
private AttachmentPanel attachmentPanel;
private CheckBox toggleWatchers;
private User currentUser;
public IssueForm( String id, final Issue issue, final boolean creating, final HeadsUpPage owner, EditIssueForm parent )
{
super( id );
this.issue = issue;
this.owner = owner;
this.parent = parent;
this.creating = creating;
this.oldAssignee = issue.getAssignee();
currentUser = ( (HeadsUpSession) getSession() ).getUser();
if ( issue.getTimeRequired() != null )
{
this.oldTimeRequired = new Duration( issue.getTimeRequired() );
}
setModel( new CompoundPropertyModel<Issue>( issue ) );
add( new Label( "project", issue.getProject().getAlias() ) );
add( new IssueTypeDropDownChoice( "type", IssueUtils.getTypes() ) );
add( new DropDownChoice<Integer>( "priority", IssueUtils.getPriorities() )
{
public boolean isNullValid()
{
return false;
}
}.setChoiceRenderer( new IChoiceRenderer<Integer>()
{
public Object getDisplayValue( Integer i )
{
return IssueUtils.getPriorityName( i );
}
public String getIdValue( Integer o, int i )
{
return o.toString();
}
} ) );
add( new TextField( "version" ) );
add( new MilestoneDropDownChoice( "milestone", issue.getProject(), issue.getMilestone() ).setNullValid( true ) );
Label status = new Label( "status", new Model<String>()
{
@Override
public String getObject()
{
return IssueUtils.getStatusName( issue.getStatus() );
}
} );
add( status );
add( new Label( "reporter", issue.getReporter().getFullnameOrUsername() ) );
final DropDownChoice<User> assignees = new UserDropDownChoice( "assignee", issue.getAssignee() );
assignees.setNullValid( true );
add( assignees );
toggleWatchers = new CheckBox( "toggleWatchers", new Model<Boolean>()
{
@Override
public void setObject( Boolean object )
{
currentUser.setPreference( "issue.automaticallyShow", object );
}
@Override
public Boolean getObject()
{
return currentUser.getPreference( "issue.automaticallyShow", true );
}
} );
// toggleWatchers.setModelObject( true );
toggleWatchers.setVisible( creating );
add( toggleWatchers );
Button assignToMe = new Button( "assignToMe" )
{
@Override
public void onSubmit()
{
issue.setAssignee( currentUser );
issue.getWatchers().add( currentUser );
assignees.setChoices( new LinkedList<User>( owner.getSecurityManager().getRealUsers() ) );
assignees.setModelObject( currentUser );
assignees.modelChanged();
super.onSubmit();
}
};
assignToMe.setVisible( issue.getStatus() < Issue.STATUS_RESOLVED &&
!( currentUser.equals( issue.getAssignee() ) ) );
add( assignToMe.setDefaultFormProcessing( false ) );
if ( creating )
{
add( new WebMarkupContainer( "created" ).setVisible( false ) );
add( new WebMarkupContainer( "updated" ).setVisible( false ) );
}
else
{
add( new Label( "created", new FormattedDateModel( issue.getCreated(),
( (HeadsUpSession) getSession() ).getTimeZone() ) ) );
add( new Label( "updated", new FormattedDateModel( issue.getUpdated(),
( (HeadsUpSession) getSession() ).getTimeZone() ) ) );
}
add( new TextField( "order" ).setRequired( false ) );
add( new Label( "watchers", new Model<String>()
{
@Override
public String getObject()
{
return IssueUtils.getWatchersDescription( issue, currentUser );
}
} ).setVisible( !creating ) );
add( new TextField( "summary" ).setRequired( true ) );
add( new TextField( "environment" ) );
boolean useTime = Boolean.parseBoolean( issue.getProject().getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_ENABLED ) );
boolean required = useTime && Boolean.parseBoolean( issue.getProject().getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_REQUIRED ) );
Duration timeEstimated = issue.getTimeEstimate();
if ( timeEstimated == null )
{
timeEstimated = new Duration( 0, Duration.UNIT_HOURS );
issue.setTimeEstimate( timeEstimated );
}
add( new DurationEditPanel( "timeEstimated", new Model<Duration>( issue.getTimeEstimate() ) ).setRequired( required ).setVisible( useTime ) );
boolean showRemain = !creating &&
Boolean.parseBoolean( issue.getProject().getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_BURNDOWN ) );
boolean resolved = issue.getStatus() >= Issue.STATUS_RESOLVED;
Duration timeRequired = issue.getTimeRequired();
if ( timeRequired == null )
{
timeRequired = new Duration( 0, Duration.UNIT_HOURS );
issue.setTimeRequired( timeRequired );
}
add( new DurationEditPanel( "timeRequired", new Model<Duration>( timeRequired ) )
.setRequired( required )
.setVisible( useTime && ( resolved || showRemain ) ) );
add( new CheckBox( "includeInInitialEstimates" ).setVisible( useTime ) );
add( new TextArea( "body" ) );
add( new TextArea( "testNotes" ) );
// if we're creating allow adding of new attachments
if ( creating )
{
add( attachmentPanel = new AttachmentPanel( "attachment", owner ) );
}
else
{
add( new WebMarkupContainer( "attachment" ).setVisible( false ) );
}
}
public void onSubmit()
{
if ( attachmentPanel != null )
{
for ( Attachment attachment : attachmentPanel.getAttachments() )
{
if ( attachment != null )
{
issue.getAttachments().add( attachment );
}
}
}
if ( !creating )
{
issue = (Issue) ( (HibernateStorage) owner.getStorage() ).getHibernateSession().merge( issue );
// if we are updating our total required then log the change
if ( issue.getTimeRequired() != null && !issue.getTimeRequired().equals( oldTimeRequired ) )
{
DurationWorked simulate = new DurationWorked();
simulate.setUpdatedRequired( issue.getTimeRequired() );
simulate.setDay( new Date() );
simulate.setIssue( issue );
simulate.setUser( currentUser );
( (HibernateStorage) owner.getStorage() ).save( simulate );
issue.getTimeWorked().add( simulate );
}
}
else if ( Boolean.parseBoolean( issue.getProject().getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_BURNDOWN ) ) )
{
issue.setTimeRequired( issue.getTimeEstimate() );
}
if ( creating )
{
if ( toggleWatchers.getModelObject() )
{
issue.getWatchers().add( currentUser );
}
}
issue.setUpdated( new Date() );
if ( issue.getMilestone() != null )
{
Milestone milestone = issue.getMilestone();
if ( creating )
{
milestone = (Milestone) ( (HibernateStorage) owner.getStorage() ).getHibernateSession().merge( milestone );
}
if ( !milestone.getIssues().contains( issue ) )
{
milestone.getIssues().add( issue );
}
}
// if we have an assignee that is not watching then add them to the watchers - assuming they have not just opted out :)
if ( issue.getAssignee() != null && !issue.getWatchers().contains( issue.getAssignee() ) )
{
if ( oldAssignee == null || !issue.getAssignee().equals( oldAssignee ) )
{
issue.getWatchers().add( issue.getAssignee() );
}
}
parent.onSubmit( issue );
PageParameters params = new PageParameters();
params.add( "project", issue.getProject().getId() );
params.add( "id", String.valueOf( issue.getId() ) );
setResponsePage( owner.getPageClass( "issues/view" ), params );
}
}
| Changing preference name and removing commented out code
| agile-apps/agile-app-issues/src/main/java/org/headsupdev/agile/app/issues/EditIssueForm.java | Changing preference name and removing commented out code |
|
Java | lgpl-2.1 | 7c0c8b2de0638c46d8d8ae29b998afa403939b2a | 0 | mbenz89/soot,cfallin/soot,mbenz89/soot,mbenz89/soot,anddann/soot,cfallin/soot,xph906/SootNew,cfallin/soot,anddann/soot,plast-lab/soot,xph906/SootNew,anddann/soot,xph906/SootNew,xph906/SootNew,plast-lab/soot,mbenz89/soot,plast-lab/soot,anddann/soot,cfallin/soot | /* Soot - a J*va Optimization Framework
* Copyright (C) 1997-1999 Raja Vallee-Rai
* Copyright (C) 2004 Ondrej Lhotak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.xmlpull.v1.XmlPullParser;
import soot.jimple.spark.internal.ClientAccessibilityOracle;
import soot.jimple.spark.internal.PublicAndProtectedAccessibility;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.ContextSensitiveCallGraph;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import soot.jimple.toolkits.pointer.DumbPointerAnalysis;
import soot.jimple.toolkits.pointer.SideEffectAnalysis;
import soot.options.CGOptions;
import soot.options.Options;
import soot.toolkits.exceptions.PedanticThrowAnalysis;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.exceptions.UnitThrowAnalysis;
import soot.util.ArrayNumberer;
import soot.util.Chain;
import soot.util.HashChain;
import soot.util.MapNumberer;
import soot.util.Numberer;
import soot.util.StringNumberer;
import test.AXMLPrinter;
import android.content.res.AXmlResourceParser;
/** Manages the SootClasses of the application being analyzed. */
public class Scene //extends AbstractHost
{
private final int defaultSdkVersion = 15;
private final Map<String, Integer> maxAPIs = new HashMap<String, Integer>();
public Scene ( Singletons.Global g )
{
setReservedNames();
// load soot.class.path system property, if defined
String scp = System.getProperty("soot.class.path");
if (scp != null)
setSootClassPath(scp);
kindNumberer = new ArrayNumberer<Kind>(new Kind[] {
Kind.INVALID,
Kind.STATIC,
Kind.VIRTUAL,
Kind.INTERFACE,
Kind.SPECIAL,
Kind.CLINIT,
Kind.THREAD,
Kind.EXECUTOR,
Kind.ASYNCTASK,
Kind.FINALIZE,
Kind.INVOKE_FINALIZE,
Kind.PRIVILEGED,
Kind.NEWINSTANCE});
addSootBasicClasses();
determineExcludedPackages();
}
private void determineExcludedPackages() {
excludedPackages = new LinkedList<String>();
if (Options.v().exclude() != null)
excludedPackages.addAll(Options.v().exclude());
// do not kill contents of the APK if we want a working new APK afterwards
if( !Options.v().include_all()
&& Options.v().output_format() != Options.output_format_dex
&& Options.v().output_format() != Options.output_format_force_dex) {
excludedPackages.add("java.*");
excludedPackages.add("sun.*");
excludedPackages.add("javax.*");
excludedPackages.add("com.sun.*");
excludedPackages.add("com.ibm.*");
excludedPackages.add("org.xml.*");
excludedPackages.add("org.w3c.*");
excludedPackages.add("apple.awt.*");
excludedPackages.add("com.apple.*");
}
}
public static Scene v() { return G.v().soot_Scene (); }
Chain<SootClass> classes = new HashChain<SootClass>();
Chain<SootClass> applicationClasses = new HashChain<SootClass>();
Chain<SootClass> libraryClasses = new HashChain<SootClass>();
Chain<SootClass> phantomClasses = new HashChain<SootClass>();
private final Map<String,RefType> nameToClass = new HashMap<String,RefType>();
final ArrayNumberer<Kind> kindNumberer;
ArrayNumberer<Type> typeNumberer = new ArrayNumberer<Type>();
ArrayNumberer<SootMethod> methodNumberer = new ArrayNumberer<SootMethod>();
Numberer<Unit> unitNumberer = new MapNumberer<Unit>();
Numberer<Context> contextNumberer = null;
Numberer<SparkField> fieldNumberer = new ArrayNumberer<SparkField>();
ArrayNumberer<SootClass> classNumberer = new ArrayNumberer<SootClass>();
StringNumberer subSigNumberer = new StringNumberer();
ArrayNumberer<Local> localNumberer = new ArrayNumberer<Local>();
private Hierarchy activeHierarchy;
private FastHierarchy activeFastHierarchy;
private CallGraph activeCallGraph;
private ReachableMethods reachableMethods;
private PointsToAnalysis activePointsToAnalysis;
private SideEffectAnalysis activeSideEffectAnalysis;
private List<SootMethod> entryPoints;
private ClientAccessibilityOracle accessibilityOracle;
boolean allowsPhantomRefs = false;
SootClass mainClass;
String sootClassPath = null;
// Two default values for constructing ExceptionalUnitGraphs:
private ThrowAnalysis defaultThrowAnalysis = null;
public void setMainClass(SootClass m)
{
mainClass = m;
if(!m.declaresMethod(getSubSigNumberer().findOrAdd( "void main(java.lang.String[])" ))) {
throw new RuntimeException("Main-class has no main method!");
}
}
Set<String> reservedNames = new HashSet<String>();
/**
Returns a set of tokens which are reserved. Any field, class, method, or local variable with such a name will be quoted.
*/
public Set<String> getReservedNames()
{
return reservedNames;
}
/**
* If this name is in the set of reserved names, then return a quoted
* version of it. Else pass it through. If the name consists of multiple
* parts separated by dots, the individual names are checked as well.
*/
public String quotedNameOf(String s)
{
StringBuilder res = new StringBuilder(s.length());
for (String part : s.split("\\.")) {
if (res.length() > 0)
res.append('.');
if(reservedNames.contains(part)) {
res.append('\'');
res.append(part);
res.append('\'');
}
else
res.append(part);
}
return res.toString();
}
public boolean hasMainClass() {
if(mainClass == null) {
setMainClassFromOptions();
}
return mainClass!=null;
}
public SootClass getMainClass()
{
if(!hasMainClass())
throw new RuntimeException("There is no main class set!");
return mainClass;
}
public SootMethod getMainMethod() {
if(!hasMainClass()) {
throw new RuntimeException("There is no main class set!");
}
SootMethod mainMethod = mainClass.getMethodUnsafe("main",
Collections.<Type>singletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ),
VoidType.v());
if (mainMethod == null) {
throw new RuntimeException("Main class declares no main method!");
}
return mainMethod;
}
public void setSootClassPath(String p)
{
sootClassPath = p;
SourceLocator.v().invalidateClassPath();
}
public String getSootClassPath()
{
if( sootClassPath == null ) {
String optionscp = Options.v().soot_classpath();
if( optionscp != null && optionscp.length() > 0 )
sootClassPath = optionscp;
//if no classpath is given on the command line, take the default
if( sootClassPath == null ) {
sootClassPath = defaultClassPath();
} else {
//if one is given...
if(Options.v().prepend_classpath()) {
//if the prepend flag is set, append the default classpath
sootClassPath += File.pathSeparator + defaultClassPath();
}
//else, leave it as it is
}
//add process-dirs
List<String> process_dir = Options.v().process_dir();
StringBuffer pds = new StringBuffer();
for (String path : process_dir) {
if(!sootClassPath.contains(path)) {
pds.append(path);
pds.append(File.pathSeparator);
}
}
sootClassPath = pds + sootClassPath;
}
return sootClassPath;
}
/**
* Returns the max Android API version number available
* in directory 'dir'
* @param dir
* @return
*/
private int getMaxAPIAvailable(String dir) {
Integer mapi = this.maxAPIs.get(dir);
if (mapi != null)
return mapi;
File d = new File(dir);
if (!d.exists())
throw new RuntimeException("The Android platform directory you have"
+ "specified (" + dir + ") does not exist. Please check.");
File[] files = d.listFiles();
if (files == null)
return -1;
int maxApi = -1;
for (File f: files) {
String name = f.getName();
if (f.isDirectory() && name.startsWith("android-")) {
try {
int v = Integer.decode(name.split("android-")[1]);
if (v > maxApi)
maxApi = v;
}
catch (NumberFormatException ex) {
// We simply ignore directories that do not follow the
// Android naming structure
}
}
}
this.maxAPIs.put(dir, maxApi);
return maxApi;
}
public String getAndroidJarPath(String jars, String apk) {
int APIVersion = getAndroidAPIVersion(jars,apk);
String jarPath = jars + File.separator + "android-" + APIVersion + File.separator + "android.jar";
// check that jar exists
File f = new File(jarPath);
if (!f.isFile())
throw new RuntimeException("error: target android.jar ("+ jarPath +") does not exist.");
return jarPath;
}
public int getAndroidAPIVersion(String jars, String apk) {
// get path to appropriate android.jar
File jarsF = new File(jars);
File apkF = new File(apk);
if (!jarsF.exists())
throw new RuntimeException("file '" + jars + "' does not exist!");
if (!apkF.exists())
throw new RuntimeException("file '" + apk + "' does not exist!");
// get path to appropriate android.jar
int APIVersion = defaultSdkVersion;
if (apk.toLowerCase().endsWith(".apk"))
APIVersion = getTargetSDKVersion(apk, jars);
final int maxAPI = getMaxAPIAvailable(jars);
if (APIVersion > maxAPI)
APIVersion = maxAPI;
return APIVersion;
}
private int getTargetSDKVersion(String apkFile, String platformJARs) {
// get AndroidManifest
InputStream manifestIS = null;
ZipFile archive = null;
try {
try {
archive = new ZipFile(apkFile);
for (Enumeration<? extends ZipEntry> entries = archive.entries(); entries.hasMoreElements();) {
ZipEntry entry = entries.nextElement();
String entryName = entry.getName();
// We are dealing with the Android manifest
if (entryName.equals("AndroidManifest.xml")) {
manifestIS = archive.getInputStream(entry);
break;
}
}
} catch (Exception e) {
throw new RuntimeException("Error when looking for manifest in apk: " + e);
}
if (manifestIS == null) {
G.v().out.println("Could not find sdk version in Android manifest! Using default: "+defaultSdkVersion);
return defaultSdkVersion;
}
// process AndroidManifest.xml
int maxAPI = getMaxAPIAvailable(platformJARs);
int sdkTargetVersion = -1;
int minSdkVersion = -1;
try {
AXmlResourceParser parser = new AXmlResourceParser();
parser.open(manifestIS);
int depth = 0;
loop: while (true) {
int type = parser.next();
switch (type) {
case XmlPullParser.START_DOCUMENT: {
break;
}
case XmlPullParser.END_DOCUMENT:
break loop;
case XmlPullParser.START_TAG: {
depth++;
String tagName = parser.getName();
if (depth == 2 && tagName.equals("uses-sdk")) {
for (int i = 0; i != parser.getAttributeCount(); ++i) {
String attributeName = parser.getAttributeName(i);
String attributeValue = AXMLPrinter.getAttributeValue(parser, i);
if (attributeName.equals("targetSdkVersion")) {
sdkTargetVersion = Integer.parseInt(attributeValue);
} else if (attributeName.equals("minSdkVersion")) {
minSdkVersion = Integer.parseInt(attributeValue);
}
}
}
break;
}
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.TEXT:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
int APIVersion = -1;
if (sdkTargetVersion != -1) {
if (sdkTargetVersion > maxAPI
&& minSdkVersion != -1
&& minSdkVersion <= maxAPI) {
G.v().out.println("warning: Android API version '"+ sdkTargetVersion +"' not available, using minApkVersion '"+ minSdkVersion +"' instead");
APIVersion = minSdkVersion;
} else {
APIVersion = sdkTargetVersion;
}
} else if (minSdkVersion != -1) {
APIVersion = minSdkVersion;
} else {
G.v().out.println("Could not find sdk version in Android manifest! Using default: "+defaultSdkVersion);
APIVersion = defaultSdkVersion;
}
if (APIVersion <= 2)
APIVersion = 3;
return APIVersion;
}
finally {
if (archive != null)
try {
archive.close();
} catch (IOException e) {
throw new RuntimeException("Error when looking for manifest in apk: " + e);
}
}
}
public String defaultClassPath() {
if (Options.v().src_prec() == Options.src_prec_apk)
return defaultAndroidClassPath();
else
return defaultJavaClassPath();
}
private String defaultAndroidClassPath() {
// check that android.jar is not in classpath
String androidJars = Options.v().android_jars();
String forceAndroidJar = Options.v().force_android_jar();
if ((androidJars == null || androidJars.equals(""))
&& (forceAndroidJar == null || forceAndroidJar.equals(""))) {
throw new RuntimeException("You are analyzing an Android application but did not define android.jar. Options -android-jars or -force-android-jar should be used.");
}
// Get the platform JAR file. It either directly specified, or
// we detect it from the target version of the APK we are
// analyzing
String jarPath = "";
if (forceAndroidJar != null && !forceAndroidJar.isEmpty()) {
jarPath = forceAndroidJar;
}
else if (androidJars != null && !androidJars.isEmpty()) {
List<String> classPathEntries = new LinkedList<String>(Arrays.asList(
Options.v().soot_classpath().split(File.pathSeparator)));
classPathEntries.addAll(Options.v().process_dir());
Set<String> targetApks = new HashSet<String>();
for (String entry : classPathEntries) {
if(entry.toLowerCase().endsWith(".apk")
|| entry.toLowerCase().endsWith(".dex")) // on Windows, file names are case-insensitive
targetApks.add(entry);
}
if (targetApks.size() == 0)
throw new RuntimeException("no apk file given");
else if (targetApks.size() > 1)
throw new RuntimeException("only one Android application can be analyzed when using option -android-jars.");
jarPath = getAndroidJarPath (androidJars, (String)targetApks.toArray()[0]);
}
// We must have a platform JAR file when analyzing Android apps
if (jarPath.equals(""))
throw new RuntimeException("android.jar not found.");
// Check the platform JAR file
File f = new File (jarPath);
if (!f.exists())
throw new RuntimeException("file '"+ jarPath +"' does not exist!");
else
G.v().out.println("Using '"+ jarPath +"' as android.jar");
return jarPath;
}
private String defaultJavaClassPath() {
StringBuilder sb = new StringBuilder();
if(System.getProperty("os.name").equals("Mac OS X")) {
//in older Mac OS X versions, rt.jar was split into classes.jar and ui.jar
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("..");
sb.append(File.separator);
sb.append("Classes");
sb.append(File.separator);
sb.append("classes.jar");
sb.append(File.pathSeparator);
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("..");
sb.append(File.separator);
sb.append("Classes");
sb.append(File.separator);
sb.append("ui.jar");
sb.append(File.pathSeparator);
}
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("lib");
sb.append(File.separator);
sb.append("rt.jar");
if(Options.v().whole_program() || Options.v().output_format()==Options.output_format_dava) {
//add jce.jar, which is necessary for whole program mode
//(java.security.Signature from rt.jar import javax.crypto.Cipher from jce.jar
sb.append(File.pathSeparator+
System.getProperty("java.home")+File.separator+"lib"+File.separator+"jce.jar");
}
return sb.toString();
}
private int stateCount;
public int getState() { return this.stateCount; }
private void modifyHierarchy() {
stateCount++;
activeHierarchy = null;
activeFastHierarchy = null;
activeSideEffectAnalysis = null;
activePointsToAnalysis = null;
}
public void addClass(SootClass c)
{
if(c.isInScene())
throw new RuntimeException("already managed: "+c.getName());
if(containsClass(c.getName()))
throw new RuntimeException("duplicate class: "+c.getName());
classes.add(c);
c.setLibraryClass();
nameToClass.put(c.getName(), c.getType());
c.getType().setSootClass(c);
c.setInScene(true);
// Phantom classes are not really part of the hierarchy anyway, so
// we can keep the old one
if (!c.isPhantom)
modifyHierarchy();
}
public void removeClass(SootClass c)
{
if(!c.isInScene())
throw new RuntimeException();
classes.remove(c);
if(c.isLibraryClass()) {
libraryClasses.remove(c);
} else if(c.isPhantomClass()) {
phantomClasses.remove(c);
} else if(c.isApplicationClass()) {
applicationClasses.remove(c);
}
c.getType().setSootClass(null);
c.setInScene(false);
modifyHierarchy();
}
public boolean containsClass(String className)
{
RefType type = nameToClass.get(className);
if( type == null ) return false;
if( !type.hasSootClass() ) return false;
SootClass c = type.getSootClass();
return c.isInScene();
}
public boolean containsType(String className)
{
return nameToClass.containsKey(className);
}
public String signatureToClass(String sig) {
if( sig.charAt(0) != '<' ) throw new RuntimeException("oops "+sig);
if( sig.charAt(sig.length()-1) != '>' ) throw new RuntimeException("oops "+sig);
int index = sig.indexOf( ":" );
if( index < 0 ) throw new RuntimeException("oops "+sig);
return sig.substring(1,index);
}
public String signatureToSubsignature(String sig) {
if( sig.charAt(0) != '<' ) throw new RuntimeException("oops "+sig);
if( sig.charAt(sig.length()-1) != '>' ) throw new RuntimeException("oops "+sig);
int index = sig.indexOf( ":" );
if( index < 0 ) throw new RuntimeException("oops "+sig);
return sig.substring(index+2,sig.length()-1);
}
public SootField grabField(String fieldSignature)
{
String cname = signatureToClass( fieldSignature );
String fname = signatureToSubsignature( fieldSignature );
if( !containsClass(cname) ) return null;
SootClass c = getSootClass(cname);
return c.getFieldUnsafe( fname );
}
public boolean containsField(String fieldSignature)
{
return grabField(fieldSignature) != null;
}
public SootMethod grabMethod(String methodSignature)
{
String cname = signatureToClass( methodSignature );
String mname = signatureToSubsignature( methodSignature );
if( !containsClass(cname) ) return null;
SootClass c = getSootClass(cname);
if( !c.declaresMethod( mname ) ) return null;
return c.getMethod( mname );
}
public boolean containsMethod(String methodSignature)
{
return grabMethod(methodSignature) != null;
}
public SootField getField(String fieldSignature)
{
SootField f = grabField( fieldSignature );
if (f != null)
return f;
throw new RuntimeException("tried to get nonexistent field "+fieldSignature);
}
public SootMethod getMethod(String methodSignature)
{
SootMethod m = grabMethod( methodSignature );
if (m != null)
return m;
throw new RuntimeException("tried to get nonexistent method "+methodSignature);
}
/**
* Attempts to load the given class and all of the required support classes.
* Returns the original class if it was loaded, or null otherwise.
*/
public SootClass tryLoadClass(String className, int desiredLevel)
{
/*
if(Options.v().time())
Main.v().resolveTimer.start();
*/
setPhantomRefs(true);
//SootResolver resolver = new SootResolver();
if( !getPhantomRefs()
&& SourceLocator.v().getClassSource(className) == null ) {
setPhantomRefs(false);
return null;
}
SootResolver resolver = SootResolver.v();
SootClass toReturn = resolver.resolveClass(className, desiredLevel);
setPhantomRefs(false);
return toReturn;
/*
if(Options.v().time())
Main.v().resolveTimer.end(); */
}
/**
* Loads the given class and all of the required support classes. Returns the first class.
*/
public SootClass loadClassAndSupport(String className)
{
SootClass ret = loadClass(className, SootClass.SIGNATURES);
if( !ret.isPhantom() ) ret = loadClass(className, SootClass.BODIES);
return ret;
}
public SootClass loadClass(String className, int desiredLevel)
{
/*
if(Options.v().time())
Main.v().resolveTimer.start();
*/
setPhantomRefs(true);
//SootResolver resolver = new SootResolver();
SootResolver resolver = SootResolver.v();
SootClass toReturn = resolver.resolveClass(className, desiredLevel);
setPhantomRefs(false);
return toReturn;
/*
if(Options.v().time())
Main.v().resolveTimer.end(); */
}
/**
* Returns the RefType with the given class name or primitive type.
* @throws RuntimeException if the Type for this name cannot be found.
* Use {@link #getRefTypeUnsafe(String)} to check if type is an registered RefType.
*/
public Type getType(String arg) {
String type = arg.replaceAll("([^\\[\\]]*)(.*)", "$1");
int arrayCount = arg.contains("[") ? arg.replaceAll("([^\\[\\]]*)(.*)", "$2").length() / 2 : 0;
Type result = getRefTypeUnsafe(type);
if (result == null) {
if (type.equals("long"))
result = LongType.v();
else if (type.equals("short"))
result = ShortType.v();
else if (type.equals("double"))
result = DoubleType.v();
else if (type.equals("int"))
result = IntType.v();
else if (type.equals("float"))
result = FloatType.v();
else if (type.equals("byte"))
result = ByteType.v();
else if (type.equals("char"))
result = CharType.v();
else if (type.equals("void"))
result = VoidType.v();
else if (type.equals("boolean"))
result = BooleanType.v();
else
throw new RuntimeException("unknown type: '" + type + "'");
}
if (arrayCount != 0) {
result = ArrayType.v(result, arrayCount);
}
return result;
}
/**
* Returns the RefType with the given className.
* @throws IllegalStateException if the RefType for this class cannot be found.
* Use {@link #containsType(String)} to check if type is registered
*/
public RefType getRefType(String className)
{
RefType refType = getRefTypeUnsafe(className);
if(refType==null) {
throw new IllegalStateException("RefType "+className+" not loaded. " +
"If you tried to get the RefType of a library class, did you call loadNecessaryClasses()? " +
"Otherwise please check Soot's classpath.");
}
return refType;
}
/**
* Returns the RefType with the given className. Returns null if no type
* with the given name can be found.
*/
public RefType getRefTypeUnsafe(String className)
{
RefType refType = nameToClass.get(className);
return refType;
}
/**
* Returns the {@link RefType} for {@link Object}.
*/
public RefType getObjectType() {
return getRefType("java.lang.Object");
}
/**
* Returns the RefType with the given className.
*/
public void addRefType(RefType type)
{
nameToClass.put(type.getClassName(), type);
}
/**
* Returns the SootClass with the given className. If no class with the
* given name exists, null is returned
* @param className The name of the class to get
* @return The class if it exists, otherwise null
*/
public SootClass getSootClassUnsafe(String className) {
RefType type = nameToClass.get(className);
if (type != null) {
SootClass tsc = type.getSootClass();
if (tsc != null)
return tsc;
}
if (allowsPhantomRefs() ||
className.equals(SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME)) {
SootClass c = new SootClass(className);
addClass(c);
c.setPhantom(true);
return c;
}
return null;
}
/**
* Returns the SootClass with the given className.
*/
public SootClass getSootClass(String className) {
SootClass sc = getSootClassUnsafe(className);
if (sc != null)
return sc;
throw new RuntimeException(System.getProperty("line.separator")
+ "Aborting: can't find classfile " + className);
}
/**
* Returns an backed chain of the classes in this manager.
*/
public Chain<SootClass> getClasses()
{
return classes;
}
/* The four following chains are mutually disjoint. */
/**
* Returns a chain of the application classes in this scene.
* These classes are the ones which can be freely analysed & modified.
*/
public Chain<SootClass> getApplicationClasses()
{
return applicationClasses;
}
/**
* Returns a chain of the library classes in this scene.
* These classes can be analysed but not modified.
*/
public Chain<SootClass> getLibraryClasses()
{
return libraryClasses;
}
/**
* Returns a chain of the phantom classes in this scene.
* These classes are referred to by other classes, but cannot be loaded.
*/
public Chain<SootClass> getPhantomClasses()
{
return phantomClasses;
}
Chain<SootClass> getContainingChain(SootClass c)
{
if (c.isApplicationClass())
return getApplicationClasses();
else if (c.isLibraryClass())
return getLibraryClasses();
else if (c.isPhantomClass())
return getPhantomClasses();
return null;
}
/****************************************************************************/
/**
Retrieves the active side-effect analysis
*/
public SideEffectAnalysis getSideEffectAnalysis()
{
if(!hasSideEffectAnalysis()) {
setSideEffectAnalysis( new SideEffectAnalysis(
getPointsToAnalysis(),
getCallGraph() ) );
}
return activeSideEffectAnalysis;
}
/**
Sets the active side-effect analysis
*/
public void setSideEffectAnalysis(SideEffectAnalysis sea)
{
activeSideEffectAnalysis = sea;
}
public boolean hasSideEffectAnalysis()
{
return activeSideEffectAnalysis != null;
}
public void releaseSideEffectAnalysis()
{
activeSideEffectAnalysis = null;
}
/****************************************************************************/
/**
Retrieves the active pointer analysis
*/
public PointsToAnalysis getPointsToAnalysis()
{
if(!hasPointsToAnalysis()) {
return DumbPointerAnalysis.v();
}
return activePointsToAnalysis;
}
/**
Sets the active pointer analysis
*/
public void setPointsToAnalysis(PointsToAnalysis pa)
{
activePointsToAnalysis = pa;
}
public boolean hasPointsToAnalysis()
{
return activePointsToAnalysis != null;
}
public void releasePointsToAnalysis()
{
activePointsToAnalysis = null;
}
/****************************************************************************/
/**
* Retrieves the active client accessibility oracle
*/
public ClientAccessibilityOracle getClientAccessibilityOracle() {
if (!hasClientAccessibilityOracle()) {
return PublicAndProtectedAccessibility.v();
}
return accessibilityOracle;
}
public boolean hasClientAccessibilityOracle() {
return accessibilityOracle != null;
}
public void setClientAccessibilityOracle(ClientAccessibilityOracle oracle) {
accessibilityOracle = oracle;
}
public void releaseClientAccessibilityOracle() {
accessibilityOracle = null;
}
/****************************************************************************/
/** Makes a new fast hierarchy is none is active, and returns the active
* fast hierarchy. */
public FastHierarchy getOrMakeFastHierarchy() {
if(!hasFastHierarchy() ) {
setFastHierarchy( new FastHierarchy() );
}
return getFastHierarchy();
}
/**
Retrieves the active fast hierarchy
*/
public FastHierarchy getFastHierarchy()
{
if(!hasFastHierarchy())
throw new RuntimeException("no active FastHierarchy present for scene");
return activeFastHierarchy;
}
/**
Sets the active hierarchy
*/
public void setFastHierarchy(FastHierarchy hierarchy)
{
activeFastHierarchy = hierarchy;
}
public boolean hasFastHierarchy()
{
return activeFastHierarchy != null;
}
public void releaseFastHierarchy()
{
activeFastHierarchy = null;
}
/****************************************************************************/
/**
Retrieves the active hierarchy
*/
public Hierarchy getActiveHierarchy()
{
if(!hasActiveHierarchy())
//throw new RuntimeException("no active Hierarchy present for scene");
setActiveHierarchy( new Hierarchy() );
return activeHierarchy;
}
/**
Sets the active hierarchy
*/
public void setActiveHierarchy(Hierarchy hierarchy)
{
activeHierarchy = hierarchy;
}
public boolean hasActiveHierarchy()
{
return activeHierarchy != null;
}
public void releaseActiveHierarchy()
{
activeHierarchy = null;
}
public boolean hasCustomEntryPoints() {
return entryPoints!=null;
}
/** Get the set of entry points that are used to build the call graph. */
public List<SootMethod> getEntryPoints() {
if( entryPoints == null ) {
entryPoints = EntryPoints.v().all();
}
return entryPoints;
}
/** Change the set of entry point methods used to build the call graph. */
public void setEntryPoints( List<SootMethod> entryPoints ) {
this.entryPoints = entryPoints;
}
private ContextSensitiveCallGraph cscg = null;
public ContextSensitiveCallGraph getContextSensitiveCallGraph() {
if(cscg == null) throw new RuntimeException("No context-sensitive call graph present in Scene. You can bulid one with Paddle.");
return cscg;
}
public void setContextSensitiveCallGraph(ContextSensitiveCallGraph cscg) {
this.cscg = cscg;
}
public CallGraph getCallGraph()
{
if(!hasCallGraph()) {
throw new RuntimeException( "No call graph present in Scene. Maybe you want Whole Program mode (-w)." );
}
return activeCallGraph;
}
public void setCallGraph(CallGraph cg)
{
reachableMethods = null;
activeCallGraph = cg;
}
public boolean hasCallGraph()
{
return activeCallGraph != null;
}
public void releaseCallGraph()
{
activeCallGraph = null;
reachableMethods = null;
}
public ReachableMethods getReachableMethods() {
if( reachableMethods == null ) {
reachableMethods = new ReachableMethods(
getCallGraph(), new ArrayList<MethodOrMethodContext>(getEntryPoints()) );
}
reachableMethods.update();
return reachableMethods;
}
public void setReachableMethods( ReachableMethods rm ) {
reachableMethods = rm;
}
public boolean hasReachableMethods() {
return reachableMethods != null;
}
public void releaseReachableMethods() {
reachableMethods = null;
}
public boolean getPhantomRefs()
{
//if( !Options.v().allow_phantom_refs() ) return false;
//return allowsPhantomRefs;
return Options.v().allow_phantom_refs();
}
public void setPhantomRefs(boolean value)
{
allowsPhantomRefs = value;
}
public boolean allowsPhantomRefs()
{
return getPhantomRefs();
}
public Numberer<Kind> kindNumberer() { return kindNumberer; }
public ArrayNumberer<Type> getTypeNumberer() { return typeNumberer; }
public ArrayNumberer<SootMethod> getMethodNumberer() { return methodNumberer; }
public Numberer<Context> getContextNumberer() { return contextNumberer; }
public Numberer<Unit> getUnitNumberer() { return unitNumberer; }
public Numberer<SparkField> getFieldNumberer() { return fieldNumberer; }
public ArrayNumberer<SootClass> getClassNumberer() { return classNumberer; }
public StringNumberer getSubSigNumberer() { return subSigNumberer; }
public ArrayNumberer<Local> getLocalNumberer() { return localNumberer; }
public void setContextNumberer( Numberer<Context> n ) {
if( contextNumberer != null )
throw new RuntimeException(
"Attempt to set context numberer when it is already set." );
contextNumberer = n;
}
/**
* Returns the {@link ThrowAnalysis} to be used by default when
* constructing CFGs which include exceptional control flow.
*
* @return the default {@link ThrowAnalysis}
*/
public ThrowAnalysis getDefaultThrowAnalysis()
{
if( defaultThrowAnalysis == null ) {
int optionsThrowAnalysis = Options.v().throw_analysis();
switch (optionsThrowAnalysis) {
case Options.throw_analysis_pedantic:
defaultThrowAnalysis = PedanticThrowAnalysis.v();
break;
case Options.throw_analysis_unit:
defaultThrowAnalysis = UnitThrowAnalysis.v();
break;
default:
throw new IllegalStateException("Options.v().throw_analysi() == " +
Options.v().throw_analysis());
}
}
return defaultThrowAnalysis;
}
/**
* Sets the {@link ThrowAnalysis} to be used by default when
* constructing CFGs which include exceptional control flow.
*
* @param ta the default {@link ThrowAnalysis}.
*/
public void setDefaultThrowAnalysis(ThrowAnalysis ta)
{
defaultThrowAnalysis = ta;
}
private void setReservedNames()
{
Set<String> rn = getReservedNames();
rn.add("newarray");
rn.add("newmultiarray");
rn.add("nop");
rn.add("ret");
rn.add("specialinvoke");
rn.add("staticinvoke");
rn.add("tableswitch");
rn.add("virtualinvoke");
rn.add("null_type");
rn.add("unknown");
rn.add("cmp");
rn.add("cmpg");
rn.add("cmpl");
rn.add("entermonitor");
rn.add("exitmonitor");
rn.add("interfaceinvoke");
rn.add("lengthof");
rn.add("lookupswitch");
rn.add("neg");
rn.add("if");
rn.add("abstract");
rn.add("annotation");
rn.add("boolean");
rn.add("break");
rn.add("byte");
rn.add("case");
rn.add("catch");
rn.add("char");
rn.add("class");
rn.add("enum");
rn.add("final");
rn.add("native");
rn.add("public");
rn.add("protected");
rn.add("private");
rn.add("static");
rn.add("synchronized");
rn.add("transient");
rn.add("volatile");
rn.add("interface");
rn.add("void");
rn.add("short");
rn.add("int");
rn.add("long");
rn.add("float");
rn.add("double");
rn.add("extends");
rn.add("implements");
rn.add("breakpoint");
rn.add("default");
rn.add("goto");
rn.add("instanceof");
rn.add("new");
rn.add("return");
rn.add("throw");
rn.add("throws");
rn.add("null");
rn.add("from");
rn.add("to");
rn.add("with");
}
private final Set<String>[] basicclasses=new Set[4];
private void addSootBasicClasses() {
basicclasses[SootClass.HIERARCHY] = new HashSet<String>();
basicclasses[SootClass.SIGNATURES] = new HashSet<String>();
basicclasses[SootClass.BODIES] = new HashSet<String>();
addBasicClass("java.lang.Object");
addBasicClass("java.lang.Class", SootClass.SIGNATURES);
addBasicClass("java.lang.Void", SootClass.SIGNATURES);
addBasicClass("java.lang.Boolean", SootClass.SIGNATURES);
addBasicClass("java.lang.Byte", SootClass.SIGNATURES);
addBasicClass("java.lang.Character", SootClass.SIGNATURES);
addBasicClass("java.lang.Short", SootClass.SIGNATURES);
addBasicClass("java.lang.Integer", SootClass.SIGNATURES);
addBasicClass("java.lang.Long", SootClass.SIGNATURES);
addBasicClass("java.lang.Float", SootClass.SIGNATURES);
addBasicClass("java.lang.Double", SootClass.SIGNATURES);
addBasicClass("java.lang.String");
addBasicClass("java.lang.StringBuffer", SootClass.SIGNATURES);
addBasicClass("java.lang.Error");
addBasicClass("java.lang.AssertionError", SootClass.SIGNATURES);
addBasicClass("java.lang.Throwable", SootClass.SIGNATURES);
addBasicClass("java.lang.NoClassDefFoundError", SootClass.SIGNATURES);
addBasicClass("java.lang.ExceptionInInitializerError");
addBasicClass("java.lang.RuntimeException");
addBasicClass("java.lang.ClassNotFoundException");
addBasicClass("java.lang.ArithmeticException");
addBasicClass("java.lang.ArrayStoreException");
addBasicClass("java.lang.ClassCastException");
addBasicClass("java.lang.IllegalMonitorStateException");
addBasicClass("java.lang.IndexOutOfBoundsException");
addBasicClass("java.lang.ArrayIndexOutOfBoundsException");
addBasicClass("java.lang.NegativeArraySizeException");
addBasicClass("java.lang.NullPointerException", SootClass.SIGNATURES);
addBasicClass("java.lang.InstantiationError");
addBasicClass("java.lang.InternalError");
addBasicClass("java.lang.OutOfMemoryError");
addBasicClass("java.lang.StackOverflowError");
addBasicClass("java.lang.UnknownError");
addBasicClass("java.lang.ThreadDeath");
addBasicClass("java.lang.ClassCircularityError");
addBasicClass("java.lang.ClassFormatError");
addBasicClass("java.lang.IllegalAccessError");
addBasicClass("java.lang.IncompatibleClassChangeError");
addBasicClass("java.lang.LinkageError");
addBasicClass("java.lang.VerifyError");
addBasicClass("java.lang.NoSuchFieldError");
addBasicClass("java.lang.AbstractMethodError");
addBasicClass("java.lang.NoSuchMethodError");
addBasicClass("java.lang.UnsatisfiedLinkError");
addBasicClass("java.lang.Thread");
addBasicClass("java.lang.Runnable");
addBasicClass("java.lang.Cloneable");
addBasicClass("java.io.Serializable");
addBasicClass("java.lang.ref.Finalizer");
addBasicClass("java.lang.invoke.LambdaMetafactory");
}
public void addBasicClass(String name) {
addBasicClass(name, SootClass.HIERARCHY);
}
public void addBasicClass(String name, int level) {
basicclasses[level].add(name);
}
/** Load just the set of basic classes soot needs, ignoring those
* specified on the command-line. You don't need to use both this and
* loadNecessaryClasses, though it will only waste time.
*/
public void loadBasicClasses() {
addReflectionTraceClasses();
for(int i=SootClass.BODIES;i>=SootClass.HIERARCHY;i--) {
for(String name: basicclasses[i]){
tryLoadClass(name,i);
}
}
}
public Set<String> getBasicClasses() {
Set<String> all = new HashSet<String>();
for(int i=0;i<basicclasses.length;i++) {
Set<String> classes = basicclasses[i];
if(classes!=null)
all.addAll(classes);
}
return all;
}
private void addReflectionTraceClasses() {
CGOptions options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
String log = options.reflection_log();
Set<String> classNames = new HashSet<String>();
if(log!=null && log.length()>0) {
BufferedReader reader = null;
String line="";
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(log)));
while((line=reader.readLine())!=null) {
if(line.length()==0) continue;
String[] portions = line.split(";",-1);
String kind = portions[0];
String target = portions[1];
String source = portions[2];
String sourceClassName = source.substring(0,source.lastIndexOf("."));
classNames.add(sourceClassName);
if(kind.equals("Class.forName")) {
classNames.add(target);
} else if(kind.equals("Class.newInstance")) {
classNames.add(target);
} else if(kind.equals("Method.invoke") || kind.equals("Constructor.newInstance")) {
classNames.add(signatureToClass(target));
} else if(kind.equals("Field.set*") || kind.equals("Field.get*")) {
classNames.add(signatureToClass(target));
} else throw new RuntimeException("Unknown entry kind: "+kind);
}
} catch (Exception e) {
throw new RuntimeException("Line: '"+line+"'", e);
}
finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
for (String c : classNames) {
addBasicClass(c, SootClass.BODIES);
}
}
private List<SootClass> dynamicClasses = null;
public Collection<SootClass> dynamicClasses() {
if(dynamicClasses==null) {
throw new IllegalStateException("Have to call loadDynamicClasses() first!");
}
return dynamicClasses;
}
private void loadNecessaryClass(String name) {
SootClass c;
c = loadClassAndSupport(name);
c.setApplicationClass();
}
/** Load the set of classes that soot needs, including those specified on the
* command-line. This is the standard way of initialising the list of
* classes soot should use.
*/
public void loadNecessaryClasses() {
loadBasicClasses();
for (String name : Options.v().classes()) {
loadNecessaryClass(name);
}
loadDynamicClasses();
if(Options.v().oaat()) {
if(Options.v().process_dir().isEmpty()) {
throw new IllegalArgumentException("If switch -oaat is used, then also -process-dir must be given.");
}
} else {
for( final String path : Options.v().process_dir() ) {
for (String cl : SourceLocator.v().getClassesUnder(path)) {
SootClass theClass = loadClassAndSupport(cl);
theClass.setApplicationClass();
}
}
}
prepareClasses();
setDoneResolving();
}
public void loadDynamicClasses() {
dynamicClasses = new ArrayList<SootClass>();
HashSet<String> dynClasses = new HashSet<String>();
dynClasses.addAll(Options.v().dynamic_class());
for( Iterator<String> pathIt = Options.v().dynamic_dir().iterator(); pathIt.hasNext(); ) {
final String path = pathIt.next();
dynClasses.addAll(SourceLocator.v().getClassesUnder(path));
}
for( Iterator<String> pkgIt = Options.v().dynamic_package().iterator(); pkgIt.hasNext(); ) {
final String pkg = pkgIt.next();
dynClasses.addAll(SourceLocator.v().classesInDynamicPackage(pkg));
}
for (String className : dynClasses) {
dynamicClasses.add( loadClassAndSupport(className) );
}
//remove non-concrete classes that may accidentally have been loaded
for (Iterator<SootClass> iterator = dynamicClasses.iterator(); iterator.hasNext();) {
SootClass c = iterator.next();
if(!c.isConcrete()) {
if(Options.v().verbose()) {
G.v().out.println("Warning: dynamic class "+c.getName()+" is abstract or an interface, and it will not be considered.");
}
iterator.remove();
}
}
}
/* Generate classes to process, adding or removing package marked by
* command line options.
*/
private void prepareClasses() {
// Remove/add all classes from packageInclusionMask as per -i option
Chain<SootClass> processedClasses = new HashChain<SootClass>();
while(true) {
Chain<SootClass> unprocessedClasses = new HashChain<SootClass>(getClasses());
unprocessedClasses.removeAll(processedClasses);
if( unprocessedClasses.isEmpty() ) break;
processedClasses.addAll(unprocessedClasses);
for (SootClass s : unprocessedClasses) {
if( s.isPhantom() ) continue;
if(Options.v().app()) {
s.setApplicationClass();
}
if (Options.v().classes().contains(s.getName())) {
s.setApplicationClass();
continue;
}
if(s.isApplicationClass() && isExcluded(s)){
s.setLibraryClass();
}
if(isIncluded(s)){
s.setApplicationClass();
}
if(s.isApplicationClass()) {
// make sure we have the support
loadClassAndSupport(s.getName());
}
}
}
}
public boolean isExcluded(SootClass sc){
String name = sc.getName();
for (String pkg : excludedPackages) {
if(name.equals(pkg) || ((pkg.endsWith(".*") || pkg.endsWith("$*")) && name.startsWith(pkg.substring(0, pkg.length() - 1)))){
return !isIncluded(sc);
}
}
return false;
}
public boolean isIncluded(SootClass sc){
String name = sc.getName();
for (String inc : (List<String>) Options.v().include()) {
if (name.equals(inc) || ((inc.endsWith(".*") || inc.endsWith("$*")) && name.startsWith(inc.substring(0, inc.length() - 1)))) {
return true;
}
}
return false;
}
List<String> pkgList;
public void setPkgList(List<String> list){
pkgList = list;
}
public List<String> getPkgList(){
return pkgList;
}
/** Create an unresolved reference to a method. */
public SootMethodRef makeMethodRef(
SootClass declaringClass,
String name,
List<Type> parameterTypes,
Type returnType,
boolean isStatic ) {
return new SootMethodRefImpl(declaringClass, name, parameterTypes,
returnType, isStatic);
}
/** Create an unresolved reference to a constructor. */
public SootMethodRef makeConstructorRef(
SootClass declaringClass,
List<Type> parameterTypes) {
return makeMethodRef(declaringClass, SootMethod.constructorName,
parameterTypes, VoidType.v(), false );
}
/** Create an unresolved reference to a field. */
public SootFieldRef makeFieldRef(
SootClass declaringClass,
String name,
Type type,
boolean isStatic) {
return new AbstractSootFieldRef(declaringClass, name, type, isStatic);
}
/** Returns the list of SootClasses that have been resolved at least to
* the level specified. */
public List<SootClass> getClasses(int desiredLevel) {
List<SootClass> ret = new ArrayList<SootClass>();
for( Iterator<SootClass> clIt = getClasses().iterator(); clIt.hasNext(); ) {
final SootClass cl = clIt.next();
if( cl.resolvingLevel() >= desiredLevel ) ret.add(cl);
}
return ret;
}
private boolean doneResolving = false;
private boolean incrementalBuild;
protected LinkedList<String> excludedPackages;
public boolean doneResolving() { return doneResolving; }
public void setDoneResolving() { doneResolving = true; }
public void setMainClassFromOptions() {
if(mainClass != null) return;
if( Options.v().main_class() != null
&& Options.v().main_class().length() > 0 ) {
setMainClass(getSootClass(Options.v().main_class()));
} else {
// try to infer a main class from the command line if none is given
for (Iterator<String> classIter = Options.v().classes().iterator(); classIter.hasNext();) {
SootClass c = getSootClass(classIter.next());
if (c.declaresMethod ("main", Collections.<Type>singletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v()))
{
G.v().out.println("No main class given. Inferred '"+c.getName()+"' as main class.");
setMainClass(c);
return;
}
}
// try to infer a main class from the usual classpath if none is given
for (Iterator<SootClass> classIter = getApplicationClasses().iterator(); classIter.hasNext();) {
SootClass c = classIter.next();
if (c.declaresMethod ("main", Collections.<Type>singletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v()))
{
G.v().out.println("No main class given. Inferred '"+c.getName()+"' as main class.");
setMainClass(c);
return;
}
}
}
}
/**
* This method returns true when in incremental build mode.
* Other classes can query this flag and change the way in which they use the Scene,
* depending on the flag's value.
*/
public boolean isIncrementalBuild() {
return incrementalBuild;
}
public void initiateIncrementalBuild() {
this.incrementalBuild = true;
}
public void incrementalBuildFinished() {
this.incrementalBuild = false;
}
/*
* Forces Soot to resolve the class with the given name to the given level,
* even if resolving has actually already finished.
*/
public SootClass forceResolve(String className, int level) {
boolean tmp = doneResolving;
doneResolving = false;
SootClass c;
try {
c = SootResolver.v().resolveClass(className, level);
} finally {
doneResolving = tmp;
}
return c;
}
}
| src/soot/Scene.java | /* Soot - a J*va Optimization Framework
* Copyright (C) 1997-1999 Raja Vallee-Rai
* Copyright (C) 2004 Ondrej Lhotak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.xmlpull.v1.XmlPullParser;
import soot.jimple.spark.internal.ClientAccessibilityOracle;
import soot.jimple.spark.internal.PublicAndProtectedAccessibility;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.ContextSensitiveCallGraph;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import soot.jimple.toolkits.pointer.DumbPointerAnalysis;
import soot.jimple.toolkits.pointer.SideEffectAnalysis;
import soot.options.CGOptions;
import soot.options.Options;
import soot.toolkits.exceptions.PedanticThrowAnalysis;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.exceptions.UnitThrowAnalysis;
import soot.util.ArrayNumberer;
import soot.util.Chain;
import soot.util.HashChain;
import soot.util.MapNumberer;
import soot.util.Numberer;
import soot.util.StringNumberer;
import test.AXMLPrinter;
import android.content.res.AXmlResourceParser;
/** Manages the SootClasses of the application being analyzed. */
public class Scene //extends AbstractHost
{
private final int defaultSdkVersion = 15;
private final Map<String, Integer> maxAPIs = new HashMap<String, Integer>();
public Scene ( Singletons.Global g )
{
setReservedNames();
// load soot.class.path system property, if defined
String scp = System.getProperty("soot.class.path");
if (scp != null)
setSootClassPath(scp);
kindNumberer = new ArrayNumberer<Kind>(new Kind[] {
Kind.INVALID,
Kind.STATIC,
Kind.VIRTUAL,
Kind.INTERFACE,
Kind.SPECIAL,
Kind.CLINIT,
Kind.THREAD,
Kind.EXECUTOR,
Kind.ASYNCTASK,
Kind.FINALIZE,
Kind.INVOKE_FINALIZE,
Kind.PRIVILEGED,
Kind.NEWINSTANCE});
addSootBasicClasses();
determineExcludedPackages();
}
private void determineExcludedPackages() {
excludedPackages = new LinkedList<String>();
if (Options.v().exclude() != null)
excludedPackages.addAll(Options.v().exclude());
// do not kill contents of the APK if we want a working new APK afterwards
if( !Options.v().include_all()
&& Options.v().output_format() != Options.output_format_dex
&& Options.v().output_format() != Options.output_format_force_dex) {
excludedPackages.add("java.*");
excludedPackages.add("sun.*");
excludedPackages.add("javax.*");
excludedPackages.add("com.sun.*");
excludedPackages.add("com.ibm.*");
excludedPackages.add("org.xml.*");
excludedPackages.add("org.w3c.*");
excludedPackages.add("apple.awt.*");
excludedPackages.add("com.apple.*");
}
}
public static Scene v() { return G.v().soot_Scene (); }
Chain<SootClass> classes = new HashChain<SootClass>();
Chain<SootClass> applicationClasses = new HashChain<SootClass>();
Chain<SootClass> libraryClasses = new HashChain<SootClass>();
Chain<SootClass> phantomClasses = new HashChain<SootClass>();
private final Map<String,RefType> nameToClass = new HashMap<String,RefType>();
final ArrayNumberer<Kind> kindNumberer;
ArrayNumberer<Type> typeNumberer = new ArrayNumberer<Type>();
ArrayNumberer<SootMethod> methodNumberer = new ArrayNumberer<SootMethod>();
Numberer<Unit> unitNumberer = new MapNumberer<Unit>();
Numberer<Context> contextNumberer = null;
Numberer<SparkField> fieldNumberer = new ArrayNumberer<SparkField>();
ArrayNumberer<SootClass> classNumberer = new ArrayNumberer<SootClass>();
StringNumberer subSigNumberer = new StringNumberer();
ArrayNumberer<Local> localNumberer = new ArrayNumberer<Local>();
private Hierarchy activeHierarchy;
private FastHierarchy activeFastHierarchy;
private CallGraph activeCallGraph;
private ReachableMethods reachableMethods;
private PointsToAnalysis activePointsToAnalysis;
private SideEffectAnalysis activeSideEffectAnalysis;
private List<SootMethod> entryPoints;
private ClientAccessibilityOracle accessibilityOracle;
boolean allowsPhantomRefs = false;
SootClass mainClass;
String sootClassPath = null;
// Two default values for constructing ExceptionalUnitGraphs:
private ThrowAnalysis defaultThrowAnalysis = null;
public void setMainClass(SootClass m)
{
mainClass = m;
if(!m.declaresMethod(getSubSigNumberer().findOrAdd( "void main(java.lang.String[])" ))) {
throw new RuntimeException("Main-class has no main method!");
}
}
Set<String> reservedNames = new HashSet<String>();
/**
Returns a set of tokens which are reserved. Any field, class, method, or local variable with such a name will be quoted.
*/
public Set<String> getReservedNames()
{
return reservedNames;
}
/**
* If this name is in the set of reserved names, then return a quoted
* version of it. Else pass it through. If the name consists of multiple
* parts separated by dots, the individual names are checked as well.
*/
public String quotedNameOf(String s)
{
StringBuilder res = new StringBuilder(s.length());
for (String part : s.split("\\.")) {
if (res.length() > 0)
res.append('.');
if(reservedNames.contains(part)) {
res.append('\'');
res.append(part);
res.append('\'');
}
else
res.append(part);
}
return res.toString();
}
public boolean hasMainClass() {
if(mainClass == null) {
setMainClassFromOptions();
}
return mainClass!=null;
}
public SootClass getMainClass()
{
if(!hasMainClass())
throw new RuntimeException("There is no main class set!");
return mainClass;
}
public SootMethod getMainMethod() {
if(!hasMainClass()) {
throw new RuntimeException("There is no main class set!");
}
SootMethod mainMethod = mainClass.getMethodUnsafe("main",
Collections.<Type>singletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ),
VoidType.v());
if (mainMethod == null) {
throw new RuntimeException("Main class declares no main method!");
}
return mainMethod;
}
public void setSootClassPath(String p)
{
sootClassPath = p;
SourceLocator.v().invalidateClassPath();
}
public String getSootClassPath()
{
if( sootClassPath == null ) {
String optionscp = Options.v().soot_classpath();
if( optionscp.length() > 0 )
sootClassPath = optionscp;
//if no classpath is given on the command line, take the default
if( sootClassPath == null ) {
sootClassPath = defaultClassPath();
} else {
//if one is given...
if(Options.v().prepend_classpath()) {
//if the prepend flag is set, append the default classpath
sootClassPath += File.pathSeparator + defaultClassPath();
}
//else, leave it as it is
}
//add process-dirs
List<String> process_dir = Options.v().process_dir();
StringBuffer pds = new StringBuffer();
for (String path : process_dir) {
if(!sootClassPath.contains(path)) {
pds.append(path);
pds.append(File.pathSeparator);
}
}
sootClassPath = pds + sootClassPath;
}
return sootClassPath;
}
/**
* Returns the max Android API version number available
* in directory 'dir'
* @param dir
* @return
*/
private int getMaxAPIAvailable(String dir) {
Integer mapi = this.maxAPIs.get(dir);
if (mapi != null)
return mapi;
File d = new File(dir);
if (!d.exists())
throw new RuntimeException("The Android platform directory you have"
+ "specified (" + dir + ") does not exist. Please check.");
File[] files = d.listFiles();
if (files == null)
return -1;
int maxApi = -1;
for (File f: files) {
String name = f.getName();
if (f.isDirectory() && name.startsWith("android-")) {
try {
int v = Integer.decode(name.split("android-")[1]);
if (v > maxApi)
maxApi = v;
}
catch (NumberFormatException ex) {
// We simply ignore directories that do not follow the
// Android naming structure
}
}
}
this.maxAPIs.put(dir, maxApi);
return maxApi;
}
public String getAndroidJarPath(String jars, String apk) {
int APIVersion = getAndroidAPIVersion(jars,apk);
String jarPath = jars + File.separator + "android-" + APIVersion + File.separator + "android.jar";
// check that jar exists
File f = new File(jarPath);
if (!f.isFile())
throw new RuntimeException("error: target android.jar ("+ jarPath +") does not exist.");
return jarPath;
}
public int getAndroidAPIVersion(String jars, String apk) {
// get path to appropriate android.jar
File jarsF = new File(jars);
File apkF = new File(apk);
if (!jarsF.exists())
throw new RuntimeException("file '" + jars + "' does not exist!");
if (!apkF.exists())
throw new RuntimeException("file '" + apk + "' does not exist!");
// get path to appropriate android.jar
int APIVersion = defaultSdkVersion;
if (apk.toLowerCase().endsWith(".apk"))
APIVersion = getTargetSDKVersion(apk, jars);
final int maxAPI = getMaxAPIAvailable(jars);
if (APIVersion > maxAPI)
APIVersion = maxAPI;
return APIVersion;
}
private int getTargetSDKVersion(String apkFile, String platformJARs) {
// get AndroidManifest
InputStream manifestIS = null;
ZipFile archive = null;
try {
try {
archive = new ZipFile(apkFile);
for (Enumeration<? extends ZipEntry> entries = archive.entries(); entries.hasMoreElements();) {
ZipEntry entry = entries.nextElement();
String entryName = entry.getName();
// We are dealing with the Android manifest
if (entryName.equals("AndroidManifest.xml")) {
manifestIS = archive.getInputStream(entry);
break;
}
}
} catch (Exception e) {
throw new RuntimeException("Error when looking for manifest in apk: " + e);
}
if (manifestIS == null) {
G.v().out.println("Could not find sdk version in Android manifest! Using default: "+defaultSdkVersion);
return defaultSdkVersion;
}
// process AndroidManifest.xml
int maxAPI = getMaxAPIAvailable(platformJARs);
int sdkTargetVersion = -1;
int minSdkVersion = -1;
try {
AXmlResourceParser parser = new AXmlResourceParser();
parser.open(manifestIS);
int depth = 0;
loop: while (true) {
int type = parser.next();
switch (type) {
case XmlPullParser.START_DOCUMENT: {
break;
}
case XmlPullParser.END_DOCUMENT:
break loop;
case XmlPullParser.START_TAG: {
depth++;
String tagName = parser.getName();
if (depth == 2 && tagName.equals("uses-sdk")) {
for (int i = 0; i != parser.getAttributeCount(); ++i) {
String attributeName = parser.getAttributeName(i);
String attributeValue = AXMLPrinter.getAttributeValue(parser, i);
if (attributeName.equals("targetSdkVersion")) {
sdkTargetVersion = Integer.parseInt(attributeValue);
} else if (attributeName.equals("minSdkVersion")) {
minSdkVersion = Integer.parseInt(attributeValue);
}
}
}
break;
}
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.TEXT:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
int APIVersion = -1;
if (sdkTargetVersion != -1) {
if (sdkTargetVersion > maxAPI
&& minSdkVersion != -1
&& minSdkVersion <= maxAPI) {
G.v().out.println("warning: Android API version '"+ sdkTargetVersion +"' not available, using minApkVersion '"+ minSdkVersion +"' instead");
APIVersion = minSdkVersion;
} else {
APIVersion = sdkTargetVersion;
}
} else if (minSdkVersion != -1) {
APIVersion = minSdkVersion;
} else {
G.v().out.println("Could not find sdk version in Android manifest! Using default: "+defaultSdkVersion);
APIVersion = defaultSdkVersion;
}
if (APIVersion <= 2)
APIVersion = 3;
return APIVersion;
}
finally {
if (archive != null)
try {
archive.close();
} catch (IOException e) {
throw new RuntimeException("Error when looking for manifest in apk: " + e);
}
}
}
public String defaultClassPath() {
if (Options.v().src_prec() == Options.src_prec_apk)
return defaultAndroidClassPath();
else
return defaultJavaClassPath();
}
private String defaultAndroidClassPath() {
// check that android.jar is not in classpath
String androidJars = Options.v().android_jars();
String forceAndroidJar = Options.v().force_android_jar();
if ((androidJars == null || androidJars.equals(""))
&& (forceAndroidJar == null || forceAndroidJar.equals(""))) {
throw new RuntimeException("You are analyzing an Android application but did not define android.jar. Options -android-jars or -force-android-jar should be used.");
}
// Get the platform JAR file. It either directly specified, or
// we detect it from the target version of the APK we are
// analyzing
String jarPath = "";
if (forceAndroidJar != null && !forceAndroidJar.isEmpty()) {
jarPath = forceAndroidJar;
}
else if (androidJars != null && !androidJars.isEmpty()) {
List<String> classPathEntries = new LinkedList<String>(Arrays.asList(
Options.v().soot_classpath().split(File.pathSeparator)));
classPathEntries.addAll(Options.v().process_dir());
Set<String> targetApks = new HashSet<String>();
for (String entry : classPathEntries) {
if(entry.toLowerCase().endsWith(".apk")
|| entry.toLowerCase().endsWith(".dex")) // on Windows, file names are case-insensitive
targetApks.add(entry);
}
if (targetApks.size() == 0)
throw new RuntimeException("no apk file given");
else if (targetApks.size() > 1)
throw new RuntimeException("only one Android application can be analyzed when using option -android-jars.");
jarPath = getAndroidJarPath (androidJars, (String)targetApks.toArray()[0]);
}
// We must have a platform JAR file when analyzing Android apps
if (jarPath.equals(""))
throw new RuntimeException("android.jar not found.");
// Check the platform JAR file
File f = new File (jarPath);
if (!f.exists())
throw new RuntimeException("file '"+ jarPath +"' does not exist!");
else
G.v().out.println("Using '"+ jarPath +"' as android.jar");
return jarPath;
}
private String defaultJavaClassPath() {
StringBuilder sb = new StringBuilder();
if(System.getProperty("os.name").equals("Mac OS X")) {
//in older Mac OS X versions, rt.jar was split into classes.jar and ui.jar
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("..");
sb.append(File.separator);
sb.append("Classes");
sb.append(File.separator);
sb.append("classes.jar");
sb.append(File.pathSeparator);
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("..");
sb.append(File.separator);
sb.append("Classes");
sb.append(File.separator);
sb.append("ui.jar");
sb.append(File.pathSeparator);
}
sb.append(System.getProperty("java.home"));
sb.append(File.separator);
sb.append("lib");
sb.append(File.separator);
sb.append("rt.jar");
if(Options.v().whole_program() || Options.v().output_format()==Options.output_format_dava) {
//add jce.jar, which is necessary for whole program mode
//(java.security.Signature from rt.jar import javax.crypto.Cipher from jce.jar
sb.append(File.pathSeparator+
System.getProperty("java.home")+File.separator+"lib"+File.separator+"jce.jar");
}
return sb.toString();
}
private int stateCount;
public int getState() { return this.stateCount; }
private void modifyHierarchy() {
stateCount++;
activeHierarchy = null;
activeFastHierarchy = null;
activeSideEffectAnalysis = null;
activePointsToAnalysis = null;
}
public void addClass(SootClass c)
{
if(c.isInScene())
throw new RuntimeException("already managed: "+c.getName());
if(containsClass(c.getName()))
throw new RuntimeException("duplicate class: "+c.getName());
classes.add(c);
c.setLibraryClass();
nameToClass.put(c.getName(), c.getType());
c.getType().setSootClass(c);
c.setInScene(true);
// Phantom classes are not really part of the hierarchy anyway, so
// we can keep the old one
if (!c.isPhantom)
modifyHierarchy();
}
public void removeClass(SootClass c)
{
if(!c.isInScene())
throw new RuntimeException();
classes.remove(c);
if(c.isLibraryClass()) {
libraryClasses.remove(c);
} else if(c.isPhantomClass()) {
phantomClasses.remove(c);
} else if(c.isApplicationClass()) {
applicationClasses.remove(c);
}
c.getType().setSootClass(null);
c.setInScene(false);
modifyHierarchy();
}
public boolean containsClass(String className)
{
RefType type = nameToClass.get(className);
if( type == null ) return false;
if( !type.hasSootClass() ) return false;
SootClass c = type.getSootClass();
return c.isInScene();
}
public boolean containsType(String className)
{
return nameToClass.containsKey(className);
}
public String signatureToClass(String sig) {
if( sig.charAt(0) != '<' ) throw new RuntimeException("oops "+sig);
if( sig.charAt(sig.length()-1) != '>' ) throw new RuntimeException("oops "+sig);
int index = sig.indexOf( ":" );
if( index < 0 ) throw new RuntimeException("oops "+sig);
return sig.substring(1,index);
}
public String signatureToSubsignature(String sig) {
if( sig.charAt(0) != '<' ) throw new RuntimeException("oops "+sig);
if( sig.charAt(sig.length()-1) != '>' ) throw new RuntimeException("oops "+sig);
int index = sig.indexOf( ":" );
if( index < 0 ) throw new RuntimeException("oops "+sig);
return sig.substring(index+2,sig.length()-1);
}
public SootField grabField(String fieldSignature)
{
String cname = signatureToClass( fieldSignature );
String fname = signatureToSubsignature( fieldSignature );
if( !containsClass(cname) ) return null;
SootClass c = getSootClass(cname);
return c.getFieldUnsafe( fname );
}
public boolean containsField(String fieldSignature)
{
return grabField(fieldSignature) != null;
}
public SootMethod grabMethod(String methodSignature)
{
String cname = signatureToClass( methodSignature );
String mname = signatureToSubsignature( methodSignature );
if( !containsClass(cname) ) return null;
SootClass c = getSootClass(cname);
if( !c.declaresMethod( mname ) ) return null;
return c.getMethod( mname );
}
public boolean containsMethod(String methodSignature)
{
return grabMethod(methodSignature) != null;
}
public SootField getField(String fieldSignature)
{
SootField f = grabField( fieldSignature );
if (f != null)
return f;
throw new RuntimeException("tried to get nonexistent field "+fieldSignature);
}
public SootMethod getMethod(String methodSignature)
{
SootMethod m = grabMethod( methodSignature );
if (m != null)
return m;
throw new RuntimeException("tried to get nonexistent method "+methodSignature);
}
/**
* Attempts to load the given class and all of the required support classes.
* Returns the original class if it was loaded, or null otherwise.
*/
public SootClass tryLoadClass(String className, int desiredLevel)
{
/*
if(Options.v().time())
Main.v().resolveTimer.start();
*/
setPhantomRefs(true);
//SootResolver resolver = new SootResolver();
if( !getPhantomRefs()
&& SourceLocator.v().getClassSource(className) == null ) {
setPhantomRefs(false);
return null;
}
SootResolver resolver = SootResolver.v();
SootClass toReturn = resolver.resolveClass(className, desiredLevel);
setPhantomRefs(false);
return toReturn;
/*
if(Options.v().time())
Main.v().resolveTimer.end(); */
}
/**
* Loads the given class and all of the required support classes. Returns the first class.
*/
public SootClass loadClassAndSupport(String className)
{
SootClass ret = loadClass(className, SootClass.SIGNATURES);
if( !ret.isPhantom() ) ret = loadClass(className, SootClass.BODIES);
return ret;
}
public SootClass loadClass(String className, int desiredLevel)
{
/*
if(Options.v().time())
Main.v().resolveTimer.start();
*/
setPhantomRefs(true);
//SootResolver resolver = new SootResolver();
SootResolver resolver = SootResolver.v();
SootClass toReturn = resolver.resolveClass(className, desiredLevel);
setPhantomRefs(false);
return toReturn;
/*
if(Options.v().time())
Main.v().resolveTimer.end(); */
}
/**
* Returns the RefType with the given class name or primitive type.
* @throws RuntimeException if the Type for this name cannot be found.
* Use {@link #getRefTypeUnsafe(String)} to check if type is an registered RefType.
*/
public Type getType(String arg) {
String type = arg.replaceAll("([^\\[\\]]*)(.*)", "$1");
int arrayCount = arg.contains("[") ? arg.replaceAll("([^\\[\\]]*)(.*)", "$2").length() / 2 : 0;
Type result = getRefTypeUnsafe(type);
if (result == null) {
if (type.equals("long"))
result = LongType.v();
else if (type.equals("short"))
result = ShortType.v();
else if (type.equals("double"))
result = DoubleType.v();
else if (type.equals("int"))
result = IntType.v();
else if (type.equals("float"))
result = FloatType.v();
else if (type.equals("byte"))
result = ByteType.v();
else if (type.equals("char"))
result = CharType.v();
else if (type.equals("void"))
result = VoidType.v();
else if (type.equals("boolean"))
result = BooleanType.v();
else
throw new RuntimeException("unknown type: '" + type + "'");
}
if (arrayCount != 0) {
result = ArrayType.v(result, arrayCount);
}
return result;
}
/**
* Returns the RefType with the given className.
* @throws IllegalStateException if the RefType for this class cannot be found.
* Use {@link #containsType(String)} to check if type is registered
*/
public RefType getRefType(String className)
{
RefType refType = getRefTypeUnsafe(className);
if(refType==null) {
throw new IllegalStateException("RefType "+className+" not loaded. " +
"If you tried to get the RefType of a library class, did you call loadNecessaryClasses()? " +
"Otherwise please check Soot's classpath.");
}
return refType;
}
/**
* Returns the RefType with the given className. Returns null if no type
* with the given name can be found.
*/
public RefType getRefTypeUnsafe(String className)
{
RefType refType = nameToClass.get(className);
return refType;
}
/**
* Returns the {@link RefType} for {@link Object}.
*/
public RefType getObjectType() {
return getRefType("java.lang.Object");
}
/**
* Returns the RefType with the given className.
*/
public void addRefType(RefType type)
{
nameToClass.put(type.getClassName(), type);
}
/**
* Returns the SootClass with the given className. If no class with the
* given name exists, null is returned
* @param className The name of the class to get
* @return The class if it exists, otherwise null
*/
public SootClass getSootClassUnsafe(String className) {
RefType type = nameToClass.get(className);
if (type != null) {
SootClass tsc = type.getSootClass();
if (tsc != null)
return tsc;
}
if (allowsPhantomRefs() ||
className.equals(SootClass.INVOKEDYNAMIC_DUMMY_CLASS_NAME)) {
SootClass c = new SootClass(className);
addClass(c);
c.setPhantom(true);
return c;
}
return null;
}
/**
* Returns the SootClass with the given className.
*/
public SootClass getSootClass(String className) {
SootClass sc = getSootClassUnsafe(className);
if (sc != null)
return sc;
throw new RuntimeException(System.getProperty("line.separator")
+ "Aborting: can't find classfile " + className);
}
/**
* Returns an backed chain of the classes in this manager.
*/
public Chain<SootClass> getClasses()
{
return classes;
}
/* The four following chains are mutually disjoint. */
/**
* Returns a chain of the application classes in this scene.
* These classes are the ones which can be freely analysed & modified.
*/
public Chain<SootClass> getApplicationClasses()
{
return applicationClasses;
}
/**
* Returns a chain of the library classes in this scene.
* These classes can be analysed but not modified.
*/
public Chain<SootClass> getLibraryClasses()
{
return libraryClasses;
}
/**
* Returns a chain of the phantom classes in this scene.
* These classes are referred to by other classes, but cannot be loaded.
*/
public Chain<SootClass> getPhantomClasses()
{
return phantomClasses;
}
Chain<SootClass> getContainingChain(SootClass c)
{
if (c.isApplicationClass())
return getApplicationClasses();
else if (c.isLibraryClass())
return getLibraryClasses();
else if (c.isPhantomClass())
return getPhantomClasses();
return null;
}
/****************************************************************************/
/**
Retrieves the active side-effect analysis
*/
public SideEffectAnalysis getSideEffectAnalysis()
{
if(!hasSideEffectAnalysis()) {
setSideEffectAnalysis( new SideEffectAnalysis(
getPointsToAnalysis(),
getCallGraph() ) );
}
return activeSideEffectAnalysis;
}
/**
Sets the active side-effect analysis
*/
public void setSideEffectAnalysis(SideEffectAnalysis sea)
{
activeSideEffectAnalysis = sea;
}
public boolean hasSideEffectAnalysis()
{
return activeSideEffectAnalysis != null;
}
public void releaseSideEffectAnalysis()
{
activeSideEffectAnalysis = null;
}
/****************************************************************************/
/**
Retrieves the active pointer analysis
*/
public PointsToAnalysis getPointsToAnalysis()
{
if(!hasPointsToAnalysis()) {
return DumbPointerAnalysis.v();
}
return activePointsToAnalysis;
}
/**
Sets the active pointer analysis
*/
public void setPointsToAnalysis(PointsToAnalysis pa)
{
activePointsToAnalysis = pa;
}
public boolean hasPointsToAnalysis()
{
return activePointsToAnalysis != null;
}
public void releasePointsToAnalysis()
{
activePointsToAnalysis = null;
}
/****************************************************************************/
/**
* Retrieves the active client accessibility oracle
*/
public ClientAccessibilityOracle getClientAccessibilityOracle() {
if (!hasClientAccessibilityOracle()) {
return PublicAndProtectedAccessibility.v();
}
return accessibilityOracle;
}
public boolean hasClientAccessibilityOracle() {
return accessibilityOracle != null;
}
public void setClientAccessibilityOracle(ClientAccessibilityOracle oracle) {
accessibilityOracle = oracle;
}
public void releaseClientAccessibilityOracle() {
accessibilityOracle = null;
}
/****************************************************************************/
/** Makes a new fast hierarchy is none is active, and returns the active
* fast hierarchy. */
public FastHierarchy getOrMakeFastHierarchy() {
if(!hasFastHierarchy() ) {
setFastHierarchy( new FastHierarchy() );
}
return getFastHierarchy();
}
/**
Retrieves the active fast hierarchy
*/
public FastHierarchy getFastHierarchy()
{
if(!hasFastHierarchy())
throw new RuntimeException("no active FastHierarchy present for scene");
return activeFastHierarchy;
}
/**
Sets the active hierarchy
*/
public void setFastHierarchy(FastHierarchy hierarchy)
{
activeFastHierarchy = hierarchy;
}
public boolean hasFastHierarchy()
{
return activeFastHierarchy != null;
}
public void releaseFastHierarchy()
{
activeFastHierarchy = null;
}
/****************************************************************************/
/**
Retrieves the active hierarchy
*/
public Hierarchy getActiveHierarchy()
{
if(!hasActiveHierarchy())
//throw new RuntimeException("no active Hierarchy present for scene");
setActiveHierarchy( new Hierarchy() );
return activeHierarchy;
}
/**
Sets the active hierarchy
*/
public void setActiveHierarchy(Hierarchy hierarchy)
{
activeHierarchy = hierarchy;
}
public boolean hasActiveHierarchy()
{
return activeHierarchy != null;
}
public void releaseActiveHierarchy()
{
activeHierarchy = null;
}
public boolean hasCustomEntryPoints() {
return entryPoints!=null;
}
/** Get the set of entry points that are used to build the call graph. */
public List<SootMethod> getEntryPoints() {
if( entryPoints == null ) {
entryPoints = EntryPoints.v().all();
}
return entryPoints;
}
/** Change the set of entry point methods used to build the call graph. */
public void setEntryPoints( List<SootMethod> entryPoints ) {
this.entryPoints = entryPoints;
}
private ContextSensitiveCallGraph cscg = null;
public ContextSensitiveCallGraph getContextSensitiveCallGraph() {
if(cscg == null) throw new RuntimeException("No context-sensitive call graph present in Scene. You can bulid one with Paddle.");
return cscg;
}
public void setContextSensitiveCallGraph(ContextSensitiveCallGraph cscg) {
this.cscg = cscg;
}
public CallGraph getCallGraph()
{
if(!hasCallGraph()) {
throw new RuntimeException( "No call graph present in Scene. Maybe you want Whole Program mode (-w)." );
}
return activeCallGraph;
}
public void setCallGraph(CallGraph cg)
{
reachableMethods = null;
activeCallGraph = cg;
}
public boolean hasCallGraph()
{
return activeCallGraph != null;
}
public void releaseCallGraph()
{
activeCallGraph = null;
reachableMethods = null;
}
public ReachableMethods getReachableMethods() {
if( reachableMethods == null ) {
reachableMethods = new ReachableMethods(
getCallGraph(), new ArrayList<MethodOrMethodContext>(getEntryPoints()) );
}
reachableMethods.update();
return reachableMethods;
}
public void setReachableMethods( ReachableMethods rm ) {
reachableMethods = rm;
}
public boolean hasReachableMethods() {
return reachableMethods != null;
}
public void releaseReachableMethods() {
reachableMethods = null;
}
public boolean getPhantomRefs()
{
//if( !Options.v().allow_phantom_refs() ) return false;
//return allowsPhantomRefs;
return Options.v().allow_phantom_refs();
}
public void setPhantomRefs(boolean value)
{
allowsPhantomRefs = value;
}
public boolean allowsPhantomRefs()
{
return getPhantomRefs();
}
public Numberer<Kind> kindNumberer() { return kindNumberer; }
public ArrayNumberer<Type> getTypeNumberer() { return typeNumberer; }
public ArrayNumberer<SootMethod> getMethodNumberer() { return methodNumberer; }
public Numberer<Context> getContextNumberer() { return contextNumberer; }
public Numberer<Unit> getUnitNumberer() { return unitNumberer; }
public Numberer<SparkField> getFieldNumberer() { return fieldNumberer; }
public ArrayNumberer<SootClass> getClassNumberer() { return classNumberer; }
public StringNumberer getSubSigNumberer() { return subSigNumberer; }
public ArrayNumberer<Local> getLocalNumberer() { return localNumberer; }
public void setContextNumberer( Numberer<Context> n ) {
if( contextNumberer != null )
throw new RuntimeException(
"Attempt to set context numberer when it is already set." );
contextNumberer = n;
}
/**
* Returns the {@link ThrowAnalysis} to be used by default when
* constructing CFGs which include exceptional control flow.
*
* @return the default {@link ThrowAnalysis}
*/
public ThrowAnalysis getDefaultThrowAnalysis()
{
if( defaultThrowAnalysis == null ) {
int optionsThrowAnalysis = Options.v().throw_analysis();
switch (optionsThrowAnalysis) {
case Options.throw_analysis_pedantic:
defaultThrowAnalysis = PedanticThrowAnalysis.v();
break;
case Options.throw_analysis_unit:
defaultThrowAnalysis = UnitThrowAnalysis.v();
break;
default:
throw new IllegalStateException("Options.v().throw_analysi() == " +
Options.v().throw_analysis());
}
}
return defaultThrowAnalysis;
}
/**
* Sets the {@link ThrowAnalysis} to be used by default when
* constructing CFGs which include exceptional control flow.
*
* @param ta the default {@link ThrowAnalysis}.
*/
public void setDefaultThrowAnalysis(ThrowAnalysis ta)
{
defaultThrowAnalysis = ta;
}
private void setReservedNames()
{
Set<String> rn = getReservedNames();
rn.add("newarray");
rn.add("newmultiarray");
rn.add("nop");
rn.add("ret");
rn.add("specialinvoke");
rn.add("staticinvoke");
rn.add("tableswitch");
rn.add("virtualinvoke");
rn.add("null_type");
rn.add("unknown");
rn.add("cmp");
rn.add("cmpg");
rn.add("cmpl");
rn.add("entermonitor");
rn.add("exitmonitor");
rn.add("interfaceinvoke");
rn.add("lengthof");
rn.add("lookupswitch");
rn.add("neg");
rn.add("if");
rn.add("abstract");
rn.add("annotation");
rn.add("boolean");
rn.add("break");
rn.add("byte");
rn.add("case");
rn.add("catch");
rn.add("char");
rn.add("class");
rn.add("enum");
rn.add("final");
rn.add("native");
rn.add("public");
rn.add("protected");
rn.add("private");
rn.add("static");
rn.add("synchronized");
rn.add("transient");
rn.add("volatile");
rn.add("interface");
rn.add("void");
rn.add("short");
rn.add("int");
rn.add("long");
rn.add("float");
rn.add("double");
rn.add("extends");
rn.add("implements");
rn.add("breakpoint");
rn.add("default");
rn.add("goto");
rn.add("instanceof");
rn.add("new");
rn.add("return");
rn.add("throw");
rn.add("throws");
rn.add("null");
rn.add("from");
rn.add("to");
rn.add("with");
}
private final Set<String>[] basicclasses=new Set[4];
private void addSootBasicClasses() {
basicclasses[SootClass.HIERARCHY] = new HashSet<String>();
basicclasses[SootClass.SIGNATURES] = new HashSet<String>();
basicclasses[SootClass.BODIES] = new HashSet<String>();
addBasicClass("java.lang.Object");
addBasicClass("java.lang.Class", SootClass.SIGNATURES);
addBasicClass("java.lang.Void", SootClass.SIGNATURES);
addBasicClass("java.lang.Boolean", SootClass.SIGNATURES);
addBasicClass("java.lang.Byte", SootClass.SIGNATURES);
addBasicClass("java.lang.Character", SootClass.SIGNATURES);
addBasicClass("java.lang.Short", SootClass.SIGNATURES);
addBasicClass("java.lang.Integer", SootClass.SIGNATURES);
addBasicClass("java.lang.Long", SootClass.SIGNATURES);
addBasicClass("java.lang.Float", SootClass.SIGNATURES);
addBasicClass("java.lang.Double", SootClass.SIGNATURES);
addBasicClass("java.lang.String");
addBasicClass("java.lang.StringBuffer", SootClass.SIGNATURES);
addBasicClass("java.lang.Error");
addBasicClass("java.lang.AssertionError", SootClass.SIGNATURES);
addBasicClass("java.lang.Throwable", SootClass.SIGNATURES);
addBasicClass("java.lang.NoClassDefFoundError", SootClass.SIGNATURES);
addBasicClass("java.lang.ExceptionInInitializerError");
addBasicClass("java.lang.RuntimeException");
addBasicClass("java.lang.ClassNotFoundException");
addBasicClass("java.lang.ArithmeticException");
addBasicClass("java.lang.ArrayStoreException");
addBasicClass("java.lang.ClassCastException");
addBasicClass("java.lang.IllegalMonitorStateException");
addBasicClass("java.lang.IndexOutOfBoundsException");
addBasicClass("java.lang.ArrayIndexOutOfBoundsException");
addBasicClass("java.lang.NegativeArraySizeException");
addBasicClass("java.lang.NullPointerException", SootClass.SIGNATURES);
addBasicClass("java.lang.InstantiationError");
addBasicClass("java.lang.InternalError");
addBasicClass("java.lang.OutOfMemoryError");
addBasicClass("java.lang.StackOverflowError");
addBasicClass("java.lang.UnknownError");
addBasicClass("java.lang.ThreadDeath");
addBasicClass("java.lang.ClassCircularityError");
addBasicClass("java.lang.ClassFormatError");
addBasicClass("java.lang.IllegalAccessError");
addBasicClass("java.lang.IncompatibleClassChangeError");
addBasicClass("java.lang.LinkageError");
addBasicClass("java.lang.VerifyError");
addBasicClass("java.lang.NoSuchFieldError");
addBasicClass("java.lang.AbstractMethodError");
addBasicClass("java.lang.NoSuchMethodError");
addBasicClass("java.lang.UnsatisfiedLinkError");
addBasicClass("java.lang.Thread");
addBasicClass("java.lang.Runnable");
addBasicClass("java.lang.Cloneable");
addBasicClass("java.io.Serializable");
addBasicClass("java.lang.ref.Finalizer");
addBasicClass("java.lang.invoke.LambdaMetafactory");
}
public void addBasicClass(String name) {
addBasicClass(name, SootClass.HIERARCHY);
}
public void addBasicClass(String name, int level) {
basicclasses[level].add(name);
}
/** Load just the set of basic classes soot needs, ignoring those
* specified on the command-line. You don't need to use both this and
* loadNecessaryClasses, though it will only waste time.
*/
public void loadBasicClasses() {
addReflectionTraceClasses();
for(int i=SootClass.BODIES;i>=SootClass.HIERARCHY;i--) {
for(String name: basicclasses[i]){
tryLoadClass(name,i);
}
}
}
public Set<String> getBasicClasses() {
Set<String> all = new HashSet<String>();
for(int i=0;i<basicclasses.length;i++) {
Set<String> classes = basicclasses[i];
if(classes!=null)
all.addAll(classes);
}
return all;
}
private void addReflectionTraceClasses() {
CGOptions options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
String log = options.reflection_log();
Set<String> classNames = new HashSet<String>();
if(log!=null && log.length()>0) {
BufferedReader reader = null;
String line="";
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(log)));
while((line=reader.readLine())!=null) {
if(line.length()==0) continue;
String[] portions = line.split(";",-1);
String kind = portions[0];
String target = portions[1];
String source = portions[2];
String sourceClassName = source.substring(0,source.lastIndexOf("."));
classNames.add(sourceClassName);
if(kind.equals("Class.forName")) {
classNames.add(target);
} else if(kind.equals("Class.newInstance")) {
classNames.add(target);
} else if(kind.equals("Method.invoke") || kind.equals("Constructor.newInstance")) {
classNames.add(signatureToClass(target));
} else if(kind.equals("Field.set*") || kind.equals("Field.get*")) {
classNames.add(signatureToClass(target));
} else throw new RuntimeException("Unknown entry kind: "+kind);
}
} catch (Exception e) {
throw new RuntimeException("Line: '"+line+"'", e);
}
finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
for (String c : classNames) {
addBasicClass(c, SootClass.BODIES);
}
}
private List<SootClass> dynamicClasses = null;
public Collection<SootClass> dynamicClasses() {
if(dynamicClasses==null) {
throw new IllegalStateException("Have to call loadDynamicClasses() first!");
}
return dynamicClasses;
}
private void loadNecessaryClass(String name) {
SootClass c;
c = loadClassAndSupport(name);
c.setApplicationClass();
}
/** Load the set of classes that soot needs, including those specified on the
* command-line. This is the standard way of initialising the list of
* classes soot should use.
*/
public void loadNecessaryClasses() {
loadBasicClasses();
for (String name : Options.v().classes()) {
loadNecessaryClass(name);
}
loadDynamicClasses();
if(Options.v().oaat()) {
if(Options.v().process_dir().isEmpty()) {
throw new IllegalArgumentException("If switch -oaat is used, then also -process-dir must be given.");
}
} else {
for( final String path : Options.v().process_dir() ) {
for (String cl : SourceLocator.v().getClassesUnder(path)) {
SootClass theClass = loadClassAndSupport(cl);
theClass.setApplicationClass();
}
}
}
prepareClasses();
setDoneResolving();
}
public void loadDynamicClasses() {
dynamicClasses = new ArrayList<SootClass>();
HashSet<String> dynClasses = new HashSet<String>();
dynClasses.addAll(Options.v().dynamic_class());
for( Iterator<String> pathIt = Options.v().dynamic_dir().iterator(); pathIt.hasNext(); ) {
final String path = pathIt.next();
dynClasses.addAll(SourceLocator.v().getClassesUnder(path));
}
for( Iterator<String> pkgIt = Options.v().dynamic_package().iterator(); pkgIt.hasNext(); ) {
final String pkg = pkgIt.next();
dynClasses.addAll(SourceLocator.v().classesInDynamicPackage(pkg));
}
for (String className : dynClasses) {
dynamicClasses.add( loadClassAndSupport(className) );
}
//remove non-concrete classes that may accidentally have been loaded
for (Iterator<SootClass> iterator = dynamicClasses.iterator(); iterator.hasNext();) {
SootClass c = iterator.next();
if(!c.isConcrete()) {
if(Options.v().verbose()) {
G.v().out.println("Warning: dynamic class "+c.getName()+" is abstract or an interface, and it will not be considered.");
}
iterator.remove();
}
}
}
/* Generate classes to process, adding or removing package marked by
* command line options.
*/
private void prepareClasses() {
// Remove/add all classes from packageInclusionMask as per -i option
Chain<SootClass> processedClasses = new HashChain<SootClass>();
while(true) {
Chain<SootClass> unprocessedClasses = new HashChain<SootClass>(getClasses());
unprocessedClasses.removeAll(processedClasses);
if( unprocessedClasses.isEmpty() ) break;
processedClasses.addAll(unprocessedClasses);
for (SootClass s : unprocessedClasses) {
if( s.isPhantom() ) continue;
if(Options.v().app()) {
s.setApplicationClass();
}
if (Options.v().classes().contains(s.getName())) {
s.setApplicationClass();
continue;
}
if(s.isApplicationClass() && isExcluded(s)){
s.setLibraryClass();
}
if(isIncluded(s)){
s.setApplicationClass();
}
if(s.isApplicationClass()) {
// make sure we have the support
loadClassAndSupport(s.getName());
}
}
}
}
public boolean isExcluded(SootClass sc){
String name = sc.getName();
for (String pkg : excludedPackages) {
if(name.equals(pkg) || ((pkg.endsWith(".*") || pkg.endsWith("$*")) && name.startsWith(pkg.substring(0, pkg.length() - 1)))){
return !isIncluded(sc);
}
}
return false;
}
public boolean isIncluded(SootClass sc){
String name = sc.getName();
for (String inc : (List<String>) Options.v().include()) {
if (name.equals(inc) || ((inc.endsWith(".*") || inc.endsWith("$*")) && name.startsWith(inc.substring(0, inc.length() - 1)))) {
return true;
}
}
return false;
}
List<String> pkgList;
public void setPkgList(List<String> list){
pkgList = list;
}
public List<String> getPkgList(){
return pkgList;
}
/** Create an unresolved reference to a method. */
public SootMethodRef makeMethodRef(
SootClass declaringClass,
String name,
List<Type> parameterTypes,
Type returnType,
boolean isStatic ) {
return new SootMethodRefImpl(declaringClass, name, parameterTypes,
returnType, isStatic);
}
/** Create an unresolved reference to a constructor. */
public SootMethodRef makeConstructorRef(
SootClass declaringClass,
List<Type> parameterTypes) {
return makeMethodRef(declaringClass, SootMethod.constructorName,
parameterTypes, VoidType.v(), false );
}
/** Create an unresolved reference to a field. */
public SootFieldRef makeFieldRef(
SootClass declaringClass,
String name,
Type type,
boolean isStatic) {
return new AbstractSootFieldRef(declaringClass, name, type, isStatic);
}
/** Returns the list of SootClasses that have been resolved at least to
* the level specified. */
public List<SootClass> getClasses(int desiredLevel) {
List<SootClass> ret = new ArrayList<SootClass>();
for( Iterator<SootClass> clIt = getClasses().iterator(); clIt.hasNext(); ) {
final SootClass cl = clIt.next();
if( cl.resolvingLevel() >= desiredLevel ) ret.add(cl);
}
return ret;
}
private boolean doneResolving = false;
private boolean incrementalBuild;
protected LinkedList<String> excludedPackages;
public boolean doneResolving() { return doneResolving; }
public void setDoneResolving() { doneResolving = true; }
public void setMainClassFromOptions() {
if(mainClass != null) return;
if( Options.v().main_class() != null
&& Options.v().main_class().length() > 0 ) {
setMainClass(getSootClass(Options.v().main_class()));
} else {
// try to infer a main class from the command line if none is given
for (Iterator<String> classIter = Options.v().classes().iterator(); classIter.hasNext();) {
SootClass c = getSootClass(classIter.next());
if (c.declaresMethod ("main", Collections.<Type>singletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v()))
{
G.v().out.println("No main class given. Inferred '"+c.getName()+"' as main class.");
setMainClass(c);
return;
}
}
// try to infer a main class from the usual classpath if none is given
for (Iterator<SootClass> classIter = getApplicationClasses().iterator(); classIter.hasNext();) {
SootClass c = classIter.next();
if (c.declaresMethod ("main", Collections.<Type>singletonList( ArrayType.v(RefType.v("java.lang.String"), 1) ), VoidType.v()))
{
G.v().out.println("No main class given. Inferred '"+c.getName()+"' as main class.");
setMainClass(c);
return;
}
}
}
}
/**
* This method returns true when in incremental build mode.
* Other classes can query this flag and change the way in which they use the Scene,
* depending on the flag's value.
*/
public boolean isIncrementalBuild() {
return incrementalBuild;
}
public void initiateIncrementalBuild() {
this.incrementalBuild = true;
}
public void incrementalBuildFinished() {
this.incrementalBuild = false;
}
/*
* Forces Soot to resolve the class with the given name to the given level,
* even if resolving has actually already finished.
*/
public SootClass forceResolve(String className, int level) {
boolean tmp = doneResolving;
doneResolving = false;
SootClass c;
try {
c = SootResolver.v().resolveClass(className, level);
} finally {
doneResolving = tmp;
}
return c;
}
}
| fixed an NPE
| src/soot/Scene.java | fixed an NPE |
|
Java | lgpl-2.1 | 831b93058cb550550965a97a9e7e50dea8c1910a | 0 | esig/dss,esig/dss | package eu.europa.esig.dss.cades.signature;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
import org.bouncycastle.asn1.cms.OtherRevocationInfoFormat;
import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
import org.bouncycastle.cert.X509CRLHolder;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.SignerInfoGeneratorBuilder;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.operator.DigestCalculatorProvider;
import org.bouncycastle.util.CollectionStore;
import org.bouncycastle.util.Encodable;
import org.bouncycastle.util.Store;
import eu.europa.esig.dss.cades.CMSUtils;
import eu.europa.esig.dss.cades.validation.CAdESSignature;
import eu.europa.esig.dss.cades.validation.CMSDocumentValidator;
import eu.europa.esig.dss.enumerations.SignatureAlgorithm;
import eu.europa.esig.dss.model.DSSDocument;
import eu.europa.esig.dss.model.DSSException;
import eu.europa.esig.dss.model.InMemoryDocument;
import eu.europa.esig.dss.model.SignatureValue;
import eu.europa.esig.dss.model.x509.CertificateToken;
import eu.europa.esig.dss.signature.BaselineBCertificateSelector;
import eu.europa.esig.dss.spi.DSSASN1Utils;
import eu.europa.esig.dss.utils.Utils;
import eu.europa.esig.dss.validation.AdvancedSignature;
import eu.europa.esig.dss.validation.CertificateVerifier;
import eu.europa.esig.dss.validation.ManifestFile;
public class CAdESCounterSignatureBuilder {
private final CertificateVerifier certificateVerifier;
/** Represents a signature detached contents */
private List<DSSDocument> detachedContents;
/** A signature signed manifest. Used for ASiC */
private ManifestFile manifestFile;
public CAdESCounterSignatureBuilder(CertificateVerifier certificateVerifier) {
this.certificateVerifier = certificateVerifier;
}
/**
* Sets detached contents
*
* @param detachedContents a list of {@link DSSDocument}
*/
public void setDetachedContents(List<DSSDocument> detachedContents) {
this.detachedContents = detachedContents;
}
/**
* Sets a signed manifest file
* NOTE: ASiC only
*
* @param manifestFile {@link ManifestFile}
*/
public void setManifestFile(ManifestFile manifestFile) {
this.manifestFile = manifestFile;
}
/**
* Adds a counter signature the provided CMSSignedData
*
* @param originalCMSSignedData {@link CMSSignedData} to add a counter signature into
* @param parameters {@link CAdESCounterSignatureParameters}
* @param signatureValue {@link SignatureValue}
* @return {@link CMSSignedDocument} with an added counter signature
*/
public CMSSignedDocument addCounterSignature(CMSSignedData originalCMSSignedData, CAdESCounterSignatureParameters parameters,
SignatureValue signatureValue) {
final List<SignerInformation> updatedSignerInfo = getUpdatedSignerInformations(originalCMSSignedData, originalCMSSignedData.getSignerInfos(),
parameters, signatureValue, null);
if (Utils.isCollectionNotEmpty(updatedSignerInfo)) {
CMSSignedData updatedCMSSignedData = CMSSignedData.replaceSigners(originalCMSSignedData, new SignerInformationStore(updatedSignerInfo));
updatedCMSSignedData = addNewCertificates(updatedCMSSignedData, originalCMSSignedData, parameters);
return new CMSSignedDocument(updatedCMSSignedData);
} else {
throw new DSSException("No updated signed info");
}
}
private List<SignerInformation> getUpdatedSignerInformations(CMSSignedData originalCMSSignedData, SignerInformationStore signerInformationStore,
CAdESCounterSignatureParameters parameters, SignatureValue signatureValue, CAdESSignature masterSignature) {
List<SignerInformation> result = new LinkedList<>();
for (SignerInformation signerInformation : signerInformationStore) {
CAdESSignature cades = new CAdESSignature(originalCMSSignedData, signerInformation);
cades.setMasterSignature(masterSignature);
cades.setDetachedContents(parameters.getDetachedContents());
cades.setManifestFile(manifestFile);
if (Utils.areStringsEqual(cades.getId(), parameters.getSignatureIdToCounterSign())) {
if (masterSignature != null) {
throw new UnsupportedOperationException("Cannot recursively add a counter-signature");
}
assertCounterSignaturePossible(signerInformation);
SignerInformationStore counterSignatureSignerInfoStore = generateCounterSignature(originalCMSSignedData, signerInformation, parameters,
signatureValue);
result.add(SignerInformation.addCounterSigners(signerInformation, counterSignatureSignerInfoStore));
} else if (signerInformation.getCounterSignatures().size() > 0) {
List<SignerInformation> updatedSignerInformations = getUpdatedSignerInformations(originalCMSSignedData,
signerInformation.getCounterSignatures(), parameters, signatureValue, cades);
result.add(SignerInformation.addCounterSigners(signerInformation, new SignerInformationStore(updatedSignerInformations)));
} else {
result.add(signerInformation);
}
}
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private CMSSignedData addNewCertificates(CMSSignedData updatedCMSSignedData, CMSSignedData originalCMSSignedData,
CAdESCounterSignatureParameters parameters) {
final List<CertificateToken> certificateTokens = new LinkedList<>();
Store<X509CertificateHolder> certificatesStore = originalCMSSignedData.getCertificates();
final Collection<X509CertificateHolder> certificatesMatches = certificatesStore.getMatches(null);
for (final X509CertificateHolder certificatesMatch : certificatesMatches) {
final CertificateToken token = DSSASN1Utils.getCertificate(certificatesMatch);
if (!certificateTokens.contains(token)) {
certificateTokens.add(token);
}
}
BaselineBCertificateSelector certificateSelectors = new BaselineBCertificateSelector(certificateVerifier, parameters);
List<CertificateToken> newCertificates = certificateSelectors.getCertificates();
for (CertificateToken certificateToken : newCertificates) {
if (!certificateTokens.contains(certificateToken)) {
certificateTokens.add(certificateToken);
}
}
final Collection<X509Certificate> certs = new ArrayList<>();
for (final CertificateToken certificateInChain : certificateTokens) {
certs.add(certificateInChain.getCertificate());
}
Store<X509CRLHolder> crlsStore = originalCMSSignedData.getCRLs();
final Collection<Encodable> crls = new HashSet<>(crlsStore.getMatches(null));
Store ocspBasicStore = originalCMSSignedData.getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
for (Object ocsp : ocspBasicStore.getMatches(null)) {
crls.add(new OtherRevocationInfoFormat(OCSPObjectIdentifiers.id_pkix_ocsp_basic, (ASN1Encodable) ocsp));
}
Store ocspResponseStore = originalCMSSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);
for (Object ocsp : ocspResponseStore.getMatches(null)) {
crls.add(new OtherRevocationInfoFormat(CMSObjectIdentifiers.id_ri_ocsp_response, (ASN1Encodable) ocsp));
}
try {
JcaCertStore jcaCertStore = new JcaCertStore(certs);
return CMSSignedData.replaceCertificatesAndCRLs(updatedCMSSignedData, jcaCertStore, originalCMSSignedData.getAttributeCertificates(),
new CollectionStore(crls));
} catch (Exception e) {
throw new DSSException("Unable to create the JcaCertStore", e);
}
}
private SignerInformationStore generateCounterSignature(CMSSignedData originalCMSSignedData, SignerInformation signerInformation,
CAdESCounterSignatureParameters parameters, SignatureValue signatureValue) {
CMSSignedDataBuilder builder = new CMSSignedDataBuilder(certificateVerifier);
SignatureAlgorithm signatureAlgorithm = parameters.getSignatureAlgorithm();
final CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId(), signatureValue.getValue());
final DigestCalculatorProvider dcp = CMSUtils.getDigestCalculatorProvider(new InMemoryDocument(signerInformation.getSignature()),
parameters.getReferenceDigestAlgorithm());
SignerInfoGeneratorBuilder signerInformationGeneratorBuilder = builder.getSignerInfoGeneratorBuilder(dcp, parameters, false);
CMSSignedDataGenerator cmsSignedDataGenerator = builder.createCMSSignedDataGenerator(parameters, customContentSigner, signerInformationGeneratorBuilder,
null);
return CMSUtils.generateCounterSigners(cmsSignedDataGenerator, signerInformation);
}
/**
* Returns a {@code SignerInformation} to be counter signed
*
* @param signatureDocument {@link DSSDocument} to find the related signature
* @param parameters {@link CAdESCounterSignatureParameters}
* @return {@link SignerInformation}
*/
public SignerInformation getSignerInformationToBeCounterSigned(DSSDocument signatureDocument, CAdESCounterSignatureParameters parameters) {
CAdESSignature cadesSignature = getSignatureById(signatureDocument, parameters);
if (cadesSignature == null) {
throw new DSSException(String.format("CAdESSignature not found with the given dss id '%s'", parameters.getSignatureIdToCounterSign()));
}
return cadesSignature.getSignerInformation();
}
private CAdESSignature getSignatureById(DSSDocument signatureDocument, CAdESCounterSignatureParameters parameters) {
CMSDocumentValidator validator = new CMSDocumentValidator(signatureDocument);
validator.setDetachedContents(parameters.getDetachedContents());
validator.setManifestFile(manifestFile);
List<AdvancedSignature> signatures = validator.getSignatures();
return findSignatureRecursive(signatures, parameters.getSignatureIdToCounterSign());
}
private CAdESSignature findSignatureRecursive(List<AdvancedSignature> signatures, String signatureId) {
if (Utils.isCollectionNotEmpty(signatures)) {
for (AdvancedSignature advancedSignature : signatures) {
if (signatureId.equals(advancedSignature.getId())) {
CAdESSignature cades = (CAdESSignature) advancedSignature;
assertCounterSignaturePossible(cades.getSignerInformation());
return cades;
}
CAdESSignature counterSignatureById = findSignatureRecursive(advancedSignature.getCounterSignatures(), signatureId);
if (counterSignatureById != null) {
// TODO : add a nested counter signature support + check if a master signature is not timestamped
throw new UnsupportedOperationException("Nested counter signatures are not supported with CAdES!");
}
return counterSignatureById;
}
}
return null;
}
private void assertCounterSignaturePossible(SignerInformation signerInformation) {
if (CMSUtils.containsATSTv2(signerInformation)) {
throw new DSSException("Cannot add a counter signature to a CAdES containing an archiveTimestampV2");
}
}
}
| dss-cades/src/main/java/eu/europa/esig/dss/cades/signature/CAdESCounterSignatureBuilder.java | package eu.europa.esig.dss.cades.signature;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
import org.bouncycastle.asn1.cms.OtherRevocationInfoFormat;
import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
import org.bouncycastle.cert.X509CRLHolder;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.SignerInfoGeneratorBuilder;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.operator.DigestCalculatorProvider;
import org.bouncycastle.util.CollectionStore;
import org.bouncycastle.util.Encodable;
import org.bouncycastle.util.Store;
import eu.europa.esig.dss.cades.CMSUtils;
import eu.europa.esig.dss.cades.validation.CAdESSignature;
import eu.europa.esig.dss.cades.validation.CMSDocumentValidator;
import eu.europa.esig.dss.enumerations.SignatureAlgorithm;
import eu.europa.esig.dss.model.DSSDocument;
import eu.europa.esig.dss.model.DSSException;
import eu.europa.esig.dss.model.InMemoryDocument;
import eu.europa.esig.dss.model.SignatureValue;
import eu.europa.esig.dss.model.x509.CertificateToken;
import eu.europa.esig.dss.signature.BaselineBCertificateSelector;
import eu.europa.esig.dss.spi.DSSASN1Utils;
import eu.europa.esig.dss.utils.Utils;
import eu.europa.esig.dss.validation.AdvancedSignature;
import eu.europa.esig.dss.validation.CertificateVerifier;
import eu.europa.esig.dss.validation.ManifestFile;
public class CAdESCounterSignatureBuilder {
private final CertificateVerifier certificateVerifier;
/** Represents a signature detached contents */
private List<DSSDocument> detachedContents;
/** A signature signed manifest. Used for ASiC */
private ManifestFile manifestFile;
public CAdESCounterSignatureBuilder(CertificateVerifier certificateVerifier) {
this.certificateVerifier = certificateVerifier;
}
/**
* Sets detached contents
*
* @param detachedContents a list of {@link DSSDocument}
*/
public void setDetachedContents(List<DSSDocument> detachedContents) {
this.detachedContents = detachedContents;
}
/**
* Sets a signed manifest file
* NOTE: ASiC only
*
* @param manifestFile {@link ManifestFile}
*/
public void setManifestFile(ManifestFile manifestFile) {
this.manifestFile = manifestFile;
}
/**
* Adds a counter signature the provided CMSSignedData
*
* @param originalCMSSignedData {@link CMSSignedData} to add a counter signature into
* @param parameters {@link CAdESCounterSignatureParameters}
* @param signatureValue {@link SignatureValue}
* @return {@link CMSSignedDocument} with an added counter signature
*/
public CMSSignedDocument addCounterSignature(CMSSignedData originalCMSSignedData, CAdESCounterSignatureParameters parameters,
SignatureValue signatureValue) {
final List<SignerInformation> updatedSignerInfo = getUpdatedSignerInformations(originalCMSSignedData, originalCMSSignedData.getSignerInfos(),
parameters, signatureValue, null);
if (Utils.isCollectionNotEmpty(updatedSignerInfo)) {
CMSSignedData updatedCMSSignedData = CMSSignedData.replaceSigners(originalCMSSignedData, new SignerInformationStore(updatedSignerInfo));
updatedCMSSignedData = addNewCertificates(updatedCMSSignedData, originalCMSSignedData, parameters);
return new CMSSignedDocument(updatedCMSSignedData);
} else {
throw new DSSException("No updated signed info");
}
}
private List<SignerInformation> getUpdatedSignerInformations(CMSSignedData originalCMSSignedData, SignerInformationStore signerInformationStore,
CAdESCounterSignatureParameters parameters, SignatureValue signatureValue, CAdESSignature masterSignature) {
List<SignerInformation> result = new LinkedList<>();
for (SignerInformation signerInformation : signerInformationStore) {
CAdESSignature cades = new CAdESSignature(originalCMSSignedData, signerInformation);
cades.setMasterSignature(masterSignature);
cades.setDetachedContents(parameters.getDetachedContents());
cades.setManifestFile(manifestFile);
if (Utils.areStringsEqual(cades.getId(), parameters.getSignatureIdToCounterSign())) {
if (masterSignature != null) {
throw new UnsupportedOperationException("Cannot recursively add a counter-signature");
}
assertCounterSignaturePossible(signerInformation);
SignerInformationStore counterSignatureSignerInfoStore = generateCounterSignature(originalCMSSignedData, signerInformation, parameters,
signatureValue);
result.add(SignerInformation.addCounterSigners(signerInformation, counterSignatureSignerInfoStore));
} else if (signerInformation.getCounterSignatures().size() > 0) {
List<SignerInformation> updatedSignerInformations = getUpdatedSignerInformations(originalCMSSignedData,
signerInformation.getCounterSignatures(), parameters, signatureValue, cades);
result.add(SignerInformation.addCounterSigners(signerInformation, new SignerInformationStore(updatedSignerInformations)));
} else {
result.add(signerInformation);
}
}
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private CMSSignedData addNewCertificates(CMSSignedData updatedCMSSignedData, CMSSignedData originalCMSSignedData,
CAdESCounterSignatureParameters parameters) {
final List<CertificateToken> certificateTokens = new LinkedList<>();
Store<X509CertificateHolder> certificatesStore = originalCMSSignedData.getCertificates();
final Collection<X509CertificateHolder> certificatesMatches = certificatesStore.getMatches(null);
for (final X509CertificateHolder certificatesMatch : certificatesMatches) {
final CertificateToken token = DSSASN1Utils.getCertificate(certificatesMatch);
if (!certificateTokens.contains(token)) {
certificateTokens.add(token);
}
}
BaselineBCertificateSelector certificateSelectors = new BaselineBCertificateSelector(certificateVerifier, parameters);
List<CertificateToken> newCertificates = certificateSelectors.getCertificates();
for (CertificateToken certificateToken : newCertificates) {
if (!certificateTokens.contains(certificateToken)) {
certificateTokens.add(certificateToken);
}
}
final Collection<X509Certificate> certs = new ArrayList<>();
for (final CertificateToken certificateInChain : certificateTokens) {
certs.add(certificateInChain.getCertificate());
}
Store<X509CRLHolder> crlsStore = originalCMSSignedData.getCRLs();
final Collection<Encodable> crls = new HashSet<>(crlsStore.getMatches(null));
Store ocspBasicStore = originalCMSSignedData.getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
for (Object ocsp : ocspBasicStore.getMatches(null)) {
crls.add(new OtherRevocationInfoFormat(OCSPObjectIdentifiers.id_pkix_ocsp_basic, (ASN1Encodable) ocsp));
}
Store ocspResponseStore = originalCMSSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);
for (Object ocsp : ocspResponseStore.getMatches(null)) {
crls.add(new OtherRevocationInfoFormat(CMSObjectIdentifiers.id_ri_ocsp_response, (ASN1Encodable) ocsp));
}
try {
JcaCertStore jcaCertStore = new JcaCertStore(certs);
return CMSSignedData.replaceCertificatesAndCRLs(updatedCMSSignedData, jcaCertStore, originalCMSSignedData.getAttributeCertificates(),
new CollectionStore(crls));
} catch (Exception e) {
throw new DSSException("Unable to create the JcaCertStore", e);
}
}
private SignerInformationStore generateCounterSignature(CMSSignedData originalCMSSignedData, SignerInformation signerInformation,
CAdESCounterSignatureParameters parameters, SignatureValue signatureValue) {
CMSSignedDataBuilder builder = new CMSSignedDataBuilder(certificateVerifier);
SignatureAlgorithm signatureAlgorithm = signatureValue.getAlgorithm();
final CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId(), signatureValue.getValue());
final DigestCalculatorProvider dcp = CMSUtils.getDigestCalculatorProvider(new InMemoryDocument(signerInformation.getSignature()),
parameters.getReferenceDigestAlgorithm());
SignerInfoGeneratorBuilder signerInformationGeneratorBuilder = builder.getSignerInfoGeneratorBuilder(dcp, parameters, false);
CMSSignedDataGenerator cmsSignedDataGenerator = builder.createCMSSignedDataGenerator(parameters, customContentSigner, signerInformationGeneratorBuilder,
null);
return CMSUtils.generateCounterSigners(cmsSignedDataGenerator, signerInformation);
}
/**
* Returns a {@code SignerInformation} to be counter signed
*
* @param signatureDocument {@link DSSDocument} to find the related signature
* @param parameters {@link CAdESCounterSignatureParameters}
* @return {@link SignerInformation}
*/
public SignerInformation getSignerInformationToBeCounterSigned(DSSDocument signatureDocument, CAdESCounterSignatureParameters parameters) {
CAdESSignature cadesSignature = getSignatureById(signatureDocument, parameters);
if (cadesSignature == null) {
throw new DSSException(String.format("CAdESSignature not found with the given dss id '%s'", parameters.getSignatureIdToCounterSign()));
}
return cadesSignature.getSignerInformation();
}
private CAdESSignature getSignatureById(DSSDocument signatureDocument, CAdESCounterSignatureParameters parameters) {
CMSDocumentValidator validator = new CMSDocumentValidator(signatureDocument);
validator.setDetachedContents(parameters.getDetachedContents());
validator.setManifestFile(manifestFile);
List<AdvancedSignature> signatures = validator.getSignatures();
return findSignatureRecursive(signatures, parameters.getSignatureIdToCounterSign());
}
private CAdESSignature findSignatureRecursive(List<AdvancedSignature> signatures, String signatureId) {
if (Utils.isCollectionNotEmpty(signatures)) {
for (AdvancedSignature advancedSignature : signatures) {
if (signatureId.equals(advancedSignature.getId())) {
CAdESSignature cades = (CAdESSignature) advancedSignature;
assertCounterSignaturePossible(cades.getSignerInformation());
return cades;
}
CAdESSignature counterSignatureById = findSignatureRecursive(advancedSignature.getCounterSignatures(), signatureId);
if (counterSignatureById != null) {
// TODO : add a nested counter signature support + check if a master signature is not timestamped
throw new UnsupportedOperationException("Nested counter signatures are not supported with CAdES!");
}
return counterSignatureById;
}
}
return null;
}
private void assertCounterSignaturePossible(SignerInformation signerInformation) {
if (CMSUtils.containsATSTv2(signerInformation)) {
throw new DSSException("Cannot add a counter signature to a CAdES containing an archiveTimestampV2");
}
}
}
| use SignatureAlgorithm retrieved from parameters
| dss-cades/src/main/java/eu/europa/esig/dss/cades/signature/CAdESCounterSignatureBuilder.java | use SignatureAlgorithm retrieved from parameters |
|
Java | apache-2.0 | 0cd5aaf4d2019db17d397587f694ae91a43d4efd | 0 | treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag | package io.digdag.standards.operator;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigException;
import io.digdag.spi.Operator;
import io.digdag.spi.OperatorFactory;
import io.digdag.spi.SecretProvider;
import io.digdag.spi.OperatorContext;
import io.digdag.spi.TaskExecutionException;
import io.digdag.spi.TaskResult;
import io.digdag.spi.TemplateEngine;
import io.digdag.util.BaseOperator;
import org.immutables.value.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import static java.nio.charset.StandardCharsets.UTF_8;
public class MailOperatorFactory
implements OperatorFactory
{
private static Logger logger = LoggerFactory.getLogger(MailOperatorFactory.class);
private final TemplateEngine templateEngine;
private final MailDefaults mailDefaults;
private final Optional<SmtpConfig> systemSmtpConfig;
@Inject
public MailOperatorFactory(TemplateEngine templateEngine, Config systemConfig)
{
this.templateEngine = templateEngine;
this.systemSmtpConfig = systemSmtpConfig(systemConfig);
this.mailDefaults = ImmutableMailDefaults.builder()
.from(systemConfig.getOptional("config.mail.from", String.class))
.subject(systemConfig.getOptional("config.mail.subject", String.class))
.build();
}
public String getType()
{
return "mail";
}
@Override
public Operator newOperator(OperatorContext context)
{
return new MailOperator(context);
}
@Value.Immutable
@Value.Style(visibility = Value.Style.ImplementationVisibility.PACKAGE)
public interface AttachConfig
{
String getPath();
String getContentType();
String getFileName();
}
@Value.Immutable
@Value.Style(visibility = Value.Style.ImplementationVisibility.PACKAGE)
interface SmtpConfig
{
String host();
int port();
boolean startTls();
boolean ssl();
boolean debug();
Optional<String> username();
Optional<String> password();
}
@Value.Immutable
@Value.Style(visibility = Value.Style.ImplementationVisibility.PACKAGE)
interface MailDefaults
{
Optional<String> subject();
Optional<String> from();
}
private class MailOperator
extends BaseOperator
{
public MailOperator(OperatorContext context)
{
super(context);
}
@Override
public TaskResult runTask()
{
SecretProvider secrets = context.getSecrets().getSecrets("mail");
Config params = request.getConfig().mergeDefault(
request.getConfig().getNestedOrGetEmpty("mail"));
String body = workspace.templateCommand(templateEngine, params, "body", UTF_8);
String subject = params.getOptional("subject", String.class).or(mailDefaults.subject()).or(() -> params.get("subject", String.class));
List<String> toList;
try {
toList = params.getList("to", String.class);
}
catch (ConfigException ex) {
toList = ImmutableList.of(params.get("to", String.class));
}
List<String> bccList = params.getListOrEmpty("bcc", String.class);
List<String> ccList = params.getListOrEmpty("cc", String.class);
boolean isHtml = params.get("html", boolean.class, false);
MimeMessage msg = new MimeMessage(createSession(secrets, params));
try {
String from = params.getOptional("from", String.class).or(mailDefaults.from()).or(() -> params.get("from", String.class));
msg.setFrom(newAddress(from));
msg.setSender(newAddress(from));
msg.setRecipients(RecipientType.TO,
toList.stream()
.map(it -> newAddress(it))
.toArray(InternetAddress[]::new));
msg.setRecipients(RecipientType.BCC,
bccList.stream()
.map(it -> newAddress(it))
.toArray(InternetAddress[]::new));
msg.setRecipients(RecipientType.CC,
ccList.stream()
.map(it -> newAddress(it))
.toArray(InternetAddress[]::new));
msg.setSubject(subject, "utf-8");
List<AttachConfig> attachFiles = attachConfigs(params);
if (attachFiles.isEmpty()) {
msg.setText(body, "utf-8", isHtml ? "html" : "plain");
}
else {
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(body, "utf-8", isHtml ? "html" : "plain");
multipart.addBodyPart(textPart);
for (AttachConfig attachFile : attachFiles) {
MimeBodyPart part = new MimeBodyPart();
part.attachFile(workspace.getFile(attachFile.getPath()), attachFile.getContentType(), null);
part.setFileName(attachFile.getFileName());
multipart.addBodyPart(part);
}
msg.setContent(multipart);
}
Transport.send(msg);
}
catch (MessagingException | IOException ex) {
throw new TaskExecutionException(ex);
}
return TaskResult.empty(request);
}
private List<AttachConfig> attachConfigs(Config params)
{
return params.getListOrEmpty("attach_files", Config.class)
.stream()
.map((a) -> {
String path = a.get("path", String.class);
return ImmutableAttachConfig.builder()
.path(path)
.fileName(
a.getOptional("filename", String.class)
.or(path.substring(Math.max(path.lastIndexOf('/'), 0)))
)
.contentType(
a.getOptional("content_type", String.class)
.or("application/octet-stream")
)
.build();
})
.collect(Collectors.toList());
}
private Session createSession(SecretProvider secrets, Config params)
{
// Use only _either_ user supplied smtp configuration _or_ system smtp configuration to avoid leaking credentials
// by e.g. connecting to a user controlled host and handing over user/password in base64 plaintext.
SmtpConfig smtpConfig = userSmtpConfig(secrets, params)
.or(systemSmtpConfig)
.orNull();
if (smtpConfig == null) {
throw new TaskExecutionException("Missing SMTP configuration");
}
Properties props = new Properties();
props.setProperty("mail.smtp.host", smtpConfig.host());
props.setProperty("mail.smtp.port", String.valueOf(smtpConfig.port()));
props.put("mail.smtp.starttls.enable", smtpConfig.startTls());
if (smtpConfig.ssl()) {
props.put("mail.smtp.socketFactory.port", smtpConfig.port());
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
}
props.setProperty("mail.debug", String.valueOf(smtpConfig.debug()));
props.setProperty("mail.smtp.connectiontimeout", "10000");
props.setProperty("mail.smtp.timeout", "60000");
Session session;
Optional<String> username = smtpConfig.username();
if (username.isPresent()) {
props.setProperty("mail.smtp.auth", "true");
String password = smtpConfig.password().or("");
session = Session.getInstance(props,
new Authenticator()
{
@Override
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username.get(), password);
}
});
}
else {
session = Session.getInstance(props);
}
return session;
}
private InternetAddress newAddress(String str)
{
try {
return new InternetAddress(str);
}
catch (AddressException ex) {
throw new ConfigException("Invalid address", ex);
}
}
}
private static Optional<SmtpConfig> systemSmtpConfig(Config systemConfig)
{
Optional<String> host = systemConfig.getOptional("config.mail.host", String.class);
if (!host.isPresent()) {
return Optional.absent();
}
SmtpConfig config = ImmutableSmtpConfig.builder()
.host(host.get())
.port(systemConfig.get("config.mail.port", int.class))
.startTls(systemConfig.get("config.mail.tls", boolean.class, true))
.ssl(systemConfig.get("config.mail.ssl", boolean.class, false))
.debug(systemConfig.get("config.mail.debug", boolean.class, false))
.username(systemConfig.getOptional("config.mail.username", String.class))
.password(systemConfig.getOptional("config.mail.password", String.class))
.build();
return Optional.of(config);
}
private static Optional<SmtpConfig> userSmtpConfig(SecretProvider secrets, Config params)
{
Optional<String> userHost = secrets.getSecretOptional("host").or(params.getOptional("host", String.class));
if (!userHost.isPresent()) {
return Optional.absent();
}
Optional<String> deprecatedPassword = params.getOptional("password", String.class);
if (deprecatedPassword.isPresent()) {
logger.warn("Unsecure 'password' parameter is deprecated.");
}
SmtpConfig config = ImmutableSmtpConfig.builder()
.host(userHost.get())
.port(secrets.getSecretOptional("port").transform(Integer::parseInt).or(params.get("port", int.class)))
.startTls(secrets.getSecretOptional("tls").transform(Boolean::parseBoolean).or(params.get("tls", boolean.class, true)))
.ssl(secrets.getSecretOptional("ssl").transform(Boolean::parseBoolean).or(params.get("ssl", boolean.class, false)))
.debug(params.get("debug", boolean.class, false))
.username(secrets.getSecretOptional("username").or(params.getOptional("username", String.class)))
.password(secrets.getSecretOptional("password"))
.build();
return Optional.of(config);
}
}
| digdag-standards/src/main/java/io/digdag/standards/operator/MailOperatorFactory.java | package io.digdag.standards.operator;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigException;
import io.digdag.spi.Operator;
import io.digdag.spi.OperatorFactory;
import io.digdag.spi.SecretProvider;
import io.digdag.spi.OperatorContext;
import io.digdag.spi.TaskExecutionException;
import io.digdag.spi.TaskResult;
import io.digdag.spi.TemplateEngine;
import io.digdag.util.BaseOperator;
import org.immutables.value.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import static java.nio.charset.StandardCharsets.UTF_8;
public class MailOperatorFactory
implements OperatorFactory
{
private static Logger logger = LoggerFactory.getLogger(MailOperatorFactory.class);
private final TemplateEngine templateEngine;
private final MailDefaults mailDefaults;
private final Optional<SmtpConfig> systemSmtpConfig;
@Inject
public MailOperatorFactory(TemplateEngine templateEngine, Config systemConfig)
{
this.templateEngine = templateEngine;
this.systemSmtpConfig = systemSmtpConfig(systemConfig);
this.mailDefaults = ImmutableMailDefaults.builder()
.from(systemConfig.getOptional("config.mail.from", String.class))
.subject(systemConfig.getOptional("config.mail.subject", String.class))
.build();
}
public String getType()
{
return "mail";
}
@Override
public Operator newOperator(OperatorContext context)
{
return new MailOperator(context);
}
@Value.Immutable
@Value.Style(visibility = Value.Style.ImplementationVisibility.PACKAGE)
public interface AttachConfig
{
String getPath();
String getContentType();
String getFileName();
}
@Value.Immutable
@Value.Style(visibility = Value.Style.ImplementationVisibility.PACKAGE)
interface SmtpConfig
{
String host();
int port();
boolean startTls();
boolean ssl();
boolean debug();
Optional<String> username();
Optional<String> password();
}
@Value.Immutable
@Value.Style(visibility = Value.Style.ImplementationVisibility.PACKAGE)
interface MailDefaults
{
Optional<String> subject();
Optional<String> from();
}
private class MailOperator
extends BaseOperator
{
public MailOperator(OperatorContext context)
{
super(context);
}
@Override
public TaskResult runTask()
{
SecretProvider secrets = context.getSecrets().getSecrets("mail");
Config params = request.getConfig().mergeDefault(
request.getConfig().getNestedOrGetEmpty("mail"));
String body = workspace.templateCommand(templateEngine, params, "body", UTF_8);
String subject = params.getOptional("subject", String.class).or(mailDefaults.subject()).or(() -> params.get("subject", String.class));
List<String> toList;
try {
toList = params.getList("to", String.class);
}
catch (ConfigException ex) {
toList = ImmutableList.of(params.get("to", String.class));
}
boolean isHtml = params.get("html", boolean.class, false);
MimeMessage msg = new MimeMessage(createSession(secrets, params));
try {
String from = params.getOptional("from", String.class).or(mailDefaults.from()).or(() -> params.get("from", String.class));
msg.setFrom(newAddress(from));
msg.setSender(newAddress(from));
msg.setRecipients(RecipientType.TO,
toList.stream()
.map(it -> newAddress(it))
.toArray(InternetAddress[]::new));
msg.setSubject(subject, "utf-8");
List<AttachConfig> attachFiles = attachConfigs(params);
if (attachFiles.isEmpty()) {
msg.setText(body, "utf-8", isHtml ? "html" : "plain");
}
else {
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(body, "utf-8", isHtml ? "html" : "plain");
multipart.addBodyPart(textPart);
for (AttachConfig attachFile : attachFiles) {
MimeBodyPart part = new MimeBodyPart();
part.attachFile(workspace.getFile(attachFile.getPath()), attachFile.getContentType(), null);
part.setFileName(attachFile.getFileName());
multipart.addBodyPart(part);
}
msg.setContent(multipart);
}
Transport.send(msg);
}
catch (MessagingException | IOException ex) {
throw new TaskExecutionException(ex);
}
return TaskResult.empty(request);
}
private List<AttachConfig> attachConfigs(Config params)
{
return params.getListOrEmpty("attach_files", Config.class)
.stream()
.map((a) -> {
String path = a.get("path", String.class);
return ImmutableAttachConfig.builder()
.path(path)
.fileName(
a.getOptional("filename", String.class)
.or(path.substring(Math.max(path.lastIndexOf('/'), 0)))
)
.contentType(
a.getOptional("content_type", String.class)
.or("application/octet-stream")
)
.build();
})
.collect(Collectors.toList());
}
private Session createSession(SecretProvider secrets, Config params)
{
// Use only _either_ user supplied smtp configuration _or_ system smtp configuration to avoid leaking credentials
// by e.g. connecting to a user controlled host and handing over user/password in base64 plaintext.
SmtpConfig smtpConfig = userSmtpConfig(secrets, params)
.or(systemSmtpConfig)
.orNull();
if (smtpConfig == null) {
throw new TaskExecutionException("Missing SMTP configuration");
}
Properties props = new Properties();
props.setProperty("mail.smtp.host", smtpConfig.host());
props.setProperty("mail.smtp.port", String.valueOf(smtpConfig.port()));
props.put("mail.smtp.starttls.enable", smtpConfig.startTls());
if (smtpConfig.ssl()) {
props.put("mail.smtp.socketFactory.port", smtpConfig.port());
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
}
props.setProperty("mail.debug", String.valueOf(smtpConfig.debug()));
props.setProperty("mail.smtp.connectiontimeout", "10000");
props.setProperty("mail.smtp.timeout", "60000");
Session session;
Optional<String> username = smtpConfig.username();
if (username.isPresent()) {
props.setProperty("mail.smtp.auth", "true");
String password = smtpConfig.password().or("");
session = Session.getInstance(props,
new Authenticator()
{
@Override
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username.get(), password);
}
});
}
else {
session = Session.getInstance(props);
}
return session;
}
private InternetAddress newAddress(String str)
{
try {
return new InternetAddress(str);
}
catch (AddressException ex) {
throw new ConfigException("Invalid address", ex);
}
}
}
private static Optional<SmtpConfig> systemSmtpConfig(Config systemConfig)
{
Optional<String> host = systemConfig.getOptional("config.mail.host", String.class);
if (!host.isPresent()) {
return Optional.absent();
}
SmtpConfig config = ImmutableSmtpConfig.builder()
.host(host.get())
.port(systemConfig.get("config.mail.port", int.class))
.startTls(systemConfig.get("config.mail.tls", boolean.class, true))
.ssl(systemConfig.get("config.mail.ssl", boolean.class, false))
.debug(systemConfig.get("config.mail.debug", boolean.class, false))
.username(systemConfig.getOptional("config.mail.username", String.class))
.password(systemConfig.getOptional("config.mail.password", String.class))
.build();
return Optional.of(config);
}
private static Optional<SmtpConfig> userSmtpConfig(SecretProvider secrets, Config params)
{
Optional<String> userHost = secrets.getSecretOptional("host").or(params.getOptional("host", String.class));
if (!userHost.isPresent()) {
return Optional.absent();
}
Optional<String> deprecatedPassword = params.getOptional("password", String.class);
if (deprecatedPassword.isPresent()) {
logger.warn("Unsecure 'password' parameter is deprecated.");
}
SmtpConfig config = ImmutableSmtpConfig.builder()
.host(userHost.get())
.port(secrets.getSecretOptional("port").transform(Integer::parseInt).or(params.get("port", int.class)))
.startTls(secrets.getSecretOptional("tls").transform(Boolean::parseBoolean).or(params.get("tls", boolean.class, true)))
.ssl(secrets.getSecretOptional("ssl").transform(Boolean::parseBoolean).or(params.get("ssl", boolean.class, false)))
.debug(params.get("debug", boolean.class, false))
.username(secrets.getSecretOptional("username").or(params.getOptional("username", String.class)))
.password(secrets.getSecretOptional("password"))
.build();
return Optional.of(config);
}
}
| Add Cc and Bcc address to mail operator.
| digdag-standards/src/main/java/io/digdag/standards/operator/MailOperatorFactory.java | Add Cc and Bcc address to mail operator. |
|
Java | apache-2.0 | 1020596f9596a65061b79728c7576e3c242b3ead | 0 | rsudev/c-geo-opensource,tobiasge/cgeo,cgeo/cgeo,cgeo/cgeo,rsudev/c-geo-opensource,tobiasge/cgeo,cgeo/cgeo,rsudev/c-geo-opensource,cgeo/cgeo,tobiasge/cgeo | package cgeo.geocaching;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.activity.TabbedViewPagerActivity;
import cgeo.geocaching.activity.TabbedViewPagerFragment;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.connector.trackable.TrackableTrackingCode;
import cgeo.geocaching.databinding.CachedetailImagesPageBinding;
import cgeo.geocaching.databinding.TrackableDetailsViewBinding;
import cgeo.geocaching.location.Units;
import cgeo.geocaching.log.LogEntry;
import cgeo.geocaching.log.LogTrackableActivity;
import cgeo.geocaching.log.LogType;
import cgeo.geocaching.log.TrackableLogsViewCreator;
import cgeo.geocaching.models.Trackable;
import cgeo.geocaching.network.AndroidBeam;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.permission.PermissionHandler;
import cgeo.geocaching.permission.PermissionRequestContext;
import cgeo.geocaching.permission.RestartLocationPermissionGrantedCallback;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.ui.ImagesList;
import cgeo.geocaching.ui.UserClickListener;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.HtmlUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.ShareUtils;
import cgeo.geocaching.utils.TextUtils;
import cgeo.geocaching.utils.UnknownTagsHandler;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.view.ActionMode;
import androidx.core.text.HtmlCompat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
public class TrackableActivity extends TabbedViewPagerActivity implements AndroidBeam.ActivitySharingInterface {
public enum Page {
DETAILS(R.string.detail),
LOGS(R.string.cache_logs),
IMAGES(R.string.cache_images);
@StringRes
private final int resId;
private final long id;
Page(@StringRes final int resId) {
this.resId = resId;
this.id = ordinal();
}
static Page find(final long pageId) {
for (Page page : Page.values()) {
if (page.id == pageId) {
return page;
}
}
return null;
}
}
private Trackable trackable = null;
private String geocode = null;
private String name = null;
private String guid = null;
private String id = null;
private String geocache = null;
private String trackingCode = null;
private TrackableBrand brand = null;
private ProgressDialog waitDialog = null;
private CharSequence clickedItemText = null;
private ImagesList imagesList = null;
private String fallbackKeywordSearch = null;
private final CompositeDisposable createDisposables = new CompositeDisposable();
private final CompositeDisposable geoDataDisposable = new CompositeDisposable();
private static final GeoDirHandler locationUpdater = new GeoDirHandler() {
@SuppressWarnings("EmptyMethod")
@Override
public void updateGeoData(final GeoData geoData) {
// Do not do anything, as we just want to maintain the GPS on
}
};
/**
* Action mode of the current contextual action bar (e.g. for copy and share actions).
*/
private ActionMode currentActionMode;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setThemeAndContentView(R.layout.tabbed_viewpager_activity_refreshable);
// set title in code, as the activity needs a hard coded title due to the intent filters
setTitle(res.getString(R.string.trackable));
// get parameters
final Bundle extras = getIntent().getExtras();
final Uri uri = AndroidBeam.getUri(getIntent());
if (extras != null) {
// try to get data from extras
geocode = extras.getString(Intents.EXTRA_GEOCODE);
name = extras.getString(Intents.EXTRA_NAME);
guid = extras.getString(Intents.EXTRA_GUID);
id = extras.getString(Intents.EXTRA_ID);
geocache = extras.getString(Intents.EXTRA_GEOCACHE);
brand = TrackableBrand.getById(extras.getInt(Intents.EXTRA_BRAND));
trackingCode = extras.getString(Intents.EXTRA_TRACKING_CODE);
fallbackKeywordSearch = extras.getString(Intents.EXTRA_KEYWORD);
}
// try to get data from URI
if (geocode == null && guid == null && id == null && uri != null) {
// check if port part needs to be removed
String address = uri.toString();
if (uri.getPort() > 0) {
address = StringUtils.remove(address, ":" + uri.getPort());
}
geocode = ConnectorFactory.getTrackableFromURL(address);
final TrackableTrackingCode tbTrackingCode = ConnectorFactory.getTrackableTrackingCodeFromURL(address);
final String uriHost = uri.getHost().toLowerCase(Locale.US);
if (uriHost.endsWith("geocaching.com")) {
geocode = uri.getQueryParameter("tracker");
guid = uri.getQueryParameter("guid");
id = uri.getQueryParameter("id");
if (StringUtils.isNotBlank(geocode)) {
geocode = geocode.toUpperCase(Locale.US);
guid = null;
id = null;
} else if (StringUtils.isNotBlank(guid)) {
geocode = null;
guid = guid.toLowerCase(Locale.US);
id = null;
} else if (StringUtils.isNotBlank(id)) {
geocode = null;
guid = null;
id = id.toLowerCase(Locale.US);
} else {
showToast(res.getString(R.string.err_tb_details_open));
finish();
return;
}
} else if (uriHost.endsWith("geokrety.org")) {
brand = TrackableBrand.GEOKRETY;
// If geocode isn't found, try to find by Tracking Code
if (geocode == null && !tbTrackingCode.isEmpty()) {
trackingCode = tbTrackingCode.trackingCode;
geocode = tbTrackingCode.trackingCode;
}
}
}
// no given data
if (geocode == null && guid == null && id == null) {
showToast(res.getString(R.string.err_tb_display));
finish();
return;
}
final String message;
if (StringUtils.isNotBlank(name)) {
message = TextUtils.stripHtml(name);
} else if (StringUtils.isNotBlank(geocode)) {
message = geocode;
} else {
message = res.getString(R.string.trackable);
}
// If we have a newer Android device setup Android Beam for easy cache sharing
AndroidBeam.enable(this, this);
createViewPager(Page.DETAILS.id, getOrderedPages(), null, true);
refreshTrackable(message);
}
@Override
public void onResume() {
super.onResume();
// resume location access
PermissionHandler.executeIfLocationPermissionGranted(this,
new RestartLocationPermissionGrantedCallback(PermissionRequestContext.TrackableActivity) {
@Override
public void executeAfter() {
if (!Settings.useLowPowerMode()) {
geoDataDisposable.add(locationUpdater.start(GeoDirHandler.UPDATE_GEODATA));
}
}
});
}
@Override
public void onPause() {
geoDataDisposable.clear();
super.onPause();
}
private void act(final Trackable newTrackable) {
trackable = newTrackable;
displayTrackable();
// reset imagelist // @todo mb: more to do?
imagesList = null;
}
private void refreshTrackable(final String message) {
waitDialog = ProgressDialog.show(this, message, res.getString(R.string.trackable_details_loading), true, true);
createDisposables.add(AndroidRxUtils.bindActivity(this, ConnectorFactory.loadTrackable(geocode, guid, id, brand)).subscribe(
newTrackable -> {
if (trackingCode != null) {
newTrackable.setTrackingcode(trackingCode);
}
act(newTrackable);
}, throwable -> {
Log.w("unable to retrieve trackable information", throwable);
showToast(res.getString(R.string.err_tb_find_that));
finish();
}, () -> act(null)));
}
@Nullable
@Override
public String getAndroidBeamUri() {
return trackable != null ? trackable.getUrl() : null;
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.trackable_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
final int itemId = item.getItemId();
if (itemId == R.id.menu_log_touch) {
startActivityForResult(LogTrackableActivity.getIntent(this, trackable, geocache), LogTrackableActivity.LOG_TRACKABLE);
} else if (itemId == R.id.menu_browser_trackable) {
ShareUtils.openUrl(this, trackable.getUrl(), true);
} else if (itemId == R.id.menu_refresh_trackable) {
refreshTrackable(StringUtils.defaultIfBlank(trackable.getName(), trackable.getGeocode()));
} else {
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
if (trackable != null) {
menu.findItem(R.id.menu_log_touch).setVisible(StringUtils.isNotBlank(geocode) && trackable.isLoggable());
menu.findItem(R.id.menu_browser_trackable).setVisible(trackable.hasUrl());
menu.findItem(R.id.menu_refresh_trackable).setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public void pullToRefreshActionTrigger() {
refreshTrackable(StringUtils.defaultIfBlank(trackable.getName(), trackable.getGeocode()));
}
public void displayTrackable() {
if (trackable == null) {
Dialogs.dismiss(waitDialog);
if (fallbackKeywordSearch != null) {
CacheListActivity.startActivityKeyword(this, fallbackKeywordSearch);
} else {
if (StringUtils.isNotBlank(geocode)) {
showToast(res.getString(R.string.err_tb_not_found, geocode));
} else {
showToast(res.getString(R.string.err_tb_find_that));
}
}
finish();
return;
}
try {
geocode = trackable.getGeocode();
if (StringUtils.isNotBlank(trackable.getName())) {
setTitle(TextUtils.stripHtml(trackable.getName()));
} else {
setTitle(trackable.getName());
}
invalidateOptionsMenuCompatible();
setOrderedPages(getOrderedPages());
reinitializeViewPager();
} catch (final Exception e) {
Log.e("TrackableActivity.loadTrackableHandler: ", e);
}
Dialogs.dismiss(waitDialog);
}
private static void setupIcon(final TrackableActivity activity, final ActionBar actionBar, final String url) {
final HtmlImage imgGetter = new HtmlImage(HtmlImage.SHARED, false, false, false);
AndroidRxUtils.bindActivity(activity, imgGetter.fetchDrawable(url)).subscribe(image -> {
if (actionBar != null) {
final int height = actionBar.getHeight();
//noinspection SuspiciousNameCombination
image.setBounds(0, 0, height, height);
actionBar.setIcon(image);
}
});
}
private static void setupIcon(final ActionBar actionBar, @DrawableRes final int resId) {
if (actionBar != null) {
actionBar.setIcon(resId);
}
}
public static void startActivity(final AbstractActivity fromContext, final String guid, final String geocode, final String name, final String geocache, final int brandId) {
final Intent trackableIntent = new Intent(fromContext, TrackableActivity.class);
trackableIntent.putExtra(Intents.EXTRA_GUID, guid);
trackableIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
trackableIntent.putExtra(Intents.EXTRA_NAME, name);
trackableIntent.putExtra(Intents.EXTRA_GEOCACHE, geocache);
trackableIntent.putExtra(Intents.EXTRA_BRAND, brandId);
fromContext.startActivity(trackableIntent);
}
@Override
@SuppressWarnings("rawtypes")
protected TabbedViewPagerFragment createNewFragment(final long pageId) {
if (pageId == Page.DETAILS.id) {
return new DetailsViewCreator();
} else if (pageId == Page.LOGS.id) {
return new TrackableLogsViewCreator(this);
} else if (pageId == Page.IMAGES.id) {
return new ImagesViewCreator();
}
throw new IllegalStateException(); // cannot happen as long as switch case is enum complete
}
private static class ImagesViewCreator extends TabbedViewPagerFragment<CachedetailImagesPageBinding> {
@Override
public CachedetailImagesPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailImagesPageBinding.inflate(inflater, container, false);
}
@Override
public void setContent() {
final TrackableActivity activity = (TrackableActivity) activityWeakReference.get();
if (activity == null) {
return;
}
final Trackable trackable = activity.getTrackable();
if (trackable == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
if (activity.imagesList == null) {
activity.imagesList = new ImagesList(activity, trackable.getGeocode(), null);
activity.createDisposables.add(activity.imagesList.loadImages(binding.getRoot(), trackable.getImages()));
}
}
}
@Override
protected String getTitle(final long pageId) {
return this.getString(Page.find(pageId).resId);
}
protected long[] getOrderedPages() {
final List<Long> pages = new ArrayList<>();
pages.add(Page.DETAILS.id);
if (trackable != null) {
if (CollectionUtils.isNotEmpty(trackable.getLogs())) {
pages.add(Page.LOGS.id);
}
if (CollectionUtils.isNotEmpty(trackable.getImages())) {
pages.add(Page.IMAGES.id);
}
}
final long[] result = new long[pages.size()];
for (int i = 0; i < pages.size(); i++) {
result[i] = pages.get(i);
}
return result;
}
public static class DetailsViewCreator extends TabbedViewPagerFragment<TrackableDetailsViewBinding> {
@Override
public TrackableDetailsViewBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return TrackableDetailsViewBinding.inflate(getLayoutInflater(), container, false);
}
@Override
@SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"}) // splitting up that method would not help improve readability
public void setContent() {
final TrackableActivity activity = (TrackableActivity) activityWeakReference.get();
if (activity == null) {
return;
}
final Trackable trackable = activity.getTrackable();
if (trackable == null) {
return;
}
binding.getRoot().setVisibility(View.VISIBLE);
final CacheDetailsCreator details = new CacheDetailsCreator(activity, binding.detailsList);
// action bar icon
if (StringUtils.isNotBlank(trackable.getIconUrl())) {
setupIcon(activity, activity.getSupportActionBar(), trackable.getIconUrl());
} else {
setupIcon(activity.getSupportActionBar(), trackable.getIconBrand());
}
// trackable name
final TextView nameTxtView = details.add(R.string.trackable_name, StringUtils.isNotBlank(trackable.getName()) ? TextUtils.stripHtml(trackable.getName()) : activity.res.getString(R.string.trackable_unknown)).right;
activity.addContextMenu(nameTxtView);
// missing status
if (trackable.isMissing()) {
nameTxtView.setPaintFlags(nameTxtView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
// trackable type
final String tbType;
if (StringUtils.isNotBlank(trackable.getType())) {
tbType = TextUtils.stripHtml(trackable.getType());
} else {
tbType = activity.res.getString(R.string.trackable_unknown);
}
details.add(R.string.trackable_brand, trackable.getBrand().getLabel());
details.add(R.string.trackable_type, tbType);
// trackable geocode
activity.addContextMenu(details.add(R.string.trackable_code, trackable.getGeocode()).right);
// retrieved status
final Date logDate = trackable.getLogDate();
final LogType logType = trackable.getLogType();
if (logDate != null && logType != null) {
final Uri uri = new Uri.Builder().scheme("https").authority("www.geocaching.com").path("/track/log.aspx").encodedQuery("LUID=" + trackable.getLogGuid()).build();
final TextView logView = details.add(R.string.trackable_status, activity.res.getString(R.string.trackable_found, logType.getL10n(), Formatter.formatDate(logDate.getTime()))).right;
logView.setOnClickListener(v -> ShareUtils.openUrl(activity, uri.toString()));
}
// trackable owner
final TextView owner = details.add(R.string.trackable_owner, activity.res.getString(R.string.trackable_unknown)).right;
if (StringUtils.isNotBlank(trackable.getOwner())) {
owner.setText(HtmlCompat.fromHtml(trackable.getOwner(), HtmlCompat.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
owner.setOnClickListener(UserClickListener.forOwnerOf(trackable));
}
// trackable spotted
if (StringUtils.isNotBlank(trackable.getSpottedName()) ||
trackable.getSpottedType() == Trackable.SPOTTED_UNKNOWN ||
trackable.getSpottedType() == Trackable.SPOTTED_OWNER ||
trackable.getSpottedType() == Trackable.SPOTTED_ARCHIVED) {
final StringBuilder text;
boolean showTimeSpan = true;
switch (trackable.getSpottedType()) {
case Trackable.SPOTTED_CACHE:
// TODO: the whole sentence fragment should not be constructed, but taken from the resources
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_in_cache)).append(' ').append(HtmlCompat.fromHtml(trackable.getSpottedName(), HtmlCompat.FROM_HTML_MODE_LEGACY));
break;
case Trackable.SPOTTED_USER:
// TODO: the whole sentence fragment should not be constructed, but taken from the resources
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_at_user)).append(' ').append(HtmlCompat.fromHtml(trackable.getSpottedName(), HtmlCompat.FROM_HTML_MODE_LEGACY));
break;
case Trackable.SPOTTED_UNKNOWN:
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_unknown_location));
break;
case Trackable.SPOTTED_OWNER:
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_owner));
break;
case Trackable.SPOTTED_ARCHIVED:
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_archived));
break;
default:
text = new StringBuilder("N/A");
showTimeSpan = false;
break;
}
// days since last spotting
if (showTimeSpan) {
for (final LogEntry log : trackable.getLogs()) {
if (log.getType() == LogType.RETRIEVED_IT || log.getType() == LogType.GRABBED_IT || log.getType() == LogType.DISCOVERED_IT || log.getType() == LogType.PLACED_IT) {
text.append(" (").append(Formatter.formatDaysAgo(log.date)).append(')');
break;
}
}
}
final TextView spotted = details.add(R.string.trackable_spotted, text.toString()).right;
spotted.setClickable(true);
if (trackable.getSpottedType() == Trackable.SPOTTED_CACHE) {
spotted.setOnClickListener(arg0 -> {
if (StringUtils.isNotBlank(trackable.getSpottedGuid())) {
CacheDetailActivity.startActivityGuid(activity, trackable.getSpottedGuid(), trackable.getSpottedName());
} else {
// for GeoKrety we only know the cache geocode
final String cacheCode = trackable.getSpottedName();
if (ConnectorFactory.canHandle(cacheCode)) {
CacheDetailActivity.startActivity(activity, cacheCode);
}
}
});
} else if (trackable.getSpottedType() == Trackable.SPOTTED_USER) {
spotted.setOnClickListener(UserClickListener.forUser(trackable, TextUtils.stripHtml(trackable.getSpottedName()), trackable.getSpottedGuid()));
} else if (trackable.getSpottedType() == Trackable.SPOTTED_OWNER) {
spotted.setOnClickListener(UserClickListener.forUser(trackable, TextUtils.stripHtml(trackable.getOwner()), trackable.getOwnerGuid()));
}
}
// trackable origin
if (StringUtils.isNotBlank(trackable.getOrigin())) {
final TextView origin = details.add(R.string.trackable_origin, "").right;
origin.setText(HtmlCompat.fromHtml(trackable.getOrigin(), HtmlCompat.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
activity.addContextMenu(origin);
}
// trackable released
final Date releasedDate = trackable.getReleased();
if (releasedDate != null) {
activity.addContextMenu(details.add(R.string.trackable_released, Formatter.formatDate(releasedDate.getTime())).right);
}
// trackable distance
if (trackable.getDistance() >= 0) {
activity.addContextMenu(details.add(R.string.trackable_distance, Units.getDistanceFromKilometers(trackable.getDistance())).right);
}
// trackable goal
if (StringUtils.isNotBlank(HtmlUtils.extractText(trackable.getGoal()))) {
binding.goalBox.setVisibility(View.VISIBLE);
binding.goal.setVisibility(View.VISIBLE);
binding.goal.setText(HtmlCompat.fromHtml(trackable.getGoal(), HtmlCompat.FROM_HTML_MODE_LEGACY, new HtmlImage(activity.geocode, true, false, binding.goal, false), null), TextView.BufferType.SPANNABLE);
binding.goal.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
activity.addContextMenu(binding.goal);
}
// trackable details
if (StringUtils.isNotBlank(HtmlUtils.extractText(trackable.getDetails()))) {
binding.detailsBox.setVisibility(View.VISIBLE);
binding.details.setVisibility(View.VISIBLE);
binding.details.setText(HtmlCompat.fromHtml(trackable.getDetails(), HtmlCompat.FROM_HTML_MODE_LEGACY, new HtmlImage(activity.geocode, true, false, binding.details, false), new UnknownTagsHandler()), TextView.BufferType.SPANNABLE);
binding.details.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
activity.addContextMenu(binding.details);
}
// trackable image
if (StringUtils.isNotBlank(trackable.getImage())) {
binding.imageBox.setVisibility(View.VISIBLE);
final ImageView trackableImage = (ImageView) activity.getLayoutInflater().inflate(R.layout.trackable_image, binding.image, false);
trackableImage.setImageResource(R.drawable.image_not_loaded);
trackableImage.setClickable(true);
trackableImage.setOnClickListener(view -> ShareUtils.openUrl(activity, trackable.getImage()));
AndroidRxUtils.bindActivity(activity, new HtmlImage(activity.geocode, true, false, false).fetchDrawable(trackable.getImage())).subscribe(trackableImage::setImageDrawable);
binding.image.addView(trackableImage);
}
}
}
@Override
public void addContextMenu(final View view) {
view.setOnLongClickListener(v -> startContextualActionBar(view));
view.setOnClickListener(v -> startContextualActionBar(view));
}
private boolean startContextualActionBar(final View view) {
if (currentActionMode != null) {
return false;
}
currentActionMode = startSupportActionMode(new ActionMode.Callback() {
@Override
public boolean onPrepareActionMode(final ActionMode actionMode, final Menu menu) {
return prepareClipboardActionMode(view, actionMode, menu);
}
private boolean prepareClipboardActionMode(final View view, final ActionMode actionMode, final Menu menu) {
clickedItemText = ((TextView) view).getText();
final int viewId = view.getId();
if (viewId == R.id.value) { // name, TB-code, origin, released, distance
final TextView textView = ((View) view.getParent()).findViewById(R.id.name);
final CharSequence itemTitle = textView.getText();
buildDetailsContextMenu(actionMode, menu, itemTitle, true);
} else if (viewId == R.id.goal) {
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.trackable_goal), false);
} else if (viewId == R.id.details) {
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.trackable_details), false);
} else if (viewId == R.id.log) {
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_logs), false);
} else {
return false;
}
return true;
}
@Override
public void onDestroyActionMode(final ActionMode actionMode) {
currentActionMode = null;
}
@Override
public boolean onCreateActionMode(final ActionMode actionMode, final Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.details_context, menu);
prepareClipboardActionMode(view, actionMode, menu);
return true;
}
@Override
public boolean onActionItemClicked(final ActionMode actionMode, final MenuItem menuItem) {
return onClipboardItemSelected(actionMode, menuItem, clickedItemText, null);
}
});
return false;
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data); // call super to make lint happy
// Refresh the logs view after coming back from logging a trackable
if (requestCode == LogTrackableActivity.LOG_TRACKABLE && resultCode == RESULT_OK) {
refreshTrackable(StringUtils.defaultIfBlank(trackable.getName(), trackable.getGeocode()));
}
}
@Override
protected void onDestroy() {
createDisposables.clear();
super.onDestroy();
}
public Trackable getTrackable() {
return trackable;
}
@Override
public void finish() {
Dialogs.dismiss(waitDialog);
super.finish();
}
}
| main/src/cgeo/geocaching/TrackableActivity.java | package cgeo.geocaching;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.activity.TabbedViewPagerActivity;
import cgeo.geocaching.activity.TabbedViewPagerFragment;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.connector.trackable.TrackableTrackingCode;
import cgeo.geocaching.databinding.CachedetailImagesPageBinding;
import cgeo.geocaching.databinding.TrackableDetailsViewBinding;
import cgeo.geocaching.location.Units;
import cgeo.geocaching.log.LogEntry;
import cgeo.geocaching.log.LogTrackableActivity;
import cgeo.geocaching.log.LogType;
import cgeo.geocaching.log.TrackableLogsViewCreator;
import cgeo.geocaching.models.Trackable;
import cgeo.geocaching.network.AndroidBeam;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.permission.PermissionHandler;
import cgeo.geocaching.permission.PermissionRequestContext;
import cgeo.geocaching.permission.RestartLocationPermissionGrantedCallback;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.ui.ImagesList;
import cgeo.geocaching.ui.UserClickListener;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.HtmlUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.ShareUtils;
import cgeo.geocaching.utils.TextUtils;
import cgeo.geocaching.utils.UnknownTagsHandler;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.view.ActionMode;
import androidx.core.text.HtmlCompat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
public class TrackableActivity extends TabbedViewPagerActivity implements AndroidBeam.ActivitySharingInterface {
public enum Page {
DETAILS(R.string.detail),
LOGS(R.string.cache_logs),
IMAGES(R.string.cache_images);
@StringRes
private final int resId;
private final long id;
Page(@StringRes final int resId) {
this.resId = resId;
this.id = ordinal();
}
static Page find(final long pageId) {
for (Page page : Page.values()) {
if (page.id == pageId) {
return page;
}
}
return null;
}
}
private Trackable trackable = null;
private String geocode = null;
private String name = null;
private String guid = null;
private String id = null;
private String geocache = null;
private String trackingCode = null;
private TrackableBrand brand = null;
private ProgressDialog waitDialog = null;
private CharSequence clickedItemText = null;
private ImagesList imagesList = null;
private String fallbackKeywordSearch = null;
private final CompositeDisposable createDisposables = new CompositeDisposable();
private final CompositeDisposable geoDataDisposable = new CompositeDisposable();
private static final GeoDirHandler locationUpdater = new GeoDirHandler() {
@SuppressWarnings("EmptyMethod")
@Override
public void updateGeoData(final GeoData geoData) {
// Do not do anything, as we just want to maintain the GPS on
}
};
/**
* Action mode of the current contextual action bar (e.g. for copy and share actions).
*/
private ActionMode currentActionMode;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setThemeAndContentView(R.layout.tabbed_viewpager_activity);
// set title in code, as the activity needs a hard coded title due to the intent filters
setTitle(res.getString(R.string.trackable));
// get parameters
final Bundle extras = getIntent().getExtras();
final Uri uri = AndroidBeam.getUri(getIntent());
if (extras != null) {
// try to get data from extras
geocode = extras.getString(Intents.EXTRA_GEOCODE);
name = extras.getString(Intents.EXTRA_NAME);
guid = extras.getString(Intents.EXTRA_GUID);
id = extras.getString(Intents.EXTRA_ID);
geocache = extras.getString(Intents.EXTRA_GEOCACHE);
brand = TrackableBrand.getById(extras.getInt(Intents.EXTRA_BRAND));
trackingCode = extras.getString(Intents.EXTRA_TRACKING_CODE);
fallbackKeywordSearch = extras.getString(Intents.EXTRA_KEYWORD);
}
// try to get data from URI
if (geocode == null && guid == null && id == null && uri != null) {
// check if port part needs to be removed
String address = uri.toString();
if (uri.getPort() > 0) {
address = StringUtils.remove(address, ":" + uri.getPort());
}
geocode = ConnectorFactory.getTrackableFromURL(address);
final TrackableTrackingCode tbTrackingCode = ConnectorFactory.getTrackableTrackingCodeFromURL(address);
final String uriHost = uri.getHost().toLowerCase(Locale.US);
if (uriHost.endsWith("geocaching.com")) {
geocode = uri.getQueryParameter("tracker");
guid = uri.getQueryParameter("guid");
id = uri.getQueryParameter("id");
if (StringUtils.isNotBlank(geocode)) {
geocode = geocode.toUpperCase(Locale.US);
guid = null;
id = null;
} else if (StringUtils.isNotBlank(guid)) {
geocode = null;
guid = guid.toLowerCase(Locale.US);
id = null;
} else if (StringUtils.isNotBlank(id)) {
geocode = null;
guid = null;
id = id.toLowerCase(Locale.US);
} else {
showToast(res.getString(R.string.err_tb_details_open));
finish();
return;
}
} else if (uriHost.endsWith("geokrety.org")) {
brand = TrackableBrand.GEOKRETY;
// If geocode isn't found, try to find by Tracking Code
if (geocode == null && !tbTrackingCode.isEmpty()) {
trackingCode = tbTrackingCode.trackingCode;
geocode = tbTrackingCode.trackingCode;
}
}
}
// no given data
if (geocode == null && guid == null && id == null) {
showToast(res.getString(R.string.err_tb_display));
finish();
return;
}
final String message;
if (StringUtils.isNotBlank(name)) {
message = TextUtils.stripHtml(name);
} else if (StringUtils.isNotBlank(geocode)) {
message = geocode;
} else {
message = res.getString(R.string.trackable);
}
// If we have a newer Android device setup Android Beam for easy cache sharing
AndroidBeam.enable(this, this);
createViewPager(Page.DETAILS.id, getOrderedPages(), null);
refreshTrackable(message);
}
@Override
public void onResume() {
super.onResume();
// resume location access
PermissionHandler.executeIfLocationPermissionGranted(this,
new RestartLocationPermissionGrantedCallback(PermissionRequestContext.TrackableActivity) {
@Override
public void executeAfter() {
if (!Settings.useLowPowerMode()) {
geoDataDisposable.add(locationUpdater.start(GeoDirHandler.UPDATE_GEODATA));
}
}
});
}
@Override
public void onPause() {
geoDataDisposable.clear();
super.onPause();
}
private void act(final Trackable newTrackable) {
trackable = newTrackable;
displayTrackable();
// reset imagelist // @todo mb: more to do?
imagesList = null;
}
private void refreshTrackable(final String message) {
waitDialog = ProgressDialog.show(this, message, res.getString(R.string.trackable_details_loading), true, true);
createDisposables.add(AndroidRxUtils.bindActivity(this, ConnectorFactory.loadTrackable(geocode, guid, id, brand)).subscribe(
newTrackable -> {
if (trackingCode != null) {
newTrackable.setTrackingcode(trackingCode);
}
act(newTrackable);
}, throwable -> {
Log.w("unable to retrieve trackable information", throwable);
showToast(res.getString(R.string.err_tb_find_that));
finish();
}, () -> act(null)));
}
@Nullable
@Override
public String getAndroidBeamUri() {
return trackable != null ? trackable.getUrl() : null;
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.trackable_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
final int itemId = item.getItemId();
if (itemId == R.id.menu_log_touch) {
startActivityForResult(LogTrackableActivity.getIntent(this, trackable, geocache), LogTrackableActivity.LOG_TRACKABLE);
} else if (itemId == R.id.menu_browser_trackable) {
ShareUtils.openUrl(this, trackable.getUrl(), true);
} else if (itemId == R.id.menu_refresh_trackable) {
refreshTrackable(StringUtils.defaultIfBlank(trackable.getName(), trackable.getGeocode()));
} else {
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
if (trackable != null) {
menu.findItem(R.id.menu_log_touch).setVisible(StringUtils.isNotBlank(geocode) && trackable.isLoggable());
menu.findItem(R.id.menu_browser_trackable).setVisible(trackable.hasUrl());
menu.findItem(R.id.menu_refresh_trackable).setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public void pullToRefreshActionTrigger() {
refreshTrackable(StringUtils.defaultIfBlank(trackable.getName(), trackable.getGeocode()));
}
public void displayTrackable() {
if (trackable == null) {
Dialogs.dismiss(waitDialog);
if (fallbackKeywordSearch != null) {
CacheListActivity.startActivityKeyword(this, fallbackKeywordSearch);
} else {
if (StringUtils.isNotBlank(geocode)) {
showToast(res.getString(R.string.err_tb_not_found, geocode));
} else {
showToast(res.getString(R.string.err_tb_find_that));
}
}
finish();
return;
}
try {
geocode = trackable.getGeocode();
if (StringUtils.isNotBlank(trackable.getName())) {
setTitle(TextUtils.stripHtml(trackable.getName()));
} else {
setTitle(trackable.getName());
}
invalidateOptionsMenuCompatible();
setOrderedPages(getOrderedPages());
reinitializeViewPager();
} catch (final Exception e) {
Log.e("TrackableActivity.loadTrackableHandler: ", e);
}
Dialogs.dismiss(waitDialog);
}
private static void setupIcon(final TrackableActivity activity, final ActionBar actionBar, final String url) {
final HtmlImage imgGetter = new HtmlImage(HtmlImage.SHARED, false, false, false);
AndroidRxUtils.bindActivity(activity, imgGetter.fetchDrawable(url)).subscribe(image -> {
if (actionBar != null) {
final int height = actionBar.getHeight();
//noinspection SuspiciousNameCombination
image.setBounds(0, 0, height, height);
actionBar.setIcon(image);
}
});
}
private static void setupIcon(final ActionBar actionBar, @DrawableRes final int resId) {
if (actionBar != null) {
actionBar.setIcon(resId);
}
}
public static void startActivity(final AbstractActivity fromContext, final String guid, final String geocode, final String name, final String geocache, final int brandId) {
final Intent trackableIntent = new Intent(fromContext, TrackableActivity.class);
trackableIntent.putExtra(Intents.EXTRA_GUID, guid);
trackableIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
trackableIntent.putExtra(Intents.EXTRA_NAME, name);
trackableIntent.putExtra(Intents.EXTRA_GEOCACHE, geocache);
trackableIntent.putExtra(Intents.EXTRA_BRAND, brandId);
fromContext.startActivity(trackableIntent);
}
@Override
@SuppressWarnings("rawtypes")
protected TabbedViewPagerFragment createNewFragment(final long pageId) {
if (pageId == Page.DETAILS.id) {
return new DetailsViewCreator();
} else if (pageId == Page.LOGS.id) {
return new TrackableLogsViewCreator(this);
} else if (pageId == Page.IMAGES.id) {
return new ImagesViewCreator();
}
throw new IllegalStateException(); // cannot happen as long as switch case is enum complete
}
private static class ImagesViewCreator extends TabbedViewPagerFragment<CachedetailImagesPageBinding> {
@Override
public CachedetailImagesPageBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return CachedetailImagesPageBinding.inflate(inflater, container, false);
}
@Override
public void setContent() {
final TrackableActivity activity = (TrackableActivity) activityWeakReference.get();
if (activity == null) {
return;
}
final Trackable trackable = activity.getTrackable();
if (trackable == null) {
return;
}
if (activity.imagesList == null) {
activity.imagesList = new ImagesList(activity, trackable.getGeocode(), null);
activity.createDisposables.add(activity.imagesList.loadImages(binding.getRoot(), trackable.getImages()));
}
}
}
@Override
protected String getTitle(final long pageId) {
return this.getString(Page.find(pageId).resId);
}
protected long[] getOrderedPages() {
final List<Long> pages = new ArrayList<>();
pages.add(Page.DETAILS.id);
if (trackable != null) {
if (CollectionUtils.isNotEmpty(trackable.getLogs())) {
pages.add(Page.LOGS.id);
}
if (CollectionUtils.isNotEmpty(trackable.getImages())) {
pages.add(Page.IMAGES.id);
}
}
final long[] result = new long[pages.size()];
for (int i = 0; i < pages.size(); i++) {
result[i] = pages.get(i);
}
return result;
}
public static class DetailsViewCreator extends TabbedViewPagerFragment<TrackableDetailsViewBinding> {
@Override
public TrackableDetailsViewBinding createView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return TrackableDetailsViewBinding.inflate(getLayoutInflater(), container, false);
}
@Override
@SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"}) // splitting up that method would not help improve readability
public void setContent() {
final TrackableActivity activity = (TrackableActivity) activityWeakReference.get();
if (activity == null) {
return;
}
final Trackable trackable = activity.getTrackable();
if (trackable == null) {
return;
}
final CacheDetailsCreator details = new CacheDetailsCreator(activity, binding.detailsList);
// action bar icon
if (StringUtils.isNotBlank(trackable.getIconUrl())) {
setupIcon(activity, activity.getSupportActionBar(), trackable.getIconUrl());
} else {
setupIcon(activity.getSupportActionBar(), trackable.getIconBrand());
}
// trackable name
final TextView nameTxtView = details.add(R.string.trackable_name, StringUtils.isNotBlank(trackable.getName()) ? TextUtils.stripHtml(trackable.getName()) : activity.res.getString(R.string.trackable_unknown)).right;
activity.addContextMenu(nameTxtView);
// missing status
if (trackable.isMissing()) {
nameTxtView.setPaintFlags(nameTxtView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
// trackable type
final String tbType;
if (StringUtils.isNotBlank(trackable.getType())) {
tbType = TextUtils.stripHtml(trackable.getType());
} else {
tbType = activity.res.getString(R.string.trackable_unknown);
}
details.add(R.string.trackable_brand, trackable.getBrand().getLabel());
details.add(R.string.trackable_type, tbType);
// trackable geocode
activity.addContextMenu(details.add(R.string.trackable_code, trackable.getGeocode()).right);
// retrieved status
final Date logDate = trackable.getLogDate();
final LogType logType = trackable.getLogType();
if (logDate != null && logType != null) {
final Uri uri = new Uri.Builder().scheme("https").authority("www.geocaching.com").path("/track/log.aspx").encodedQuery("LUID=" + trackable.getLogGuid()).build();
final TextView logView = details.add(R.string.trackable_status, activity.res.getString(R.string.trackable_found, logType.getL10n(), Formatter.formatDate(logDate.getTime()))).right;
logView.setOnClickListener(v -> ShareUtils.openUrl(activity, uri.toString()));
}
// trackable owner
final TextView owner = details.add(R.string.trackable_owner, activity.res.getString(R.string.trackable_unknown)).right;
if (StringUtils.isNotBlank(trackable.getOwner())) {
owner.setText(HtmlCompat.fromHtml(trackable.getOwner(), HtmlCompat.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
owner.setOnClickListener(UserClickListener.forOwnerOf(trackable));
}
// trackable spotted
if (StringUtils.isNotBlank(trackable.getSpottedName()) ||
trackable.getSpottedType() == Trackable.SPOTTED_UNKNOWN ||
trackable.getSpottedType() == Trackable.SPOTTED_OWNER ||
trackable.getSpottedType() == Trackable.SPOTTED_ARCHIVED) {
final StringBuilder text;
boolean showTimeSpan = true;
switch (trackable.getSpottedType()) {
case Trackable.SPOTTED_CACHE:
// TODO: the whole sentence fragment should not be constructed, but taken from the resources
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_in_cache)).append(' ').append(HtmlCompat.fromHtml(trackable.getSpottedName(), HtmlCompat.FROM_HTML_MODE_LEGACY));
break;
case Trackable.SPOTTED_USER:
// TODO: the whole sentence fragment should not be constructed, but taken from the resources
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_at_user)).append(' ').append(HtmlCompat.fromHtml(trackable.getSpottedName(), HtmlCompat.FROM_HTML_MODE_LEGACY));
break;
case Trackable.SPOTTED_UNKNOWN:
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_unknown_location));
break;
case Trackable.SPOTTED_OWNER:
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_owner));
break;
case Trackable.SPOTTED_ARCHIVED:
text = new StringBuilder(activity.res.getString(R.string.trackable_spotted_archived));
break;
default:
text = new StringBuilder("N/A");
showTimeSpan = false;
break;
}
// days since last spotting
if (showTimeSpan) {
for (final LogEntry log : trackable.getLogs()) {
if (log.getType() == LogType.RETRIEVED_IT || log.getType() == LogType.GRABBED_IT || log.getType() == LogType.DISCOVERED_IT || log.getType() == LogType.PLACED_IT) {
text.append(" (").append(Formatter.formatDaysAgo(log.date)).append(')');
break;
}
}
}
final TextView spotted = details.add(R.string.trackable_spotted, text.toString()).right;
spotted.setClickable(true);
if (trackable.getSpottedType() == Trackable.SPOTTED_CACHE) {
spotted.setOnClickListener(arg0 -> {
if (StringUtils.isNotBlank(trackable.getSpottedGuid())) {
CacheDetailActivity.startActivityGuid(activity, trackable.getSpottedGuid(), trackable.getSpottedName());
} else {
// for GeoKrety we only know the cache geocode
final String cacheCode = trackable.getSpottedName();
if (ConnectorFactory.canHandle(cacheCode)) {
CacheDetailActivity.startActivity(activity, cacheCode);
}
}
});
} else if (trackable.getSpottedType() == Trackable.SPOTTED_USER) {
spotted.setOnClickListener(UserClickListener.forUser(trackable, TextUtils.stripHtml(trackable.getSpottedName()), trackable.getSpottedGuid()));
} else if (trackable.getSpottedType() == Trackable.SPOTTED_OWNER) {
spotted.setOnClickListener(UserClickListener.forUser(trackable, TextUtils.stripHtml(trackable.getOwner()), trackable.getOwnerGuid()));
}
}
// trackable origin
if (StringUtils.isNotBlank(trackable.getOrigin())) {
final TextView origin = details.add(R.string.trackable_origin, "").right;
origin.setText(HtmlCompat.fromHtml(trackable.getOrigin(), HtmlCompat.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
activity.addContextMenu(origin);
}
// trackable released
final Date releasedDate = trackable.getReleased();
if (releasedDate != null) {
activity.addContextMenu(details.add(R.string.trackable_released, Formatter.formatDate(releasedDate.getTime())).right);
}
// trackable distance
if (trackable.getDistance() >= 0) {
activity.addContextMenu(details.add(R.string.trackable_distance, Units.getDistanceFromKilometers(trackable.getDistance())).right);
}
// trackable goal
if (StringUtils.isNotBlank(HtmlUtils.extractText(trackable.getGoal()))) {
binding.goalBox.setVisibility(View.VISIBLE);
binding.goal.setVisibility(View.VISIBLE);
binding.goal.setText(HtmlCompat.fromHtml(trackable.getGoal(), HtmlCompat.FROM_HTML_MODE_LEGACY, new HtmlImage(activity.geocode, true, false, binding.goal, false), null), TextView.BufferType.SPANNABLE);
binding.goal.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
activity.addContextMenu(binding.goal);
}
// trackable details
if (StringUtils.isNotBlank(HtmlUtils.extractText(trackable.getDetails()))) {
binding.detailsBox.setVisibility(View.VISIBLE);
binding.details.setVisibility(View.VISIBLE);
binding.details.setText(HtmlCompat.fromHtml(trackable.getDetails(), HtmlCompat.FROM_HTML_MODE_LEGACY, new HtmlImage(activity.geocode, true, false, binding.details, false), new UnknownTagsHandler()), TextView.BufferType.SPANNABLE);
binding.details.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
activity.addContextMenu(binding.details);
}
// trackable image
if (StringUtils.isNotBlank(trackable.getImage())) {
binding.imageBox.setVisibility(View.VISIBLE);
final ImageView trackableImage = (ImageView) activity.getLayoutInflater().inflate(R.layout.trackable_image, binding.image, false);
trackableImage.setImageResource(R.drawable.image_not_loaded);
trackableImage.setClickable(true);
trackableImage.setOnClickListener(view -> ShareUtils.openUrl(activity, trackable.getImage()));
AndroidRxUtils.bindActivity(activity, new HtmlImage(activity.geocode, true, false, false).fetchDrawable(trackable.getImage())).subscribe(trackableImage::setImageDrawable);
binding.image.addView(trackableImage);
}
}
}
@Override
public void addContextMenu(final View view) {
view.setOnLongClickListener(v -> startContextualActionBar(view));
view.setOnClickListener(v -> startContextualActionBar(view));
}
private boolean startContextualActionBar(final View view) {
if (currentActionMode != null) {
return false;
}
currentActionMode = startSupportActionMode(new ActionMode.Callback() {
@Override
public boolean onPrepareActionMode(final ActionMode actionMode, final Menu menu) {
return prepareClipboardActionMode(view, actionMode, menu);
}
private boolean prepareClipboardActionMode(final View view, final ActionMode actionMode, final Menu menu) {
clickedItemText = ((TextView) view).getText();
final int viewId = view.getId();
if (viewId == R.id.value) { // name, TB-code, origin, released, distance
final TextView textView = ((View) view.getParent()).findViewById(R.id.name);
final CharSequence itemTitle = textView.getText();
buildDetailsContextMenu(actionMode, menu, itemTitle, true);
} else if (viewId == R.id.goal) {
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.trackable_goal), false);
} else if (viewId == R.id.details) {
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.trackable_details), false);
} else if (viewId == R.id.log) {
buildDetailsContextMenu(actionMode, menu, res.getString(R.string.cache_logs), false);
} else {
return false;
}
return true;
}
@Override
public void onDestroyActionMode(final ActionMode actionMode) {
currentActionMode = null;
}
@Override
public boolean onCreateActionMode(final ActionMode actionMode, final Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.details_context, menu);
prepareClipboardActionMode(view, actionMode, menu);
return true;
}
@Override
public boolean onActionItemClicked(final ActionMode actionMode, final MenuItem menuItem) {
return onClipboardItemSelected(actionMode, menuItem, clickedItemText, null);
}
});
return false;
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data); // call super to make lint happy
// Refresh the logs view after coming back from logging a trackable
if (requestCode == LogTrackableActivity.LOG_TRACKABLE && resultCode == RESULT_OK) {
refreshTrackable(StringUtils.defaultIfBlank(trackable.getName(), trackable.getGeocode()));
}
}
@Override
protected void onDestroy() {
createDisposables.clear();
super.onDestroy();
}
public Trackable getTrackable() {
return trackable;
}
@Override
public void finish() {
Dialogs.dismiss(waitDialog);
super.finish();
}
}
| fix trackable details display (follow-up to #10900)
| main/src/cgeo/geocaching/TrackableActivity.java | fix trackable details display (follow-up to #10900) |
|
Java | apache-2.0 | 398baedff00450b9cc535d643fc9e836f8dbaed8 | 0 | yangfuhai/jboot,yangfuhai/jboot | /**
* Copyright (c) 2015-2021, Michael Yang 杨福海 ([email protected]).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jboot.aop;
import com.jfinal.aop.AopFactory;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.proxy.Proxy;
import com.jfinal.proxy.ProxyManager;
import io.jboot.aop.annotation.*;
import io.jboot.aop.cglib.JbootCglibProxyFactory;
import io.jboot.app.config.ConfigUtil;
import io.jboot.app.config.JbootConfigManager;
import io.jboot.app.config.annotation.ConfigModel;
import io.jboot.components.event.JbootEventListener;
import io.jboot.components.mq.JbootmqMessageListener;
import io.jboot.components.rpc.Jbootrpc;
import io.jboot.components.rpc.JbootrpcManager;
import io.jboot.components.rpc.JbootrpcReferenceConfig;
import io.jboot.components.rpc.annotation.RPCInject;
import io.jboot.db.model.JbootModel;
import io.jboot.exception.JbootException;
import io.jboot.service.JbootServiceBase;
import io.jboot.utils.*;
import io.jboot.web.controller.JbootController;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class JbootAopFactory extends AopFactory {
private static final Log LOG = Log.getLog(JbootAopFactory.class);
//排除默认的映射
private final static Class<?>[] DEFAULT_EXCLUDES_MAPPING_CLASSES = new Class[]{
JbootEventListener.class
, JbootmqMessageListener.class
, Serializable.class
};
private static JbootAopFactory me = new JbootAopFactory();
public static JbootAopFactory me() {
return me;
}
private Map<String, Object> beansCache = new ConcurrentHashMap<>();
private Map<String, Class<?>> beanNameClassesMapping = new ConcurrentHashMap<>();
private JbootAopFactory() {
ProxyManager.me().setProxyFactory(new JbootCglibProxyFactory());
setInjectSuperClass(true);
initBeanMapping();
}
@Override
protected Object createObject(Class<?> targetClass) {
ConfigModel configModel = targetClass.getAnnotation(ConfigModel.class);
if (configModel != null) {
return JbootConfigManager.me().get(targetClass);
}
StaticConstruct staticConstruct = targetClass.getAnnotation(StaticConstruct.class);
if (staticConstruct != null) {
return ClassUtil.newInstanceByStaticConstruct(targetClass, staticConstruct);
}
return Proxy.get(targetClass);
}
@Override
protected void doInject(Class<?> targetClass, Object targetObject) throws ReflectiveOperationException {
targetClass = getUsefulClass(targetClass);
doInjectTargetClass(targetClass, targetObject);
doInvokePostConstructMethod(targetClass, targetObject);
}
/**
* 执行 @PostConstruct 注解方法
*
* @param targetClass
* @param targetObject
* @throws ReflectiveOperationException
*/
protected void doInvokePostConstructMethod(Class<?> targetClass, Object targetObject) throws ReflectiveOperationException {
Method[] methods = targetClass.getDeclaredMethods();
for (Method method : methods) {
if (method.getParameterCount() == 0) {
PostConstruct postConstruct = method.getAnnotation(PostConstruct.class);
if (postConstruct != null) {
method.setAccessible(true);
method.invoke(targetObject);
break;
}
}
}
Class<?> superClass = targetClass.getSuperclass();
if (notSystemClass(superClass)) {
doInvokePostConstructMethod(superClass, targetObject);
}
}
/**
* 执行注入操作
*
* @param targetClass
* @param targetObject
* @throws ReflectiveOperationException
*/
protected void doInjectTargetClass(Class<?> targetClass, Object targetObject) throws ReflectiveOperationException {
Field[] fields = targetClass.getDeclaredFields();
if (fields.length != 0) {
for (Field field : fields) {
Inject inject = field.getAnnotation(Inject.class);
if (inject != null) {
Bean bean = field.getAnnotation(Bean.class);
String beanName = bean != null ? AnnotationUtil.get(bean.name()) : null;
if (StrUtil.isNotBlank(beanName)) {
doInjectByName(targetObject, field, beanName);
} else {
doInjectJFinalOrginal(targetObject, field, inject);
}
continue;
}
RPCInject rpcInject = field.getAnnotation(RPCInject.class);
if (rpcInject != null) {
doInjectRPC(targetObject, field, rpcInject);
continue;
}
ConfigValue configValue = field.getAnnotation(ConfigValue.class);
if (configValue != null) {
doInjectConfigValue(targetObject, field, configValue);
continue;
}
}
}
// 是否对超类进行注入
if (injectSuperClass) {
Class<?> superClass = targetClass.getSuperclass();
if (notSystemClass(superClass)) {
doInjectTargetClass(superClass, targetObject);
}
}
}
protected boolean notSystemClass(Class clazz) {
return clazz != JbootController.class
&& clazz != Controller.class
&& clazz != JbootServiceBase.class
&& clazz != Object.class
&& clazz != JbootModel.class
&& clazz != Model.class
&& clazz != null;
}
private void doInjectByName(Object targetObject, Field field, String beanName) throws ReflectiveOperationException {
Object fieldInjectedObject = beansCache.get(beanName);
if (fieldInjectedObject == null) {
Class<?> fieldInjectedClass = beanNameClassesMapping.get(beanName);
if (fieldInjectedClass == null || fieldInjectedClass == Void.class) {
fieldInjectedClass = field.getType();
}
fieldInjectedObject = doGet(fieldInjectedClass);
beansCache.put(beanName, fieldInjectedObject);
}
setFieldValue(field, targetObject, fieldInjectedObject);
}
/**
* JFinal 原生 service 注入
*
* @param targetObject
* @param field
* @param inject
* @throws ReflectiveOperationException
*/
private void doInjectJFinalOrginal(Object targetObject, Field field, Inject inject) throws ReflectiveOperationException {
Class<?> fieldInjectedClass = inject.value();
if (fieldInjectedClass == Void.class) {
fieldInjectedClass = field.getType();
}
Object fieldInjectedObject = doGet(fieldInjectedClass);
setFieldValue(field, targetObject, fieldInjectedObject);
}
/**
* 注入 rpc service
*
* @param targetObject
* @param field
* @param rpcInject
*/
private void doInjectRPC(Object targetObject, Field field, RPCInject rpcInject) {
try {
Class<?> fieldInjectedClass = field.getType();
JbootrpcReferenceConfig referenceConfig = new JbootrpcReferenceConfig(rpcInject);
Jbootrpc jbootrpc = JbootrpcManager.me().getJbootrpc();
Object fieldInjectedObject = jbootrpc.serviceObtain(fieldInjectedClass, referenceConfig);
setFieldValue(field, targetObject, fieldInjectedObject);
} catch (Exception ex) {
LOG.error("Can not inject rpc service in " + targetObject.getClass() + " by config " + rpcInject, ex);
}
}
/**
* 注入配置文件
*
* @param targetObject
* @param field
* @param configValue
* @throws IllegalAccessException
*/
private void doInjectConfigValue(Object targetObject, Field field, ConfigValue configValue) throws IllegalAccessException {
String key = AnnotationUtil.get(configValue.value());
Class<?> fieldInjectedClass = field.getType();
String value = JbootConfigManager.me().getConfigValue(key);
if (StrUtil.isNotBlank(value)) {
Object fieldInjectedObject = ConfigUtil.convert(fieldInjectedClass, value, field.getGenericType());
if (fieldInjectedObject != null) {
setFieldValue(field, targetObject, fieldInjectedObject);
}
}
}
/**
* 允许多次执行 AddMapping,方便在应用运行中可以切换 Mapping
*
* @param from
* @param to
* @param <T>
* @return
*/
@Override
public synchronized <T> AopFactory addMapping(Class<T> from, Class<? extends T> to) {
if (from == null || to == null) {
throw new IllegalArgumentException("The parameter from and to can not be null");
}
if (mapping == null) {
mapping = new HashMap<>(128, 0.25F);
}
Class mappingClass = mapping.get(from);
if (mappingClass != null) {
if (mappingClass == to) {
return this;
} else {
singletonCache.remove(mappingClass);
LogKit.warn("Aop Class[" + from + "] mapping changed from " + mappingClass + " to " + to);
}
}
mapping.put(from, to);
return this;
}
protected void setFieldValue(Field field, Object toObj, Object data) throws IllegalAccessException {
field.setAccessible(true);
field.set(toObj, data);
}
/**
* 初始化 @Bean 注解的映射关系
*/
private void initBeanMapping() {
// 初始化 @Configuration 里的 beans
initConfigurationBeansObject();
// 添加映射
initBeansMapping();
}
/**
* 初始化 @Configuration 里的 bean 配置
*/
private void initConfigurationBeansObject() {
List<Class> configurationClasses = ClassScanner.scanClassByAnnotation(Configuration.class, true);
for (Class<?> configurationClass : configurationClasses) {
Object configurationObj = ClassUtil.newInstance(configurationClass, false);
if (configurationObj == null) {
throw new NullPointerException("can not newInstance for class : " + configurationClass);
}
Method[] methods = configurationClass.getDeclaredMethods();
for (Method method : methods) {
Bean beanAnnotation = method.getAnnotation(Bean.class);
if (beanAnnotation != null) {
Class<?> returnType = method.getReturnType();
if (returnType == void.class){
throw new JbootException("@Bean annotation can not use for void method: " + ClassUtil.buildMethodString(method));
}
String beanName = StrUtil.obtainDefault(AnnotationUtil.get(beanAnnotation.name()), method.getName());
if (beansCache.containsKey(beanName)) {
throw new JbootException("application has contains beanName \"" + beanName + "\" for " + getBean(beanName)
+ ", can not add again by method: " + ClassUtil.buildMethodString(method));
}
try {
Object methodObj = method.invoke(configurationObj);
if (methodObj != null){
beansCache.put(beanName, methodObj);
singletonCache.put(returnType, methodObj);
}
}catch (Exception ex){
throw new RuntimeException(ex);
}
}
}
}
}
/**
* 添加 所有的 Bean 和实现类 的映射
*/
private void initBeansMapping() {
List<Class> classes = ClassScanner.scanClassByAnnotation(Bean.class, true);
for (Class implClass : classes) {
Bean bean = (Bean) implClass.getAnnotation(Bean.class);
String beanName = AnnotationUtil.get(bean.name());
if (StrUtil.isNotBlank(beanName)) {
if (beanNameClassesMapping.containsKey(beanName)) {
throw new JbootException("application has contains beanName \"" + beanName + "\" for " + getBean(beanName)
+ ", can not add for class " + implClass);
}
beanNameClassesMapping.put(beanName, implClass);
} else {
Class<?>[] interfaceClasses = implClass.getInterfaces();
if (interfaceClasses.length == 0) {
//add self
this.addMapping(implClass, implClass);
} else {
Class<?>[] excludes = buildExcludeClasses(implClass);
for (Class<?> interfaceClass : interfaceClasses) {
if (!inExcludes(interfaceClass, excludes)) {
this.addMapping(interfaceClass, implClass);
}
}
}
}
}
}
private Class<?>[] buildExcludeClasses(Class<?> implClass) {
BeanExclude beanExclude = implClass.getAnnotation(BeanExclude.class);
//对某些系统的类 进行排除,例如:Serializable 等
return beanExclude == null
? DEFAULT_EXCLUDES_MAPPING_CLASSES
: ArrayUtil.concat(DEFAULT_EXCLUDES_MAPPING_CLASSES, beanExclude.value());
}
private boolean inExcludes(Class interfaceClass, Class[] excludes) {
for (Class ex : excludes) {
if (ex.isAssignableFrom(interfaceClass)) {
return true;
}
}
return false;
}
public <T> T getBean(String name) {
return (T) beansCache.get(name);
}
public void setBean(String name, Object obj) {
beansCache.put(name, obj);
}
}
| src/main/java/io/jboot/aop/JbootAopFactory.java | /**
* Copyright (c) 2015-2021, Michael Yang 杨福海 ([email protected]).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jboot.aop;
import com.jfinal.aop.AopFactory;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.proxy.Proxy;
import com.jfinal.proxy.ProxyManager;
import io.jboot.aop.annotation.*;
import io.jboot.aop.cglib.JbootCglibProxyFactory;
import io.jboot.app.config.ConfigUtil;
import io.jboot.app.config.JbootConfigManager;
import io.jboot.app.config.annotation.ConfigModel;
import io.jboot.components.event.JbootEventListener;
import io.jboot.components.mq.JbootmqMessageListener;
import io.jboot.components.rpc.Jbootrpc;
import io.jboot.components.rpc.JbootrpcManager;
import io.jboot.components.rpc.JbootrpcReferenceConfig;
import io.jboot.components.rpc.annotation.RPCInject;
import io.jboot.db.model.JbootModel;
import io.jboot.exception.JbootException;
import io.jboot.service.JbootServiceBase;
import io.jboot.utils.*;
import io.jboot.web.controller.JbootController;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class JbootAopFactory extends AopFactory {
private static final Log LOG = Log.getLog(JbootAopFactory.class);
//排除默认的映射
private final static Class<?>[] DEFAULT_EXCLUDES_MAPPING_CLASSES = new Class[]{
JbootEventListener.class
, JbootmqMessageListener.class
, Serializable.class
};
private static JbootAopFactory me = new JbootAopFactory();
public static JbootAopFactory me() {
return me;
}
private Map<String, Object> beansCache = new ConcurrentHashMap<>();
private Map<String, Class<?>> beanNameClassesMapping = new ConcurrentHashMap<>();
private JbootAopFactory() {
ProxyManager.me().setProxyFactory(new JbootCglibProxyFactory());
setInjectSuperClass(true);
initBeanMapping();
}
@Override
protected Object createObject(Class<?> targetClass) {
ConfigModel configModel = targetClass.getAnnotation(ConfigModel.class);
if (configModel != null) {
return JbootConfigManager.me().get(targetClass);
}
StaticConstruct staticConstruct = targetClass.getAnnotation(StaticConstruct.class);
if (staticConstruct != null) {
return ClassUtil.newInstanceByStaticConstruct(targetClass, staticConstruct);
}
return Proxy.get(targetClass);
}
@Override
protected void doInject(Class<?> targetClass, Object targetObject) throws ReflectiveOperationException {
targetClass = getUsefulClass(targetClass);
doInjectTargetClass(targetClass, targetObject);
doInvokePostConstructMethod(targetClass, targetObject);
}
/**
* 执行 @PostConstruct 注解方法
*
* @param targetClass
* @param targetObject
* @throws ReflectiveOperationException
*/
protected void doInvokePostConstructMethod(Class<?> targetClass, Object targetObject) throws ReflectiveOperationException {
Method[] methods = targetClass.getDeclaredMethods();
for (Method method : methods) {
if (method.getParameterCount() == 0) {
PostConstruct postConstruct = method.getAnnotation(PostConstruct.class);
if (postConstruct != null) {
method.setAccessible(true);
method.invoke(targetObject);
break;
}
}
}
Class<?> superClass = targetClass.getSuperclass();
if (notSystemClass(superClass)) {
doInvokePostConstructMethod(superClass, targetObject);
}
}
/**
* 执行注入操作
*
* @param targetClass
* @param targetObject
* @throws ReflectiveOperationException
*/
protected void doInjectTargetClass(Class<?> targetClass, Object targetObject) throws ReflectiveOperationException {
Field[] fields = targetClass.getDeclaredFields();
if (fields.length != 0) {
for (Field field : fields) {
Inject inject = field.getAnnotation(Inject.class);
if (inject != null) {
Bean bean = field.getAnnotation(Bean.class);
String beanName = bean != null ? AnnotationUtil.get(bean.name()) : null;
if (StrUtil.isNotBlank(beanName)) {
doInjectByName(targetObject, field, beanName);
} else {
doInjectJFinalOrginal(targetObject, field, inject);
}
continue;
}
RPCInject rpcInject = field.getAnnotation(RPCInject.class);
if (rpcInject != null) {
doInjectRPC(targetObject, field, rpcInject);
continue;
}
ConfigValue configValue = field.getAnnotation(ConfigValue.class);
if (configValue != null) {
doInjectConfigValue(targetObject, field, configValue);
continue;
}
}
}
// 是否对超类进行注入
if (injectSuperClass) {
Class<?> superClass = targetClass.getSuperclass();
if (notSystemClass(superClass)) {
doInjectTargetClass(superClass, targetObject);
}
}
}
protected boolean notSystemClass(Class clazz) {
return clazz != JbootController.class
&& clazz != Controller.class
&& clazz != JbootServiceBase.class
&& clazz != Object.class
&& clazz != JbootModel.class
&& clazz != Model.class
&& clazz != null;
}
private void doInjectByName(Object targetObject, Field field, String beanName) throws ReflectiveOperationException {
Object fieldInjectedObject = beansCache.get(beanName);
if (fieldInjectedObject == null) {
Class<?> fieldInjectedClass = beanNameClassesMapping.get(beanName);
if (fieldInjectedClass == null || fieldInjectedClass == Void.class) {
fieldInjectedClass = field.getType();
}
fieldInjectedObject = doGet(fieldInjectedClass);
beansCache.put(beanName, fieldInjectedObject);
}
setFieldValue(field, targetObject, fieldInjectedObject);
}
/**
* JFinal 原生 service 注入
*
* @param targetObject
* @param field
* @param inject
* @throws ReflectiveOperationException
*/
private void doInjectJFinalOrginal(Object targetObject, Field field, Inject inject) throws ReflectiveOperationException {
Class<?> fieldInjectedClass = inject.value();
if (fieldInjectedClass == Void.class) {
fieldInjectedClass = field.getType();
}
Object fieldInjectedObject = doGet(fieldInjectedClass);
setFieldValue(field, targetObject, fieldInjectedObject);
}
/**
* 注入 rpc service
*
* @param targetObject
* @param field
* @param rpcInject
*/
private void doInjectRPC(Object targetObject, Field field, RPCInject rpcInject) {
try {
Class<?> fieldInjectedClass = field.getType();
JbootrpcReferenceConfig referenceConfig = new JbootrpcReferenceConfig(rpcInject);
Jbootrpc jbootrpc = JbootrpcManager.me().getJbootrpc();
Object fieldInjectedObject = jbootrpc.serviceObtain(fieldInjectedClass, referenceConfig);
setFieldValue(field, targetObject, fieldInjectedObject);
} catch (Exception ex) {
LOG.error("Can not inject rpc service in " + targetObject.getClass() + " by config " + rpcInject, ex);
}
}
/**
* 注入配置文件
*
* @param targetObject
* @param field
* @param configValue
* @throws IllegalAccessException
*/
private void doInjectConfigValue(Object targetObject, Field field, ConfigValue configValue) throws IllegalAccessException {
String key = AnnotationUtil.get(configValue.value());
Class<?> fieldInjectedClass = field.getType();
String value = JbootConfigManager.me().getConfigValue(key);
if (StrUtil.isNotBlank(value)) {
Object fieldInjectedObject = ConfigUtil.convert(fieldInjectedClass, value, field.getGenericType());
if (fieldInjectedObject != null) {
setFieldValue(field, targetObject, fieldInjectedObject);
}
}
}
/**
* 允许多次执行 AddMapping,方便在应用运行中可以切换 Mapping
*
* @param from
* @param to
* @param <T>
* @return
*/
@Override
public synchronized <T> AopFactory addMapping(Class<T> from, Class<? extends T> to) {
if (from == null || to == null) {
throw new IllegalArgumentException("The parameter from and to can not be null");
}
if (mapping == null) {
mapping = new HashMap<>(128, 0.25F);
}
Class mappingClass = mapping.get(from);
if (mappingClass != null) {
if (mappingClass == to) {
return this;
} else {
singletonCache.remove(mappingClass);
LogKit.warn("Aop Class[" + from + "] mapping changed from " + mappingClass + " to " + to);
}
}
mapping.put(from, to);
return this;
}
protected void setFieldValue(Field field, Object toObj, Object data) throws IllegalAccessException {
field.setAccessible(true);
field.set(toObj, data);
}
/**
* 初始化 @Bean 注解的映射关系
*/
private void initBeanMapping() {
// 添加映射
initBeansMapping();
// 初始化 @Configuration 里的 beans
initConfigurationBeansObject();
}
/**
* 添加 所有的 Bean 和实现类 的映射
*/
private void initBeansMapping() {
List<Class> classes = ClassScanner.scanClassByAnnotation(Bean.class, true);
for (Class implClass : classes) {
Bean bean = (Bean) implClass.getAnnotation(Bean.class);
String beanName = AnnotationUtil.get(bean.name());
if (StrUtil.isNotBlank(beanName)) {
if (beanNameClassesMapping.containsKey(beanName)) {
throw new JbootException("application has contains beanName \"" + beanName + "\" for " + getBean(beanName)
+ ", can not add for class " + implClass);
}
beanNameClassesMapping.put(beanName, implClass);
} else {
Class<?>[] interfaceClasses = implClass.getInterfaces();
if (interfaceClasses.length == 0) {
//add self
this.addMapping(implClass, implClass);
} else {
Class<?>[] excludes = buildExcludeClasses(implClass);
for (Class<?> interfaceClass : interfaceClasses) {
if (!inExcludes(interfaceClass, excludes)) {
this.addMapping(interfaceClass, implClass);
}
}
}
}
}
}
/**
* 初始化 @Configuration 里的 bean 配置
*/
private void initConfigurationBeansObject() {
List<Class> configurationClasses = ClassScanner.scanClassByAnnotation(Configuration.class, true);
for (Class<?> configurationClass : configurationClasses) {
Object configurationObj = ClassUtil.newInstance(configurationClass, false);
if (configurationObj == null) {
throw new NullPointerException("can not newInstance for class : " + configurationClass);
}
Method[] methods = configurationClass.getDeclaredMethods();
for (Method method : methods) {
Bean bean = method.getAnnotation(Bean.class);
if (bean != null) {
String beanName = StrUtil.obtainDefault(AnnotationUtil.get(bean.name()), method.getName());
if (beansCache.containsKey(beanName)) {
throw new JbootException("application has contains beanName \"" + beanName + "\" for " + getBean(beanName)
+ ", can not add again by method:" + ClassUtil.buildMethodString(method));
}
Object methodObj = null;
try {
methodObj = method.invoke(configurationObj);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (methodObj != null) {
inject(methodObj);
beansCache.put(beanName, methodObj);
//空注解
if (StrUtil.isBlank(bean.name())) {
singletonCache.put(method.getReturnType(), methodObj);
// Class implClass = ClassUtil.getUsefulClass(methodObj.getClass());
//// Class<?>[] interfaceClasses = implClass.getInterfaces();
// Class<?>[] interfaceClasses = ClassUtil.getInterfaces(implClass);
// //add self
// this.addMapping(implClass, implClass);
//
// Class<?>[] excludes = buildExcludeClasses(implClass);
// for (Class<?> interfaceClass : interfaceClasses) {
// if (!inExcludes(interfaceClass, excludes)) {
// this.addMapping(interfaceClass, implClass);
// }
// }
}
}
}
}
}
}
private Class<?>[] buildExcludeClasses(Class<?> implClass) {
BeanExclude beanExclude = implClass.getAnnotation(BeanExclude.class);
//对某些系统的类 进行排除,例如:Serializable 等
return beanExclude == null
? DEFAULT_EXCLUDES_MAPPING_CLASSES
: ArrayUtil.concat(DEFAULT_EXCLUDES_MAPPING_CLASSES, beanExclude.value());
}
private boolean inExcludes(Class interfaceClass, Class[] excludes) {
for (Class ex : excludes) {
if (ex.isAssignableFrom(interfaceClass)) {
return true;
}
}
return false;
}
public <T> T getBean(String name) {
return (T) beansCache.get(name);
}
public void setBean(String name, Object obj) {
beansCache.put(name, obj);
}
}
| optimize @Configuration init
| src/main/java/io/jboot/aop/JbootAopFactory.java | optimize @Configuration init |
|
Java | apache-2.0 | fe475da4a9c01d165176cd1983102032009ec1ca | 0 | vadmeste/minio-java,balamurugana/minio-java,minio/minio-java | /*
* Minio Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2015, 2016, 2017, 2018 Minio, 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.
*/
import java.security.*;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
import java.util.concurrent.TimeUnit;
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.joda.time.DateTime;
import okhttp3.OkHttpClient;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.MultipartBody;
import okhttp3.Response;
import io.minio.*;
import io.minio.messages.*;
import io.minio.errors.*;
@SuppressFBWarnings(value = "REC", justification = "Allow catching super class Exception since it's tests")
public class FunctionalTest {
private static final String PASS = "PASS";
private static final String FAILED = "FAIL";
private static final String IGNORED = "NA";
private static final int MB = 1024 * 1024;
private static final Random random = new Random(new SecureRandom().nextLong());
private static final String customContentType = "application/javascript";
private static final String nullContentType = null;
private static String bucketName = getRandomName();
private static boolean mintEnv = false;
private static Path dataFile1Mb;
private static Path dataFile65Mb;
private static String endpoint;
private static String accessKey;
private static String secretKey;
private static String region;
private static MinioClient client = null;
/**
* Do no-op.
*/
public static void ignore(Object ...args) {
}
/**
* Create given sized file and returns its name.
*/
public static String createFile(int size) throws IOException {
String filename = getRandomName();
try (OutputStream os = Files.newOutputStream(Paths.get(filename), CREATE, APPEND)) {
int totalBytesWritten = 0;
int bytesToWrite = 0;
byte[] buf = new byte[1 * MB];
while (totalBytesWritten < size) {
random.nextBytes(buf);
bytesToWrite = size - totalBytesWritten;
if (bytesToWrite > buf.length) {
bytesToWrite = buf.length;
}
os.write(buf, 0, bytesToWrite);
totalBytesWritten += bytesToWrite;
}
}
return filename;
}
/**
* Create 1 MB temporary file.
*/
public static String createFile1Mb() throws IOException {
if (mintEnv) {
String filename = getRandomName();
Files.createSymbolicLink(Paths.get(filename).toAbsolutePath(), dataFile1Mb);
return filename;
}
return createFile(1 * MB);
}
/**
* Create 65 MB temporary file.
*/
public static String createFile65Mb() throws IOException {
if (mintEnv) {
String filename = getRandomName();
Files.createSymbolicLink(Paths.get(filename).toAbsolutePath(), dataFile65Mb);
return filename;
}
return createFile(65 * MB);
}
/**
* Generate random name.
*/
public static String getRandomName() {
return "minio-java-test-" + new BigInteger(32, random).toString(32);
}
/**
* Returns byte array contains all data in given InputStream.
*/
public static byte[] readAllBytes(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
}
/**
* Prints a success log entry in JSON format.
*/
public static void mintSuccessLog(String function, String args, long startTime) {
if (mintEnv) {
System.out.println(new MintLogger(function, args, System.currentTimeMillis() - startTime,
PASS, null, null, null));
}
}
/**
* Prints a failure log entry in JSON format.
*/
public static void mintFailedLog(String function, String args, long startTime, String message, String error) {
if (mintEnv) {
System.out.println(new MintLogger(function, args, System.currentTimeMillis() - startTime,
FAILED, null, message, error));
}
}
/**
* Prints a ignore log entry in JSON format.
*/
public static void mintIgnoredLog(String function, String args, long startTime) {
if (mintEnv) {
System.out.println(new MintLogger(function, args, System.currentTimeMillis() - startTime,
IGNORED, null, null, null));
}
}
/**
* Read object content of the given url.
*/
public static byte[] readObject(String urlString) throws Exception {
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("GET", null)
.build();
OkHttpClient transport = new OkHttpClient().newBuilder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
Response response = transport.newCall(request).execute();
if (response == null) {
throw new Exception("empty response");
}
if (!response.isSuccessful()) {
String errorXml = "";
// read entire body stream to string.
Scanner scanner = new Scanner(response.body().charStream());
scanner.useDelimiter("\\A");
if (scanner.hasNext()) {
errorXml = scanner.next();
}
scanner.close();
response.body().close();
throw new Exception("failed to read object. Response: " + response + ", Response body: " + errorXml);
}
return readAllBytes(response.body().byteStream());
}
/**
* Write data to given object url.
*/
public static void writeObject(String urlString, byte[] dataBytes) throws Exception {
Request.Builder requestBuilder = new Request.Builder();
// Set header 'x-amz-acl' to 'bucket-owner-full-control', so objects created
// anonymously, can be downloaded by bucket owner in AWS S3.
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("PUT", RequestBody.create(null, dataBytes))
.addHeader("x-amz-acl", "bucket-owner-full-control")
.build();
OkHttpClient transport = new OkHttpClient().newBuilder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
Response response = transport.newCall(request).execute();
if (response == null) {
throw new Exception("empty response");
}
if (!response.isSuccessful()) {
String errorXml = "";
// read entire body stream to string.
Scanner scanner = new Scanner(response.body().charStream());
scanner.useDelimiter("\\A");
if (scanner.hasNext()) {
errorXml = scanner.next();
}
scanner.close();
response.body().close();
throw new Exception("failed to create object. Response: " + response + ", Response body: " + errorXml);
}
}
/**
* Test: makeBucket(String bucketName).
*/
public static void makeBucket_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: makeBucket(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(name);
client.removeBucket(name);
mintSuccessLog("makeBucket(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("makeBucket(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: makeBucket(String bucketName, String region).
*/
public static void makeBucketwithRegion_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: makeBucket(String bucketName, String region)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(name, "eu-west-1");
client.removeBucket(name);
mintSuccessLog("makeBucket(String bucketName, String region)", "region: eu-west-1", startTime);
} catch (Exception e) {
mintFailedLog("makeBucket(String bucketName, String region)", "region: eu-west-1", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: makeBucket(String bucketName, String region) where bucketName has
* periods in its name.
*/
public static void makeBucketWithPeriod_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: makeBucket(String bucketName, String region)");
}
long startTime = System.currentTimeMillis();
String name = getRandomName() + ".withperiod";
try {
client.makeBucket(name, "eu-central-1");
client.removeBucket(name);
mintSuccessLog("makeBucket(String bucketName, String region)",
"name: " + name + ", region: eu-central-1", startTime);
} catch (Exception e) {
mintFailedLog("makeBucket(String bucketName, String region)", "name: " + name + ", region: eu-central-1",
startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listBuckets().
*/
public static void listBuckets_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: listBuckets()");
}
long startTime = System.currentTimeMillis();
try {
Date expectedTime = new Date();
String bucketName = getRandomName();
boolean found = false;
client.makeBucket(bucketName);
for (Bucket bucket : client.listBuckets()) {
if (bucket.name().equals(bucketName)) {
if (found) {
throw new Exception("[FAILED] duplicate entry " + bucketName + " found in list buckets");
}
found = true;
Date time = bucket.creationDate();
long diff = time.getTime() - expectedTime.getTime();
// excuse 15 minutes
if (diff > (15 * 60 * 1000)) {
throw new Exception("[FAILED] bucket creation time too apart. expected: " + expectedTime
+ ", got: " + time);
}
}
}
client.removeBucket(bucketName);
if (!found) {
throw new Exception("[FAILED] created bucket not found in list buckets");
}
mintSuccessLog("listBuckets()", null, startTime);
} catch (Exception e) {
mintFailedLog("listBuckets()", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: bucketExists(String bucketName).
*/
public static void bucketExists_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: bucketExists(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(name);
if (!client.bucketExists(name)) {
throw new Exception("[FAILED] bucket does not exist");
}
client.removeBucket(name);
mintSuccessLog("bucketExists(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("bucketExists(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeBucket(String bucketName).
*/
public static void removeBucket_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: removeBucket(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(name);
client.removeBucket(name);
mintSuccessLog("removeBucket(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeBucket(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Tear down test setup.
*/
public static void setup() throws Exception {
client.makeBucket(bucketName);
}
/**
* Tear down test setup.
*/
public static void teardown() throws Exception {
client.removeBucket(bucketName);
}
/**
* Test: putObject(String bucketName, String objectName, String filename).
*/
public static void putObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, String filename)");
}
long startTime = System.currentTimeMillis();
try {
String filename = createFile1Mb();
client.putObject(bucketName, filename, filename);
Files.delete(Paths.get(filename));
client.removeObject(bucketName, filename);
mintSuccessLog("putObject(String bucketName, String objectName, String filename)", "filename: 1MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, String filename)", "filename: 1MB", startTime,
null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: multipart: putObject(String bucketName, String objectName, String filename).
*/
public static void putObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: multipart: putObject(String bucketName, String objectName, String filename)");
}
long startTime = System.currentTimeMillis();
try {
String filename = createFile65Mb();
client.putObject(bucketName, filename, filename);
Files.delete(Paths.get(filename));
client.removeObject(bucketName, filename);
mintSuccessLog("putObject(String bucketName, String objectName, String filename)", "filename: 65MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, String filename)", "filename: 65MB", startTime,
null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: With content-type: putObject(String bucketName, String objectName, String filename, String contentType).
*/
public static void putObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, String filename,"
+ " String contentType)");
}
long startTime = System.currentTimeMillis();
try {
String filename = createFile1Mb();
client.putObject(bucketName, filename, filename, customContentType);
Files.delete(Paths.get(filename));
client.removeObject(bucketName, filename);
mintSuccessLog("putObject(String bucketName, String objectName, String filename, String contentType)",
"contentType: " + customContentType, startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, String filename, String contentType)",
"contentType: " + customContentType, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream body, long size, String contentType).
*/
public static void putObject_test4() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream body, "
+ "long size, String contentType)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, customContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, long size,"
+ " String contentType)",
"size: 1 MB, objectName: " + customContentType, startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size, String contentType)",
"size: 1 MB, objectName: " + customContentType, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: multipart resume: putObject(String bucketName, String objectName, InputStream body, long size,
* String contentType).
*/
public static void putObject_test5() throws Exception {
if (!mintEnv) {
System.out.println("Test: multipart resume: putObject(String bucketName, String objectName, InputStream body, "
+ "long size, String contentType)");
}
long startTime = System.currentTimeMillis();
long size = 20 * MB;
try {
String objectName = getRandomName();
try (InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, size, nullContentType);
} catch (EOFException e) {
ignore();
}
size = 13 * MB;
try (final InputStream is = new ContentInputStream(size)) {
client.putObject(bucketName, objectName, is, size, nullContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, long size,"
+ " String contentType)",
"contentType: " + nullContentType + ", size: " + String.valueOf(size), startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size, String contentType)",
"contentType: " + nullContentType + ", size: " + String.valueOf(size), startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream body, long size, String contentType).
* where objectName has multiple path segments.
*/
public static void putObject_test6() throws Exception {
if (!mintEnv) {
System.out.println("Test: objectName with path segments: "
+ "putObject(String bucketName, String objectName, InputStream body, "
+ "long size, String contentType)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = "/path/to/" + getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, customContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, long size,"
+ " String contentType)",
"size: 1 MB, contentType: " + customContentType, startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size,"
+ " String contentType)",
"size: 1 MB, contentType: " + customContentType, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test put object with unknown sized stream.
*/
public static void testPutObjectUnknownStreamSize(long size) throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream body, "
+ "String contentType)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(size)) {
client.putObject(bucketName, objectName, is, customContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, String contentType)",
"contentType: " + customContentType, startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size, String contentType)",
"contentType: " + customContentType, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream body, String contentType).
*/
public static void putObject_test7() throws Exception {
testPutObjectUnknownStreamSize(3 * MB);
}
/**
* Test: multipart: putObject(String bucketName, String objectName, InputStream body, String contentType).
*/
public static void putObject_test8() throws Exception {
testPutObjectUnknownStreamSize(537 * MB);
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* Map<String, String> headerMap).
*/
public static void putObject_test9() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap).");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
try (final InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, 13 * MB, headerMap);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* Map<String, String> headerMap) with Storage Class REDUCED_REDUNDANCY.
*/
@SuppressFBWarnings("UCF")
public static void putObject_test10() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap). with Storage Class REDUCED_REDUNDANCY set");
}
long startTime = System.currentTimeMillis();
try {
String storageClass = "REDUCED_REDUNDANCY";
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
headerMap.put("X-Amz-Storage-Class", storageClass);
try (final InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, 13 * MB, headerMap);
}
ObjectStat objectStat = client.statObject(bucketName, objectName);
Map<String, List<String>> returnHeader = objectStat.httpHeaders();
List<String> returnStorageClass = returnHeader.get("X-Amz-Storage-Class");
if ((returnStorageClass != null) && (!storageClass.equals(returnStorageClass.get(0)))) {
throw new Exception("Metadata mismatch");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* Map<String, String> headerMap) with Storage Class STANDARD.
*/
public static void putObject_test11() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap). with Storage Class STANDARD set");
}
long startTime = System.currentTimeMillis();
try {
String storageClass = "STANDARD";
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
headerMap.put("X-Amz-Storage-Class", storageClass);
try (final InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, 13 * MB, headerMap);
}
ObjectStat objectStat = client.statObject(bucketName, objectName);
Map<String, List<String>> returnHeader = objectStat.httpHeaders();
List<String> returnStorageClass = returnHeader.get("X-Amz-Storage-Class");
// Standard storage class shouldn't be present in metadata response
if (returnStorageClass != null) {
throw new Exception("Did not expect: " + storageClass + " in response metadata");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* Map<String, String> headerMap). with invalid Storage Class set
*/
public static void putObject_test12() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap). with invalid Storage Class set");
}
long startTime = System.currentTimeMillis();
try {
String storageClass = "INVALID";
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
headerMap.put("X-Amz-Storage-Class", storageClass);
try (final InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, 13 * MB, headerMap);
} catch (ErrorResponseException e) {
if (!e.errorResponse().code().equals("InvalidStorageClass")) {
throw e;
}
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* ServerSideEncryption sse). To test SSE_C
*/
public static void putObject_test13() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C. ");
}
long startTime = System.currentTimeMillis();
// Generate a new 256 bit AES key - This key must be remembered by the client.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, sse);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C.",
"size: 1 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C.",
"size: 1 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* ServerSideEncryption sse). To test SSE_S3
*/
public static void putObject_test14() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_S3.");
}
long startTime = System.currentTimeMillis();
ServerSideEncryption sse = ServerSideEncryption.atRest();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, sse);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_S3.",
"size: 1 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_S3.",
"size: 1 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* ServerSideEncryption sse). To test SSE_KMS
*/
public static void putObject_test15() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_KMS.");
}
long startTime = System.currentTimeMillis();
Map<String,String> myContext = new HashMap<>();
myContext.put("key1","value1");
String keyId = "";
keyId = System.getenv("MINT_KEY_ID");
if (keyId.equals("")) {
mintIgnoredLog("getBucketPolicy(String bucketName)", null, startTime);
}
ServerSideEncryption sse = ServerSideEncryption.withManagedKeys("keyId", myContext);
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, sse);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_KMS.",
"size: 1 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_KMS.",
"size: 1 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* ServerSideEncryption sse). To test SSE_C (multi-part upload).
*/
public static void putObject_test16() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C (Multi-part upload). ");
}
long startTime = System.currentTimeMillis();
// Generate a new 256 bit AES key - This key must be remembered by the client.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 6 * MB, sse);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C (Multi-part upload).",
"size: 6 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C (Multi-part upload).",
"size: 6 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: statObject(String bucketName, String objectName).
*/
public static void statObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: statObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
headerMap.put("x-amz-meta-my-custom-data", "foo");
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, headerMap);
}
ObjectStat objectStat = client.statObject(bucketName, objectName);
if (!(objectName.equals(objectStat.name()) && (objectStat.length() == 1)
&& bucketName.equals(objectStat.bucketName()) && objectStat.contentType().equals(customContentType))) {
throw new Exception("[FAILED] object stat differs");
}
Map<String, List<String>> httpHeaders = objectStat.httpHeaders();
if (!httpHeaders.containsKey("x-amz-meta-my-custom-data")) {
throw new Exception("[FAILED] metadata not found in object stat");
}
List<String> values = httpHeaders.get("x-amz-meta-my-custom-data");
if (values.size() != 1) {
throw new Exception("[FAILED] too many metadata value. expected: 1, got: " + values.size());
}
if (!values.get(0).equals("foo")) {
throw new Exception("[FAILED] wrong metadata value. expected: foo, got: " + values.get(0));
}
client.removeObject(bucketName, objectName);
mintSuccessLog("statObject(String bucketName, String objectName)",null, startTime);
} catch (Exception e) {
mintFailedLog("statObject(String bucketName, String objectName)",null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: statObject(String bucketName, String objectName, ServerSideEncryption sse).
* To test statObject using SSE_C.
*/
public static void statObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: statObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
// Generate a new 256 bit AES key - This key must be remembered by the client.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, sse);
}
ObjectStat objectStat = client.statObject(bucketName, objectName, sse);
if (!(objectName.equals(objectStat.name()) && (objectStat.length() == 1)
&& bucketName.equals(objectStat.bucketName()))) {
throw new Exception("[FAILED] object stat differs");
}
Map<String, List<String>> httpHeaders = objectStat.httpHeaders();
if (!httpHeaders.containsKey("X-Amz-Server-Side-Encryption-Customer-Algorithm")) {
throw new Exception("[FAILED] metadata not found in object stat");
}
List<String> values = httpHeaders.get("X-Amz-Server-Side-Encryption-Customer-Algorithm");
if (values.size() != 1) {
throw new Exception("[FAILED] too many metadata value. expected: 1, got: " + values.size());
}
if (!values.get(0).equals("AES256")) {
throw new Exception("[FAILED] wrong metadata value. expected: AES256, got: " + values.get(0));
}
client.removeObject(bucketName, objectName);
mintSuccessLog("statObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.",null, startTime);
} catch (Exception e) {
mintFailedLog("statObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.",null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName).
*/
public static void getObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName)",null, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName)",null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, long offset).
*/
public static void getObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName, long offset)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName, 1000L)
.close();
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, long offset)", "offset: 1000", startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, long offset)", "offset: 1000", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, long offset, Long length).
*/
public static void getObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName, long offset, Long length)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName, 1000L, 1024 * 1024L)
.close();
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, long offset, Long length)",
"offset: 1000, length: 1 MB", startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, long offset, Long length)",
"offset: 1000, length: 1 MB", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, String filename).
*/
public static void getObject_test4() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName, String filename)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName, objectName + ".downloaded");
Files.delete(Paths.get(objectName + ".downloaded"));
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, String filename)", null, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, String filename)",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, String filename).
* where objectName has multiple path segments.
*/
public static void getObject_test5() throws Exception {
if (!mintEnv) {
System.out.println("Test: objectName with multiple path segments: "
+ "getObject(String bucketName, String objectName, String filename)");
}
long startTime = System.currentTimeMillis();
String baseObjectName = getRandomName();
String objectName = "path/to/" + baseObjectName;
try {
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName, baseObjectName + ".downloaded");
Files.delete(Paths.get(baseObjectName + ".downloaded"));
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, String filename)",
"objectName: " + objectName, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, String filename)",
"objectName: " + objectName, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName) zero size object.
*/
public static void getObject_test6() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName) zero size object");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(0)) {
client.putObject(bucketName, objectName, is, 0, nullContentType);
}
client.getObject(bucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, ServerSideEncryption sse).
* To test getObject when object is put using SSE_C.
*/
public static void getObject_test7() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName, ServerSideEncryption sse) using SSE_C");
}
long startTime = System.currentTimeMillis();
// Generate a new 256 bit AES key - This key must be remembered by the client.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
try {
String objectName = getRandomName();
String putString;
int bytes_read_put;
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, sse);
byte [] putbyteArray = new byte[is.available()];
bytes_read_put = is.read(putbyteArray);
putString = new String(putbyteArray, StandardCharsets.UTF_8);
}
InputStream stream = client.getObject(bucketName, objectName, sse);
byte [] getbyteArray = new byte[stream.available()];
int bytes_read_get = stream.read(getbyteArray);
String getString = new String(getbyteArray, StandardCharsets.UTF_8);
stream.close();
//client.getObject(bucketName, objectName, sse)
// .close();
// Compare if contents received are same as the initial uploaded object.
if ((!putString.equals(getString)) || (bytes_read_put != bytes_read_get) ) {
throw new Exception("Contents received from getObject doesn't match initial contents.");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.",null, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.",null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, long offset, Long length) with offset=0.
*/
public static void getObject_test8() throws Exception {
if (!mintEnv) {
System.out.println(
"Test: getObject(String bucketName, String objectName, long offset, Long length) with offset=0"
);
}
final long startTime = System.currentTimeMillis();
final int fullLength = 1024;
final int partialLength = 256;
final long offset = 0L;
final String objectName = getRandomName();
try {
try (final InputStream is = new ContentInputStream(fullLength)) {
client.putObject(bucketName, objectName, is, fullLength, nullContentType);
}
try (
final InputStream partialObjectStream = client.getObject(
bucketName,
objectName,
offset,
Long.valueOf(partialLength)
)
) {
byte[] result = new byte[fullLength];
final int read = partialObjectStream.read(result);
result = Arrays.copyOf(result, read);
if (result.length != partialLength) {
throw new Exception(
String.format(
"Expecting only the first %d bytes from partial getObject request; received %d bytes instead.",
partialLength,
read
)
);
}
}
client.removeObject(bucketName, objectName);
mintSuccessLog(
"getObject(String bucketName, String objectName, long offset, Long length) with offset=0",
String.format("offset: %d, length: %d bytes", offset, partialLength),
startTime
);
} catch (final Exception e) {
mintFailedLog(
"getObject(String bucketName, String objectName, long offset, Long length) with offset=0",
String.format("offset: %d, length: %d bytes", offset, partialLength),
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace())
);
throw e;
}
}
/**
* Test: listObjects(final String bucketName).
*/
public static void listObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: listObjects(final String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[3];
int i = 0;
for (i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName)) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listObjects(bucketName, final String prefix).
*/
public static void listObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: listObjects(final String bucketName, final String prefix)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[3];
int i = 0;
for (i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName, "minio")) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName, final String prefix)", "prefix :minio", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix)", "prefix :minio", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listObjects(bucketName, final String prefix, final boolean recursive).
*/
public static void listObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: listObjects(final String bucketName, final String prefix, final boolean recursive)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[3];
int i = 0;
for (i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName, "minio", true)) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minio, recursive: true", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minio, recursive: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listObjects(final string bucketName).
*/
public static void listObject_test4() throws Exception {
if (!mintEnv) {
System.out.println("Test: empty bucket: listObjects(final String bucketName, final String prefix,"
+ " final boolean recursive)");
}
long startTime = System.currentTimeMillis();
try {
int i = 0;
for (Result<?> r : client.listObjects(bucketName, "minioemptybucket", true)) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
mintSuccessLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minioemptybucket, recursive: true", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minioemptybucket, recursive: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: recursive: listObjects(bucketName, final String prefix, final boolean recursive).
*/
public static void listObject_test5() throws Exception {
if (!mintEnv) {
System.out.println("Test: recursive: listObjects(final String bucketName, final String prefix, "
+ "final boolean recursive)");
}
long startTime = System.currentTimeMillis();
try {
int objCount = 1050;
String[] objectNames = new String[objCount];
int i = 0;
for (i = 0; i < objCount; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName, "minio", true)) {
ignore(i++, r.get());
}
// Check the number of uploaded objects
if (i != objCount) {
throw new Exception("item count differs, expected: " + objCount + ", got: " + i);
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minio, recursive: true", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minio, recursive: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listObjects(bucketName, final String prefix, final boolean recursive, final boolean useVersion1).
*/
public static void listObject_test6() throws Exception {
if (!mintEnv) {
System.out.println("Test: listObjects(final String bucketName, final String prefix, final boolean recursive, "
+ "final boolean useVersion1)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[3];
int i = 0;
for (i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName, "minio", true, true)) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName, final String prefix, "
+ "final boolean recursive, final boolean useVersion1)",
"prefix :minio, recursive: true, useVersion1: true", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix, "
+ "final boolean recursive, final boolean useVersion1)",
"prefix :minio, recursive: true, useVersion1: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeObject(String bucketName, String objectName).
*/
public static void removeObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: removeObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, nullContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("removeObject(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeObject(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeObject(final String bucketName, final Iterable<String> objectNames).
*/
public static void removeObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: removeObject(final String bucketName, final Iterable<String> objectNames)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[4];
for (int i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
objectNames[3] = "nonexistent-object";
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("removeObject(final String bucketName, final Iterable<String> objectNames)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeObject(final String bucketName, final Iterable<String> objectNames)",
null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listIncompleteUploads(String bucketName).
*/
public static void listIncompleteUploads_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: listIncompleteUploads(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 9 * MB, nullContentType);
} catch (EOFException e) {
ignore();
}
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
ignore(i++, r.get());
if (i == 10) {
break;
}
}
client.removeIncompleteUpload(bucketName, objectName);
mintSuccessLog("listIncompleteUploads(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("listIncompleteUploads(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listIncompleteUploads(String bucketName, String prefix).
*/
public static void listIncompleteUploads_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: listIncompleteUploads(String bucketName, String prefix)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 9 * MB, nullContentType);
} catch (EOFException e) {
ignore();
}
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio")) {
ignore(i++, r.get());
if (i == 10) {
break;
}
}
client.removeIncompleteUpload(bucketName, objectName);
mintSuccessLog("listIncompleteUploads(String bucketName, String prefix)", null, startTime);
} catch (Exception e) {
mintFailedLog("listIncompleteUploads(String bucketName, String prefix)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive).
*/
public static void listIncompleteUploads_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: listIncompleteUploads(final String bucketName, final String prefix, "
+ "final boolean recursive)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 9 * MB, nullContentType);
} catch (EOFException e) {
ignore();
}
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio", true)) {
ignore(i++, r.get());
if (i == 10) {
break;
}
}
client.removeIncompleteUpload(bucketName, objectName);
mintSuccessLog("listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)",
"prefix: minio, recursive: true", startTime);
} catch (Exception e) {
mintFailedLog("listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)",
"prefix: minio, recursive: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeIncompleteUpload(String bucketName, String objectName).
*/
public static void removeIncompleteUploads_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: removeIncompleteUpload(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 9 * MB, nullContentType);
} catch (EOFException e) {
ignore();
}
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
ignore(i++, r.get());
if (i == 10) {
break;
}
}
client.removeIncompleteUpload(bucketName, objectName);
mintSuccessLog("removeIncompleteUpload(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeIncompleteUpload(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* public String presignedGetObject(String bucketName, String objectName).
*/
public static void presignedGetObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedGetObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
byte[] inBytes;
try (final InputStream is = new ContentInputStream(3 * MB)) {
inBytes = readAllBytes(is);
}
String urlString = client.presignedGetObject(bucketName, objectName);
byte[] outBytes = readObject(urlString);
if (!Arrays.equals(inBytes, outBytes)) {
throw new Exception("object content differs");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedGetObject(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedGetObject(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: presignedGetObject(String bucketName, String objectName, Integer expires).
*/
public static void presignedGetObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedGetObject(String bucketName, String objectName, Integer expires)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
byte[] inBytes;
try (final InputStream is = new ContentInputStream(3 * MB)) {
inBytes = readAllBytes(is);
}
String urlString = client.presignedGetObject(bucketName, objectName, 3600);
byte[] outBytes = readObject(urlString);
if (!Arrays.equals(inBytes, outBytes)) {
throw new Exception("object content differs");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedGetObject(String bucketName, String objectName, Integer expires)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedGetObject(String bucketName, String objectName, Integer expires)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* public String presignedGetObject(String bucketName, String objectName, Integer expires, Map reqParams).
*/
public static void presignedGetObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedGetObject(String bucketName, String objectName, Integer expires, "
+ "Map<String, String> reqParams)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
byte[] inBytes;
try (final InputStream is = new ContentInputStream(3 * MB)) {
inBytes = readAllBytes(is);
}
Map<String, String> reqParams = new HashMap<>();
reqParams.put("response-content-type", "application/json");
String urlString = client.presignedGetObject(bucketName, objectName, 3600, reqParams);
byte[] outBytes = readObject(urlString);
if (!Arrays.equals(inBytes, outBytes)) {
throw new Exception("object content differs");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedGetObject(String bucketName, String objectName, Integer expires, Map<String,"
+ " String> reqParams)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedGetObject(String bucketName, String objectName, Integer expires, Map<String,"
+ " String> reqParams)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* public String presignedPutObject(String bucketName, String objectName).
*/
public static void presignedPutObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedPutObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
String urlString = client.presignedPutObject(bucketName, objectName);
byte[] data = "hello, world".getBytes(StandardCharsets.UTF_8);
writeObject(urlString, data);
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedPutObject(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedPutObject(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: presignedPutObject(String bucketName, String objectName, Integer expires).
*/
public static void presignedPutObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
String urlString = client.presignedPutObject(bucketName, objectName, 3600);
byte[] data = "hello, world".getBytes(StandardCharsets.UTF_8);
writeObject(urlString, data);
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedPutObject(String bucketName, String objectName, Integer expires)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedPutObject(String bucketName, String objectName, Integer expires)", null, startTime,
null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: presignedPostPolicy(PostPolicy policy).
*/
public static void presignedPostPolicy_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedPostPolicy(PostPolicy policy)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
PostPolicy policy = new PostPolicy(bucketName, objectName, DateTime.now().plusDays(7));
policy.setContentRange(1 * MB, 4 * MB);
Map<String, String> formData = client.presignedPostPolicy(policy);
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
for (Map.Entry<String, String> entry : formData.entrySet()) {
multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
try (final InputStream is = new ContentInputStream(3 * MB)) {
multipartBuilder.addFormDataPart("file", objectName, RequestBody.create(null, readAllBytes(is)));
}
Request.Builder requestBuilder = new Request.Builder();
String urlString = client.getObjectUrl(bucketName, "");
Request request = requestBuilder.url(urlString).post(multipartBuilder.build()).build();
OkHttpClient transport = new OkHttpClient().newBuilder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
Response response = transport.newCall(request).execute();
if (response == null) {
throw new Exception("no response from server");
}
if (!response.isSuccessful()) {
String errorXml = "";
// read entire body stream to string.
Scanner scanner = new Scanner(response.body().charStream());
scanner.useDelimiter("\\A");
if (scanner.hasNext()) {
errorXml = scanner.next();
}
scanner.close();
throw new Exception("failed to upload object. Response: " + response + ", Error: " + errorXml);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedPostPolicy(PostPolicy policy)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedPostPolicy(PostPolicy policy)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: PutObject(): do put object using multi-threaded way in parallel.
*/
public static void threadedPutObject() throws Exception {
if (!mintEnv) {
System.out.println("Test: threadedPutObject");
}
long startTime = System.currentTimeMillis();
try {
Thread[] threads = new Thread[7];
for (int i = 0; i < 7; i++) {
threads[i] = new Thread(new PutObjectRunnable(client, bucketName, createFile65Mb()));
}
for (int i = 0; i < 7; i++) {
threads[i].start();
}
// Waiting for threads to complete.
for (int i = 0; i < 7; i++) {
threads[i].join();
}
// All threads are completed.
mintSuccessLog("putObject(String bucketName, String objectName, String filename)",
"filename: threaded65MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, String filename)",
"filename: threaded65MB", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName).
*/
public static void copyObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
client.copyObject(bucketName, objectName, destBucketName);
client.getObject(destBucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with ETag to match.
*/
public static void copyObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with Matching ETag (Negative Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions invalidETag = new CopyConditions();
invalidETag.setMatchETag("TestETag");
try {
client.copyObject(bucketName, objectName, destBucketName, invalidETag);
} catch (ErrorResponseException e) {
if (!e.errorResponse().code().equals("PreconditionFailed")) {
throw e;
}
}
client.removeObject(bucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ " CopyConditions copyConditions)", "CopyConditions: invalidETag",startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyConditions: invalidETag", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with ETag to match.
*/
public static void copyObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with Matching ETag (Positive Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
ObjectStat stat = client.statObject(bucketName, objectName);
CopyConditions copyConditions = new CopyConditions();
copyConditions.setMatchETag(stat.etag());
// File should be copied as ETag set in copyConditions matches object's ETag.
client.copyObject(bucketName, objectName, destBucketName, copyConditions);
client.getObject(destBucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ " CopyConditions copyConditions)", null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ " CopyConditions copyConditions)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with ETag to not match.
*/
public static void copyObject_test4() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with not matching ETag"
+ " (Positive Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions copyConditions = new CopyConditions();
copyConditions.setMatchETagNone("TestETag");
// File should be copied as ETag set in copyConditions doesn't match object's ETag.
client.copyObject(bucketName, objectName, destBucketName, copyConditions);
client.getObject(destBucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ " CopyConditions copyConditions)", null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions)",
null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with ETag to not match.
*/
public static void copyObject_test5() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with not matching ETag"
+ " (Negative Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
ObjectStat stat = client.statObject(bucketName, objectName);
CopyConditions matchingETagNone = new CopyConditions();
matchingETagNone.setMatchETagNone(stat.etag());
try {
client.copyObject(bucketName, objectName, destBucketName, matchingETagNone);
} catch (ErrorResponseException e) {
// File should not be copied as ETag set in copyConditions matches object's ETag.
if (!e.errorResponse().code().equals("PreconditionFailed")) {
throw e;
}
}
client.removeObject(bucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)", null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with object modified after condition.
*/
public static void copyObject_test6() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with modified after "
+ "condition (Positive Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions modifiedDateCondition = new CopyConditions();
DateTime dateRepresentation = new DateTime(2015, Calendar.MAY, 3, 10, 10);
modifiedDateCondition.setModified(dateRepresentation);
// File should be copied as object was modified after the set date.
client.copyObject(bucketName, objectName, destBucketName, modifiedDateCondition);
client.getObject(destBucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyCondition: modifiedDateCondition", startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyCondition: modifiedDateCondition", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with object modified after condition.
*/
public static void copyObject_test7() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with modified after"
+ " condition (Negative Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions invalidUnmodifiedCondition = new CopyConditions();
DateTime dateRepresentation = new DateTime(2015, Calendar.MAY, 3, 10, 10);
invalidUnmodifiedCondition.setUnmodified(dateRepresentation);
try {
client.copyObject(bucketName, objectName, destBucketName, invalidUnmodifiedCondition);
} catch (ErrorResponseException e) {
// File should not be copied as object was modified after date set in copyConditions.
if (!e.errorResponse().code().equals("PreconditionFailed")) {
throw e;
}
}
client.removeObject(bucketName, objectName);
// Destination bucket is expected to be empty, otherwise it will trigger an exception.
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyCondition: invalidUnmodifiedCondition", startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyCondition: invalidUnmodifiedCondition", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions, Map metadata) replace
* object metadata.
*/
public static void copyObject_test8() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions, Map<String, String> metadata)"
+ " replace object metadata");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, "application/octet-stream");
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
Map<String, String> metadata = new HashMap<>();
metadata.put("Content-Type", customContentType);
client.copyObject(bucketName, objectName, destBucketName, objectName, copyConditions, metadata);
ObjectStat objectStat = client.statObject(destBucketName, objectName);
if (!customContentType.equals(objectStat.contentType())) {
throw new Exception("content type differs. expected: " + customContentType + ", got: "
+ objectStat.contentType());
}
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions, Map<String, String> metadata)",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions, Map<String, String> metadata)",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions, Map metadata) remove
* object metadata.
*/
public static void copyObject_test9() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions, Map<String, String> metadata)"
+ " remove object metadata");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("X-Amz-Meta-Test", "testValue");
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, headerMap);
}
// Attempt to remove the user-defined metadata from the object
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
client.copyObject(bucketName, objectName, bucketName,
objectName, copyConditions, new HashMap<String,String>());
ObjectStat objectStat = client.statObject(bucketName, objectName);
if (objectStat.httpHeaders().containsKey("X-Amz-Meta-Test")) {
throw new Exception("expected user-defined metadata has been removed");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions, Map<String, String> metadata)",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions, Map<String, String> metadata)",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, String destBucketName,
* CopyConditions copyConditions, ServerSideEncryption sseTarget)
* To test using SSE_C.
*/
public static void copyObject_test10() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_C. ");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
// Generate a new 256 bit AES key - This key must be remembered by the client.
byte[] key = "01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
ServerSideEncryption ssePut = ServerSideEncryption.withCustomerKey(secretKeySpec);
ServerSideEncryption sseSource = ServerSideEncryption.copyWithCustomerKey(secretKeySpec);
byte[] keyTarget = "98765432100123456789012345678901".getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpecTarget = new SecretKeySpec(keyTarget, "AES");
ServerSideEncryption sseTarget = ServerSideEncryption.withCustomerKey(secretKeySpecTarget);
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, ssePut);
}
// Attempt to remove the user-defined metadata from the object
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
client.copyObject(bucketName, objectName, sseSource, bucketName,
objectName, copyConditions, sseTarget);
ObjectStat objectStat = client.statObject(bucketName, objectName, sseTarget);
client.removeObject(bucketName, objectName);
mintSuccessLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_C.",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_C.",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, String destBucketName,
* CopyConditions copyConditions, ServerSideEncryption sseTarget)
* To test using SSE_S3.
*/
public static void copyObject_test11() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_S3. ");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
ServerSideEncryption sse = ServerSideEncryption.atRest();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, sse);
}
// Attempt to remove the user-defined metadata from the object
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
client.copyObject(bucketName, objectName, null, bucketName,
objectName, copyConditions, sse);
ObjectStat objectStat = client.statObject(bucketName, objectName);
if (objectStat.httpHeaders().containsKey("X-Amz-Meta-Test")) {
throw new Exception("expected user-defined metadata has been removed");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_S3.",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_S3.",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, String destBucketName,
* CopyConditions copyConditions, ServerSideEncryption sseTarget)
* To test using SSE_KMS.
*/
public static void copyObject_test12() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_KMS. ");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
Map<String,String> myContext = new HashMap<>();
myContext.put("key1","value1");
String keyId = "";
keyId = System.getenv("MINT_KEY_ID");
if (keyId.equals("")) {
mintIgnoredLog("getBucketPolicy(String bucketName)", null, startTime);
}
ServerSideEncryption sse = ServerSideEncryption.withManagedKeys("keyId", myContext);
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, sse);
}
// Attempt to remove the user-defined metadata from the object
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
client.copyObject(bucketName, objectName, null, bucketName,
objectName, copyConditions, sse);
ObjectStat objectStat = client.statObject(bucketName, objectName);
if (objectStat.httpHeaders().containsKey("X-Amz-Meta-Test")) {
throw new Exception("expected user-defined metadata has been removed");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_KMS.",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_KMS.",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getBucketPolicy(String bucketName).
*/
public static void getBucketPolicy_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: getBucketPolicy(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:GetObject\"],\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":[\"*\"]},\"Resource\":[\"arn:aws:s3:::" + bucketName
+ "/myobject*\"],\"Sid\":\"\"}]}";
client.setBucketPolicy(bucketName, policy);
client.getBucketPolicy(bucketName);
mintSuccessLog("getBucketPolicy(String bucketName)", null, startTime);
} catch (Exception e) {
ErrorResponse errorResponse = null;
if (e instanceof ErrorResponseException) {
ErrorResponseException exp = (ErrorResponseException) e;
errorResponse = exp.errorResponse();
}
// Ignore NotImplemented error
if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) {
mintIgnoredLog("getBucketPolicy(String bucketName)", null, startTime);
} else {
mintFailedLog("getBucketPolicy(String bucketName)", null, startTime,
null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
}
/**
* Test: setBucketPolicy(String bucketName, String policy).
*/
public static void setBucketPolicy_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: setBucketPolicy(String bucketName, String policy)");
}
long startTime = System.currentTimeMillis();
try {
String policy = "{\"Statement\":[{\"Action\":\"s3:GetObject\",\"Effect\":\"Allow\",\"Principal\":"
+ "\"*\",\"Resource\":\"arn:aws:s3:::" + bucketName + "/myobject*\"}],\"Version\": \"2012-10-17\"}";
client.setBucketPolicy(bucketName, policy);
mintSuccessLog("setBucketPolicy(String bucketName, String policy)", null, startTime);
} catch (Exception e) {
ErrorResponse errorResponse = null;
if (e instanceof ErrorResponseException) {
ErrorResponseException exp = (ErrorResponseException) e;
errorResponse = exp.errorResponse();
}
// Ignore NotImplemented error
if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) {
mintIgnoredLog("setBucketPolicy(String bucketName, String objectPrefix, "
+ "PolicyType policyType)", null, startTime);
} else {
mintFailedLog("setBucketPolicy(String bucketName, String objectPrefix, "
+ "PolicyType policyType)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
}
/**
* Test: setBucketNotification(String bucketName, NotificationConfiguration notificationConfiguration).
*/
public static void setBucketNotification_test1() throws Exception {
// This test requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' environment variables.
String topic = System.getenv("MINIO_JAVA_TEST_TOPIC");
String region = System.getenv("MINIO_JAVA_TEST_REGION");
if (topic == null || topic.equals("") || region == null || region.equals("")) {
// do not run functional test as required environment variables are missing.
return;
}
if (!mintEnv) {
System.out.println("Test: setBucketNotification(String bucketName, "
+ "NotificationConfiguration notificationConfiguration)");
}
long startTime = System.currentTimeMillis();
try {
String destBucketName = getRandomName();
client.makeBucket(destBucketName, region);
NotificationConfiguration notificationConfiguration = new NotificationConfiguration();
// Add a new topic configuration.
List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList();
TopicConfiguration topicConfiguration = new TopicConfiguration();
topicConfiguration.setTopic(topic);
List<EventType> eventList = new LinkedList<>();
eventList.add(EventType.OBJECT_CREATED_PUT);
eventList.add(EventType.OBJECT_CREATED_COPY);
topicConfiguration.setEvents(eventList);
Filter filter = new Filter();
filter.setPrefixRule("images");
filter.setSuffixRule("pg");
topicConfiguration.setFilter(filter);
topicConfigurationList.add(topicConfiguration);
notificationConfiguration.setTopicConfigurationList(topicConfigurationList);
client.setBucketNotification(destBucketName, notificationConfiguration);
client.removeBucket(destBucketName);
mintSuccessLog("setBucketNotification(String bucketName, NotificationConfiguration notificationConfiguration)",
null, startTime);
} catch (Exception e) {
mintFailedLog("setBucketNotification(String bucketName, NotificationConfiguration notificationConfiguration)",
null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getBucketNotification(String bucketName).
*/
public static void getBucketNotification_test1() throws Exception {
// This test requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' environment variables.
String topic = System.getenv("MINIO_JAVA_TEST_TOPIC");
String region = System.getenv("MINIO_JAVA_TEST_REGION");
if (topic == null || topic.equals("") || region == null || region.equals("")) {
// do not run functional test as required environment variables are missing.
return;
}
if (!mintEnv) {
System.out.println("Test: getBucketNotification(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String destBucketName = getRandomName();
client.makeBucket(destBucketName, region);
NotificationConfiguration notificationConfiguration = new NotificationConfiguration();
// Add a new topic configuration.
List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList();
TopicConfiguration topicConfiguration = new TopicConfiguration();
topicConfiguration.setTopic(topic);
List<EventType> eventList = new LinkedList<>();
eventList.add(EventType.OBJECT_CREATED_PUT);
topicConfiguration.setEvents(eventList);
topicConfigurationList.add(topicConfiguration);
notificationConfiguration.setTopicConfigurationList(topicConfigurationList);
client.setBucketNotification(destBucketName, notificationConfiguration);
String expectedResult = notificationConfiguration.toString();
notificationConfiguration = client.getBucketNotification(destBucketName);
topicConfigurationList = notificationConfiguration.topicConfigurationList();
topicConfiguration = topicConfigurationList.get(0);
topicConfiguration.setId(null);
String result = notificationConfiguration.toString();
if (!result.equals(expectedResult)) {
System.out.println("FAILED. expected: " + expectedResult + ", got: " + result);
}
client.removeBucket(destBucketName);
mintSuccessLog("getBucketNotification(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("getBucketNotification(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeAllBucketNotification(String bucketName).
*/
public static void removeAllBucketNotification_test1() throws Exception {
// This test requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' environment variables.
String topic = System.getenv("MINIO_JAVA_TEST_TOPIC");
String region = System.getenv("MINIO_JAVA_TEST_REGION");
if (topic == null || topic.equals("") || region == null || region.equals("")) {
// do not run functional test as required environment variables are missing.
return;
}
if (!mintEnv) {
System.out.println("Test: removeAllBucketNotification(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String destBucketName = getRandomName();
client.makeBucket(destBucketName, region);
NotificationConfiguration notificationConfiguration = new NotificationConfiguration();
// Add a new topic configuration.
List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList();
TopicConfiguration topicConfiguration = new TopicConfiguration();
topicConfiguration.setTopic(topic);
List<EventType> eventList = new LinkedList<>();
eventList.add(EventType.OBJECT_CREATED_PUT);
eventList.add(EventType.OBJECT_CREATED_COPY);
topicConfiguration.setEvents(eventList);
Filter filter = new Filter();
filter.setPrefixRule("images");
filter.setSuffixRule("pg");
topicConfiguration.setFilter(filter);
topicConfigurationList.add(topicConfiguration);
notificationConfiguration.setTopicConfigurationList(topicConfigurationList);
client.setBucketNotification(destBucketName, notificationConfiguration);
notificationConfiguration = new NotificationConfiguration();
String expectedResult = notificationConfiguration.toString();
client.removeAllBucketNotification(destBucketName);
notificationConfiguration = client.getBucketNotification(destBucketName);
String result = notificationConfiguration.toString();
if (!result.equals(expectedResult)) {
throw new Exception("[FAILED] Expected: " + expectedResult + ", Got: " + result);
}
client.removeBucket(destBucketName);
mintSuccessLog("removeAllBucketNotification(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeAllBucketNotification(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* runTests: runs as much as possible of test combinations.
*/
public static void runTests() throws Exception {
makeBucket_test1();
if (endpoint.toLowerCase(Locale.US).contains("s3")) {
makeBucketwithRegion_test();
makeBucketWithPeriod_test();
}
listBuckets_test();
bucketExists_test();
removeBucket_test();
setup();
putObject_test1();
putObject_test2();
putObject_test3();
putObject_test4();
putObject_test5();
putObject_test6();
putObject_test7();
putObject_test8();
putObject_test9();
putObject_test10();
putObject_test11();
putObject_test12();
statObject_test1();
getObject_test1();
getObject_test2();
getObject_test3();
getObject_test4();
getObject_test5();
getObject_test6();
getObject_test8();
listObject_test1();
listObject_test2();
listObject_test3();
listObject_test4();
listObject_test5();
listObject_test6();
removeObject_test1();
removeObject_test2();
listIncompleteUploads_test1();
listIncompleteUploads_test2();
listIncompleteUploads_test3();
removeIncompleteUploads_test();
presignedGetObject_test1();
presignedGetObject_test2();
presignedGetObject_test3();
presignedPutObject_test1();
presignedPutObject_test2();
presignedPostPolicy_test();
copyObject_test1();
copyObject_test2();
copyObject_test3();
copyObject_test4();
copyObject_test5();
copyObject_test6();
copyObject_test7();
copyObject_test8();
copyObject_test9();
// SSE_C tests will only work over TLS connection
Locale locale = Locale.ENGLISH;
boolean tlsEnabled = endpoint.toLowerCase(locale).contains("https://");
if (tlsEnabled) {
statObject_test2();
getObject_test7();
putObject_test13();
putObject_test16();
copyObject_test10();
}
// SSE_S3 and SSE_KMS only work with endpoint="s3.amazonaws.com"
String requestUrl = endpoint;
if (requestUrl.equals("s3.amazonaws.com")) {
putObject_test14();
putObject_test15();
copyObject_test11();
copyObject_test12();
}
getBucketPolicy_test1();
setBucketPolicy_test1();
threadedPutObject();
teardown();
// notification tests requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' environment variables
// to be set appropriately.
setBucketNotification_test1();
getBucketNotification_test1();
removeAllBucketNotification_test1();
}
/**
* runQuickTests: runs tests those completely quicker.
*/
public static void runQuickTests() throws Exception {
makeBucket_test1();
listBuckets_test();
bucketExists_test();
removeBucket_test();
setup();
putObject_test1();
statObject_test1();
getObject_test1();
listObject_test1();
removeObject_test1();
listIncompleteUploads_test1();
removeIncompleteUploads_test();
presignedGetObject_test1();
presignedPutObject_test1();
presignedPostPolicy_test();
copyObject_test1();
getBucketPolicy_test1();
setBucketPolicy_test1();
teardown();
}
/**
* main().
*/
public static void main(String[] args) {
if (args.length != 4) {
System.out.println("usage: FunctionalTest <ENDPOINT> <ACCESSKEY> <SECRETKEY> <REGION>");
System.exit(-1);
}
String dataDir = System.getenv("MINT_DATA_DIR");
if (dataDir != null && !dataDir.equals("")) {
mintEnv = true;
dataFile1Mb = Paths.get(dataDir, "datafile-1-MB");
dataFile65Mb = Paths.get(dataDir, "datafile-65-MB");
}
String mintMode = null;
if (mintEnv) {
mintMode = System.getenv("MINT_MODE");
}
endpoint = args[0];
accessKey = args[1];
secretKey = args[2];
region = args[3];
try {
client = new MinioClient(endpoint, accessKey, secretKey);
// Enable trace for debugging.
// client.traceOn(System.out);
// For mint environment, run tests based on mint mode
if (mintEnv) {
if (mintMode != null && mintMode.equals("full")) {
FunctionalTest.runTests();
} else {
FunctionalTest.runQuickTests();
}
} else {
FunctionalTest.runTests();
// Get new bucket name to avoid minio azure gateway failure.
bucketName = getRandomName();
// Quick tests with passed region.
client = new MinioClient(endpoint, accessKey, secretKey, region);
FunctionalTest.runQuickTests();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
| functional/FunctionalTest.java | /*
* Minio Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2015, 2016, 2017, 2018 Minio, 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.
*/
import java.security.*;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.joda.time.DateTime;
import okhttp3.OkHttpClient;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.MultipartBody;
import okhttp3.Response;
import io.minio.*;
import io.minio.messages.*;
import io.minio.errors.*;
@SuppressFBWarnings(value = "REC", justification = "Allow catching super class Exception since it's tests")
public class FunctionalTest {
private static final String PASS = "PASS";
private static final String FAILED = "FAIL";
private static final String IGNORED = "NA";
private static final int MB = 1024 * 1024;
private static final Random random = new Random(new SecureRandom().nextLong());
private static final String customContentType = "application/javascript";
private static final String nullContentType = null;
private static String bucketName = getRandomName();
private static boolean mintEnv = false;
private static Path dataFile1Mb;
private static Path dataFile65Mb;
private static String endpoint;
private static String accessKey;
private static String secretKey;
private static String region;
private static MinioClient client = null;
/**
* Do no-op.
*/
public static void ignore(Object ...args) {
}
/**
* Create given sized file and returns its name.
*/
public static String createFile(int size) throws IOException {
String filename = getRandomName();
try (OutputStream os = Files.newOutputStream(Paths.get(filename), CREATE, APPEND)) {
int totalBytesWritten = 0;
int bytesToWrite = 0;
byte[] buf = new byte[1 * MB];
while (totalBytesWritten < size) {
random.nextBytes(buf);
bytesToWrite = size - totalBytesWritten;
if (bytesToWrite > buf.length) {
bytesToWrite = buf.length;
}
os.write(buf, 0, bytesToWrite);
totalBytesWritten += bytesToWrite;
}
}
return filename;
}
/**
* Create 1 MB temporary file.
*/
public static String createFile1Mb() throws IOException {
if (mintEnv) {
String filename = getRandomName();
Files.createSymbolicLink(Paths.get(filename).toAbsolutePath(), dataFile1Mb);
return filename;
}
return createFile(1 * MB);
}
/**
* Create 65 MB temporary file.
*/
public static String createFile65Mb() throws IOException {
if (mintEnv) {
String filename = getRandomName();
Files.createSymbolicLink(Paths.get(filename).toAbsolutePath(), dataFile65Mb);
return filename;
}
return createFile(65 * MB);
}
/**
* Generate random name.
*/
public static String getRandomName() {
return "minio-java-test-" + new BigInteger(32, random).toString(32);
}
/**
* Returns byte array contains all data in given InputStream.
*/
public static byte[] readAllBytes(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
}
/**
* Prints a success log entry in JSON format.
*/
public static void mintSuccessLog(String function, String args, long startTime) {
if (mintEnv) {
System.out.println(new MintLogger(function, args, System.currentTimeMillis() - startTime,
PASS, null, null, null));
}
}
/**
* Prints a failure log entry in JSON format.
*/
public static void mintFailedLog(String function, String args, long startTime, String message, String error) {
if (mintEnv) {
System.out.println(new MintLogger(function, args, System.currentTimeMillis() - startTime,
FAILED, null, message, error));
}
}
/**
* Prints a ignore log entry in JSON format.
*/
public static void mintIgnoredLog(String function, String args, long startTime) {
if (mintEnv) {
System.out.println(new MintLogger(function, args, System.currentTimeMillis() - startTime,
IGNORED, null, null, null));
}
}
/**
* Read object content of the given url.
*/
public static byte[] readObject(String urlString) throws Exception {
Request.Builder requestBuilder = new Request.Builder();
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("GET", null)
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response == null) {
throw new Exception("empty response");
}
if (!response.isSuccessful()) {
String errorXml = "";
// read entire body stream to string.
Scanner scanner = new Scanner(response.body().charStream());
scanner.useDelimiter("\\A");
if (scanner.hasNext()) {
errorXml = scanner.next();
}
scanner.close();
response.body().close();
throw new Exception("failed to read object. Response: " + response + ", Response body: " + errorXml);
}
return readAllBytes(response.body().byteStream());
}
/**
* Write data to given object url.
*/
public static void writeObject(String urlString, byte[] dataBytes) throws Exception {
Request.Builder requestBuilder = new Request.Builder();
// Set header 'x-amz-acl' to 'bucket-owner-full-control', so objects created
// anonymously, can be downloaded by bucket owner in AWS S3.
Request request = requestBuilder
.url(HttpUrl.parse(urlString))
.method("PUT", RequestBody.create(null, dataBytes))
.addHeader("x-amz-acl", "bucket-owner-full-control")
.build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response == null) {
throw new Exception("empty response");
}
if (!response.isSuccessful()) {
String errorXml = "";
// read entire body stream to string.
Scanner scanner = new Scanner(response.body().charStream());
scanner.useDelimiter("\\A");
if (scanner.hasNext()) {
errorXml = scanner.next();
}
scanner.close();
response.body().close();
throw new Exception("failed to create object. Response: " + response + ", Response body: " + errorXml);
}
}
/**
* Test: makeBucket(String bucketName).
*/
public static void makeBucket_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: makeBucket(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(name);
client.removeBucket(name);
mintSuccessLog("makeBucket(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("makeBucket(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: makeBucket(String bucketName, String region).
*/
public static void makeBucketwithRegion_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: makeBucket(String bucketName, String region)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(name, "eu-west-1");
client.removeBucket(name);
mintSuccessLog("makeBucket(String bucketName, String region)", "region: eu-west-1", startTime);
} catch (Exception e) {
mintFailedLog("makeBucket(String bucketName, String region)", "region: eu-west-1", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: makeBucket(String bucketName, String region) where bucketName has
* periods in its name.
*/
public static void makeBucketWithPeriod_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: makeBucket(String bucketName, String region)");
}
long startTime = System.currentTimeMillis();
String name = getRandomName() + ".withperiod";
try {
client.makeBucket(name, "eu-central-1");
client.removeBucket(name);
mintSuccessLog("makeBucket(String bucketName, String region)",
"name: " + name + ", region: eu-central-1", startTime);
} catch (Exception e) {
mintFailedLog("makeBucket(String bucketName, String region)", "name: " + name + ", region: eu-central-1",
startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listBuckets().
*/
public static void listBuckets_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: listBuckets()");
}
long startTime = System.currentTimeMillis();
try {
Date expectedTime = new Date();
String bucketName = getRandomName();
boolean found = false;
client.makeBucket(bucketName);
for (Bucket bucket : client.listBuckets()) {
if (bucket.name().equals(bucketName)) {
if (found) {
throw new Exception("[FAILED] duplicate entry " + bucketName + " found in list buckets");
}
found = true;
Date time = bucket.creationDate();
long diff = time.getTime() - expectedTime.getTime();
// excuse 15 minutes
if (diff > (15 * 60 * 1000)) {
throw new Exception("[FAILED] bucket creation time too apart. expected: " + expectedTime
+ ", got: " + time);
}
}
}
client.removeBucket(bucketName);
if (!found) {
throw new Exception("[FAILED] created bucket not found in list buckets");
}
mintSuccessLog("listBuckets()", null, startTime);
} catch (Exception e) {
mintFailedLog("listBuckets()", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: bucketExists(String bucketName).
*/
public static void bucketExists_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: bucketExists(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(name);
if (!client.bucketExists(name)) {
throw new Exception("[FAILED] bucket does not exist");
}
client.removeBucket(name);
mintSuccessLog("bucketExists(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("bucketExists(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeBucket(String bucketName).
*/
public static void removeBucket_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: removeBucket(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String name = getRandomName();
client.makeBucket(name);
client.removeBucket(name);
mintSuccessLog("removeBucket(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeBucket(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Tear down test setup.
*/
public static void setup() throws Exception {
client.makeBucket(bucketName);
}
/**
* Tear down test setup.
*/
public static void teardown() throws Exception {
client.removeBucket(bucketName);
}
/**
* Test: putObject(String bucketName, String objectName, String filename).
*/
public static void putObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, String filename)");
}
long startTime = System.currentTimeMillis();
try {
String filename = createFile1Mb();
client.putObject(bucketName, filename, filename);
Files.delete(Paths.get(filename));
client.removeObject(bucketName, filename);
mintSuccessLog("putObject(String bucketName, String objectName, String filename)", "filename: 1MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, String filename)", "filename: 1MB", startTime,
null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: multipart: putObject(String bucketName, String objectName, String filename).
*/
public static void putObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: multipart: putObject(String bucketName, String objectName, String filename)");
}
long startTime = System.currentTimeMillis();
try {
String filename = createFile65Mb();
client.putObject(bucketName, filename, filename);
Files.delete(Paths.get(filename));
client.removeObject(bucketName, filename);
mintSuccessLog("putObject(String bucketName, String objectName, String filename)", "filename: 65MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, String filename)", "filename: 65MB", startTime,
null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: With content-type: putObject(String bucketName, String objectName, String filename, String contentType).
*/
public static void putObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, String filename,"
+ " String contentType)");
}
long startTime = System.currentTimeMillis();
try {
String filename = createFile1Mb();
client.putObject(bucketName, filename, filename, customContentType);
Files.delete(Paths.get(filename));
client.removeObject(bucketName, filename);
mintSuccessLog("putObject(String bucketName, String objectName, String filename, String contentType)",
"contentType: " + customContentType, startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, String filename, String contentType)",
"contentType: " + customContentType, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream body, long size, String contentType).
*/
public static void putObject_test4() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream body, "
+ "long size, String contentType)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, customContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, long size,"
+ " String contentType)",
"size: 1 MB, objectName: " + customContentType, startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size, String contentType)",
"size: 1 MB, objectName: " + customContentType, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: multipart resume: putObject(String bucketName, String objectName, InputStream body, long size,
* String contentType).
*/
public static void putObject_test5() throws Exception {
if (!mintEnv) {
System.out.println("Test: multipart resume: putObject(String bucketName, String objectName, InputStream body, "
+ "long size, String contentType)");
}
long startTime = System.currentTimeMillis();
long size = 20 * MB;
try {
String objectName = getRandomName();
try (InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, size, nullContentType);
} catch (EOFException e) {
ignore();
}
size = 13 * MB;
try (final InputStream is = new ContentInputStream(size)) {
client.putObject(bucketName, objectName, is, size, nullContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, long size,"
+ " String contentType)",
"contentType: " + nullContentType + ", size: " + String.valueOf(size), startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size, String contentType)",
"contentType: " + nullContentType + ", size: " + String.valueOf(size), startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream body, long size, String contentType).
* where objectName has multiple path segments.
*/
public static void putObject_test6() throws Exception {
if (!mintEnv) {
System.out.println("Test: objectName with path segments: "
+ "putObject(String bucketName, String objectName, InputStream body, "
+ "long size, String contentType)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = "/path/to/" + getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, customContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, long size,"
+ " String contentType)",
"size: 1 MB, contentType: " + customContentType, startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size,"
+ " String contentType)",
"size: 1 MB, contentType: " + customContentType, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test put object with unknown sized stream.
*/
public static void testPutObjectUnknownStreamSize(long size) throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream body, "
+ "String contentType)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(size)) {
client.putObject(bucketName, objectName, is, customContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream body, String contentType)",
"contentType: " + customContentType, startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream body, long size, String contentType)",
"contentType: " + customContentType, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream body, String contentType).
*/
public static void putObject_test7() throws Exception {
testPutObjectUnknownStreamSize(3 * MB);
}
/**
* Test: multipart: putObject(String bucketName, String objectName, InputStream body, String contentType).
*/
public static void putObject_test8() throws Exception {
testPutObjectUnknownStreamSize(537 * MB);
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* Map<String, String> headerMap).
*/
public static void putObject_test9() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap).");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
try (final InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, 13 * MB, headerMap);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* Map<String, String> headerMap) with Storage Class REDUCED_REDUNDANCY.
*/
@SuppressFBWarnings("UCF")
public static void putObject_test10() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap). with Storage Class REDUCED_REDUNDANCY set");
}
long startTime = System.currentTimeMillis();
try {
String storageClass = "REDUCED_REDUNDANCY";
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
headerMap.put("X-Amz-Storage-Class", storageClass);
try (final InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, 13 * MB, headerMap);
}
ObjectStat objectStat = client.statObject(bucketName, objectName);
Map<String, List<String>> returnHeader = objectStat.httpHeaders();
List<String> returnStorageClass = returnHeader.get("X-Amz-Storage-Class");
if ((returnStorageClass != null) && (!storageClass.equals(returnStorageClass.get(0)))) {
throw new Exception("Metadata mismatch");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* Map<String, String> headerMap) with Storage Class STANDARD.
*/
public static void putObject_test11() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap). with Storage Class STANDARD set");
}
long startTime = System.currentTimeMillis();
try {
String storageClass = "STANDARD";
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
headerMap.put("X-Amz-Storage-Class", storageClass);
try (final InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, 13 * MB, headerMap);
}
ObjectStat objectStat = client.statObject(bucketName, objectName);
Map<String, List<String>> returnHeader = objectStat.httpHeaders();
List<String> returnStorageClass = returnHeader.get("X-Amz-Storage-Class");
// Standard storage class shouldn't be present in metadata response
if (returnStorageClass != null) {
throw new Exception("Did not expect: " + storageClass + " in response metadata");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* Map<String, String> headerMap). with invalid Storage Class set
*/
public static void putObject_test12() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap). with invalid Storage Class set");
}
long startTime = System.currentTimeMillis();
try {
String storageClass = "INVALID";
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
headerMap.put("X-Amz-Storage-Class", storageClass);
try (final InputStream is = new ContentInputStream(13 * MB)) {
client.putObject(bucketName, objectName, is, 13 * MB, headerMap);
} catch (ErrorResponseException e) {
if (!e.errorResponse().code().equals("InvalidStorageClass")) {
throw e;
}
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, Map<String, String> headerMap)",
"size: 13 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* ServerSideEncryption sse). To test SSE_C
*/
public static void putObject_test13() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C. ");
}
long startTime = System.currentTimeMillis();
// Generate a new 256 bit AES key - This key must be remembered by the client.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, sse);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C.",
"size: 1 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C.",
"size: 1 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* ServerSideEncryption sse). To test SSE_S3
*/
public static void putObject_test14() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_S3.");
}
long startTime = System.currentTimeMillis();
ServerSideEncryption sse = ServerSideEncryption.atRest();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, sse);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_S3.",
"size: 1 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_S3.",
"size: 1 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* ServerSideEncryption sse). To test SSE_KMS
*/
public static void putObject_test15() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_KMS.");
}
long startTime = System.currentTimeMillis();
Map<String,String> myContext = new HashMap<>();
myContext.put("key1","value1");
String keyId = "";
keyId = System.getenv("MINT_KEY_ID");
if (keyId.equals("")) {
mintIgnoredLog("getBucketPolicy(String bucketName)", null, startTime);
}
ServerSideEncryption sse = ServerSideEncryption.withManagedKeys("keyId", myContext);
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1 * MB)) {
client.putObject(bucketName, objectName, is, 1 * MB, sse);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_KMS.",
"size: 1 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_KMS.",
"size: 1 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: putObject(String bucketName, String objectName, InputStream stream, long size,
* ServerSideEncryption sse). To test SSE_C (multi-part upload).
*/
public static void putObject_test16() throws Exception {
if (!mintEnv) {
System.out.println("Test: putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C (Multi-part upload). ");
}
long startTime = System.currentTimeMillis();
// Generate a new 256 bit AES key - This key must be remembered by the client.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 6 * MB, sse);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C (Multi-part upload).",
"size: 6 MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, InputStream stream, "
+ "long size, ServerSideEncryption sse) using SSE_C (Multi-part upload).",
"size: 6 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: statObject(String bucketName, String objectName).
*/
public static void statObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: statObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", customContentType);
headerMap.put("x-amz-meta-my-custom-data", "foo");
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, headerMap);
}
ObjectStat objectStat = client.statObject(bucketName, objectName);
if (!(objectName.equals(objectStat.name()) && (objectStat.length() == 1)
&& bucketName.equals(objectStat.bucketName()) && objectStat.contentType().equals(customContentType))) {
throw new Exception("[FAILED] object stat differs");
}
Map<String, List<String>> httpHeaders = objectStat.httpHeaders();
if (!httpHeaders.containsKey("x-amz-meta-my-custom-data")) {
throw new Exception("[FAILED] metadata not found in object stat");
}
List<String> values = httpHeaders.get("x-amz-meta-my-custom-data");
if (values.size() != 1) {
throw new Exception("[FAILED] too many metadata value. expected: 1, got: " + values.size());
}
if (!values.get(0).equals("foo")) {
throw new Exception("[FAILED] wrong metadata value. expected: foo, got: " + values.get(0));
}
client.removeObject(bucketName, objectName);
mintSuccessLog("statObject(String bucketName, String objectName)",null, startTime);
} catch (Exception e) {
mintFailedLog("statObject(String bucketName, String objectName)",null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: statObject(String bucketName, String objectName, ServerSideEncryption sse).
* To test statObject using SSE_C.
*/
public static void statObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: statObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
// Generate a new 256 bit AES key - This key must be remembered by the client.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, sse);
}
ObjectStat objectStat = client.statObject(bucketName, objectName, sse);
if (!(objectName.equals(objectStat.name()) && (objectStat.length() == 1)
&& bucketName.equals(objectStat.bucketName()))) {
throw new Exception("[FAILED] object stat differs");
}
Map<String, List<String>> httpHeaders = objectStat.httpHeaders();
if (!httpHeaders.containsKey("X-Amz-Server-Side-Encryption-Customer-Algorithm")) {
throw new Exception("[FAILED] metadata not found in object stat");
}
List<String> values = httpHeaders.get("X-Amz-Server-Side-Encryption-Customer-Algorithm");
if (values.size() != 1) {
throw new Exception("[FAILED] too many metadata value. expected: 1, got: " + values.size());
}
if (!values.get(0).equals("AES256")) {
throw new Exception("[FAILED] wrong metadata value. expected: AES256, got: " + values.get(0));
}
client.removeObject(bucketName, objectName);
mintSuccessLog("statObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.",null, startTime);
} catch (Exception e) {
mintFailedLog("statObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.",null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName).
*/
public static void getObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName)",null, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName)",null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, long offset).
*/
public static void getObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName, long offset)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName, 1000L)
.close();
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, long offset)", "offset: 1000", startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, long offset)", "offset: 1000", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, long offset, Long length).
*/
public static void getObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName, long offset, Long length)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName, 1000L, 1024 * 1024L)
.close();
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, long offset, Long length)",
"offset: 1000, length: 1 MB", startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, long offset, Long length)",
"offset: 1000, length: 1 MB", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, String filename).
*/
public static void getObject_test4() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName, String filename)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName, objectName + ".downloaded");
Files.delete(Paths.get(objectName + ".downloaded"));
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, String filename)", null, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, String filename)",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, String filename).
* where objectName has multiple path segments.
*/
public static void getObject_test5() throws Exception {
if (!mintEnv) {
System.out.println("Test: objectName with multiple path segments: "
+ "getObject(String bucketName, String objectName, String filename)");
}
long startTime = System.currentTimeMillis();
String baseObjectName = getRandomName();
String objectName = "path/to/" + baseObjectName;
try {
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
client.getObject(bucketName, objectName, baseObjectName + ".downloaded");
Files.delete(Paths.get(baseObjectName + ".downloaded"));
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, String filename)",
"objectName: " + objectName, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, String filename)",
"objectName: " + objectName, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName) zero size object.
*/
public static void getObject_test6() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName) zero size object");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(0)) {
client.putObject(bucketName, objectName, is, 0, nullContentType);
}
client.getObject(bucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, ServerSideEncryption sse).
* To test getObject when object is put using SSE_C.
*/
public static void getObject_test7() throws Exception {
if (!mintEnv) {
System.out.println("Test: getObject(String bucketName, String objectName, ServerSideEncryption sse) using SSE_C");
}
long startTime = System.currentTimeMillis();
// Generate a new 256 bit AES key - This key must be remembered by the client.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey());
try {
String objectName = getRandomName();
String putString;
int bytes_read_put;
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, sse);
byte [] putbyteArray = new byte[is.available()];
bytes_read_put = is.read(putbyteArray);
putString = new String(putbyteArray, StandardCharsets.UTF_8);
}
InputStream stream = client.getObject(bucketName, objectName, sse);
byte [] getbyteArray = new byte[stream.available()];
int bytes_read_get = stream.read(getbyteArray);
String getString = new String(getbyteArray, StandardCharsets.UTF_8);
stream.close();
//client.getObject(bucketName, objectName, sse)
// .close();
// Compare if contents received are same as the initial uploaded object.
if ((!putString.equals(getString)) || (bytes_read_put != bytes_read_get) ) {
throw new Exception("Contents received from getObject doesn't match initial contents.");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("getObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.",null, startTime);
} catch (Exception e) {
mintFailedLog("getObject(String bucketName, String objectName, ServerSideEncryption sse)"
+ " using SSE_C.",null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getObject(String bucketName, String objectName, long offset, Long length) with offset=0.
*/
public static void getObject_test8() throws Exception {
if (!mintEnv) {
System.out.println(
"Test: getObject(String bucketName, String objectName, long offset, Long length) with offset=0"
);
}
final long startTime = System.currentTimeMillis();
final int fullLength = 1024;
final int partialLength = 256;
final long offset = 0L;
final String objectName = getRandomName();
try {
try (final InputStream is = new ContentInputStream(fullLength)) {
client.putObject(bucketName, objectName, is, fullLength, nullContentType);
}
try (
final InputStream partialObjectStream = client.getObject(
bucketName,
objectName,
offset,
Long.valueOf(partialLength)
)
) {
byte[] result = new byte[fullLength];
final int read = partialObjectStream.read(result);
result = Arrays.copyOf(result, read);
if (result.length != partialLength) {
throw new Exception(
String.format(
"Expecting only the first %d bytes from partial getObject request; received %d bytes instead.",
partialLength,
read
)
);
}
}
client.removeObject(bucketName, objectName);
mintSuccessLog(
"getObject(String bucketName, String objectName, long offset, Long length) with offset=0",
String.format("offset: %d, length: %d bytes", offset, partialLength),
startTime
);
} catch (final Exception e) {
mintFailedLog(
"getObject(String bucketName, String objectName, long offset, Long length) with offset=0",
String.format("offset: %d, length: %d bytes", offset, partialLength),
startTime,
null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace())
);
throw e;
}
}
/**
* Test: listObjects(final String bucketName).
*/
public static void listObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: listObjects(final String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[3];
int i = 0;
for (i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName)) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listObjects(bucketName, final String prefix).
*/
public static void listObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: listObjects(final String bucketName, final String prefix)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[3];
int i = 0;
for (i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName, "minio")) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName, final String prefix)", "prefix :minio", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix)", "prefix :minio", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listObjects(bucketName, final String prefix, final boolean recursive).
*/
public static void listObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: listObjects(final String bucketName, final String prefix, final boolean recursive)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[3];
int i = 0;
for (i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName, "minio", true)) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minio, recursive: true", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minio, recursive: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listObjects(final string bucketName).
*/
public static void listObject_test4() throws Exception {
if (!mintEnv) {
System.out.println("Test: empty bucket: listObjects(final String bucketName, final String prefix,"
+ " final boolean recursive)");
}
long startTime = System.currentTimeMillis();
try {
int i = 0;
for (Result<?> r : client.listObjects(bucketName, "minioemptybucket", true)) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
mintSuccessLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minioemptybucket, recursive: true", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minioemptybucket, recursive: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: recursive: listObjects(bucketName, final String prefix, final boolean recursive).
*/
public static void listObject_test5() throws Exception {
if (!mintEnv) {
System.out.println("Test: recursive: listObjects(final String bucketName, final String prefix, "
+ "final boolean recursive)");
}
long startTime = System.currentTimeMillis();
try {
int objCount = 1050;
String[] objectNames = new String[objCount];
int i = 0;
for (i = 0; i < objCount; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName, "minio", true)) {
ignore(i++, r.get());
}
// Check the number of uploaded objects
if (i != objCount) {
throw new Exception("item count differs, expected: " + objCount + ", got: " + i);
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minio, recursive: true", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix, final boolean recursive)",
"prefix :minio, recursive: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listObjects(bucketName, final String prefix, final boolean recursive, final boolean useVersion1).
*/
public static void listObject_test6() throws Exception {
if (!mintEnv) {
System.out.println("Test: listObjects(final String bucketName, final String prefix, final boolean recursive, "
+ "final boolean useVersion1)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[3];
int i = 0;
for (i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
i = 0;
for (Result<?> r : client.listObjects(bucketName, "minio", true, true)) {
ignore(i++, r.get());
if (i == 3) {
break;
}
}
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("listObjects(final String bucketName, final String prefix, "
+ "final boolean recursive, final boolean useVersion1)",
"prefix :minio, recursive: true, useVersion1: true", startTime);
} catch (Exception e) {
mintFailedLog("listObjects(final String bucketName, final String prefix, "
+ "final boolean recursive, final boolean useVersion1)",
"prefix :minio, recursive: true, useVersion1: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeObject(String bucketName, String objectName).
*/
public static void removeObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: removeObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, nullContentType);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("removeObject(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeObject(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeObject(final String bucketName, final Iterable<String> objectNames).
*/
public static void removeObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: removeObject(final String bucketName, final Iterable<String> objectNames)");
}
long startTime = System.currentTimeMillis();
try {
String[] objectNames = new String[4];
for (int i = 0; i < 3; i++) {
objectNames[i] = getRandomName();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectNames[i], is, 1, nullContentType);
}
}
objectNames[3] = "nonexistent-object";
for (Result<?> r : client.removeObject(bucketName, Arrays.asList(objectNames))) {
ignore(r.get());
}
mintSuccessLog("removeObject(final String bucketName, final Iterable<String> objectNames)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeObject(final String bucketName, final Iterable<String> objectNames)",
null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listIncompleteUploads(String bucketName).
*/
public static void listIncompleteUploads_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: listIncompleteUploads(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 9 * MB, nullContentType);
} catch (EOFException e) {
ignore();
}
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
ignore(i++, r.get());
if (i == 10) {
break;
}
}
client.removeIncompleteUpload(bucketName, objectName);
mintSuccessLog("listIncompleteUploads(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("listIncompleteUploads(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listIncompleteUploads(String bucketName, String prefix).
*/
public static void listIncompleteUploads_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: listIncompleteUploads(String bucketName, String prefix)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 9 * MB, nullContentType);
} catch (EOFException e) {
ignore();
}
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio")) {
ignore(i++, r.get());
if (i == 10) {
break;
}
}
client.removeIncompleteUpload(bucketName, objectName);
mintSuccessLog("listIncompleteUploads(String bucketName, String prefix)", null, startTime);
} catch (Exception e) {
mintFailedLog("listIncompleteUploads(String bucketName, String prefix)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive).
*/
public static void listIncompleteUploads_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: listIncompleteUploads(final String bucketName, final String prefix, "
+ "final boolean recursive)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 9 * MB, nullContentType);
} catch (EOFException e) {
ignore();
}
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio", true)) {
ignore(i++, r.get());
if (i == 10) {
break;
}
}
client.removeIncompleteUpload(bucketName, objectName);
mintSuccessLog("listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)",
"prefix: minio, recursive: true", startTime);
} catch (Exception e) {
mintFailedLog("listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)",
"prefix: minio, recursive: true", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeIncompleteUpload(String bucketName, String objectName).
*/
public static void removeIncompleteUploads_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: removeIncompleteUpload(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(6 * MB)) {
client.putObject(bucketName, objectName, is, 9 * MB, nullContentType);
} catch (EOFException e) {
ignore();
}
int i = 0;
for (Result<Upload> r : client.listIncompleteUploads(bucketName)) {
ignore(i++, r.get());
if (i == 10) {
break;
}
}
client.removeIncompleteUpload(bucketName, objectName);
mintSuccessLog("removeIncompleteUpload(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeIncompleteUpload(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* public String presignedGetObject(String bucketName, String objectName).
*/
public static void presignedGetObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedGetObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
byte[] inBytes;
try (final InputStream is = new ContentInputStream(3 * MB)) {
inBytes = readAllBytes(is);
}
String urlString = client.presignedGetObject(bucketName, objectName);
byte[] outBytes = readObject(urlString);
if (!Arrays.equals(inBytes, outBytes)) {
throw new Exception("object content differs");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedGetObject(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedGetObject(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: presignedGetObject(String bucketName, String objectName, Integer expires).
*/
public static void presignedGetObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedGetObject(String bucketName, String objectName, Integer expires)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
byte[] inBytes;
try (final InputStream is = new ContentInputStream(3 * MB)) {
inBytes = readAllBytes(is);
}
String urlString = client.presignedGetObject(bucketName, objectName, 3600);
byte[] outBytes = readObject(urlString);
if (!Arrays.equals(inBytes, outBytes)) {
throw new Exception("object content differs");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedGetObject(String bucketName, String objectName, Integer expires)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedGetObject(String bucketName, String objectName, Integer expires)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* public String presignedGetObject(String bucketName, String objectName, Integer expires, Map reqParams).
*/
public static void presignedGetObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedGetObject(String bucketName, String objectName, Integer expires, "
+ "Map<String, String> reqParams)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
byte[] inBytes;
try (final InputStream is = new ContentInputStream(3 * MB)) {
inBytes = readAllBytes(is);
}
Map<String, String> reqParams = new HashMap<>();
reqParams.put("response-content-type", "application/json");
String urlString = client.presignedGetObject(bucketName, objectName, 3600, reqParams);
byte[] outBytes = readObject(urlString);
if (!Arrays.equals(inBytes, outBytes)) {
throw new Exception("object content differs");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedGetObject(String bucketName, String objectName, Integer expires, Map<String,"
+ " String> reqParams)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedGetObject(String bucketName, String objectName, Integer expires, Map<String,"
+ " String> reqParams)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* public String presignedPutObject(String bucketName, String objectName).
*/
public static void presignedPutObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedPutObject(String bucketName, String objectName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
String urlString = client.presignedPutObject(bucketName, objectName);
byte[] data = "hello, world".getBytes(StandardCharsets.UTF_8);
writeObject(urlString, data);
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedPutObject(String bucketName, String objectName)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedPutObject(String bucketName, String objectName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: presignedPutObject(String bucketName, String objectName, Integer expires).
*/
public static void presignedPutObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
String urlString = client.presignedPutObject(bucketName, objectName, 3600);
byte[] data = "hello, world".getBytes(StandardCharsets.UTF_8);
writeObject(urlString, data);
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedPutObject(String bucketName, String objectName, Integer expires)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedPutObject(String bucketName, String objectName, Integer expires)", null, startTime,
null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: presignedPostPolicy(PostPolicy policy).
*/
public static void presignedPostPolicy_test() throws Exception {
if (!mintEnv) {
System.out.println("Test: presignedPostPolicy(PostPolicy policy)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
PostPolicy policy = new PostPolicy(bucketName, objectName, DateTime.now().plusDays(7));
policy.setContentRange(1 * MB, 4 * MB);
Map<String, String> formData = client.presignedPostPolicy(policy);
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
for (Map.Entry<String, String> entry : formData.entrySet()) {
multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
try (final InputStream is = new ContentInputStream(3 * MB)) {
multipartBuilder.addFormDataPart("file", objectName, RequestBody.create(null, readAllBytes(is)));
}
Request.Builder requestBuilder = new Request.Builder();
String urlString = client.getObjectUrl(bucketName, "");
Request request = requestBuilder.url(urlString).post(multipartBuilder.build()).build();
OkHttpClient transport = new OkHttpClient();
Response response = transport.newCall(request).execute();
if (response == null) {
throw new Exception("no response from server");
}
if (!response.isSuccessful()) {
String errorXml = "";
// read entire body stream to string.
Scanner scanner = new Scanner(response.body().charStream());
scanner.useDelimiter("\\A");
if (scanner.hasNext()) {
errorXml = scanner.next();
}
scanner.close();
throw new Exception("failed to upload object. Response: " + response + ", Error: " + errorXml);
}
client.removeObject(bucketName, objectName);
mintSuccessLog("presignedPostPolicy(PostPolicy policy)", null, startTime);
} catch (Exception e) {
mintFailedLog("presignedPostPolicy(PostPolicy policy)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: PutObject(): do put object using multi-threaded way in parallel.
*/
public static void threadedPutObject() throws Exception {
if (!mintEnv) {
System.out.println("Test: threadedPutObject");
}
long startTime = System.currentTimeMillis();
try {
Thread[] threads = new Thread[7];
for (int i = 0; i < 7; i++) {
threads[i] = new Thread(new PutObjectRunnable(client, bucketName, createFile65Mb()));
}
for (int i = 0; i < 7; i++) {
threads[i].start();
}
// Waiting for threads to complete.
for (int i = 0; i < 7; i++) {
threads[i].join();
}
// All threads are completed.
mintSuccessLog("putObject(String bucketName, String objectName, String filename)",
"filename: threaded65MB", startTime);
} catch (Exception e) {
mintFailedLog("putObject(String bucketName, String objectName, String filename)",
"filename: threaded65MB", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName).
*/
public static void copyObject_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
client.copyObject(bucketName, objectName, destBucketName);
client.getObject(destBucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with ETag to match.
*/
public static void copyObject_test2() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with Matching ETag (Negative Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions invalidETag = new CopyConditions();
invalidETag.setMatchETag("TestETag");
try {
client.copyObject(bucketName, objectName, destBucketName, invalidETag);
} catch (ErrorResponseException e) {
if (!e.errorResponse().code().equals("PreconditionFailed")) {
throw e;
}
}
client.removeObject(bucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ " CopyConditions copyConditions)", "CopyConditions: invalidETag",startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyConditions: invalidETag", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with ETag to match.
*/
public static void copyObject_test3() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with Matching ETag (Positive Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
ObjectStat stat = client.statObject(bucketName, objectName);
CopyConditions copyConditions = new CopyConditions();
copyConditions.setMatchETag(stat.etag());
// File should be copied as ETag set in copyConditions matches object's ETag.
client.copyObject(bucketName, objectName, destBucketName, copyConditions);
client.getObject(destBucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ " CopyConditions copyConditions)", null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ " CopyConditions copyConditions)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with ETag to not match.
*/
public static void copyObject_test4() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with not matching ETag"
+ " (Positive Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions copyConditions = new CopyConditions();
copyConditions.setMatchETagNone("TestETag");
// File should be copied as ETag set in copyConditions doesn't match object's ETag.
client.copyObject(bucketName, objectName, destBucketName, copyConditions);
client.getObject(destBucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ " CopyConditions copyConditions)", null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions)",
null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with ETag to not match.
*/
public static void copyObject_test5() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with not matching ETag"
+ " (Negative Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
ObjectStat stat = client.statObject(bucketName, objectName);
CopyConditions matchingETagNone = new CopyConditions();
matchingETagNone.setMatchETagNone(stat.etag());
try {
client.copyObject(bucketName, objectName, destBucketName, matchingETagNone);
} catch (ErrorResponseException e) {
// File should not be copied as ETag set in copyConditions matches object's ETag.
if (!e.errorResponse().code().equals("PreconditionFailed")) {
throw e;
}
}
client.removeObject(bucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)", null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with object modified after condition.
*/
public static void copyObject_test6() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with modified after "
+ "condition (Positive Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions modifiedDateCondition = new CopyConditions();
DateTime dateRepresentation = new DateTime(2015, Calendar.MAY, 3, 10, 10);
modifiedDateCondition.setModified(dateRepresentation);
// File should be copied as object was modified after the set date.
client.copyObject(bucketName, objectName, destBucketName, modifiedDateCondition);
client.getObject(destBucketName, objectName)
.close();
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyCondition: modifiedDateCondition", startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyCondition: modifiedDateCondition", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions) with object modified after condition.
*/
public static void copyObject_test7() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions) with modified after"
+ " condition (Negative Case)");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, nullContentType);
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions invalidUnmodifiedCondition = new CopyConditions();
DateTime dateRepresentation = new DateTime(2015, Calendar.MAY, 3, 10, 10);
invalidUnmodifiedCondition.setUnmodified(dateRepresentation);
try {
client.copyObject(bucketName, objectName, destBucketName, invalidUnmodifiedCondition);
} catch (ErrorResponseException e) {
// File should not be copied as object was modified after date set in copyConditions.
if (!e.errorResponse().code().equals("PreconditionFailed")) {
throw e;
}
}
client.removeObject(bucketName, objectName);
// Destination bucket is expected to be empty, otherwise it will trigger an exception.
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyCondition: invalidUnmodifiedCondition", startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions)",
"CopyCondition: invalidUnmodifiedCondition", startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions, Map metadata) replace
* object metadata.
*/
public static void copyObject_test8() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions, Map<String, String> metadata)"
+ " replace object metadata");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
try (final InputStream is = new ContentInputStream(3 * MB)) {
client.putObject(bucketName, objectName, is, 3 * MB, "application/octet-stream");
}
String destBucketName = getRandomName();
client.makeBucket(destBucketName);
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
Map<String, String> metadata = new HashMap<>();
metadata.put("Content-Type", customContentType);
client.copyObject(bucketName, objectName, destBucketName, objectName, copyConditions, metadata);
ObjectStat objectStat = client.statObject(destBucketName, objectName);
if (!customContentType.equals(objectStat.contentType())) {
throw new Exception("content type differs. expected: " + customContentType + ", got: "
+ objectStat.contentType());
}
client.removeObject(bucketName, objectName);
client.removeObject(destBucketName, objectName);
client.removeBucket(destBucketName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions, Map<String, String> metadata)",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions, Map<String, String> metadata)",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, String destBucketName,
* CopyConditions copyConditions, Map metadata) remove
* object metadata.
*/
public static void copyObject_test9() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, String destBucketName,"
+ "CopyConditions copyConditions, Map<String, String> metadata)"
+ " remove object metadata");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
Map<String, String> headerMap = new HashMap<>();
headerMap.put("X-Amz-Meta-Test", "testValue");
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, headerMap);
}
// Attempt to remove the user-defined metadata from the object
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
client.copyObject(bucketName, objectName, bucketName,
objectName, copyConditions, new HashMap<String,String>());
ObjectStat objectStat = client.statObject(bucketName, objectName);
if (objectStat.httpHeaders().containsKey("X-Amz-Meta-Test")) {
throw new Exception("expected user-defined metadata has been removed");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions, Map<String, String> metadata)",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, String destBucketName, "
+ "CopyConditions copyConditions, Map<String, String> metadata)",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, String destBucketName,
* CopyConditions copyConditions, ServerSideEncryption sseTarget)
* To test using SSE_C.
*/
public static void copyObject_test10() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_C. ");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
// Generate a new 256 bit AES key - This key must be remembered by the client.
byte[] key = "01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
ServerSideEncryption ssePut = ServerSideEncryption.withCustomerKey(secretKeySpec);
ServerSideEncryption sseSource = ServerSideEncryption.copyWithCustomerKey(secretKeySpec);
byte[] keyTarget = "98765432100123456789012345678901".getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpecTarget = new SecretKeySpec(keyTarget, "AES");
ServerSideEncryption sseTarget = ServerSideEncryption.withCustomerKey(secretKeySpecTarget);
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, ssePut);
}
// Attempt to remove the user-defined metadata from the object
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
client.copyObject(bucketName, objectName, sseSource, bucketName,
objectName, copyConditions, sseTarget);
ObjectStat objectStat = client.statObject(bucketName, objectName, sseTarget);
client.removeObject(bucketName, objectName);
mintSuccessLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_C.",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_C.",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, String destBucketName,
* CopyConditions copyConditions, ServerSideEncryption sseTarget)
* To test using SSE_S3.
*/
public static void copyObject_test11() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_S3. ");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
ServerSideEncryption sse = ServerSideEncryption.atRest();
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, sse);
}
// Attempt to remove the user-defined metadata from the object
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
client.copyObject(bucketName, objectName, null, bucketName,
objectName, copyConditions, sse);
ObjectStat objectStat = client.statObject(bucketName, objectName);
if (objectStat.httpHeaders().containsKey("X-Amz-Meta-Test")) {
throw new Exception("expected user-defined metadata has been removed");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_S3.",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_S3.",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, String destBucketName,
* CopyConditions copyConditions, ServerSideEncryption sseTarget)
* To test using SSE_KMS.
*/
public static void copyObject_test12() throws Exception {
if (!mintEnv) {
System.out.println("Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_KMS. ");
}
long startTime = System.currentTimeMillis();
try {
String objectName = getRandomName();
Map<String,String> myContext = new HashMap<>();
myContext.put("key1","value1");
String keyId = "";
keyId = System.getenv("MINT_KEY_ID");
if (keyId.equals("")) {
mintIgnoredLog("getBucketPolicy(String bucketName)", null, startTime);
}
ServerSideEncryption sse = ServerSideEncryption.withManagedKeys("keyId", myContext);
try (final InputStream is = new ContentInputStream(1)) {
client.putObject(bucketName, objectName, is, 1, sse);
}
// Attempt to remove the user-defined metadata from the object
CopyConditions copyConditions = new CopyConditions();
copyConditions.setReplaceMetadataDirective();
client.copyObject(bucketName, objectName, null, bucketName,
objectName, copyConditions, sse);
ObjectStat objectStat = client.statObject(bucketName, objectName);
if (objectStat.httpHeaders().containsKey("X-Amz-Meta-Test")) {
throw new Exception("expected user-defined metadata has been removed");
}
client.removeObject(bucketName, objectName);
mintSuccessLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_KMS.",
null, startTime);
} catch (Exception e) {
mintFailedLog("copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, "
+ "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)"
+ " using SSE_KMS.",
null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getBucketPolicy(String bucketName).
*/
public static void getBucketPolicy_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: getBucketPolicy(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:GetObject\"],\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":[\"*\"]},\"Resource\":[\"arn:aws:s3:::" + bucketName
+ "/myobject*\"],\"Sid\":\"\"}]}";
client.setBucketPolicy(bucketName, policy);
client.getBucketPolicy(bucketName);
mintSuccessLog("getBucketPolicy(String bucketName)", null, startTime);
} catch (Exception e) {
ErrorResponse errorResponse = null;
if (e instanceof ErrorResponseException) {
ErrorResponseException exp = (ErrorResponseException) e;
errorResponse = exp.errorResponse();
}
// Ignore NotImplemented error
if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) {
mintIgnoredLog("getBucketPolicy(String bucketName)", null, startTime);
} else {
mintFailedLog("getBucketPolicy(String bucketName)", null, startTime,
null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
}
/**
* Test: setBucketPolicy(String bucketName, String policy).
*/
public static void setBucketPolicy_test1() throws Exception {
if (!mintEnv) {
System.out.println("Test: setBucketPolicy(String bucketName, String policy)");
}
long startTime = System.currentTimeMillis();
try {
String policy = "{\"Statement\":[{\"Action\":\"s3:GetObject\",\"Effect\":\"Allow\",\"Principal\":"
+ "\"*\",\"Resource\":\"arn:aws:s3:::" + bucketName + "/myobject*\"}],\"Version\": \"2012-10-17\"}";
client.setBucketPolicy(bucketName, policy);
mintSuccessLog("setBucketPolicy(String bucketName, String policy)", null, startTime);
} catch (Exception e) {
ErrorResponse errorResponse = null;
if (e instanceof ErrorResponseException) {
ErrorResponseException exp = (ErrorResponseException) e;
errorResponse = exp.errorResponse();
}
// Ignore NotImplemented error
if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) {
mintIgnoredLog("setBucketPolicy(String bucketName, String objectPrefix, "
+ "PolicyType policyType)", null, startTime);
} else {
mintFailedLog("setBucketPolicy(String bucketName, String objectPrefix, "
+ "PolicyType policyType)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
}
/**
* Test: setBucketNotification(String bucketName, NotificationConfiguration notificationConfiguration).
*/
public static void setBucketNotification_test1() throws Exception {
// This test requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' environment variables.
String topic = System.getenv("MINIO_JAVA_TEST_TOPIC");
String region = System.getenv("MINIO_JAVA_TEST_REGION");
if (topic == null || topic.equals("") || region == null || region.equals("")) {
// do not run functional test as required environment variables are missing.
return;
}
if (!mintEnv) {
System.out.println("Test: setBucketNotification(String bucketName, "
+ "NotificationConfiguration notificationConfiguration)");
}
long startTime = System.currentTimeMillis();
try {
String destBucketName = getRandomName();
client.makeBucket(destBucketName, region);
NotificationConfiguration notificationConfiguration = new NotificationConfiguration();
// Add a new topic configuration.
List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList();
TopicConfiguration topicConfiguration = new TopicConfiguration();
topicConfiguration.setTopic(topic);
List<EventType> eventList = new LinkedList<>();
eventList.add(EventType.OBJECT_CREATED_PUT);
eventList.add(EventType.OBJECT_CREATED_COPY);
topicConfiguration.setEvents(eventList);
Filter filter = new Filter();
filter.setPrefixRule("images");
filter.setSuffixRule("pg");
topicConfiguration.setFilter(filter);
topicConfigurationList.add(topicConfiguration);
notificationConfiguration.setTopicConfigurationList(topicConfigurationList);
client.setBucketNotification(destBucketName, notificationConfiguration);
client.removeBucket(destBucketName);
mintSuccessLog("setBucketNotification(String bucketName, NotificationConfiguration notificationConfiguration)",
null, startTime);
} catch (Exception e) {
mintFailedLog("setBucketNotification(String bucketName, NotificationConfiguration notificationConfiguration)",
null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: getBucketNotification(String bucketName).
*/
public static void getBucketNotification_test1() throws Exception {
// This test requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' environment variables.
String topic = System.getenv("MINIO_JAVA_TEST_TOPIC");
String region = System.getenv("MINIO_JAVA_TEST_REGION");
if (topic == null || topic.equals("") || region == null || region.equals("")) {
// do not run functional test as required environment variables are missing.
return;
}
if (!mintEnv) {
System.out.println("Test: getBucketNotification(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String destBucketName = getRandomName();
client.makeBucket(destBucketName, region);
NotificationConfiguration notificationConfiguration = new NotificationConfiguration();
// Add a new topic configuration.
List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList();
TopicConfiguration topicConfiguration = new TopicConfiguration();
topicConfiguration.setTopic(topic);
List<EventType> eventList = new LinkedList<>();
eventList.add(EventType.OBJECT_CREATED_PUT);
topicConfiguration.setEvents(eventList);
topicConfigurationList.add(topicConfiguration);
notificationConfiguration.setTopicConfigurationList(topicConfigurationList);
client.setBucketNotification(destBucketName, notificationConfiguration);
String expectedResult = notificationConfiguration.toString();
notificationConfiguration = client.getBucketNotification(destBucketName);
topicConfigurationList = notificationConfiguration.topicConfigurationList();
topicConfiguration = topicConfigurationList.get(0);
topicConfiguration.setId(null);
String result = notificationConfiguration.toString();
if (!result.equals(expectedResult)) {
System.out.println("FAILED. expected: " + expectedResult + ", got: " + result);
}
client.removeBucket(destBucketName);
mintSuccessLog("getBucketNotification(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("getBucketNotification(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* Test: removeAllBucketNotification(String bucketName).
*/
public static void removeAllBucketNotification_test1() throws Exception {
// This test requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' environment variables.
String topic = System.getenv("MINIO_JAVA_TEST_TOPIC");
String region = System.getenv("MINIO_JAVA_TEST_REGION");
if (topic == null || topic.equals("") || region == null || region.equals("")) {
// do not run functional test as required environment variables are missing.
return;
}
if (!mintEnv) {
System.out.println("Test: removeAllBucketNotification(String bucketName)");
}
long startTime = System.currentTimeMillis();
try {
String destBucketName = getRandomName();
client.makeBucket(destBucketName, region);
NotificationConfiguration notificationConfiguration = new NotificationConfiguration();
// Add a new topic configuration.
List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList();
TopicConfiguration topicConfiguration = new TopicConfiguration();
topicConfiguration.setTopic(topic);
List<EventType> eventList = new LinkedList<>();
eventList.add(EventType.OBJECT_CREATED_PUT);
eventList.add(EventType.OBJECT_CREATED_COPY);
topicConfiguration.setEvents(eventList);
Filter filter = new Filter();
filter.setPrefixRule("images");
filter.setSuffixRule("pg");
topicConfiguration.setFilter(filter);
topicConfigurationList.add(topicConfiguration);
notificationConfiguration.setTopicConfigurationList(topicConfigurationList);
client.setBucketNotification(destBucketName, notificationConfiguration);
notificationConfiguration = new NotificationConfiguration();
String expectedResult = notificationConfiguration.toString();
client.removeAllBucketNotification(destBucketName);
notificationConfiguration = client.getBucketNotification(destBucketName);
String result = notificationConfiguration.toString();
if (!result.equals(expectedResult)) {
throw new Exception("[FAILED] Expected: " + expectedResult + ", Got: " + result);
}
client.removeBucket(destBucketName);
mintSuccessLog("removeAllBucketNotification(String bucketName)", null, startTime);
} catch (Exception e) {
mintFailedLog("removeAllBucketNotification(String bucketName)", null, startTime, null,
e.toString() + " >>> " + Arrays.toString(e.getStackTrace()));
throw e;
}
}
/**
* runTests: runs as much as possible of test combinations.
*/
public static void runTests() throws Exception {
makeBucket_test1();
if (endpoint.toLowerCase(Locale.US).contains("s3")) {
makeBucketwithRegion_test();
makeBucketWithPeriod_test();
}
listBuckets_test();
bucketExists_test();
removeBucket_test();
setup();
putObject_test1();
putObject_test2();
putObject_test3();
putObject_test4();
putObject_test5();
putObject_test6();
putObject_test7();
putObject_test8();
putObject_test9();
putObject_test10();
putObject_test11();
putObject_test12();
statObject_test1();
getObject_test1();
getObject_test2();
getObject_test3();
getObject_test4();
getObject_test5();
getObject_test6();
getObject_test8();
listObject_test1();
listObject_test2();
listObject_test3();
listObject_test4();
listObject_test5();
listObject_test6();
removeObject_test1();
removeObject_test2();
listIncompleteUploads_test1();
listIncompleteUploads_test2();
listIncompleteUploads_test3();
removeIncompleteUploads_test();
presignedGetObject_test1();
presignedGetObject_test2();
presignedGetObject_test3();
presignedPutObject_test1();
presignedPutObject_test2();
presignedPostPolicy_test();
copyObject_test1();
copyObject_test2();
copyObject_test3();
copyObject_test4();
copyObject_test5();
copyObject_test6();
copyObject_test7();
copyObject_test8();
copyObject_test9();
// SSE_C tests will only work over TLS connection
Locale locale = Locale.ENGLISH;
boolean tlsEnabled = endpoint.toLowerCase(locale).contains("https://");
if (tlsEnabled) {
statObject_test2();
getObject_test7();
putObject_test13();
putObject_test16();
copyObject_test10();
}
// SSE_S3 and SSE_KMS only work with endpoint="s3.amazonaws.com"
String requestUrl = endpoint;
if (requestUrl.equals("s3.amazonaws.com")) {
putObject_test14();
putObject_test15();
copyObject_test11();
copyObject_test12();
}
getBucketPolicy_test1();
setBucketPolicy_test1();
threadedPutObject();
teardown();
// notification tests requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' environment variables
// to be set appropriately.
setBucketNotification_test1();
getBucketNotification_test1();
removeAllBucketNotification_test1();
}
/**
* runQuickTests: runs tests those completely quicker.
*/
public static void runQuickTests() throws Exception {
makeBucket_test1();
listBuckets_test();
bucketExists_test();
removeBucket_test();
setup();
putObject_test1();
statObject_test1();
getObject_test1();
listObject_test1();
removeObject_test1();
listIncompleteUploads_test1();
removeIncompleteUploads_test();
presignedGetObject_test1();
presignedPutObject_test1();
presignedPostPolicy_test();
copyObject_test1();
getBucketPolicy_test1();
setBucketPolicy_test1();
teardown();
}
/**
* main().
*/
public static void main(String[] args) {
if (args.length != 4) {
System.out.println("usage: FunctionalTest <ENDPOINT> <ACCESSKEY> <SECRETKEY> <REGION>");
System.exit(-1);
}
String dataDir = System.getenv("MINT_DATA_DIR");
if (dataDir != null && !dataDir.equals("")) {
mintEnv = true;
dataFile1Mb = Paths.get(dataDir, "datafile-1-MB");
dataFile65Mb = Paths.get(dataDir, "datafile-65-MB");
}
String mintMode = null;
if (mintEnv) {
mintMode = System.getenv("MINT_MODE");
}
endpoint = args[0];
accessKey = args[1];
secretKey = args[2];
region = args[3];
try {
client = new MinioClient(endpoint, accessKey, secretKey);
// Enable trace for debugging.
// client.traceOn(System.out);
// For mint environment, run tests based on mint mode
if (mintEnv) {
if (mintMode != null && mintMode.equals("full")) {
FunctionalTest.runTests();
} else {
FunctionalTest.runQuickTests();
}
} else {
FunctionalTest.runTests();
// Get new bucket name to avoid minio azure gateway failure.
bucketName = getRandomName();
// Quick tests with passed region.
client = new MinioClient(endpoint, accessKey, secretKey, region);
FunctionalTest.runQuickTests();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
| Set connection timeout for presignedPostPolicy functional test (#717)
Increase connection time out to 20 secs to prevent socket expiry.
Fixes #716 | functional/FunctionalTest.java | Set connection timeout for presignedPostPolicy functional test (#717) |
|
Java | apache-2.0 | 52c63fba0252afb8aacc8823a2333cbbcec61468 | 0 | vatbub/hangman-solver,vatbub/hangman-solver | package common;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javafx.util.converter.ByteStringConverter;
/**
* All custom internet functions
*
* @author Frederik Kammel
*
*/
public class Internet {
/**
* Sends an event to the IFTTT Maker Channel. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
*
* @param IFTTTMakerChannelApiKey Your Maker API Key. Get your one on <a href="https://ifttt.com/maker">https://ifttt.com/maker</a>
* @param eventName The name of the event to trigger.
* @throws IOException Should actually never be thrown but occurs if something is wrong with the connection (e. g. not connected)
*/
public static String sendEventToIFTTTMakerChannel(String IFTTTMakerChannelApiKey, String eventName) throws IOException {
return sendEventToIFTTTMakerChannel(IFTTTMakerChannelApiKey, eventName, "");
}
/**
* Sends an event to the IFTTT Maker Channel. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
*
* @param IFTTTMakerChannelApiKey Your Maker API Key. Get your one on <a href="https://ifttt.com/maker">https://ifttt.com/maker</a>
* @param eventName The name of the event to trigger.
* @param Details1 You can send up to three additional fields to the MAker channel which you can use then as IFTTT ingredients. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
* @throws IOException Should actually never be thrown but occurs if something is wrong with the connection (e. g. not connected)
*/
public static String sendEventToIFTTTMakerChannel(String IFTTTMakerChannelApiKey, String eventName, String Details1) throws IOException {
return sendEventToIFTTTMakerChannel(IFTTTMakerChannelApiKey, eventName, Details1, "");
}
/**
* Sends an event to the IFTTT Maker Channel. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
*
* @param IFTTTMakerChannelApiKey Your Maker API Key. Get your one on <a href="https://ifttt.com/maker">https://ifttt.com/maker</a>
* @param eventName The name of the event to trigger.
* @param Details1 You can send up to three additional fields to the MAker channel which you can use then as IFTTT ingredients. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
* @param Details2 The second additional parameter.
* @throws IOException Should actually never be thrown but occurs if something is wrong with the connection (e. g. not connected)
*/
public static String sendEventToIFTTTMakerChannel(String IFTTTMakerChannelApiKey, String eventName, String Details1,
String Details2) throws IOException {
return sendEventToIFTTTMakerChannel(IFTTTMakerChannelApiKey, eventName, Details1, Details2, "");
}
/**
* Sends an event to the IFTTT Maker Channel. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
*
* @param IFTTTMakerChannelApiKey Your Maker API Key. Get your one on <a href="https://ifttt.com/maker">https://ifttt.com/maker</a>
* @param eventName The name of the event to trigger.
* @param Details1 You can send up to three additional fields to the MAker channel which you can use then as IFTTT ingredients. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
* @param Details2 The second additional parameter.
* @param Details3 The third additional parameter.
* @throws IOException Should actually never be thrown but occurs if something is wrong with the connection (e. g. not connected)
*/
public static String sendEventToIFTTTMakerChannel(String IFTTTMakerChannelApiKey, String eventName, String Details1,
String Details2, String Details3) throws IOException {
HttpURLConnection connection = null;
String response = "";
URL url;
try {
url = new URL("https://maker.ifttt.com/trigger/" + eventName + "/with/key/" + IFTTTMakerChannelApiKey);
String postData = "{ \"value1\" : \"" + Details1 + "\", \"value2\" : \"" + Details2 + "\", \"value3\" : \""
+ Details3 + "\" }";
byte[] postData2 = postData.getBytes(StandardCharsets.UTF_8);
System.out.println(postData);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
ByteStringConverter bs = new ByteStringConverter();
wr.write(postData2);
connection.connect();
Reader in;
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;) {
response = response + Character.toString((char) c);
}
return response;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
}
| src/main/java/common/Internet.java | package common;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javafx.util.converter.ByteStringConverter;
/**
* All custom internet functions
*
* @author Frederik Kammel
*
*/
public class Internet {
/**
* Sends an event to the IFTTT Maker Channel. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
*
* @param IFTTTMakerChannelApiKey Your Maker API Key. Get your one on <a href="https://ifttt.com/maker"</a>
* @param eventName The name of the event to trigger.
* @throws IOException Should actually never be thrown but occurs if something is wrong with the connection (e. g. not connected)
*/
public static String sendEventToIFTTTMakerChannel(String IFTTTMakerChannelApiKey, String eventName) throws IOException {
return sendEventToIFTTTMakerChannel(IFTTTMakerChannelApiKey, eventName, "");
}
/**
* Sends an event to the IFTTT Maker Channel. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
*
* @param IFTTTMakerChannelApiKey Your Maker API Key. Get your one on <a href="https://ifttt.com/maker">https://ifttt.com/maker</a>
* @param eventName The name of the event to trigger.
* @param Details1 You can send up to three additional fields to the MAker channel which you can use then as IFTTT ingredients. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
* @throws IOException Should actually never be thrown but occurs if something is wrong with the connection (e. g. not connected)
*/
public static String sendEventToIFTTTMakerChannel(String IFTTTMakerChannelApiKey, String eventName, String Details1) throws IOException {
return sendEventToIFTTTMakerChannel(IFTTTMakerChannelApiKey, eventName, Details1, "");
}
/**
* Sends an event to the IFTTT Maker Channel. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
*
* @param IFTTTMakerChannelApiKey Your Maker API Key. Get your one on <a href="https://ifttt.com/maker">https://ifttt.com/maker</a>
* @param eventName The name of the event to trigger.
* @param Details1 You can send up to three additional fields to the MAker channel which you can use then as IFTTT ingredients. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
* @param Details2 The second additional parameter.
* @throws IOException Should actually never be thrown but occurs if something is wrong with the connection (e. g. not connected)
*/
public static String sendEventToIFTTTMakerChannel(String IFTTTMakerChannelApiKey, String eventName, String Details1,
String Details2) throws IOException {
return sendEventToIFTTTMakerChannel(IFTTTMakerChannelApiKey, eventName, Details1, Details2, "");
}
/**
* Sends an event to the IFTTT Maker Channel. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
*
* @param IFTTTMakerChannelApiKey Your Maker API Key. Get your one on <a href="https://ifttt.com/maker">https://ifttt.com/maker</a>
* @param eventName The name of the event to trigger.
* @param Details1 You can send up to three additional fields to the MAker channel which you can use then as IFTTT ingredients. See <a href="https://maker.ifttt.com/use/">https://maker.ifttt.com/use/</a> for more information.
* @param Details2 The second additional parameter.
* @param Details3 The third additional parameter.
* @throws IOException Should actually never be thrown but occurs if something is wrong with the connection (e. g. not connected)
*/
public static String sendEventToIFTTTMakerChannel(String IFTTTMakerChannelApiKey, String eventName, String Details1,
String Details2, String Details3) throws IOException {
HttpURLConnection connection = null;
String response = "";
URL url;
try {
url = new URL("https://maker.ifttt.com/trigger/" + eventName + "/with/key/" + IFTTTMakerChannelApiKey);
String postData = "{ \"value1\" : \"" + Details1 + "\", \"value2\" : \"" + Details2 + "\", \"value3\" : \""
+ Details3 + "\" }";
byte[] postData2 = postData.getBytes(StandardCharsets.UTF_8);
System.out.println(postData);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
ByteStringConverter bs = new ByteStringConverter();
wr.write(postData2);
connection.connect();
Reader in;
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;) {
response = response + Character.toString((char) c);
}
return response;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
}
| And again fixed some more invalid javadoc | src/main/java/common/Internet.java | And again fixed some more invalid javadoc |
|
Java | apache-2.0 | 366c315a6677049c03a17025771dea5b72834899 | 0 | HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j | /**
* Copyright (c) 2002-2010 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel;
import java.util.Iterator;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Expander;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipExpander;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.traversal.BranchOrderingPolicy;
import org.neo4j.graphdb.traversal.BranchSelector;
import org.neo4j.graphdb.traversal.PruneEvaluator;
import org.neo4j.graphdb.traversal.TraversalBranch;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.helpers.Predicate;
import org.neo4j.kernel.impl.traversal.FinalTraversalBranch;
import org.neo4j.kernel.impl.traversal.TraversalDescriptionImpl;
/**
* A factory for objects regarding traversal of the graph. F.ex. it has a
* method {@link #description()} for creating a new
* {@link TraversalDescription}, methods for creating new
* {@link TraversalBranch} instances and more.
*/
public class Traversal
{
private static final BranchOrderingPolicy PREORDER_DEPTH_FIRST_SELECTOR =
new BranchOrderingPolicy()
{
public BranchSelector create( TraversalBranch startSource )
{
return new PreorderDepthFirstSelector( startSource );
}
};
private static final BranchOrderingPolicy POSTORDER_DEPTH_FIRST_SELECTOR =
new BranchOrderingPolicy()
{
public BranchSelector create( TraversalBranch startSource )
{
return new PostorderDepthFirstSelector( startSource );
}
};
private static final BranchOrderingPolicy PREORDER_BREADTH_FIRST_SELECTOR =
new BranchOrderingPolicy()
{
public BranchSelector create( TraversalBranch startSource )
{
return new PreorderBreadthFirstSelector( startSource );
}
};
private static final BranchOrderingPolicy POSTORDER_BREADTH_FIRST_SELECTOR =
new BranchOrderingPolicy()
{
public BranchSelector create( TraversalBranch startSource )
{
return new PostorderBreadthFirstSelector( startSource );
}
};
private static final Predicate<Path> RETURN_ALL = new Predicate<Path>()
{
public boolean accept( Path item )
{
return true;
}
};
private static final Predicate<Path> RETURN_ALL_BUT_START_NODE = new Predicate<Path>()
{
public boolean accept( Path item )
{
return item.length() > 0;
}
};
/**
* Creates a new {@link TraversalDescription} with default value for
* everything so that it's OK to call
* {@link TraversalDescription#traverse(org.neo4j.graphdb.Node)} without
* modification. But it isn't a very useful traversal, instead you should
* add rules and behaviours to it before traversing.
*
* @return a new {@link TraversalDescription} with default values.
*/
public static TraversalDescription description()
{
return new TraversalDescriptionImpl();
}
/**
* Creates a new {@link RelationshipExpander} which is set to expand
* relationships with {@code type} and {@code direction}.
*
* @param type the {@link RelationshipType} to expand.
* @param dir the {@link Direction} to expand.
* @return a new {@link RelationshipExpander}.
*/
public static Expander expanderForTypes( RelationshipType type,
Direction dir )
{
return StandardExpander.create( type, dir );
}
/**
* Creates a new {@link RelationshipExpander} which is set to expand
* relationships with {@code type} in any direction.
*
* @param type the {@link RelationshipType} to expand.
* @return a new {@link RelationshipExpander}.
*/
public static Expander expanderForTypes( RelationshipType type )
{
return StandardExpander.create( type, Direction.BOTH );
}
/**
* Returns an empty {@link Expander} which, if not modified, will expand
* all relationships when asked to expand a {@link Node}. Criterias
* can be added to narrow the {@link Expansion}.
* @return an empty {@link Expander} which, if not modified, will expand
* all relationship for {@link Node}s.
*/
public static Expander emptyExpander()
{
return StandardExpander.DEFAULT; // TODO: should this be a PROPER empty?
}
/**
* Creates a new {@link RelationshipExpander} which is set to expand
* relationships with two different types and directions.
*
* @param type1 a {@link RelationshipType} to expand.
* @param dir1 a {@link Direction} to expand.
* @param type2 another {@link RelationshipType} to expand.
* @param dir2 another {@link Direction} to expand.
* @return a new {@link RelationshipExpander}.
*/
public static Expander expanderForTypes( RelationshipType type1,
Direction dir1, RelationshipType type2, Direction dir2 )
{
return StandardExpander.create( type1, dir1, type2, dir2 );
}
/**
* Creates a new {@link RelationshipExpander} which is set to expand
* relationships with multiple types and directions.
*
* @param type1 a {@link RelationshipType} to expand.
* @param dir1 a {@link Direction} to expand.
* @param type2 another {@link RelationshipType} to expand.
* @param dir2 another {@link Direction} to expand.
* @param more additional pairs or type/direction to expand.
* @return a new {@link RelationshipExpander}.
*/
public static Expander expanderForTypes( RelationshipType type1,
Direction dir1, RelationshipType type2, Direction dir2,
Object... more )
{
return StandardExpander.create( type1, dir1, type2, dir2, more );
}
/**
* Returns a {@link RelationshipExpander} which expands relationships
* of all types and directions.
* @return a relationship expander which expands all relationships.
*/
public static Expander expanderForAllTypes()
{
return expanderForAllTypes( Direction.BOTH );
}
/**
* Returns a {@link RelationshipExpander} which expands relationships
* of all types in the given {@code direction}.
* @return a relationship expander which expands all relationships in
* the given {@code direction}.
*/
public static Expander expanderForAllTypes( Direction direction )
{
return StandardExpander.create( direction );
}
/**
* Returns a {@link RelationshipExpander} wrapped as an {@link Expander}.
* @param expander {@link RelationshipExpander} to wrap.
* @return a {@link RelationshipExpander} wrapped as an {@link Expander}.
*/
public static Expander expander( RelationshipExpander expander )
{
if ( expander instanceof Expander )
{
return (Expander) expander;
}
return StandardExpander.wrap( expander );
}
/**
* Combines two {@link TraversalBranch}s with a common
* {@link TraversalBranch#node() head node} in order to obtain an
* {@link TraversalBranch} representing a path from the start node of the
* <code>source</code> {@link TraversalBranch} to the start node of the
* <code>target</code> {@link TraversalBranch}. The resulting
* {@link TraversalBranch} will not {@link TraversalBranch#next() expand
* further}, and does not provide a {@link TraversalBranch#parent() parent}
* {@link TraversalBranch}.
*
* @param source the {@link TraversalBranch} where the resulting path starts
* @param target the {@link TraversalBranch} where the resulting path ends
* @throws IllegalArgumentException if the {@link TraversalBranch#node()
* head nodes} of the supplied {@link TraversalBranch}s does not
* match
* @return an {@link TraversalBranch} that represents the path from the
* start node of the <code>source</code> {@link TraversalBranch} to
* the start node of the <code>target</code> {@link TraversalBranch}
*/
public static TraversalBranch combineSourcePaths( TraversalBranch source,
TraversalBranch target )
{
if ( !source.node().equals( target.node() ) )
{
throw new IllegalArgumentException(
"The nodes of the head and tail must match" );
}
Path headPath = source.position(), tailPath = target.position();
Relationship[] relationships = new Relationship[headPath.length()
+ tailPath.length()];
Iterator<Relationship> iter = headPath.relationships().iterator();
for ( int i = 0; iter.hasNext(); i++ )
{
relationships[i] = iter.next();
}
iter = tailPath.relationships().iterator();
for ( int i = relationships.length - 1; iter.hasNext(); i-- )
{
relationships[i] = iter.next();
}
return new FinalTraversalBranch( tailPath.startNode(), relationships );
}
/**
* A {@link PruneEvaluator} which prunes everything beyond {@code depth}.
* @param depth the depth to prune beyond (after).
* @return a {@link PruneEvaluator} which prunes everything after
* {@code depth}.
*/
public static PruneEvaluator pruneAfterDepth( final int depth )
{
return new PruneEvaluator()
{
public boolean pruneAfter( Path position )
{
return position.length() >= depth;
}
};
}
/**
* A traversal return filter which returns all {@link Path}s it encounters.
*
* @return a return filter which returns everything.
*/
public static Predicate<Path> returnAll()
{
return RETURN_ALL;
}
/**
* Returns a filter which accepts items accepted by at least one of the
* supplied filters.
*
* @param filters
* @return
*/
public static Predicate<Path> returnAcceptedByAny( final Predicate<Path>... filters )
{
return new Predicate<Path>()
{
public boolean accept( Path item )
{
for ( Predicate<Path> filter : filters )
{
if ( filter.accept( item ) )
{
return true;
}
}
return false;
}
};
}
/**
* A traversal return filter which returns all {@link Path}s except the
* position of the start node.
*
* @return a return filter which returns everything except the start node.
*/
public static Predicate<Path> returnAllButStartNode()
{
return RETURN_ALL_BUT_START_NODE;
}
/**
* Returns a "preorder depth first" ordering policy. A depth first selector
* always tries to select positions (from the current position) which are
* deeper than the current position.
*
* @return a {@link BranchOrderingPolicy} for a preorder depth first
* selector.
*/
public static BranchOrderingPolicy preorderDepthFirst()
{
return PREORDER_DEPTH_FIRST_SELECTOR;
}
/**
* Returns a "postorder depth first" ordering policy. A depth first selector
* always tries to select positions (from the current position) which are
* deeper than the current position. A postorder depth first selector
* selects deeper position before the shallower ones.
*
* @return a {@link BranchOrderingPolicy} for a postorder depth first
* selector.
*/
public static BranchOrderingPolicy postorderDepthFirst()
{
return POSTORDER_DEPTH_FIRST_SELECTOR;
}
/**
* Returns a "preorder breadth first" ordering policy. A breadth first
* selector always selects all positions on the current depth before
* advancing to the next depth.
*
* @return a {@link BranchOrderingPolicy} for a preorder breadth first
* selector.
*/
public static BranchOrderingPolicy preorderBreadthFirst()
{
return PREORDER_BREADTH_FIRST_SELECTOR;
}
/**
* Returns a "postorder breadth first" ordering policy. A breadth first
* selector always selects all positions on the current depth before
* advancing to the next depth. A postorder breadth first selector selects
* the levels in the reversed order, starting with the deepest.
*
* @return a {@link BranchOrderingPolicy} for a postorder breadth first
* selector.
*/
public static BranchOrderingPolicy postorderBreadthFirst()
{
return POSTORDER_BREADTH_FIRST_SELECTOR;
}
/**
* Provides hooks to help build a string representation of a {@link Path}.
* @param <T> the type of {@link Path}.
*/
public static interface PathDescriptor<T extends Path>
{
/**
* Returns a string representation of a {@link Node}.
* @param path the {@link Path} we're building a string representation
* from.
* @param node the {@link Node} to return a string representation of.
* @return a string representation of a {@link Node}.
*/
String nodeRepresentation( T path, Node node );
/**
* Returns a string representation of a {@link Relationship}.
* @param path the {@link Path} we're building a string representation
* from.
* @param from the previous {@link Node} in the path.
* @param relationship the {@link Relationship} to return a string
* representation of.
* @return a string representation of a {@link Relationship}.
*/
String relationshipRepresentation( T path, Node from,
Relationship relationship );
}
/**
* The default {@link PathDescriptor} used in common toString()
* representations in classes implementing {@link Path}.
* @param <T> the type of {@link Path}.
*/
public static class DefaultPathDescriptor<T extends Path> implements PathDescriptor<T>
{
public String nodeRepresentation( Path path, Node node )
{
return "(" + node.getId() + ")";
}
public String relationshipRepresentation( Path path,
Node from, Relationship relationship )
{
String prefix = "--", suffix = "--";
if ( from.equals( relationship.getEndNode() ) )
{
prefix = "<--";
}
else
{
suffix = "-->";
}
return prefix + "[" + relationship.getType().name() + "," +
relationship.getId() + "]" + suffix;
}
}
/**
* Method for building a string representation of a {@link Path}, using
* the given {@code builder}.
* @param <T> the type of {@link Path}.
* @param path the {@link Path} to build a string representation of.
* @param builder the {@link PathDescriptor} to get
* {@link Node} and {@link Relationship} representations from.
* @return a string representation of a {@link Path}.
*/
public static <T extends Path> String pathToString( T path, PathDescriptor<T> builder )
{
Node current = path.startNode();
StringBuilder result = new StringBuilder();
for ( Relationship rel : path.relationships() )
{
result.append( builder.nodeRepresentation( path, current ) );
result.append( builder.relationshipRepresentation( path, current, rel ) );
current = rel.getOtherNode( current );
}
result.append( builder.nodeRepresentation( path, current ) );
return result.toString();
}
/**
* Returns the default string representation of a {@link Path}. It uses
* the {@link DefaultPathDescriptor} to get representations.
* @param path the {@link Path} to build a string representation of.
* @return the default string representation of a {@link Path}.
*/
public static String defaultPathToString( Path path )
{
return pathToString( path, new DefaultPathDescriptor<Path>() );
}
/**
* Returns a quite simple string representation of a {@link Path}. It
* doesn't print relationship types or ids, just directions.
* @param path the {@link Path} to build a string representation of.
* @return a quite simple representation of a {@link Path}.
*/
public static String simplePathToString( Path path )
{
return pathToString( path, new DefaultPathDescriptor<Path>()
{
@Override
public String relationshipRepresentation( Path path, Node from,
Relationship relationship )
{
return relationship.getStartNode().equals( from ) ? "-->" : "<--";
}
} );
}
/**
* Returns a quite simple string representation of a {@link Path}. It
* doesn't print relationship types or ids, just directions. it uses the
* {@code nodePropertyKey} to try to display that property value as in the
* node representation instead of the node id. If that property doesn't
* exist, the id is used.
* @param path the {@link Path} to build a string representation of.
* @return a quite simple representation of a {@link Path}.
*/
public static String simplePathToString( Path path, final String nodePropertyKey )
{
return pathToString( path, new DefaultPathDescriptor<Path>()
{
@Override
public String nodeRepresentation( Path path, Node node )
{
return "(" + node.getProperty( nodePropertyKey, node.getId() ) + ")";
}
@Override
public String relationshipRepresentation( Path path, Node from,
Relationship relationship )
{
return relationship.getStartNode().equals( from ) ? "-->" : "<--";
}
} );
}
public static Predicate<Path> returnWhereLastRelationshipTypeIs(
final RelationshipType firstRelationshipType,
final RelationshipType... relationshipTypes )
{
return new Predicate<Path>()
{
public boolean accept( Path p )
{
Relationship lastRel = p.lastRelationship();
if ( lastRel == null )
{
return false;
}
if ( lastRel.isType( firstRelationshipType ) )
{
return true;
}
for ( RelationshipType currentType : relationshipTypes )
{
if ( lastRel.isType( currentType ) )
{
return true;
}
}
return false;
}
};
}
}
| community/src/main/java/org/neo4j/kernel/Traversal.java | /**
* Copyright (c) 2002-2010 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel;
import java.util.Iterator;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Expander;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipExpander;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.traversal.BranchOrderingPolicy;
import org.neo4j.graphdb.traversal.BranchSelector;
import org.neo4j.graphdb.traversal.PruneEvaluator;
import org.neo4j.graphdb.traversal.TraversalBranch;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.helpers.Predicate;
import org.neo4j.kernel.impl.traversal.FinalTraversalBranch;
import org.neo4j.kernel.impl.traversal.TraversalDescriptionImpl;
/**
* A factory for objects regarding traversal of the graph. F.ex. it has a
* method {@link #description()} for creating a new
* {@link TraversalDescription}, methods for creating new
* {@link TraversalBranch} instances and more.
*/
public class Traversal
{
private static final BranchOrderingPolicy PREORDER_DEPTH_FIRST_SELECTOR =
new BranchOrderingPolicy()
{
public BranchSelector create( TraversalBranch startSource )
{
return new PreorderDepthFirstSelector( startSource );
}
};
private static final BranchOrderingPolicy POSTORDER_DEPTH_FIRST_SELECTOR =
new BranchOrderingPolicy()
{
public BranchSelector create( TraversalBranch startSource )
{
return new PostorderDepthFirstSelector( startSource );
}
};
private static final BranchOrderingPolicy PREORDER_BREADTH_FIRST_SELECTOR =
new BranchOrderingPolicy()
{
public BranchSelector create( TraversalBranch startSource )
{
return new PreorderBreadthFirstSelector( startSource );
}
};
private static final BranchOrderingPolicy POSTORDER_BREADTH_FIRST_SELECTOR =
new BranchOrderingPolicy()
{
public BranchSelector create( TraversalBranch startSource )
{
return new PostorderBreadthFirstSelector( startSource );
}
};
private static final Predicate<Path> RETURN_ALL = new Predicate<Path>()
{
public boolean accept( Path item )
{
return true;
}
};
private static final Predicate<Path> RETURN_ALL_BUT_START_NODE = new Predicate<Path>()
{
public boolean accept( Path item )
{
return item.length() > 0;
}
};
/**
* Creates a new {@link TraversalDescription} with default value for
* everything so that it's OK to call
* {@link TraversalDescription#traverse(org.neo4j.graphdb.Node)} without
* modification. But it isn't a very useful traversal, instead you should
* add rules and behaviours to it before traversing.
*
* @return a new {@link TraversalDescription} with default values.
*/
public static TraversalDescription description()
{
return new TraversalDescriptionImpl();
}
/**
* Creates a new {@link RelationshipExpander} which is set to expand
* relationships with {@code type} and {@code direction}.
*
* @param type the {@link RelationshipType} to expand.
* @param dir the {@link Direction} to expand.
* @return a new {@link RelationshipExpander}.
*/
public static Expander expanderForTypes( RelationshipType type,
Direction dir )
{
return StandardExpander.create( type, dir );
}
/**
* Returns an empty {@link Expander} which, if not modified, will expand
* all relationships when asked to expand a {@link Node}. Criterias
* can be added to narrow the {@link Expansion}.
* @return an empty {@link Expander} which, if not modified, will expand
* all relationship for {@link Node}s.
*/
public static Expander emptyExpander()
{
return StandardExpander.DEFAULT; // TODO: should this be a PROPER empty?
}
/**
* Creates a new {@link RelationshipExpander} which is set to expand
* relationships with two different types and directions.
*
* @param type1 a {@link RelationshipType} to expand.
* @param dir1 a {@link Direction} to expand.
* @param type2 another {@link RelationshipType} to expand.
* @param dir2 another {@link Direction} to expand.
* @return a new {@link RelationshipExpander}.
*/
public static Expander expanderForTypes( RelationshipType type1,
Direction dir1, RelationshipType type2, Direction dir2 )
{
return StandardExpander.create( type1, dir1, type2, dir2 );
}
/**
* Creates a new {@link RelationshipExpander} which is set to expand
* relationships with multiple types and directions.
*
* @param type1 a {@link RelationshipType} to expand.
* @param dir1 a {@link Direction} to expand.
* @param type2 another {@link RelationshipType} to expand.
* @param dir2 another {@link Direction} to expand.
* @param more additional pairs or type/direction to expand.
* @return a new {@link RelationshipExpander}.
*/
public static Expander expanderForTypes( RelationshipType type1,
Direction dir1, RelationshipType type2, Direction dir2,
Object... more )
{
return StandardExpander.create( type1, dir1, type2, dir2, more );
}
/**
* Returns a {@link RelationshipExpander} which expands relationships
* of all types and directions.
* @return a relationship expander which expands all relationships.
*/
public static Expander expanderForAllTypes()
{
return expanderForAllTypes( Direction.BOTH );
}
/**
* Returns a {@link RelationshipExpander} which expands relationships
* of all types in the given {@code direction}.
* @return a relationship expander which expands all relationships in
* the given {@code direction}.
*/
public static Expander expanderForAllTypes( Direction direction )
{
return StandardExpander.create( direction );
}
/**
* Returns a {@link RelationshipExpander} wrapped as an {@link Expander}.
* @param expander {@link RelationshipExpander} to wrap.
* @return a {@link RelationshipExpander} wrapped as an {@link Expander}.
*/
public static Expander expander( RelationshipExpander expander )
{
if ( expander instanceof Expander )
{
return (Expander) expander;
}
return StandardExpander.wrap( expander );
}
/**
* Combines two {@link TraversalBranch}s with a common
* {@link TraversalBranch#node() head node} in order to obtain an
* {@link TraversalBranch} representing a path from the start node of the
* <code>source</code> {@link TraversalBranch} to the start node of the
* <code>target</code> {@link TraversalBranch}. The resulting
* {@link TraversalBranch} will not {@link TraversalBranch#next() expand
* further}, and does not provide a {@link TraversalBranch#parent() parent}
* {@link TraversalBranch}.
*
* @param source the {@link TraversalBranch} where the resulting path starts
* @param target the {@link TraversalBranch} where the resulting path ends
* @throws IllegalArgumentException if the {@link TraversalBranch#node()
* head nodes} of the supplied {@link TraversalBranch}s does not
* match
* @return an {@link TraversalBranch} that represents the path from the
* start node of the <code>source</code> {@link TraversalBranch} to
* the start node of the <code>target</code> {@link TraversalBranch}
*/
public static TraversalBranch combineSourcePaths( TraversalBranch source,
TraversalBranch target )
{
if ( !source.node().equals( target.node() ) )
{
throw new IllegalArgumentException(
"The nodes of the head and tail must match" );
}
Path headPath = source.position(), tailPath = target.position();
Relationship[] relationships = new Relationship[headPath.length()
+ tailPath.length()];
Iterator<Relationship> iter = headPath.relationships().iterator();
for ( int i = 0; iter.hasNext(); i++ )
{
relationships[i] = iter.next();
}
iter = tailPath.relationships().iterator();
for ( int i = relationships.length - 1; iter.hasNext(); i-- )
{
relationships[i] = iter.next();
}
return new FinalTraversalBranch( tailPath.startNode(), relationships );
}
/**
* A {@link PruneEvaluator} which prunes everything beyond {@code depth}.
* @param depth the depth to prune beyond (after).
* @return a {@link PruneEvaluator} which prunes everything after
* {@code depth}.
*/
public static PruneEvaluator pruneAfterDepth( final int depth )
{
return new PruneEvaluator()
{
public boolean pruneAfter( Path position )
{
return position.length() >= depth;
}
};
}
/**
* A traversal return filter which returns all {@link Path}s it encounters.
*
* @return a return filter which returns everything.
*/
public static Predicate<Path> returnAll()
{
return RETURN_ALL;
}
/**
* Returns a filter which accepts items accepted by at least one of the
* supplied filters.
*
* @param filters
* @return
*/
public static Predicate<Path> returnAcceptedByAny( final Predicate<Path>... filters )
{
return new Predicate<Path>()
{
public boolean accept( Path item )
{
for ( Predicate<Path> filter : filters )
{
if ( filter.accept( item ) )
{
return true;
}
}
return false;
}
};
}
/**
* A traversal return filter which returns all {@link Path}s except the
* position of the start node.
*
* @return a return filter which returns everything except the start node.
*/
public static Predicate<Path> returnAllButStartNode()
{
return RETURN_ALL_BUT_START_NODE;
}
/**
* Returns a "preorder depth first" ordering policy. A depth first selector
* always tries to select positions (from the current position) which are
* deeper than the current position.
*
* @return a {@link BranchOrderingPolicy} for a preorder depth first
* selector.
*/
public static BranchOrderingPolicy preorderDepthFirst()
{
return PREORDER_DEPTH_FIRST_SELECTOR;
}
/**
* Returns a "postorder depth first" ordering policy. A depth first selector
* always tries to select positions (from the current position) which are
* deeper than the current position. A postorder depth first selector
* selects deeper position before the shallower ones.
*
* @return a {@link BranchOrderingPolicy} for a postorder depth first
* selector.
*/
public static BranchOrderingPolicy postorderDepthFirst()
{
return POSTORDER_DEPTH_FIRST_SELECTOR;
}
/**
* Returns a "preorder breadth first" ordering policy. A breadth first
* selector always selects all positions on the current depth before
* advancing to the next depth.
*
* @return a {@link BranchOrderingPolicy} for a preorder breadth first
* selector.
*/
public static BranchOrderingPolicy preorderBreadthFirst()
{
return PREORDER_BREADTH_FIRST_SELECTOR;
}
/**
* Returns a "postorder breadth first" ordering policy. A breadth first
* selector always selects all positions on the current depth before
* advancing to the next depth. A postorder breadth first selector selects
* the levels in the reversed order, starting with the deepest.
*
* @return a {@link BranchOrderingPolicy} for a postorder breadth first
* selector.
*/
public static BranchOrderingPolicy postorderBreadthFirst()
{
return POSTORDER_BREADTH_FIRST_SELECTOR;
}
/**
* Provides hooks to help build a string representation of a {@link Path}.
* @param <T> the type of {@link Path}.
*/
public static interface PathDescriptor<T extends Path>
{
/**
* Returns a string representation of a {@link Node}.
* @param path the {@link Path} we're building a string representation
* from.
* @param node the {@link Node} to return a string representation of.
* @return a string representation of a {@link Node}.
*/
String nodeRepresentation( T path, Node node );
/**
* Returns a string representation of a {@link Relationship}.
* @param path the {@link Path} we're building a string representation
* from.
* @param from the previous {@link Node} in the path.
* @param relationship the {@link Relationship} to return a string
* representation of.
* @return a string representation of a {@link Relationship}.
*/
String relationshipRepresentation( T path, Node from,
Relationship relationship );
}
/**
* The default {@link PathDescriptor} used in common toString()
* representations in classes implementing {@link Path}.
* @param <T> the type of {@link Path}.
*/
public static class DefaultPathDescriptor<T extends Path> implements PathDescriptor<T>
{
public String nodeRepresentation( Path path, Node node )
{
return "(" + node.getId() + ")";
}
public String relationshipRepresentation( Path path,
Node from, Relationship relationship )
{
String prefix = "--", suffix = "--";
if ( from.equals( relationship.getEndNode() ) )
{
prefix = "<--";
}
else
{
suffix = "-->";
}
return prefix + "[" + relationship.getType().name() + "," +
relationship.getId() + "]" + suffix;
}
}
/**
* Method for building a string representation of a {@link Path}, using
* the given {@code builder}.
* @param <T> the type of {@link Path}.
* @param path the {@link Path} to build a string representation of.
* @param builder the {@link PathDescriptor} to get
* {@link Node} and {@link Relationship} representations from.
* @return a string representation of a {@link Path}.
*/
public static <T extends Path> String pathToString( T path, PathDescriptor<T> builder )
{
Node current = path.startNode();
StringBuilder result = new StringBuilder();
for ( Relationship rel : path.relationships() )
{
result.append( builder.nodeRepresentation( path, current ) );
result.append( builder.relationshipRepresentation( path, current, rel ) );
current = rel.getOtherNode( current );
}
result.append( builder.nodeRepresentation( path, current ) );
return result.toString();
}
/**
* Returns the default string representation of a {@link Path}. It uses
* the {@link DefaultPathDescriptor} to get representations.
* @param path the {@link Path} to build a string representation of.
* @return the default string representation of a {@link Path}.
*/
public static String defaultPathToString( Path path )
{
return pathToString( path, new DefaultPathDescriptor<Path>() );
}
/**
* Returns a quite simple string representation of a {@link Path}. It
* doesn't print relationship types or ids, just directions.
* @param path the {@link Path} to build a string representation of.
* @return a quite simple representation of a {@link Path}.
*/
public static String simplePathToString( Path path )
{
return pathToString( path, new DefaultPathDescriptor<Path>()
{
@Override
public String relationshipRepresentation( Path path, Node from,
Relationship relationship )
{
return relationship.getStartNode().equals( from ) ? "-->" : "<--";
}
} );
}
/**
* Returns a quite simple string representation of a {@link Path}. It
* doesn't print relationship types or ids, just directions. it uses the
* {@code nodePropertyKey} to try to display that property value as in the
* node representation instead of the node id. If that property doesn't
* exist, the id is used.
* @param path the {@link Path} to build a string representation of.
* @return a quite simple representation of a {@link Path}.
*/
public static String simplePathToString( Path path, final String nodePropertyKey )
{
return pathToString( path, new DefaultPathDescriptor<Path>()
{
@Override
public String nodeRepresentation( Path path, Node node )
{
return "(" + node.getProperty( nodePropertyKey, node.getId() ) + ")";
}
@Override
public String relationshipRepresentation( Path path, Node from,
Relationship relationship )
{
return relationship.getStartNode().equals( from ) ? "-->" : "<--";
}
} );
}
public static Predicate<Path> returnWhereLastRelationshipTypeIs(
final RelationshipType firstRelationshipType,
final RelationshipType... relationshipTypes )
{
return new Predicate<Path>()
{
public boolean accept( Path p )
{
Relationship lastRel = p.lastRelationship();
if ( lastRel == null )
{
return false;
}
if ( lastRel.isType( firstRelationshipType ) )
{
return true;
}
for ( RelationshipType currentType : relationshipTypes )
{
if ( lastRel.isType( currentType ) )
{
return true;
}
}
return false;
}
};
}
}
| Added a simple utility for expander for a certain type in any direction
git-svn-id: ab16e2fa1fbc06680b955d2946a056ad3c063f42@6374 0b971d98-bb2f-0410-8247-b05b2b5feb2a
| community/src/main/java/org/neo4j/kernel/Traversal.java | Added a simple utility for expander for a certain type in any direction |
|
Java | apache-2.0 | 4eec02027d3b2e963f83b3d3e15d205338fd9177 | 0 | Anisotrop/gateway,jfallows/gateway,kaazing/gateway,Anisotrop/gateway,jfallows/gateway,sanjay-saxena/gateway,mjolie/gateway,nemigaservices/gateway,a-zuckut/gateway,mjolie/gateway,adrian-galbenus/gateway,mgherghe/gateway,mgherghe/gateway,irina-mitrea-luxoft/gateway,cmebarrow/gateway,kaazing/gateway,AdrianCozma/gateway,Anisotrop/gateway,adrian-galbenus/gateway,mgherghe/gateway,kaazing/gateway,vmaraloiu/gateway,jitsni/gateway,chao-sun-kaazing/gateway,jfallows/gateway,sanjay-saxena/gateway,nemigaservices/gateway,a-zuckut/gateway,nemigaservices/gateway,dpwspoon/gateway,danibusu/gateway,vmaraloiu/gateway,nemigaservices/gateway,cmebarrow/gateway,vmaraloiu/gateway,danibusu/gateway,AdrianCozma/gateway,vmaraloiu/gateway,cmebarrow/gateway,mjolie/gateway,DoruM/gateway,jfallows/gateway,adrian-galbenus/gateway,a-zuckut/gateway,stanculescu/gateway,chao-sun-kaazing/gateway,justinma246/gateway,kaazing/gateway,chao-sun-kaazing/gateway,sanjay-saxena/gateway,DoruM/gateway,justinma246/gateway,stanculescu/gateway,a-zuckut/gateway,jitsni/gateway,dpwspoon/gateway,DoruM/gateway,danibusu/gateway,stanculescu/gateway,justinma246/gateway,mjolie/gateway,irina-mitrea-luxoft/gateway,cmebarrow/gateway,AdrianCozma/gateway,DoruM/gateway,chao-sun-kaazing/gateway,danibusu/gateway,irina-mitrea-luxoft/gateway,AdrianCozma/gateway,jitsni/gateway,mgherghe/gateway,justinma246/gateway,dpwspoon/gateway,irina-mitrea-luxoft/gateway,adrian-galbenus/gateway,sanjay-saxena/gateway,stanculescu/gateway,jitsni/gateway,Anisotrop/gateway,dpwspoon/gateway | /**
* Copyright 2007-2015, Kaazing Corporation. 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 org.kaazing.gateway.server.context.resolve;
import com.hazelcast.config.AwsConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.Join;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MulticastConfig;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.config.TcpIpConfig;
import com.hazelcast.core.Cluster;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.core.IdGenerator;
import com.hazelcast.core.Member;
import com.hazelcast.core.MembershipEvent;
import com.hazelcast.core.MembershipListener;
import com.hazelcast.impl.GroupProperties;
import com.hazelcast.logging.LogEvent;
import com.hazelcast.logging.LogListener;
import com.hazelcast.logging.LoggingService;
import com.hazelcast.nio.Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.kaazing.gateway.server.messaging.buffer.ClusterMemoryMessageBufferFactory;
import org.kaazing.gateway.server.messaging.collections.ClusterCollectionsFactory;
import org.kaazing.gateway.service.cluster.BalancerMapListener;
import org.kaazing.gateway.service.cluster.ClusterConnectOptionsContext;
import org.kaazing.gateway.service.cluster.ClusterContext;
import org.kaazing.gateway.service.cluster.ClusterMessaging;
import org.kaazing.gateway.service.cluster.InstanceKeyListener;
import org.kaazing.gateway.service.cluster.MemberId;
import org.kaazing.gateway.service.cluster.MembershipEventListener;
import org.kaazing.gateway.service.cluster.ReceiveListener;
import org.kaazing.gateway.service.cluster.SendListener;
import org.kaazing.gateway.service.messaging.buffer.MessageBufferFactory;
import org.kaazing.gateway.service.messaging.collections.CollectionsFactory;
import org.kaazing.gateway.util.GL;
import org.kaazing.gateway.util.Utils;
import org.kaazing.gateway.util.aws.AwsUtils;
import org.kaazing.gateway.util.scheduler.SchedulerProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.kaazing.gateway.server.context.resolve.DefaultServiceContext.BALANCER_MAP_NAME;
import static org.kaazing.gateway.server.context.resolve.DefaultServiceContext.MEMBERID_BALANCER_MAP_NAME;
/**
* ClusterContext for KEG
* <p/>
* <br>Balancer data<ol> <li> HttpBalancerService.MEMBERID_BALANCER_MAP_NAME: <ul><li> List of balanced URIs for one member
* <li>Key: Cluster member id <li>Value: Map(key: balancerURI, value: acceptURIs) </ul> <li>HttpBalancerService.BALANCER_MAP_NAME
* <ul><li> List of balanced URIs for whole cluster <li>Key: balanceURI <li>Value: acceptURIs </ul> </ol>
*/
public class DefaultClusterContext implements ClusterContext, LogListener {
private static final String CLUSTER_LOG_FORMAT = "HAZELCAST: [%s] - %s";
private static final String INSTANCE_KEY_MAP = "instanceKeyMap";
// This is also used in DefaultServiceContext
static final String CLUSTER_LOGGER_NAME = "ha";
private final Logger logger = LoggerFactory.getLogger(CLUSTER_LOGGER_NAME);
private final String localInstanceKey = Utils.randomHexString(16);
private MessageBufferFactory messageBufferFactory;
private CollectionsFactory collectionsFactory;
private List<MemberId> localInterfaces = new ArrayList<>();
private final List<MemberId> clusterMembers = new ArrayList<>();
private final List<MembershipEventListener> membershipEventListeners = new ArrayList<>();
private final List<InstanceKeyListener> instanceKeyListeners = new ArrayList<>();
private final List<BalancerMapListener> balancerMapListeners = new ArrayList<>();
private ClusterMessaging clusterMessaging;
private MemberId localNodeId;
private final String clusterName;
private HazelcastInstance clusterInstance;
private final SchedulerProvider schedulerProvider;
private final ClusterConnectOptionsContext connectOptions;
private final AtomicBoolean clusterInitialized = new AtomicBoolean(false);
public DefaultClusterContext(String name,
List<MemberId> interfaces,
List<MemberId> members,
SchedulerProvider schedulerProvider) {
this(name, interfaces, members, schedulerProvider, null);
}
public DefaultClusterContext(String name,
List<MemberId> interfaces,
List<MemberId> members,
SchedulerProvider schedulerProvider,
ClusterConnectOptionsContext connectOptions) {
this.clusterName = name;
this.localInterfaces.addAll(interfaces);
this.clusterMembers.addAll(members);
this.schedulerProvider = schedulerProvider;
this.connectOptions = connectOptions;
}
@Override
public void start() {
// Check that we have either localInterfaces or clusterMembers
if (localInterfaces.size() + clusterMembers.size() == 0) {
// if no local interfaces
if (localInterfaces.size() == 0) {
GL.info(CLUSTER_LOGGER_NAME, "No network interfaces specified in the gateway configuration");
throw new IllegalArgumentException("No network interfaces specified in the gateway configuration");
}
// if no members
if (clusterMembers.size() == 0) {
GL.info(CLUSTER_LOGGER_NAME, "No cluster members specified in the gateway configuration");
throw new IllegalArgumentException("No cluster members specified in the gateway configuration");
}
}
try {
// from ha.xml and then add members interfaces
Config config = initializeHazelcastConfig();
initializeCluster(config);
GL.info(CLUSTER_LOGGER_NAME, "Cluster Member started: IP Address: {}; Port: {}; id: {}",
localNodeId.getHost(), localNodeId.getPort(), localNodeId.getId());
} catch (Exception e) {
GL.error(CLUSTER_LOGGER_NAME, "Unable to initialize cluster due to an exception: {}", e);
throw new RuntimeException(String.format("Unable to initialize cluster due to an exception: %s", e), e);
}
}
@Override
public void dispose() {
// If we're in client mode, then we may not have this clusterMessaging
// object. So don't try to destroy it if it is not there at all
// (KG-3496).
if (clusterMessaging != null) {
clusterMessaging.destroy();
}
if (clusterInstance != null) {
// KG-5837: do not call Hazelcast.shutdownAll() since that will hobble all in-process gateways
clusterInstance.getLifecycleService().shutdown();
}
}
private Config initializeHazelcastConfig() throws Exception {
Config hazelCastConfig = new Config();
hazelCastConfig.getGroupConfig().setName(getClusterName());
hazelCastConfig.getGroupConfig().setPassword("5942");
MapConfig mapConfig = hazelCastConfig.getMapConfig("serverSessions");
mapConfig.setBackupCount(3);
MapConfig sharedBalancerMapConfig = hazelCastConfig.getMapConfig(BALANCER_MAP_NAME);
sharedBalancerMapConfig.setBackupCount(Integer.MAX_VALUE);
MapConfig memberBalancerMapConfig = hazelCastConfig.getMapConfig(MEMBERID_BALANCER_MAP_NAME);
memberBalancerMapConfig.setBackupCount(Integer.MAX_VALUE);
// disable port auto increment
hazelCastConfig.setPortAutoIncrement(false);
// The first accepts port is the port used by all network interfaces.
int clusterPort = (localInterfaces.size() > 0) ? localInterfaces.get(0).getPort() : -1;
// TO turn off logging in hazelcast API.
// Note: must use Logger.getLogger, not LogManager.getLogger
java.util.logging.Logger logger = java.util.logging.Logger.getLogger("com.hazelcast");
logger.setLevel(Level.OFF);
// initialize hazelcast
if (clusterPort != -1) {
hazelCastConfig.setPort(clusterPort);
}
NetworkConfig networkConfig = new NetworkConfig();
for (MemberId localInterface : localInterfaces) {
String protocol = localInterface.getProtocol();
if ("udp".equalsIgnoreCase(protocol) || "aws".equalsIgnoreCase(protocol)) {
throw new IllegalArgumentException("Cannot accept on a multicast or aws address, use unicast address starting " +
"with tcp://");
}
// NOTE: The version of Hazelcast(1.9.4.8) that is being used does not support IPv6 address. The Hazelcast library
// throws NumberFormatException when IPv6 address is specified as an interface to bind to.
String hostAddress = localInterface.getHost();
InetAddress address = InetAddress.getByName(hostAddress);
if (address instanceof Inet6Address) {
throw new IllegalArgumentException("ERROR: Cluster member accept url - '" + localInterface.toString() +
"' consists of IPv6 address which is not supported. Use Ipv4 address instead.");
}
networkConfig.getInterfaces().addInterface(localInterface.getHost());
if (localInterface.getPort() != clusterPort) {
throw new IllegalArgumentException("Port numbers on the network interfaces in <accept> do not match");
}
}
boolean usingMulticast = false;
Join joinConfig = networkConfig.getJoin();
MulticastConfig multicastConfig = joinConfig.getMulticastConfig();
// Disable multicast to avoid using the default multicast address 224.2.2.3:54327.
// In this way, new cluster members joining the cluster won't accidentally join
// due to having configured the default multicast address. If multicast adresses are mentioned below,
// we enable it. See KG-6045 for an example of an accidental multicast cluster connection.
multicastConfig.setEnabled(false);
TcpIpConfig tcpIpConfig = joinConfig.getTcpIpConfig();
List<InetSocketAddress> multicastAddresses = new ArrayList<>();
List<InetSocketAddress> unicastAddresses = new ArrayList<>();
MemberId awsMember = null;
for (MemberId member : clusterMembers) {
if (member.getProtocol().equals("udp")) {
multicastAddresses.add(new InetSocketAddress(member.getHost(), member.getPort()));
} else if (member.getProtocol().equals("tcp")) {
unicastAddresses.add(new InetSocketAddress(member.getHost(), member.getPort()));
} else if (member.getProtocol().equals("aws")) {
awsMember = member;
// There should be only one <connect> tag when AWS is being
// used. We have already validated that in
// GatewayContextResolver.processClusterMembers() method.
}
}
if (awsMember == null) {
// Gateway is running in an on-premise env.
int multicastAddressesCount = multicastAddresses.size();
if (multicastAddressesCount > 1) {
throw new IllegalArgumentException("Conflicting multicast discovery addresses in cluster configuration");
} else if (multicastAddressesCount > 0) {
if (AwsUtils.isDeployedToAWS()) {
throw new IllegalArgumentException("Multicast cluster configuration not supported on AWS, use " +
"aws://security-group/<security-group-name> in connect tag");
}
multicastConfig.setEnabled(true);
InetSocketAddress multicastAddress = multicastAddresses.get(0);
multicastConfig.setMulticastGroup(multicastAddress.getHostName());
multicastConfig.setMulticastPort(multicastAddress.getPort());
}
if (unicastAddresses.size() > 0) {
tcpIpConfig.setEnabled(!usingMulticast);
for (InetSocketAddress unicastAddress : unicastAddresses) {
tcpIpConfig.addAddress(new Address(unicastAddress));
}
}
// Check if address specified to bind to is a wildcard address. If it is a wildcard address,
// do not override the property PROP_SOCKET_BIND_ANY. If not, set the PROP_SOCKET_BIND_ANY to false so
// that Hazelcast won't discard the interface specified to bind to.
boolean useAnyAddress = false;
// Check to see if the address specified is the wildcard address
for (String networkInterface : networkConfig.getInterfaces().getInterfaces()) {
InetAddress address = InetAddress.getByName(networkInterface);
if (address.isAnyLocalAddress()) {
// this will prevent PROP_SOCKET_BIND_ANY property from being overridden to false
// so that Hazelcast can bind to wildcard address
useAnyAddress = true;
break;
}
}
// Override the PROP_SOCKET_BIND_ANY to false if the address to bind to is not wildcard address
// Explicitly enable the interface so that Hazelcast will pick the one specified
if (!useAnyAddress) {
networkConfig.getInterfaces().setEnabled(true);
hazelCastConfig.setProperty(GroupProperties.PROP_SOCKET_BIND_ANY, "false");
}
} else {
// Gateway is running in the AWS/Cloud env.
// Get rid of the leading slash "/" in the path.
String path = awsMember.getPath();
String groupName = null;
if (path != null) {
if ((path.indexOf("/") == 0) && (path.length() > 1)) {
groupName = path.substring(1, path.length());
}
}
// If the groupName is not specified, then we will get it from
// the meta-data.
if ((groupName == null) || (groupName.length() == 0)) {
groupName = AwsUtils.getSecurityGroupName();
}
multicastConfig.setEnabled(false);
tcpIpConfig.setEnabled(false);
AwsConfig awsConfig = joinConfig.getAwsConfig();
awsConfig.setEnabled(true);
awsConfig.setAccessKey(connectOptions.getAwsAccessKeyId());
awsConfig.setSecretKey(connectOptions.getAwsSecretKey());
awsConfig.setRegion(AwsUtils.getRegion());
awsConfig.setSecurityGroupName(groupName);
// KG-7725: Hazelcast wants to bind on an interface, and if the Gateway doesn't
// tell it which ones to pick it'll pick one on its own. Make sure interfaces
// are explicitly enabled, and grab the local IP address since this will be the
// IP address used to do discovery of other Gateways in the given security group.
// Otherwise an elastic IP associated with the instance might cause Hazelcast to
// pick a different IP address to listen on than the one used to connect to other
// members, meaning where Gateways are listening is *not* where Gateways try to
// connect to other Gateways. In those situations the cluster does not form.
String localIPv4 = AwsUtils.getLocalIPv4();
networkConfig.getInterfaces().setEnabled(true);
networkConfig.getInterfaces().clear();
networkConfig.getInterfaces().addInterface(localIPv4);
// KG-12825: Override the property PROP_SOCKET_BIND_ANY and set it to false so that
// Hazelcast does not discard the interface explicitly specified to bind to.
hazelCastConfig.setProperty(GroupProperties.PROP_SOCKET_BIND_ANY, "false");
}
hazelCastConfig.setNetworkConfig(networkConfig);
// Override the shutdown hook in Hazelcast so that the connection counts can be correctly maintained.
// The cluster instance should be shutdown by the Gateway, so there should be no need for the default
// Hazelcast shutdown hook.
hazelCastConfig.setProperty(GroupProperties.PROP_SHUTDOWNHOOK_ENABLED, "false");
return hazelCastConfig;
}
@SuppressWarnings("unused")
private List<String> processInterfaceOrMemberEntry(String entry) {
if (entry == null) {
return null;
}
ArrayList<String> addresses = new ArrayList<>();
int starIndex = entry.indexOf('*');
int dashIndex = entry.indexOf('-');
if (starIndex == -1 && dashIndex == -1) {
addresses.add(entry);
return addresses;
}
String[] parts = entry.split("\\.");
if (parts.length != 4) {
throw new IllegalArgumentException("Invalid wildcard in the entry for cluster configuration: " + entry);
}
// Prevent wildcards in the first part
if (parts[0].contains("*") && parts[0].contains("-")) {
throw new IllegalArgumentException(
"Invalid wildcard in the entry for cluster configuration, first part of the address cannot contain a " +
"wildcard: "
+ entry);
}
String part1 = parts[0];
String[] part2s = processEntryPart(entry, parts[1]);
String[] part3s = processEntryPart(entry, parts[2]);
String[] part4s = processEntryPart(entry, parts[3]);
for (int i = 0; i < part2s.length; i++) {
for (int j = 0; j < part3s.length; j++) {
for (int k = 0; k < part4s.length; k++) {
addresses.add(part1 + "." + part2s[i] + "." + part3s[j] + "." + part4s[k]);
}
}
}
return addresses;
}
private String[] processEntryPart(String entry, String ipPart) {
// No wild cards
if (!ipPart.contains("*") && !ipPart.contains("-")) {
String[] resolvedParts = new String[1];
resolvedParts[0] = ipPart;
return resolvedParts;
}
// process *
if (ipPart.equals("*")) {
String[] resolvedParts = new String[256];
for (int i = 0; i < 256; i++) {
resolvedParts[i] = String.valueOf(i);
}
return resolvedParts;
}
// process ranges
if (ipPart.contains("-")) {
String[] rangeParts = ipPart.split("-");
if (rangeParts.length != 2) {
throw new IllegalArgumentException("Invalid wildcard in the entry for cluster configuration: " + entry);
}
int start = Integer.parseInt(rangeParts[0]);
int end = Integer.parseInt(rangeParts[1]);
String[] resolvedParts = new String[end - start + 1];
for (int i = start; i <= end; i++) {
resolvedParts[i] = String.valueOf(i);
}
return resolvedParts;
}
throw new IllegalArgumentException("Invalid wildcard in the entry for cluster configuration: " + entry);
}
@Override
public MemberId getLocalMember() {
return this.localNodeId;
}
@Override
public Collection<MemberId> getMemberIds() {
Map<MemberId, String> instanceKeyMap = getCollectionsFactory().getMap(INSTANCE_KEY_MAP);
return instanceKeyMap.keySet();
}
private MemberId getMemberId(Member member) {
InetSocketAddress inetSocketAddress = member.getInetSocketAddress();
String hostname = inetSocketAddress.getHostName();
if (!inetSocketAddress.isUnresolved()) {
String ipAddr = inetSocketAddress.getAddress().getHostAddress();
hostname = ipAddr;
GL.debug(CLUSTER_LOGGER_NAME, "getMemberId: Hostname: {}; IP Address: {}", hostname, ipAddr);
}
return new MemberId("tcp", hostname, inetSocketAddress.getPort());
}
private MembershipListener membershipListener = new MembershipListener() {
@Override
public void memberAdded(MembershipEvent membershipEvent) {
MemberId newMemberId = getMemberId(membershipEvent.getMember());
GL.info(CLUSTER_LOGGER_NAME, "Cluster member {} is now online", newMemberId.getId());
fireMemberAdded(newMemberId);
logClusterMembers();
}
@Override
public void memberRemoved(MembershipEvent membershipEvent) {
MemberId removedMember = getMemberId(membershipEvent.getMember());
GL.info(CLUSTER_LOGGER_NAME, "Cluster member {} has gone down", removedMember);
// Clean up the member's instanceKey
Map<MemberId, String> instanceKeyMap = getCollectionsFactory().getMap(INSTANCE_KEY_MAP);
instanceKeyMap.remove(removedMember);
// cleanup balancer URIs for the member that went down
Map<MemberId, Map<URI, List<URI>>> memberIdBalancerUriMap =
getCollectionsFactory().getMap(MEMBERID_BALANCER_MAP_NAME);
if (memberIdBalancerUriMap == null) {
throw new IllegalStateException("MemberId to BalancerMap is null");
}
IMap<URI, TreeSet<URI>> sharedBalanceUriMap = getCollectionsFactory().getMap(BALANCER_MAP_NAME);
if (sharedBalanceUriMap == null) {
throw new IllegalStateException("Shared balanced URIs map is null");
}
Map<URI, List<URI>> memberBalancedUrisMap = memberIdBalancerUriMap.remove(removedMember);
if (memberBalancedUrisMap != null) {
GL.debug(CLUSTER_LOGGER_NAME, "Cleaning up balancer cluster state for member {}", removedMember);
try {
for (URI key : memberBalancedUrisMap.keySet()) {
GL.debug(CLUSTER_LOGGER_NAME, "URI Key: {}", key);
List<URI> memberBalancedUris = memberBalancedUrisMap.get(key);
TreeSet<URI> globalBalancedUris = null;
TreeSet<URI> newGlobalBalancedUris = null;
do {
globalBalancedUris = sharedBalanceUriMap.get(key);
newGlobalBalancedUris = new TreeSet<URI>(globalBalancedUris);
for (URI memberBalancedUri : memberBalancedUris) {
GL.debug(CLUSTER_LOGGER_NAME, "Attempting to removing Balanced URI : {}", memberBalancedUri);
newGlobalBalancedUris.remove(memberBalancedUri);
}
} while (!sharedBalanceUriMap.replace(key, globalBalancedUris, newGlobalBalancedUris));
GL.debug(CLUSTER_LOGGER_NAME, "Removed balanced URIs for cluster member {}, new global list: {}",
removedMember, newGlobalBalancedUris);
}
} catch (Exception e) {
throw new IllegalStateException("Unable to remove the balanced URIs served by the member going down from " +
"global map");
}
}
fireMemberRemoved(removedMember);
logClusterMembers();
}
};
@Override
public String getInstanceKey(MemberId memberId) {
if (memberId == localNodeId) {
return this.localInstanceKey; // quicker, and works with CLIENT_MODE, too.
}
Map<MemberId, String> instanceKeyMap = getCollectionsFactory().getMap(INSTANCE_KEY_MAP);
return instanceKeyMap.get(memberId);
}
private EntryListener<MemberId, String> instanceKeyEntryListener = new EntryListener<MemberId, String>() {
// WE're supporting the idea of 'instance keys' (i.e. random strings that are supposed
// to be unique per instance of a gateway) solely for management to be able to tell the
// difference between two instances of a gateway accessed through the same management URL.
// The Console supports displaying history, and it needs to know when reconnecting to a
// given management URL whether or not the configuration might have changed. Because
// member IDs generally don't change (for now they're based on the cluster accept URL),
// they're a bad indicator of an instance stopping and being restarted. Thus the need for the
// instance key. When a member is added or removed, the instanceKey is also added or
// removed, and we can trigger events for management to update their cluster state.
@Override
public void entryAdded(EntryEvent<MemberId, String> newEntryEvent) {
fireInstanceKeyAdded(newEntryEvent.getValue());
}
@Override
public void entryEvicted(EntryEvent<MemberId, String> evictedEntryEvent) {
throw new RuntimeException("Instance keys should not be evicted, only added or removed.");
}
@Override
public void entryRemoved(EntryEvent<MemberId, String> removedEntryEvent) {
fireInstanceKeyRemoved(removedEntryEvent.getValue());
}
@Override
public void entryUpdated(EntryEvent<MemberId, String> updatedEntryEvent) {
throw new RuntimeException("Instance keys can not be updated, only added or removed.");
}
};
private EntryListener<URI, Collection<URI>> balancerMapEntryListener = new EntryListener<URI, Collection<URI>>() {
@Override
public void entryAdded(EntryEvent<URI, Collection<URI>> newEntryEvent) {
GL.trace(CLUSTER_LOGGER_NAME, "New entry for balance URI: {} value: {}", newEntryEvent.getKey(), newEntryEvent
.getValue());
fireBalancerEntryAdded(newEntryEvent);
}
@Override
public void entryEvicted(EntryEvent<URI, Collection<URI>> evictedEntryEvent) {
throw new RuntimeException("Balancer map entries should not be evicted, only added or removed.");
}
@Override
public void entryRemoved(EntryEvent<URI, Collection<URI>> removedEntryEvent) {
GL.trace(CLUSTER_LOGGER_NAME, "Entry removed for balance URI: {} value: {}", removedEntryEvent
.getKey(), removedEntryEvent.getValue());
fireBalancerEntryRemoved(removedEntryEvent);
}
@Override
public void entryUpdated(EntryEvent<URI, Collection<URI>> updatedEntryEvent) {
GL.trace(CLUSTER_LOGGER_NAME, "Entry updated for balance URI: {} value: {}", updatedEntryEvent
.getKey(), updatedEntryEvent.getValue());
fireBalancerEntryUpdated(updatedEntryEvent);
}
};
// cluster collections
@Override
public Lock getLock(Object obj) {
return clusterInstance.getLock(obj);
}
@Override
public IdGenerator getIdGenerator(String name) {
return clusterInstance.getIdGenerator(name);
}
// cluster communication
@Override
public void addReceiveQueue(String name) {
if (clusterMessaging != null) {
clusterMessaging.addReceiveQueue(name);
}
}
@Override
public void addReceiveTopic(String name) {
if (clusterMessaging != null) {
clusterMessaging.addReceiveTopic(name);
}
}
@Override
public void send(Object msg, SendListener listener, MemberId member) {
if (clusterMessaging != null) {
clusterMessaging.send(msg, listener, member);
}
}
@Override
public void send(Object msg, SendListener listener, String name) {
if (clusterMessaging != null) {
clusterMessaging.send(msg, listener, name);
}
}
@SuppressWarnings("unchecked")
@Override
public Object send(Object msg, MemberId member) throws Exception {
if (clusterMessaging != null) {
return clusterMessaging.send(msg, member);
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public Object send(Object msg, String name) throws Exception {
if (clusterMessaging != null) {
return clusterMessaging.send(msg, name);
}
return null;
}
@Override
public <T> void setReceiver(Class<T> type, ReceiveListener<T> receiveListener) {
if (clusterMessaging != null) {
clusterMessaging.setReceiver(type, receiveListener);
}
}
@Override
public <T> void removeReceiver(Class<T> type) {
if (clusterMessaging != null) {
clusterMessaging.removeReceiver(type);
}
}
@Override
public void addMembershipEventListener(MembershipEventListener eventListener) {
if (eventListener != null) {
membershipEventListeners.add(eventListener);
}
}
@Override
public void removeMembershipEventListener(MembershipEventListener eventListener) {
if (eventListener != null) {
membershipEventListeners.remove(eventListener);
}
}
@Override
public void addInstanceKeyListener(InstanceKeyListener instanceKeyListener) {
if (instanceKeyListener != null) {
instanceKeyListeners.add(instanceKeyListener);
}
}
@Override
public void removeInstanceKeyListener(InstanceKeyListener instanceKeyListener) {
if (instanceKeyListener != null) {
instanceKeyListeners.remove(instanceKeyListener);
}
}
@Override
public void addBalancerMapListener(BalancerMapListener balancerMapListener) {
if (balancerMapListener != null) {
balancerMapListeners.add(balancerMapListener);
}
}
@Override
public void removeBalancerMapListener(BalancerMapListener balancerMapListener) {
if (balancerMapListener != null) {
balancerMapListeners.remove(balancerMapListener);
}
}
@Override
public String getClusterName() {
return this.clusterName;
}
@Override
public List<MemberId> getAccepts() {
return localInterfaces;
}
@Override
public List<MemberId> getConnects() {
return clusterMembers;
}
@Override
public ClusterConnectOptionsContext getConnectOptions() {
return connectOptions;
}
@Override
public MessageBufferFactory getMessageBufferFactory() {
return messageBufferFactory;
}
@Override
public void logClusterState() {
logClusterMembers();
logBalancerMap();
}
private void logClusterMembers() {
// log current cluster state on TRACE level
if (clusterInstance != null) {
Cluster cluster = clusterInstance.getCluster();
if (cluster != null) {
GL.trace(CLUSTER_LOGGER_NAME, "Current cluster members:");
Set<Member> currentMembers = clusterInstance.getCluster().getMembers();
for (Member currentMember : currentMembers) {
MemberId memberId = getMemberId(currentMember);
GL.trace(CLUSTER_LOGGER_NAME, " member: {}", memberId);
}
}
}
}
private void logBalancerMap() {
GL.trace(CLUSTER_LOGGER_NAME, "Current balancer map:");
Map<URI, TreeSet<URI>> balancerMap = getCollectionsFactory().getMap(BALANCER_MAP_NAME);
for (URI balanceURI : balancerMap.keySet()) {
TreeSet<URI> balanceTargets = balancerMap.get(balanceURI);
GL.trace(CLUSTER_LOGGER_NAME, " balance URI: {} target list: {}", balanceURI, balanceTargets);
}
}
/**
* Fire member added event
*/
private void fireMemberAdded(MemberId newMember) {
GL.debug(CLUSTER_LOGGER_NAME, "Firing member added for : {}", newMember);
for (MembershipEventListener listener : membershipEventListeners) {
try {
listener.memberAdded(newMember);
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in member added event {}", e);
}
}
}
/**
* Fire member removed event
*/
private void fireMemberRemoved(MemberId exMember) {
GL.debug(CLUSTER_LOGGER_NAME, "Firing member removed for: {}", exMember);
for (MembershipEventListener listener : membershipEventListeners) {
try {
listener.memberRemoved(exMember);
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in member removed event {}", e);
}
}
}
/**
* Fire instanceKeyAdded event
*/
private void fireInstanceKeyAdded(String instanceKey) {
GL.debug(CLUSTER_LOGGER_NAME, "Firing instanceKeyAdded for: {}", instanceKey);
for (InstanceKeyListener listener : instanceKeyListeners) {
try {
listener.instanceKeyAdded(instanceKey);
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in instanceKeyAdded event {}", e);
}
}
}
/**
* Fire instanceKeyRemoved event
*/
private void fireInstanceKeyRemoved(String instanceKey) {
GL.debug(CLUSTER_LOGGER_NAME, "Firing instanceKeyRemoved for: {}", instanceKey);
for (InstanceKeyListener listener : instanceKeyListeners) {
try {
listener.instanceKeyRemoved(instanceKey);
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in instanceKeyRemoved event {}", e);
}
}
}
/**
* Fire balancerEntryAdded event
*/
private void fireBalancerEntryAdded(EntryEvent<URI, Collection<URI>> entryEvent) {
URI balancerURI = entryEvent.getKey();
GL.debug(CLUSTER_LOGGER_NAME, "Firing balancerEntryAdded for: {}", balancerURI);
for (BalancerMapListener listener : balancerMapListeners) {
try {
listener.balancerEntryAdded(balancerURI, entryEvent.getValue());
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in balancerEntryAdded event {}", e);
}
}
}
/**
* Fire balancerEntryRemoved event
*/
private void fireBalancerEntryRemoved(EntryEvent<URI, Collection<URI>> entryEvent) {
URI balancerURI = entryEvent.getKey();
GL.debug(CLUSTER_LOGGER_NAME, "Firing balancerEntryRemoved for: {}", balancerURI);
for (BalancerMapListener listener : balancerMapListeners) {
try {
listener.balancerEntryRemoved(balancerURI, entryEvent.getValue());
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in balancerEntryRemoved event {}", e);
}
}
}
/**
* Fire balancerEntryUpdated event
*/
private void fireBalancerEntryUpdated(EntryEvent<URI, Collection<URI>> entryEvent) {
URI balancerURI = entryEvent.getKey();
GL.debug(CLUSTER_LOGGER_NAME, "Firing balancerEntryUpdated for: {}", balancerURI);
for (BalancerMapListener listener : balancerMapListeners) {
try {
listener.balancerEntryUpdated(balancerURI, entryEvent.getValue());
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in balancerEntryUpdated event {}", e);
}
}
}
@Override
public CollectionsFactory getCollectionsFactory() {
initializeCluster(null);
return this.collectionsFactory;
}
private void initializeCluster(Config config) {
if (clusterInitialized.compareAndSet(false, true)) {
clusterInstance = Hazelcast.newHazelcastInstance(config);
if (clusterInstance == null) {
throw new RuntimeException("Unable to initialize the cluster");
}
Cluster cluster = clusterInstance.getCluster();
cluster.addMembershipListener(this.membershipListener);
// Register a listener for Hazelcast logging events
LoggingService loggingService = clusterInstance.getLoggingService();
loggingService.addLogListener(Level.FINEST, this);
this.collectionsFactory = new ClusterCollectionsFactory(clusterInstance);
this.messageBufferFactory = new ClusterMemoryMessageBufferFactory(clusterInstance);
localNodeId = getMemberId(cluster.getLocalMember());
clusterMessaging = new ClusterMessaging(this, clusterInstance, schedulerProvider);
IMap<MemberId, String> instanceKeyMap = collectionsFactory.getMap(INSTANCE_KEY_MAP);
instanceKeyMap.put(localNodeId, localInstanceKey);
instanceKeyMap.addEntryListener(instanceKeyEntryListener, true);
IMap<URI, Collection<URI>> balancerMap = collectionsFactory.getMap(BALANCER_MAP_NAME);
balancerMap.addEntryListener(balancerMapEntryListener, true);
}
}
@Override
public void log(LogEvent logEvent) {
Member member = logEvent.getMember();
LogRecord record = logEvent.getLogRecord();
Level level = record.getLevel();
if (level.equals(Level.SEVERE)) {
logger.error(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
} else if (level.equals(Level.WARNING)) {
logger.warn(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
} else if (level.equals(Level.INFO)) {
logger.info(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
} else if (level.equals(Level.FINE)) {
if (logger.isDebugEnabled()) {
logger.debug(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
}
} else if (level.equals(Level.FINER) ||
level.equals(Level.FINEST)) {
if (logger.isTraceEnabled()) {
logger.trace(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
}
}
}
}
| server/src/main/java/org/kaazing/gateway/server/context/resolve/DefaultClusterContext.java | /**
* Copyright 2007-2015, Kaazing Corporation. 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 org.kaazing.gateway.server.context.resolve;
import com.hazelcast.config.AwsConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.Join;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MulticastConfig;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.config.TcpIpConfig;
import com.hazelcast.core.Cluster;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.core.IdGenerator;
import com.hazelcast.core.Member;
import com.hazelcast.core.MembershipEvent;
import com.hazelcast.core.MembershipListener;
import com.hazelcast.impl.GroupProperties;
import com.hazelcast.logging.LogEvent;
import com.hazelcast.logging.LogListener;
import com.hazelcast.logging.LoggingService;
import com.hazelcast.nio.Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.kaazing.gateway.server.messaging.buffer.ClusterMemoryMessageBufferFactory;
import org.kaazing.gateway.server.messaging.collections.ClusterCollectionsFactory;
import org.kaazing.gateway.service.cluster.BalancerMapListener;
import org.kaazing.gateway.service.cluster.ClusterConnectOptionsContext;
import org.kaazing.gateway.service.cluster.ClusterContext;
import org.kaazing.gateway.service.cluster.ClusterMessaging;
import org.kaazing.gateway.service.cluster.InstanceKeyListener;
import org.kaazing.gateway.service.cluster.MemberId;
import org.kaazing.gateway.service.cluster.MembershipEventListener;
import org.kaazing.gateway.service.cluster.ReceiveListener;
import org.kaazing.gateway.service.cluster.SendListener;
import org.kaazing.gateway.service.messaging.buffer.MessageBufferFactory;
import org.kaazing.gateway.service.messaging.collections.CollectionsFactory;
import org.kaazing.gateway.util.GL;
import org.kaazing.gateway.util.Utils;
import org.kaazing.gateway.util.aws.AwsUtils;
import org.kaazing.gateway.util.scheduler.SchedulerProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.kaazing.gateway.server.context.resolve.DefaultServiceContext.BALANCER_MAP_NAME;
import static org.kaazing.gateway.server.context.resolve.DefaultServiceContext.MEMBERID_BALANCER_MAP_NAME;
/**
* ClusterContext for KEG
* <p/>
* <br>Balancer data<ol> <li> HttpBalancerService.MEMBERID_BALANCER_MAP_NAME: <ul><li> List of balanced URIs for one member
* <li>Key: Cluster member id <li>Value: Map(key: balancerURI, value: acceptURIs) </ul> <li>HttpBalancerService.BALANCER_MAP_NAME
* <ul><li> List of balanced URIs for whole cluster <li>Key: balanceURI <li>Value: acceptURIs </ul> </ol>
*/
public class DefaultClusterContext implements ClusterContext, LogListener {
private static final String CLUSTER_LOG_FORMAT = "HAZELCAST: [%s] - %s";
private static final String INSTANCE_KEY_MAP = "instanceKeyMap";
// This is also used in DefaultServiceContext
static final String CLUSTER_LOGGER_NAME = "ha";
private final Logger logger = LoggerFactory.getLogger(CLUSTER_LOGGER_NAME);
private final String localInstanceKey = Utils.randomHexString(16);
private MessageBufferFactory messageBufferFactory;
private CollectionsFactory collectionsFactory;
private List<MemberId> localInterfaces = new ArrayList<>();
private final List<MemberId> clusterMembers = new ArrayList<>();
private final List<MembershipEventListener> membershipEventListeners = new ArrayList<>();
private final List<InstanceKeyListener> instanceKeyListeners = new ArrayList<>();
private final List<BalancerMapListener> balancerMapListeners = new ArrayList<>();
private ClusterMessaging clusterMessaging;
private MemberId localNodeId;
private final String clusterName;
private HazelcastInstance clusterInstance;
private final SchedulerProvider schedulerProvider;
private final ClusterConnectOptionsContext connectOptions;
private final AtomicBoolean clusterInitialized = new AtomicBoolean(false);
public DefaultClusterContext(String name,
List<MemberId> interfaces,
List<MemberId> members,
SchedulerProvider schedulerProvider) {
this(name, interfaces, members, schedulerProvider, null);
}
public DefaultClusterContext(String name,
List<MemberId> interfaces,
List<MemberId> members,
SchedulerProvider schedulerProvider,
ClusterConnectOptionsContext connectOptions) {
this.clusterName = name;
this.localInterfaces.addAll(interfaces);
this.clusterMembers.addAll(members);
this.schedulerProvider = schedulerProvider;
this.connectOptions = connectOptions;
}
@Override
public void start() {
// Check that we have either localInterfaces or clusterMembers
if (localInterfaces.size() + clusterMembers.size() == 0) {
// if no local interfaces
if (localInterfaces.size() == 0) {
GL.info(CLUSTER_LOGGER_NAME, "No network interfaces specified in the gateway configuration");
throw new IllegalArgumentException("No network interfaces specified in the gateway configuration");
}
// if no members
if (clusterMembers.size() == 0) {
GL.info(CLUSTER_LOGGER_NAME, "No cluster members specified in the gateway configuration");
throw new IllegalArgumentException("No cluster members specified in the gateway configuration");
}
}
try {
// from ha.xml and then add members interfaces
Config config = initializeHazelcastConfig();
initializeCluster(config);
GL.info(CLUSTER_LOGGER_NAME, "Cluster Member started: IP Address: {}; Port: {}; id: {}",
localNodeId.getHost(), localNodeId.getPort(), localNodeId.getId());
} catch (Exception e) {
GL.error(CLUSTER_LOGGER_NAME, "Unable to initialize cluster due to an exception: {}", e);
throw new RuntimeException(String.format("Unable to initialize cluster due to an exception: %s", e), e);
}
}
@Override
public void dispose() {
// If we're in client mode, then we may not have this clusterMessaging
// object. So don't try to destroy it if it is not there at all
// (KG-3496).
if (clusterMessaging != null) {
clusterMessaging.destroy();
}
if (clusterInstance != null) {
// KG-5837: do not call Hazelcast.shutdownAll() since that will hobble all in-process gateways
clusterInstance.getLifecycleService().shutdown();
}
}
private Config initializeHazelcastConfig() throws Exception {
Config hazelCastConfig = new Config();
hazelCastConfig.getGroupConfig().setName(getClusterName());
hazelCastConfig.getGroupConfig().setPassword("5942");
MapConfig mapConfig = hazelCastConfig.getMapConfig("serverSessions");
mapConfig.setBackupCount(3);
MapConfig sharedBalancerMapConfig = hazelCastConfig.getMapConfig(BALANCER_MAP_NAME);
sharedBalancerMapConfig.setBackupCount(Integer.MAX_VALUE);
MapConfig memberBalancerMapConfig = hazelCastConfig.getMapConfig(MEMBERID_BALANCER_MAP_NAME);
memberBalancerMapConfig.setBackupCount(Integer.MAX_VALUE);
// disable port auto increment
hazelCastConfig.setPortAutoIncrement(false);
// The first accepts port is the port used by all network interfaces.
int clusterPort = (localInterfaces.size() > 0) ? localInterfaces.get(0).getPort() : -1;
// TO turn off logging in hazelcast API.
// Note: must use Logger.getLogger, not LogManager.getLogger
java.util.logging.Logger logger = java.util.logging.Logger.getLogger("com.hazelcast");
logger.setLevel(Level.OFF);
// initialize hazelcast
if (clusterPort != -1) {
hazelCastConfig.setPort(clusterPort);
}
NetworkConfig networkConfig = new NetworkConfig();
for (MemberId localInterface : localInterfaces) {
String protocol = localInterface.getProtocol();
if ("udp".equalsIgnoreCase(protocol) || "aws".equalsIgnoreCase(protocol)) {
throw new IllegalArgumentException("Cannot accept on a multicast or aws address, use unicast address starting " +
"with tcp://");
}
// NOTE: The version of Hazelcast(1.9.4.8) that is being used does not support IPv6 address. The Hazelcast library
// throws NumberFormatException when IPv6 address is specified as an interface to bind to.
String hostAddress = localInterface.getHost();
InetAddress address = InetAddress.getByName(hostAddress);
if (address instanceof Inet6Address) {
throw new IllegalArgumentException("ERROR: Cluster member accept url - '" + localInterface.toString() +
"' consists of IPv6 address which is not supported. Use Ipv4 address instead.");
}
networkConfig.getInterfaces().addInterface(localInterface.getHost());
if (localInterface.getPort() != clusterPort) {
throw new IllegalArgumentException("Port numbers on the network interfaces in <accept> do not match");
}
}
boolean usingMulticast = false;
Join joinConfig = networkConfig.getJoin();
MulticastConfig multicastConfig = joinConfig.getMulticastConfig();
// Disable multicast to avoid using the default multicast address 224.2.2.3:54327.
// In this way, new cluster members joining the cluster won't accidentally join
// due to having configured the default multicast address. If multicast adresses are mentioned below,
// we enable it. See KG-6045 for an example of an accidental multicast cluster connection.
multicastConfig.setEnabled(false);
TcpIpConfig tcpIpConfig = joinConfig.getTcpIpConfig();
List<InetSocketAddress> multicastAddresses = new ArrayList<>();
List<InetSocketAddress> unicastAddresses = new ArrayList<>();
MemberId awsMember = null;
for (MemberId member : clusterMembers) {
if (member.getProtocol().equals("udp")) {
multicastAddresses.add(new InetSocketAddress(member.getHost(), member.getPort()));
} else if (member.getProtocol().equals("tcp")) {
unicastAddresses.add(new InetSocketAddress(member.getHost(), member.getPort()));
} else if (member.getProtocol().equals("aws")) {
awsMember = member;
// There should be only one <connect> tag when AWS is being
// used. We have already validated that in
// GatewayContextResolver.processClusterMembers() method.
}
}
if (awsMember == null) {
// Gateway is running in an on-premise env.
int multicastAddressesCount = multicastAddresses.size();
if (multicastAddressesCount > 1) {
throw new IllegalArgumentException("Conflicting multicast discovery addresses in cluster configuration");
} else if (multicastAddressesCount > 0) {
if (AwsUtils.isDeployedToAWS()) {
throw new IllegalArgumentException("Multicast cluster configuration not supported on AWS, use " +
"aws://security-group/<security-group-name> in connect tag");
}
multicastConfig.setEnabled(true);
InetSocketAddress multicastAddress = multicastAddresses.get(0);
multicastConfig.setMulticastGroup(multicastAddress.getHostName());
multicastConfig.setMulticastPort(multicastAddress.getPort());
}
if (unicastAddresses.size() > 0) {
tcpIpConfig.setEnabled(!usingMulticast);
for (InetSocketAddress unicastAddress : unicastAddresses) {
tcpIpConfig.addAddress(new Address(unicastAddress));
}
}
// Check if address specified to bind to is a wildcard address. If it is a wildcard address,
// do not override the property PROP_SOCKET_BIND_ANY. If not, set the PROP_SOCKET_BIND_ANY to false so
// that Hazelcast won't discard the interface specified to bind to.
boolean useAnyAddress = false;
// Check to see if the address specified is the wildcard address
for (String networkInterface : networkConfig.getInterfaces().getInterfaces()) {
InetAddress address = InetAddress.getByName(networkInterface);
if (address.isAnyLocalAddress()) {
// this will prevent PROP_SOCKET_BIND_ANY property from being overridden to false
// so that Hazelcast can bind to wildcard address
useAnyAddress = true;
break;
}
}
// Override the PROP_SOCKET_BIND_ANY to false if the address to bind to is not wildcard address
// Explicitly enable the interface so that Hazelcast will pick the one specified
if (!useAnyAddress) {
networkConfig.getInterfaces().setEnabled(true);
hazelCastConfig.setProperty(GroupProperties.PROP_SOCKET_BIND_ANY, "false");
}
} else {
// Gateway is running in the AWS/Cloud env.
// Get rid of the leading slash "/" in the path.
String path = awsMember.getPath();
String groupName = null;
if (path != null) {
if ((path.indexOf("/") == 0) && (path.length() > 1)) {
groupName = path.substring(1, path.length());
}
}
// If the groupName is not specified, then we will get it from
// the meta-data.
if ((groupName == null) || (groupName.length() == 0)) {
groupName = AwsUtils.getSecurityGroupName();
}
multicastConfig.setEnabled(false);
tcpIpConfig.setEnabled(false);
AwsConfig awsConfig = joinConfig.getAwsConfig();
awsConfig.setEnabled(true);
awsConfig.setAccessKey(connectOptions.getAwsAccessKeyId());
awsConfig.setSecretKey(connectOptions.getAwsSecretKey());
awsConfig.setRegion(AwsUtils.getRegion());
awsConfig.setSecurityGroupName(groupName);
// KG-7725: Hazelcast wants to bind on an interface, and if the Gateway doesn't
// tell it which ones to pick it'll pick one on its own. Make sure interfaces
// are explicitly enabled, and grab the local IP address since this will be the
// IP address used to do discovery of other Gateways in the given security group.
// Otherwise an elastic IP associated with the instance might cause Hazelcast to
// pick a different IP address to listen on than the one used to connect to other
// members, meaning where Gateways are listening is *not* where Gateways try to
// connect to other Gateways. In those situations the cluster does not form.
String localIPv4 = AwsUtils.getLocalIPv4();
networkConfig.getInterfaces().setEnabled(true);
networkConfig.getInterfaces().clear();
networkConfig.getInterfaces().addInterface(localIPv4);
// KG-12825: Override the property PROP_SOCKET_BIND_ANY and set it to false so that
// Hazelcast does not discard the interface explicitly specified to bind to.
hazelCastConfig.setProperty(GroupProperties.PROP_SOCKET_BIND_ANY, "false");
}
hazelCastConfig.setNetworkConfig(networkConfig);
// Override the shutdown hook in Hazelcast so that the connection counts can be correctly maintained.
// The cluster instance should be shutdown by the Gateway, so there should be no need for the default
// Hazelcast shutdown hook.
hazelCastConfig.setProperty(GroupProperties.PROP_SHUTDOWNHOOK_ENABLED, "false");
return hazelCastConfig;
}
@SuppressWarnings("unused")
private List<String> processInterfaceOrMemberEntry(String entry) {
if (entry == null) {
return null;
}
ArrayList<String> addresses = new ArrayList<>();
int starIndex = entry.indexOf('*');
int dashIndex = entry.indexOf('-');
if (starIndex == -1 && dashIndex == -1) {
addresses.add(entry);
return addresses;
}
String[] parts = entry.split("\\.");
if (parts.length != 4) {
throw new IllegalArgumentException("Invalid wildcard in the entry for cluster configuration: " + entry);
}
// Prevent wildcards in the first part
if (parts[0].contains("*") && parts[0].contains("-")) {
throw new IllegalArgumentException(
"Invalid wildcard in the entry for cluster configuration, first part of the address cannot contain a " +
"wildcard: "
+ entry);
}
String part1 = parts[0];
String[] part2s = processEntryPart(entry, parts[1]);
String[] part3s = processEntryPart(entry, parts[2]);
String[] part4s = processEntryPart(entry, parts[3]);
for (int i = 0; i < part2s.length; i++) {
for (int j = 0; j < part3s.length; j++) {
for (int k = 0; k < part4s.length; k++) {
addresses.add(part1 + "." + part2s[i] + "." + part3s[j] + "." + part4s[k]);
}
}
}
return addresses;
}
private String[] processEntryPart(String entry, String ipPart) {
// No wild cards
if (!ipPart.contains("*") && !ipPart.contains("-")) {
String[] resolvedParts = new String[1];
resolvedParts[0] = ipPart;
return resolvedParts;
}
// process *
if (ipPart.equals("*")) {
String[] resolvedParts = new String[256];
for (int i = 0; i < 256; i++) {
resolvedParts[i] = String.valueOf(i);
}
return resolvedParts;
}
// process ranges
if (ipPart.contains("-")) {
String[] rangeParts = ipPart.split("-");
if (rangeParts.length != 2) {
throw new IllegalArgumentException("Invalid wildcard in the entry for cluster configuration: " + entry);
}
int start = Integer.parseInt(rangeParts[0]);
int end = Integer.parseInt(rangeParts[1]);
String[] resolvedParts = new String[end - start + 1];
for (int i = start; i <= end; i++) {
resolvedParts[i] = String.valueOf(i);
}
return resolvedParts;
}
throw new IllegalArgumentException("Invalid wildcard in the entry for cluster configuration: " + entry);
}
@Override
public MemberId getLocalMember() {
return this.localNodeId;
}
@Override
public Collection<MemberId> getMemberIds() {
Map<MemberId, String> instanceKeyMap = getCollectionsFactory().getMap(INSTANCE_KEY_MAP);
return instanceKeyMap.keySet();
}
private MemberId getMemberId(Member member) {
InetSocketAddress inetSocketAddress = member.getInetSocketAddress();
String hostname = inetSocketAddress.getHostName();
if (!inetSocketAddress.isUnresolved()) {
String ipAddr = inetSocketAddress.getAddress().getHostAddress();
hostname = ipAddr;
GL.debug(CLUSTER_LOGGER_NAME, "getMemberId: Hostname: {}; IP Address: {}", hostname, ipAddr);
}
return new MemberId("tcp", hostname, inetSocketAddress.getPort());
}
private MembershipListener membershipListener = new MembershipListener() {
@Override
public void memberAdded(MembershipEvent membershipEvent) {
MemberId newMemberId = getMemberId(membershipEvent.getMember());
GL.info(CLUSTER_LOGGER_NAME, "Cluster member {} is now online", newMemberId.getId());
fireMemberAdded(newMemberId);
logClusterMembers();
}
@Override
public void memberRemoved(MembershipEvent membershipEvent) {
MemberId removedMember = getMemberId(membershipEvent.getMember());
GL.info(CLUSTER_LOGGER_NAME, "Cluster member {} has gone down", removedMember);
// Clean up the member's instanceKey
Map<MemberId, String> instanceKeyMap = getCollectionsFactory().getMap(INSTANCE_KEY_MAP);
instanceKeyMap.remove(removedMember);
// cleanup balancer URIs for the member that went down
Map<MemberId, Map<URI, List<URI>>> memberIdBalancerUriMap =
getCollectionsFactory().getMap(MEMBERID_BALANCER_MAP_NAME);
if (memberIdBalancerUriMap == null) {
throw new IllegalStateException("MemberId to BalancerMap is null");
}
IMap<URI, TreeSet<URI>> sharedBalanceUriMap = getCollectionsFactory().getMap(BALANCER_MAP_NAME);
if (sharedBalanceUriMap == null) {
throw new IllegalStateException("Shared balanced URIs map is null");
}
Map<URI, List<URI>> memberBalancedUrisMap = memberIdBalancerUriMap.remove(removedMember);
if (memberBalancedUrisMap != null) {
GL.debug(CLUSTER_LOGGER_NAME, "Cleaning up balancer cluster state for member {}", removedMember);
try {
for (URI key : memberBalancedUrisMap.keySet()) {
GL.debug(CLUSTER_LOGGER_NAME, "URI Key: {}", key);
List<URI> memberBalancedUris = memberBalancedUrisMap.get(key);
TreeSet<URI> globalBalancedUris = null;
TreeSet<URI> newGlobalBalancedUris = null;
do {
globalBalancedUris = sharedBalanceUriMap.get(key);
newGlobalBalancedUris = new TreeSet<URI>(globalBalancedUris);
for (URI memberBalancedUri : memberBalancedUris) {
GL.debug(CLUSTER_LOGGER_NAME, "Attempting to removing Balanced URI : {}", memberBalancedUri);
newGlobalBalancedUris.remove(memberBalancedUri);
}
} while (!sharedBalanceUriMap.replace(key, globalBalancedUris, newGlobalBalancedUris));
GL.debug(CLUSTER_LOGGER_NAME, "Removed balanced URIs for cluster member {}, new global list: {}",
removedMember, newGlobalBalancedUris);
}
} catch (Exception e) {
throw new IllegalStateException("Unable to remove the balanced URIs served by the member going down from " +
"global map");
}
}
fireMemberRemoved(removedMember);
logClusterMembers();
}
};
@Override
public String getInstanceKey(MemberId memberId) {
if (memberId == localNodeId) {
return this.localInstanceKey; // quicker, and works with CLIENT_MODE, too.
}
Map<MemberId, String> instanceKeyMap = getCollectionsFactory().getMap(INSTANCE_KEY_MAP);
return instanceKeyMap.get(memberId);
}
private EntryListener<MemberId, String> instanceKeyEntryListener = new EntryListener<MemberId, String>() {
// WE're supporting the idea of 'instance keys' (i.e. random strings that are supposed
// to be unique per instance of a gateway) solely for management to be able to tell the
// difference between two instances of a gateway accessed through the same management URL.
// The Console supports displaying history, and it needs to know when reconnecting to a
// given management URL whether or not the configuration might have changed. Because
// member IDs generally don't change (for now they're based on the cluster accept URL),
// they're a bad indicator of an instance stopping and being restarted. Thus the need for the
// instance key. When a member is added or removed, the instanceKey is also added or
// removed, and we can trigger events for management to update their cluster state.
@Override
public void entryAdded(EntryEvent<MemberId, String> newEntryEvent) {
fireInstanceKeyAdded(newEntryEvent.getValue());
}
@Override
public void entryEvicted(EntryEvent<MemberId, String> evictedEntryEvent) {
throw new RuntimeException("Instance keys should not be evicted, only added or removed.");
}
@Override
public void entryRemoved(EntryEvent<MemberId, String> removedEntryEvent) {
fireInstanceKeyRemoved(removedEntryEvent.getValue());
}
@Override
public void entryUpdated(EntryEvent<MemberId, String> updatedEntryEvent) {
throw new RuntimeException("Instance keys can not be updated, only added or removed.");
}
};
private EntryListener<URI, Collection<URI>> balancerMapEntryListener = new EntryListener<URI, Collection<URI>>() {
@Override
public void entryAdded(EntryEvent<URI, Collection<URI>> newEntryEvent) {
GL.trace(CLUSTER_LOGGER_NAME, "New entry for balance URI: {} value: {}", newEntryEvent.getKey(), newEntryEvent
.getValue());
fireBalancerEntryAdded(newEntryEvent);
}
@Override
public void entryEvicted(EntryEvent<URI, Collection<URI>> evictedEntryEvent) {
throw new RuntimeException("Balancer map entries should not be evicted, only added or removed.");
}
@Override
public void entryRemoved(EntryEvent<URI, Collection<URI>> removedEntryEvent) {
GL.trace(CLUSTER_LOGGER_NAME, "Entry removed for balance URI: {} value: {}", removedEntryEvent
.getKey(), removedEntryEvent.getValue());
fireBalancerEntryRemoved(removedEntryEvent);
}
@Override
public void entryUpdated(EntryEvent<URI, Collection<URI>> updatedEntryEvent) {
GL.trace(CLUSTER_LOGGER_NAME, "Entry updated for balance URI: {} value: {}", updatedEntryEvent
.getKey(), updatedEntryEvent.getValue());
fireBalancerEntryUpdated(updatedEntryEvent);
}
};
// cluster collections
@Override
public Lock getLock(Object obj) {
return clusterInstance.getLock(obj);
}
@Override
public IdGenerator getIdGenerator(String name) {
return clusterInstance.getIdGenerator(name);
}
// cluster communication
@Override
public void addReceiveQueue(String name) {
if (clusterMessaging != null) {
clusterMessaging.addReceiveQueue(name);
}
}
@Override
public void addReceiveTopic(String name) {
if (clusterMessaging != null) {
clusterMessaging.addReceiveTopic(name);
}
}
@Override
public void send(Object msg, SendListener listener, MemberId member) {
if (clusterMessaging != null) {
clusterMessaging.send(msg, listener, member);
}
}
@Override
public void send(Object msg, SendListener listener, String name) {
if (clusterMessaging != null) {
clusterMessaging.send(msg, listener, name);
}
}
@SuppressWarnings("unchecked")
@Override
public Object send(Object msg, MemberId member) throws Exception {
if (clusterMessaging != null) {
return clusterMessaging.send(msg, member);
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public Object send(Object msg, String name) throws Exception {
if (clusterMessaging != null) {
return clusterMessaging.send(msg, name);
}
return null;
}
@Override
public <T> void setReceiver(Class<T> type, ReceiveListener<T> receiveListener) {
if (clusterMessaging != null) {
clusterMessaging.setReceiver(type, receiveListener);
}
}
@Override
public <T> void removeReceiver(Class<T> type) {
if (clusterMessaging != null) {
clusterMessaging.removeReceiver(type);
}
}
@Override
public void addMembershipEventListener(MembershipEventListener eventListener) {
if (eventListener != null) {
membershipEventListeners.add(eventListener);
}
}
@Override
public void removeMembershipEventListener(MembershipEventListener eventListener) {
if (eventListener != null) {
membershipEventListeners.remove(eventListener);
}
}
@Override
public void addInstanceKeyListener(InstanceKeyListener instanceKeyListener) {
if (instanceKeyListener != null) {
instanceKeyListeners.add(instanceKeyListener);
}
}
@Override
public void removeInstanceKeyListener(InstanceKeyListener instanceKeyListener) {
if (instanceKeyListener != null) {
instanceKeyListeners.remove(instanceKeyListener);
}
}
@Override
public void addBalancerMapListener(BalancerMapListener balancerMapListener) {
if (balancerMapListener != null) {
balancerMapListeners.add(balancerMapListener);
}
}
@Override
public void removeBalancerMapListener(BalancerMapListener balancerMapListener) {
if (balancerMapListener != null) {
balancerMapListeners.remove(balancerMapListener);
}
}
@Override
public String getClusterName() {
return this.clusterName;
}
@Override
public List<MemberId> getAccepts() {
return localInterfaces;
}
@Override
public List<MemberId> getConnects() {
return clusterMembers;
}
@Override
public ClusterConnectOptionsContext getConnectOptions() {
return connectOptions;
}
@Override
public MessageBufferFactory getMessageBufferFactory() {
return messageBufferFactory;
}
@Override
public void logClusterState() {
logClusterMembers();
logBalancerMap();
}
private void logClusterMembers() {
// log current cluster state on TRACE level
if (clusterInstance != null) {
Cluster cluster = clusterInstance.getCluster();
if (cluster != null) {
GL.trace(CLUSTER_LOGGER_NAME, "Current cluster members:");
Set<Member> currentMembers = clusterInstance.getCluster().getMembers();
for (Member currentMember : currentMembers) {
MemberId memberId = getMemberId(currentMember);
GL.trace(CLUSTER_LOGGER_NAME, " member: {}", memberId);
}
}
}
}
private void logBalancerMap() {
GL.trace(CLUSTER_LOGGER_NAME, "Current balancer map:");
Map<URI, TreeSet<URI>> balancerMap = getCollectionsFactory().getMap(BALANCER_MAP_NAME);
for (URI balanceURI : balancerMap.keySet()) {
Set<URI> balanceTargets = balancerMap.get(balanceURI);
GL.trace(CLUSTER_LOGGER_NAME, " balance URI: {} target list: {}", balanceURI, balanceTargets);
}
}
/**
* Fire member added event
*/
private void fireMemberAdded(MemberId newMember) {
GL.debug(CLUSTER_LOGGER_NAME, "Firing member added for : {}", newMember);
for (MembershipEventListener listener : membershipEventListeners) {
try {
listener.memberAdded(newMember);
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in member added event {}", e);
}
}
}
/**
* Fire member removed event
*/
private void fireMemberRemoved(MemberId exMember) {
GL.debug(CLUSTER_LOGGER_NAME, "Firing member removed for: {}", exMember);
for (MembershipEventListener listener : membershipEventListeners) {
try {
listener.memberRemoved(exMember);
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in member removed event {}", e);
}
}
}
/**
* Fire instanceKeyAdded event
*/
private void fireInstanceKeyAdded(String instanceKey) {
GL.debug(CLUSTER_LOGGER_NAME, "Firing instanceKeyAdded for: {}", instanceKey);
for (InstanceKeyListener listener : instanceKeyListeners) {
try {
listener.instanceKeyAdded(instanceKey);
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in instanceKeyAdded event {}", e);
}
}
}
/**
* Fire instanceKeyRemoved event
*/
private void fireInstanceKeyRemoved(String instanceKey) {
GL.debug(CLUSTER_LOGGER_NAME, "Firing instanceKeyRemoved for: {}", instanceKey);
for (InstanceKeyListener listener : instanceKeyListeners) {
try {
listener.instanceKeyRemoved(instanceKey);
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in instanceKeyRemoved event {}", e);
}
}
}
/**
* Fire balancerEntryAdded event
*/
private void fireBalancerEntryAdded(EntryEvent<URI, Collection<URI>> entryEvent) {
URI balancerURI = entryEvent.getKey();
GL.debug(CLUSTER_LOGGER_NAME, "Firing balancerEntryAdded for: {}", balancerURI);
for (BalancerMapListener listener : balancerMapListeners) {
try {
listener.balancerEntryAdded(balancerURI, entryEvent.getValue());
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in balancerEntryAdded event {}", e);
}
}
}
/**
* Fire balancerEntryRemoved event
*/
private void fireBalancerEntryRemoved(EntryEvent<URI, Collection<URI>> entryEvent) {
URI balancerURI = entryEvent.getKey();
GL.debug(CLUSTER_LOGGER_NAME, "Firing balancerEntryRemoved for: {}", balancerURI);
for (BalancerMapListener listener : balancerMapListeners) {
try {
listener.balancerEntryRemoved(balancerURI, entryEvent.getValue());
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in balancerEntryRemoved event {}", e);
}
}
}
/**
* Fire balancerEntryUpdated event
*/
private void fireBalancerEntryUpdated(EntryEvent<URI, Collection<URI>> entryEvent) {
URI balancerURI = entryEvent.getKey();
GL.debug(CLUSTER_LOGGER_NAME, "Firing balancerEntryUpdated for: {}", balancerURI);
for (BalancerMapListener listener : balancerMapListeners) {
try {
listener.balancerEntryUpdated(balancerURI, entryEvent.getValue());
} catch (Throwable e) {
GL.error(CLUSTER_LOGGER_NAME, "Error in balancerEntryUpdated event {}", e);
}
}
}
@Override
public CollectionsFactory getCollectionsFactory() {
initializeCluster(null);
return this.collectionsFactory;
}
private void initializeCluster(Config config) {
if (clusterInitialized.compareAndSet(false, true)) {
clusterInstance = Hazelcast.newHazelcastInstance(config);
if (clusterInstance == null) {
throw new RuntimeException("Unable to initialize the cluster");
}
Cluster cluster = clusterInstance.getCluster();
cluster.addMembershipListener(this.membershipListener);
// Register a listener for Hazelcast logging events
LoggingService loggingService = clusterInstance.getLoggingService();
loggingService.addLogListener(Level.FINEST, this);
this.collectionsFactory = new ClusterCollectionsFactory(clusterInstance);
this.messageBufferFactory = new ClusterMemoryMessageBufferFactory(clusterInstance);
localNodeId = getMemberId(cluster.getLocalMember());
clusterMessaging = new ClusterMessaging(this, clusterInstance, schedulerProvider);
IMap<MemberId, String> instanceKeyMap = collectionsFactory.getMap(INSTANCE_KEY_MAP);
instanceKeyMap.put(localNodeId, localInstanceKey);
instanceKeyMap.addEntryListener(instanceKeyEntryListener, true);
IMap<URI, Collection<URI>> balancerMap = collectionsFactory.getMap(BALANCER_MAP_NAME);
balancerMap.addEntryListener(balancerMapEntryListener, true);
}
}
@Override
public void log(LogEvent logEvent) {
Member member = logEvent.getMember();
LogRecord record = logEvent.getLogRecord();
Level level = record.getLevel();
if (level.equals(Level.SEVERE)) {
logger.error(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
} else if (level.equals(Level.WARNING)) {
logger.warn(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
} else if (level.equals(Level.INFO)) {
logger.info(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
} else if (level.equals(Level.FINE)) {
if (logger.isDebugEnabled()) {
logger.debug(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
}
} else if (level.equals(Level.FINER) ||
level.equals(Level.FINEST)) {
if (logger.isTraceEnabled()) {
logger.trace(String.format(CLUSTER_LOG_FORMAT, member, record.getMessage()));
}
}
}
}
| Update DefaultClusterContext.java | server/src/main/java/org/kaazing/gateway/server/context/resolve/DefaultClusterContext.java | Update DefaultClusterContext.java |
|
Java | apache-2.0 | b9fa62d4b3ec9def2986a106792e7307152b6d06 | 0 | MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab | package org.myrobotlab.service;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.FloatBuffer;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import org.myrobotlab.codec.CodecUtils;
import org.myrobotlab.cv.CvData;
import org.myrobotlab.framework.Instantiator;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.jme3.AnalogHandler;
import org.myrobotlab.jme3.HudText;
import org.myrobotlab.jme3.Jme3App;
import org.myrobotlab.jme3.Jme3Msg;
import org.myrobotlab.jme3.Jme3ServoController;
import org.myrobotlab.jme3.Jme3Util;
import org.myrobotlab.jme3.MainMenuState;
import org.myrobotlab.jme3.Search;
import org.myrobotlab.jme3.UserData;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.math.Mapper;
import org.myrobotlab.math.geometry.Point3df;
import org.myrobotlab.math.geometry.PointCloud;
import org.myrobotlab.service.abstracts.AbstractComputerVision;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.virtual.VirtualMotor;
import org.slf4j.Logger;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.AssetManager;
import com.jme3.asset.plugins.FileLocator;
import com.jme3.bullet.BulletAppState;
// import com.jme3.bullet.animation.DynamicAnimControl;
import com.jme3.collision.CollisionResults;
import com.jme3.export.binary.BinaryExporter;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.input.FlyByCamera;
import com.jme3.input.InputManager;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.AnalogListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseAxisTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.material.RenderState.FaceCullMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Ray;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.renderer.ViewPort;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.CameraNode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.Spatial.CullHint;
import com.jme3.scene.control.BillboardControl;
import com.jme3.scene.control.CameraControl.ControlDirection;
import com.jme3.scene.debug.Grid;
import com.jme3.scene.plugins.blender.BlenderLoader;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Quad;
import com.jme3.system.AppSettings;
import com.jme3.util.BufferUtils;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.lemur.style.BaseStyles;
/**
* A simulator built on JMonkey 3 Engine.
*
* @author GroG, calamity, kwatters, moz4r and many others ...
*
*/
public class JMonkeyEngine extends Service implements ActionListener {
public final static Logger log = LoggerFactory.getLogger(JMonkeyEngine.class);
private static final long serialVersionUID = 1L;
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(JMonkeyEngine.class.getCanonicalName());
meta.addDescription("is a 3d game engine, used for simulators");
meta.setAvailable(true); // false if you do not want it viewable in a gui
// TODO: extract version numbers like this into a constant/enum
String jmeVersion = "3.2.2-stable";
meta.addDependency("org.jmonkeyengine", "jme3-core", jmeVersion);
meta.addDependency("org.jmonkeyengine", "jme3-desktop", jmeVersion);
meta.addDependency("org.jmonkeyengine", "jme3-lwjgl", jmeVersion);
meta.addDependency("org.jmonkeyengine", "jme3-jogg", jmeVersion);
// meta.addDependency("org.jmonkeyengine", "jme3-test-data", jmeVersion);
meta.addDependency("com.simsilica", "lemur", "1.11.0");
meta.addDependency("com.simsilica", "lemur-proto", "1.10.0");
// meta.addDependency("org.jmonkeyengine", "jme3-bullet", jmeVersion);
// meta.addDependency("org.jmonkeyengine", "jme3-bullet-native",
// jmeVersion);
// meta.addDependency("jme3utilities", "Minie", "0.6.2");
// "new" physics - ik forward kinematics ...
// not really supposed to use blender models - export to j3o
meta.addDependency("org.jmonkeyengine", "jme3-blender", jmeVersion);
// jbullet ==> org="net.sf.sociaal" name="jME3-jbullet" rev="3.0.0.20130526"
// audio dependencies
meta.addDependency("de.jarnbjo", "j-ogg-all", "1.0.0");
meta.addCategory("simulator");
return meta;
}
boolean altLeftPressed = false;
transient AnalogListener analog = null;
transient Jme3App app;
transient AssetManager assetManager;
String assetsDir = getDataDir() + File.separator + "assets";
boolean autoAttach = true;
boolean autoAttachAll = true;
transient BulletAppState bulletAppState;
transient Node camera = new Node("camera");
transient Vector3f cameraDirection = new Vector3f();
transient Camera cameraSettings;
transient CameraNode camNode;
boolean ctrlLeftPressed = false;
boolean mouseLeftPressed = false;
String defaultAppType = "Jme3App";
long deltaMs;
transient DisplayMode displayMode = null;
transient FlyByCamera flyCam;
String fontColor = "#66ff66"; // green
int fontSize = 14;
boolean fullscreen = false;
transient Node guiNode;
transient Map<String, HudText> guiText = new TreeMap<>();
int height = 768;
transient AtomicInteger id = new AtomicInteger();
transient InputManager inputManager;
protected Queue<Jme3Msg> jmeMsgQueue = new ConcurrentLinkedQueue<Jme3Msg>();
final public String KEY_SEPERATOR = "/";
transient DisplayMode lastDisplayMode = null;
transient MainMenuState menu;
String modelsDir = assetsDir + File.separator + "Models";
final Map<String, String> nameMappings = new TreeMap<String, String>();
transient Map<String, Spatial> nodesx = new TreeMap<String, Spatial>();
// https://stackoverflow.com/questions/16861727/jmonkey-engine-3-0-drawing-points
FloatBuffer pointCloudBuffer = null;
transient Material pointCloudMat = null;
transient Mesh pointCloudMesh = new Mesh();
transient Node rootNode;
transient Spatial selectedForView = null;
transient Spatial selectedForMovement = null;
int selectIndex = 0;
transient Jme3ServoController servoController;
transient AppSettings settings;
boolean shiftLeftPressed = false;
long sleepMs;
long startUpdateTs;
transient AppStateManager stateManager;
transient Jme3Util util;
transient ViewPort viewPort;
int width = 1024;
public JMonkeyEngine(String n) {
super(n);
File d = new File(modelsDir);
d.mkdirs();
util = new Jme3Util(this);
analog = new AnalogHandler(this);
servoController = new Jme3ServoController(this);
}
public void addBox(String boxName) {
addBox(boxName, 1f, 1f, 1f); // room box
}
public void addBox(String boxName, float width, float depth, float height) {
addBox(boxName, width, depth, height, null, null);
moveTo(boxName, 0f, height, 0f); // center it on the floor fully above the
// ground
}
// FIXME make method "without" name to be added to the _system_box node ..
public void addBox(String name, Float width, Float depth, Float height, String color, Boolean fill) {
Node boxNode = null;
Spatial check = get(name);
if (check != null && check instanceof Geometry) {
log.error("addBox - scene graph already has {} and it is a Geometry", check);
return;
} else if (check != null && check instanceof Node) {
boxNode = (Node) check;
} else {
boxNode = new Node(name);
}
if (width == null) {
width = 1f;
}
if (depth == null) {
depth = 1f;
}
if (height == null) {
height = 1f;
}
Box box = new Box(width, depth, height); // 1 meter square
// wireCube.setMode(Mesh.Mode.LineLoop);
// box.setMode(Mesh.Mode.Lines);
// FIXME - geom & matterial always xxx-geometry ? & xxx-material ??
Geometry geom = new Geometry(String.format("%s._geometry", name), box);
Material mat1 = null;
if (fill == null || fill.equals(false)) {
// mat1 = new Material(assetManager,
// "Common/MatDefs/Light/Lighting.j3md");
mat1 = new Material(assetManager, "Common/MatDefs/Light/PBRLighting.j3md");
box.setMode(Mesh.Mode.Lines);
} else {
mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat1.setColor("Color", Jme3Util.toColor(color));
}
// mat1 = new Material(assetManager, "Common/MatDefs/Light/Deferred.j3md");
// mat1.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Front);
geom.setMaterial(mat1);
boxNode.attachChild(geom);
// FIXME - optimize rootNode/geom/nodes & jme3Node !
// UserData o = new UserData(this, boxNode);
// nodes.put(name, o);
rootNode.attachChild(boxNode);
moveTo(name, 0.0f, 0.5f * height, 0.0f);
// index(boxNode);
}
public void addGrid(String name) {
addGrid(name, new Vector3f(0, 0, 0), 40, "CCCCCC");
}
public void addGrid(String name, Vector3f pos, int size, String color) {
Spatial s = get(name);
if (s != null) {
log.warn("addGrid {} already exists");
return;
}
Geometry g = new Geometry("wireframe grid", new Grid(size, size, 1.0f));
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.getAdditionalRenderState().setWireframe(true);
mat.setColor("Color", Jme3Util.toColor(color));
g.setMaterial(mat);
g.center().move(pos);
Node n = new Node(name);
n.attachChild(g);
rootNode.attachChild(n);
}
public void addMsg(Jme3Msg msg) {
jmeMsgQueue.add(msg);
}
public void attach(Attachable service) throws Exception {
app.attach(service);
// Cv Publisher ..
if (service instanceof AbstractComputerVision) {
AbstractComputerVision cv = (AbstractComputerVision) service;
subscribe(service.getName(), "publishCvData");
}
if (service instanceof ServoControl) {
servoController.attach(service);
}
// backward attach ?
}
public void attachChild(Spatial node) {
rootNode.attachChild(node);
}
/**
* binds two objects together ...
*
* @param child
* @param parent
*/
public void bind(String child, String parent) {
Jme3Msg msg = new Jme3Msg();
msg.method = "bind";
msg.data = new Object[] { child, parent };
addMsg(msg);
}
public Map<String, UserData> buildTree() {
TreeMap<String, UserData> tree = new TreeMap<String, UserData>();
return buildTree(tree, "", rootNode, false, false);
}
/**
* The buildTree method creates a data structure for quick access and indexing
* of nodes - it can build it in two different ways - one which uses full
* depth for an access key useDepth=true and another that is a flat model.
* Both can have collisions. When the parents of nodes change, the depth model
* "should" change to reflect the changes in branches. The flat model does not
* need to change, but has a higher likelyhood of collisions.
*
* @param tree
* @param path
* @param spatial
* @param useDepthKeys
* @return
*/
public Map<String, UserData> buildTree(Map<String, UserData> tree, String path, Spatial spatial, boolean includeGeometries, boolean useDepthKeys) {
if (useDepthKeys) {
path = path + KEY_SEPERATOR + spatial.getName();
} else {
path = spatial.getName();
}
if (tree.containsKey(path)) {
UserData s = tree.get(path);
log.error("buildTree collision {}", path);
}
// only interested in nodes, since nodes "can" have user data...
// Geometries cannot or (should not?)
if (!includeGeometries && (spatial instanceof Geometry)) {
return tree;
}
// putting both nodes & geometries on the tree
tree.put(path, spatial.getUserData("data"));
if (spatial instanceof Node) {
List<Spatial> children = ((Node) spatial).getChildren();
for (int i = 0; i < children.size(); ++i) {
buildTree(tree, path, children.get(i), includeGeometries, useDepthKeys);
}
}
return tree;
}
public void clone(String name, String newName) {
}
public Geometry createBoundingBox(Spatial spatial) {
return util.createBoundingBox(spatial);
}
public Node createUnitAxis() {
return util.createUnitAxis();
}
public VirtualMotor createVirtualMotor(String name) {
// TODO Auto-generated method stub
return null;
}
/**
* cycles through children at same level
*/
public void cycle() {
if (selectedForView == null) {
Spatial s = rootNode.getChild(0);
setSelected(s);
}
Node parent = selectedForView.getParent();
if (parent == null) {
return;
}
List<Spatial> siblings = parent.getChildren();
if (shiftLeftPressed) {
--selectIndex;
} else {
++selectIndex;
}
if (selectIndex > siblings.size() - 1) {
selectIndex = 0;
} else if (selectIndex < 0) {
selectIndex = siblings.size() - 1;
}
setSelected(siblings.get(selectIndex));
}
public void enableBoundingBox(Spatial spatial, boolean b) {
Node node = getNode(spatial);
UserData data = getUserData(node);
data.enableBoundingBox(b);
}
public void enableBoundingBox(String name, boolean b) {
UserData o = getUserData(name);
enableBoundingBox(o.getSpatial(), b);
}
// FIXME !!!! enableCoodinateAxes - same s bb including parent if geometry
public void enableCoordinateAxes(Spatial spatial, boolean b) {
Node node = getNode(spatial);
UserData data = getUserData(node);
data.enableCoordinateAxes(b);
}
public void enableFlyCam(boolean b) {
flyCam.setEnabled(b);
}
public void enableFullScreen(boolean fullscreen) {
this.fullscreen = fullscreen;
if (fullscreen) {
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
displayMode = device.getDisplayMode();
// DisplayMode[] modes = device.getDisplayModes(); list of possible diplay
// modes
// remember last display mode
displayMode = device.getDisplayMode();
settings = app.getContext().getSettings();
log.info("settings {}", settings);
settings.setTitle(getName());
settings.setResolution(displayMode.getWidth(), displayMode.getHeight());
settings.setFrequency(displayMode.getRefreshRate());
settings.setBitsPerPixel(displayMode.getBitDepth());
// settings.setFullscreen(device.isFullScreenSupported());
settings.setFullscreen(fullscreen);
app.setSettings(settings);
app.restart();
// app.restart(); // restart the context to apply changes
} else {
settings = app.getContext().getSettings();
log.info("settings {}", settings);
/*
* settings.setFrequency(displayMode.getRefreshRate());
* settings.setBitsPerPixel(displayMode.getBitDepth());
*/
settings.setFullscreen(fullscreen);
settings.setResolution(width, height);
app.setSettings(settings);
app.restart();
}
}
public String format(Node node, Integer selected) {
StringBuilder sb = new StringBuilder();
List<Spatial> children = node.getChildren();
sb.append("[");
for (int i = 0; i < children.size(); ++i) {
if (i != 0) {
sb.append(", ");
}
sb.append(node.getChild(i).getName());
}
sb.append("]");
return sb.toString();
}
public Spatial get(String name) {
return get(name, null);
}
/**
* the all purpose get by name method
*
* @param string
* @return
*/
public Spatial get(String name, Node startNode) {
if (startNode == null) {
startNode = rootNode;
}
Spatial child = startNode.getChild(name);
if (child == null) {
error("get(%s) could not find child");
}
return child;
}
public Jme3App getApp() {
return app;
}
public AssetManager getAssetManager() {
return assetManager;
}
private String getExt(String name) {
int pos = name.lastIndexOf(".");
String ext = null;
if (pos != -1) {
ext = name.substring(pos + 1).toLowerCase();
}
return ext;
}
public Geometry getGeometry(String name) {
return getGeometry(name, null);
}
public Geometry getGeometry(String name, Node startNode) {
Spatial spatial = get(name, startNode);
if (spatial instanceof Geometry) {
return (Geometry) spatial;
} else {
log.error("could not find Geometry {}", name);
return null;
}
}
public Queue<Jme3Msg> getjmeMsgQueue() {
return jmeMsgQueue;
}
public String getKeyPath(Spatial spatial) {
if (spatial == null) {
return null;
}
StringBuilder sb = new StringBuilder(spatial.getName());
Node p = spatial.getParent();
while (p != null) {
sb.insert(0, String.format("%s%s", p.getName(), KEY_SEPERATOR));
p = p.getParent();
}
return sb.toString();
}
private String getNameNoExt(String name) {
int pos = name.lastIndexOf(".");
String nameNoExt = name;
if (pos != -1) {
nameNoExt = name.substring(0, pos);
}
return nameNoExt;
}
public Node getNode(Spatial spatial) {
if (spatial instanceof Geometry) {
return spatial.getParent();
}
return (Node) spatial;
}
public Node getNode(String name) {
return getNode(name, null);
}
public Node getNode(String name, Node startNode) {
Spatial spatial = get(name, startNode);
if (spatial instanceof Node) {
return (Node) spatial;
} else {
log.error("could not find Node {}", name);
return null;
}
}
public Spatial getRootChild(Spatial spatial) {
if (spatial == null) {
log.error("spatial is null");
return null;
}
Spatial c = spatial;
Spatial p = c.getParent();
if (spatial == rootNode) {
return null;
}
while (p != null && p != rootNode) {
c = p;
p = c.getParent();
}
if (p != null) {
return c;
}
return spatial;
}
public Node getRootNode() {
return rootNode;
}
public Spatial getSelected() {
return selectedForView;
}
public AppSettings getSettings() {
return settings;
}
public Spatial getTopNode(Spatial spatial) {
if (spatial == null) {
return null;
}
Spatial top = spatial;
while (top.getParent() != null) {
top = top.getParent();
}
return top;
}
// TODO - possibly Geometries
// Unique Naming and map/index
public UserData getUserData(Node node) {
UserData data = node.getUserData("data");
if (data == null) {
data = new UserData(this, node);
// FIXME - add map/index
// getAncestorKey(x) + rootKey if its not root = key
}
return data;
}
/**
* The workhorse - where everyone "searches" for the user data they need. It
* works agains a flat or depth key'd tree. If the node is found but the user
* data has not been created, it creates it and assigns the references... if
* the node cannot be found, it returns null
*
* @param path
* - full path for a depth tree, name for a flat map
* @return
*/
public UserData getUserData(String path /* , boolean useDepth */) {
if (nameMappings.containsKey(path)) {
path = nameMappings.get(path);
}
Spatial spatial = get(path);
if (spatial == null) {
error("geteUserData %s cannot be found", path);
return null;
}
if (spatial instanceof Geometry) {
error("geteUserData %s found but is Geometry not Node", path);
return null;
}
UserData userData = spatial.getUserData("data");
if (userData == null) {
userData = new UserData(this, spatial);
}
return userData;
}
public void initPointCloud(PointCloud pc) {
Point3df[] points = pc.getData();
Vector3f[] lineVerticies = new Vector3f[points.length];
for (int i = 0; i < points.length; ++i) {
Point3df p = points[i];
lineVerticies[i] = new Vector3f(p.x, p.y, p.z);
}
pointCloudBuffer = BufferUtils.createFloatBuffer(lineVerticies);
// pointCloudMesh.setMode(Mesh.Mode.TriangleFan);
pointCloudMesh.setMode(Mesh.Mode.Points);
// pointCloudMesh.setMode(Mesh.Mode.Lines);
// pointCloudMesh.setMode(Mesh.Mode.Triangles);
// https://hub.jmonkeyengine.org/t/how-to-render-a-3d-point-cloud/27341/11
pointCloudMesh.setBuffer(VertexBuffer.Type.Position, 3, pointCloudBuffer);
pointCloudMesh.setBuffer(VertexBuffer.Type.Color, 4, pc.getColors());
pointCloudMesh.updateBound();
pointCloudMesh.updateCounts();
// pointCloudMesh.setPointSize(0.0003);
Geometry geo = new Geometry("line", pointCloudMesh);
pointCloudMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
// pointCloudMat = new Material(assetManager,
// "Common/MatDefs/Misc/Particle.j3md");
pointCloudMat.setColor("Color", ColorRGBA.Green);
pointCloudMat.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Off);
// pointCloudMat.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Front);
pointCloudMat.setBoolean("VertexColor", false); // important for points !!
// pointCloudMat.setBoolean("VertexColor", false); // important for points
// !!
geo.setMaterial(pointCloudMat);
rootNode.attachChild(geo);
}
// FIXME - more parameters - location & rotation (new function "move")
// FIXME - scale should not be in this - scale as one of 3 methods rotate !!!!
// translate
// TODO - must be re-entrant - perhaps even on a schedule ?
// TODO - removeNode
public void load(String inFileName) {
log.info("load({})", inFileName);
// UserData o = null;
try {
if (inFileName == null) {
error("file name cannot be null");
return;
}
File file = getFile(inFileName);
if (!file.exists()) {
error(String.format("file %s does not exits", inFileName));
return;
}
String filename = file.getName();
String ext = getExt(filename);
String simpleName = getNameNoExt(filename);
if (!ext.equals("json")) {
Spatial spatial = assetManager.loadModel(filename);
spatial.setName(simpleName);
Node node = null;
if (spatial instanceof Node) {
node = (Node) spatial;
} else {
node = new Node(spatial.getName());
node.attachChild(spatial);
}
rootNode.attachChild(node);
} else {
// now for the json meta data ....
/*
* String json = FileIO.toString(inFileName); Map<String, Object> list =
* CodecUtils.fromJson(json, nodes.getClass()); for (String name :
* list.keySet()) { String nodePart = CodecUtils.toJson(list.get(name));
* UserData node = CodecUtils.fromJson(nodePart, UserData.class); //
* get/create transient parts //
* node.setService(Runtime.getService(name)); // node.setJme(this); //
* putN // nodes.put(node.getName(), node); }
*/
}
} catch (Exception e) {
error(e);
}
}
public Spatial loadModel(String assetPath) {
return assetManager.loadModel(assetPath);
}
public void loadModels() {
// load the root data dir
loadModels(modelsDir);
loadNodes(modelsDir);
}
public void loadModels(String dirPath) {
File dir = new File(dirPath);
if (!dir.isDirectory()) {
error("%s is not a directory", dirPath);
return;
}
assetManager.registerLocator(dirPath, FileLocator.class);
// get list of files in dir ..
File[] files = dir.listFiles();
// scan for all non json files first ...
// initially set them invisible ...
for (File f : files) {
if (!f.isDirectory() && !"json".equals(getExt(f.getName()))) {
load(f.getAbsolutePath());
}
}
// process structure json files ..
// breadth first search ...
for (File f : files) {
if (f.isDirectory()) {
loadModels(f.getAbsolutePath());
}
}
}
/**
* load a node with all potential children
*
* @param parentDirPath
*/
public void loadNode(String parentDirPath) {
File parentFile = new File(parentDirPath);
if (!parentFile.isDirectory()) {
// parent is not a directory ...
// we are done here ..
return;
}
String parentName = parentFile.getName();
File[] files = parentFile.listFiles();
// depth first search - process all children first
// to build the tree
for (File f : files) {
if (f.isDirectory()) {
loadNode(f.getAbsolutePath());
}
}
Node parentNode = getNode(parentName);
// parent is a dir - we have processed our children - now we process
// the parent "if" we don't already have a reference to a node with the same
// name
if (parentNode == null) {
putNode(parentName);
parentNode = putNode(parentName);
for (File f : files) {
String childname = getNameNoExt(f.getName());
if (getNode(childname) == null) {
log.error("loadNode {} can not attach child to {} not found in nodes", parentDirPath, childname);
} else {
parentNode.attachChild(getNode(childname));
}
}
} else {
// FIXME - it "may" already contain the parent name - but also "may" not
// have all sub-children attached
// possibly implement - attaching children
}
// index(parentNode);
// saveNodes();
}
/**
* based on a directory structure - add missing nodes and bindings top node
* will be bound to root
*
* @param dirPath
*/
public void loadNodes(String dirPath) {
File dir = new File(dirPath);
if (!dir.isDirectory()) {
error("%s is not a directory", dirPath);
return;
}
// get list of files in dir ..
File[] files = dir.listFiles();
// scan for all non json files first ...
// initially set them invisible ...
for (File f : files) {
if (f.isDirectory()) {
loadNode(f.getAbsolutePath());
}
}
}
public void cameraLookAt(String name) {
Spatial s = get(name);
if (s == null) {
log.error("cameraLookAt - cannot find {}", name);
return;
}
cameraLookAt(s);
}
public void cameraLookAt(Spatial spatial) {
camera.lookAt(spatial.getWorldTranslation(), Vector3f.UNIT_Y);
}
// relative move
// favor the xy plane because we are not birds ?
public void move(String name, float x, float y) {
// must "get z"
// move(name, x, y, null);
}
public void moveTo(String name, float x, float y, float z) {
Jme3Msg msg = new Jme3Msg();
msg.method = "moveTo";
msg.data = new Object[] { name, x, y, z };
addMsg(msg);
}
@Override
public void onAction(String name, boolean keyPressed, float tpf) {
log.info("onAction {} {} {}", name, keyPressed, tpf);
if (name.equals("mouse-click-left") && !mouseLeftPressed) {
Geometry target = checkCollision();
setSelected(target);
}
if ("full-screen".equals(name)) {
enableFullScreen(true);
} else if ("menu".equals(name)) {
menu.setEnabled(true);
} else if ("select-root".equals(name)) {
setSelected(rootNode);
} else if ("camera".equals(name)) {
setSelected("camera");
} else if ("exit-full-screen".equals(name)) {
enableFullScreen(false);
} else if ("cycle".equals(name) && keyPressed) {
cycle();
} else if (name.equals("shift-left")) {
shiftLeftPressed = keyPressed;
} else if (name.equals("ctrl-left")) {
ctrlLeftPressed = keyPressed;
} else if (name.equals("alt-left")) {
altLeftPressed = keyPressed;
} else if ("export".equals(name) && keyPressed) {
saveSpatial(selectedForView.getName());
} else if ("mouse-click-left".equals(name)) {
mouseLeftPressed = keyPressed;
} else {
warn("%s - key %b %f not found", name, keyPressed, tpf);
}
}
public void setSelected(String name) {
Spatial s = get(name);
if (s == null) {
log.error("setSelected {} is null", name);
return;
}
setSelected(s);
}
/**
* onAnalog
*
* @param name
* @param keyPressed
* @param tpf
*/
public void onAnalog(String name, float keyPressed, float tpf) {
log.info("onAnalog [{} {} {}]", name, keyPressed, tpf);
if (selectedForMovement == null) {
selectedForMovement = camera;// FIXME "new" selectedMove vs selected
}
// wheelmouse zoom (done)
// alt+ctrl+lmb - zoom <br> (done)
// alt+lmb - rotate<br> (done)
// alt+shft+lmb - pan (done)
// rotate around selection -
// https://www.youtube.com/watch?v=IVZPm9HAMD4&feature=youtu.be
// wrap text of breadcrumbs
// draggable - resize for menu - what you set is how it stays
// when menu active - inputs(hotkey when non-menu) should be deactive
log.info("{}", keyPressed);
// ROTATE
if (mouseLeftPressed && altLeftPressed && !shiftLeftPressed) {
if (name.equals("mouse-axis-x")) {
selectedForMovement.rotate(0, -keyPressed, 0);
} else if (name.equals("mouse-axis-x-negative")) {
selectedForMovement.rotate(0, keyPressed, 0);
} else if (name.equals("mouse-axis-y")) {
selectedForMovement.rotate(-keyPressed, 0, 0);
} else if (name.equals("mouse-axis-y-negative")) {
selectedForMovement.rotate(keyPressed, 0, 0);
}
}
// PAN
if (mouseLeftPressed && altLeftPressed && shiftLeftPressed) {
if (name.equals("mouse-axis-x")) {
selectedForMovement.move(keyPressed*3, 0, 0);
} else if (name.equals("mouse-axis-x-negative")) {
selectedForMovement.move(-keyPressed*3, 0, 0);
} else if (name.equals("mouse-axis-y")) {
selectedForMovement.move(0, keyPressed*3, 0);
} else if (name.equals("mouse-axis-y-negative")) {
selectedForMovement.move(0, -keyPressed*3, 0);
}
}
// ZOOM
if (mouseLeftPressed && altLeftPressed && ctrlLeftPressed) {
if (name.equals("mouse-axis-y")) {
selectedForMovement.move(0, 0, keyPressed*10);
} else if (name.equals("mouse-axis-y-negative")) {
selectedForMovement.move(0, 0, -keyPressed*10);
}
}
if (name.equals("mouse-wheel-up") || name.equals("forward")) {
// selected.setLocalScale(selected.getLocalScale().mult(1.0f));
selectedForMovement.move(0, 0, keyPressed * -1);
} else if (name.equals("mouse-wheel-down") || name.equals("backward")) {
// selected.setLocalScale(selected.getLocalScale().mult(1.0f));
selectedForMovement.move(0, 0, keyPressed * 1);
}
}
// FIXME make a more general Collision check..
public Geometry checkCollision() {
// Reset results list.
CollisionResults results = new CollisionResults();
// Convert screen click to 3d position
Vector2f click2d = inputManager.getCursorPosition();
Vector3f click3d = cameraSettings.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone();
Vector3f dir = cameraSettings.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 1f).subtractLocal(click3d).normalizeLocal();
// Aim the ray from the clicked spot forwards.
Ray ray = new Ray(click3d, dir);
// Collect intersections between ray and all nodes in results list.
rootNode.collideWith(ray, results);
// (Print the results so we see what is going on:)
for (int i = 0; i < results.size(); i++) {
// (For each “hit”, we know distance, impact point, geometry.)
float dist = results.getCollision(i).getDistance();
Vector3f pt = results.getCollision(i).getContactPoint();
String target = results.getCollision(i).getGeometry().getName();
System.out.println("Selection #" + i + ": " + target + " at " + pt + ", " + dist + " WU away.");
}
// Use the results -- we rotate the selected geometry.
if (results.size() > 0) {
// The closest result is the target that the player picked:
Geometry target = results.getClosestCollision().getGeometry();
// Here comes the action:
log.info("you clicked " + target.getName());
return target;
}
return null;
}
/**
* A method to accept Computer Vision data (from OpenCV or BoofCv) and to
* appropriately delegate it out to more specific methods
*
* @param data
*/
public void onCvData(CvData data) {
onPointCloud(data.getPointCloud());
}
public void onPointCloud(PointCloud pc) {
if (pc == null) {
return;
}
// pointCloudMat.setBoolean("VertexColor", false);
// pointCloudMesh.setPointSize(0.01f);
if (pointCloudBuffer == null) {
initPointCloud(pc);
// addBox("box-1");
}
pointCloudBuffer.rewind();
Point3df[] points = pc.getData();
for (int i = 0; i < points.length; ++i) {
Point3df p = points[i];
// log.info("p {}", p);
// pointCloudBuffer.put(480 - p.y);
// pointCloudBuffer.put(640 - p.x);
pointCloudBuffer.put(p.x);
pointCloudBuffer.put(p.y);
pointCloudBuffer.put(p.z);
// lineVerticies[index] = new Vector3f(480 - p.y, 640 - p.x, p.z);
}
pointCloudMesh.setBuffer(VertexBuffer.Type.Position, 3, pointCloudBuffer);
pointCloudMesh.setBuffer(VertexBuffer.Type.Color, 4, pc.getColors());
}
// auto Register
public void onRegistered(Service service) throws Exception {
// new service - see if we can virtualize it
log.info("{}.onRegistered({})", getName(), service);
if (autoAttach) {
if (autoAttachAll) {
// spin through all apps - attempt to attach
}
attach(service);
}
}
public Node putNode(String name) {
Node check = getNode(name);
if (check != null) {
return check;
}
Node n = new Node(name);
rootNode.attachChild(n);
return n;
}
public void putText(Spatial spatial, int x, int y) {
Vector3f xyz = spatial.getWorldTranslation();
Quaternion q = spatial.getLocalRotation();
float[] angles = new float[3]; // yaw, roll, pitch
q.toAngles(angles);
boolean isNode = (spatial instanceof Node);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s-%s\n", (isNode) ? "node" : "geom", spatial.getName()));
sb.append(String.format("x:%.3f y:%.3f z:%.3f\n", xyz.x, xyz.y, xyz.z));
sb.append(String.format("yaw:%.2f roll:%.2f pitch:%.2f\n", angles[0] * 180 / FastMath.PI, angles[1] * 180 / FastMath.PI, angles[2] * 180 / FastMath.PI));
if (isNode) {
sb.append(format((Node) spatial, 0));
}
putText(sb.toString(), 10, 10);
}
public void putText(String text, int x, int y) {
putText(text, x, y, null, null);
}
// put 2d text into a 3d scene graph
public void putText(String text, int x, int y, int z) {
Node n;
Node n2;
Quad q = new Quad(2, 2);
Geometry g = new Geometry("Quad", q);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.Blue);
g.setMaterial(mat);
Quad q2 = new Quad(1, 1);
Geometry g3 = new Geometry("Quad2", q2);
Material mat2 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat2.setColor("Color", ColorRGBA.Yellow);
g3.setMaterial(mat2);
// g3.setLocalTranslation(.5f, .5f, .01f);
// Box b = new Box(.25f, .5f, .25f);
Box b = new Box(1.0f, 1.0f, 1.0f);
Geometry g2 = new Geometry("Box", b);
// g2.setLocalTranslation(0, 0, 3);
g2.setMaterial(mat);
BitmapFont font = assetManager.loadFont("Common/Default.fnt");
BitmapText bmText = new BitmapText(font, false);
bmText.setSize(30);
bmText.setText("Billboard Data");
bmText.setQueueBucket(Bucket.Transparent);
bmText.setColor(ColorRGBA.White);
Node bb = new Node("billboard");
BillboardControl control = new BillboardControl();
control.setAlignment(BillboardControl.Alignment.Screen);
bb.addControl(control);
bb.attachChild(bmText);
bb.attachChild(g);
bb.attachChild(g3);
n = new Node("parent");
n.attachChild(g2);
n.attachChild(bb);
rootNode.attachChild(n);
n2 = new Node("parentParent");
n2.setLocalTranslation(Vector3f.UNIT_X.mult(5));
n2.attachChild(n);
rootNode.attachChild(n2);
}
public void putText(String text, int x, int y, String color) {
putText(text, x, y, color, null);
}
/**
* put text on the guiNode HUD display for jmonkey FIXME - do the same logic
* in OpenCV overlay !
*
* @param text
* @param x
* @param y
*/
public void putText(String text, int x, int y, String color, Integer size) {
HudText hud = null;
if (color == null) {
color = fontColor;
}
if (size == null) {
size = fontSize;
}
String key = String.format("%d-%d", x, y);
if (guiText.containsKey(key)) {
hud = guiText.get(key);
hud.setText(text, color, size);
} else {
hud = new HudText(this, text, x, y);
hud.setText(text, color, size);
guiText.put(key, hud);
app.getGuiNode().attachChild(hud.getNode());
}
}
public void rename(String name, String newName) {
Spatial data = get(name);
if (data == null) {
error("rename(%s, %s) could not find %s", name, newName, name);
return;
}
data.setName(newName);
}
/**
* use default axis
*
* @param object
* @param degrees
*/
public void rotate(String object, float degrees) {
// TODO Auto-generated method stub
}
public void rotateOnAxis(String name, String axis, double degrees) {
Jme3Msg msg = new Jme3Msg();
msg.method = "rotateOnAxis";
msg.data = new Object[] { name, axis, (float) degrees };
addMsg(msg);
}
public void rotateTo(String name, double degrees) {
Jme3Msg msg = new Jme3Msg();
msg.method = "rotateTo";
msg.data = new Object[] { name, degrees };
addMsg(msg);
}
public boolean saveSpatial(String name) {
Spatial spatial = get(name);
return saveSpatial(spatial, spatial.getName());
}
public boolean saveSpatial(Spatial spatial) {
return saveSpatial(spatial, null);
}
// FIXME - fix name - because it can save a Geometry too
public boolean saveSpatial(Spatial spatial, String filename) {
try {
if (spatial == null) {
error("cannot save null spatial");
return false;
}
String name = spatial.getName();
if (filename == null) {
filename = name + ".j3o";
}
filename = FileIO.cleanFileName(filename);
BinaryExporter exporter = BinaryExporter.getInstance();
FileOutputStream out = new FileOutputStream(filename);
exporter.save(spatial, out);
out.close();
/*
* worthless...
*
* out = new FileOutputStream(name + ".xml"); XMLExporter xmlExporter =
* XMLExporter.getInstance(); xmlExporter.save(spatial, out); out.close();
*/
return true;
} catch (Exception e) {
log.error("exporter.save threw", e);
}
return false;
}
public boolean saveNodes() {
return saveSpatial(rootNode, null);
}
// this just saves keys !!!
public void saveKeys(Spatial toSave) {
try {
String filename = FileIO.cleanFileName(toSave.getName()) + ".txt";
TreeMap<String, UserData> tree = new TreeMap<String, UserData>();
buildTree(tree, "", toSave, false, true);
// String ret = CodecUtils.toJson(tree);
FileOutputStream fos = new FileOutputStream(filename);
for (String key : tree.keySet()) {
String type = (tree.get(key) != null && tree.get(key).getSpatial() != null && tree.get(key).getSpatial() instanceof Node) ? " (Node)" : " (Geometry)";
fos.write(String.format("%s\n", key + type).getBytes());
}
fos.close();
} catch (Exception e) {
error(e);
}
}
// FIXME - base64 encoding of j3o file - "all in one file" gltf instead ???
public boolean saveToJson(String jsonPath) {
try {
String json = CodecUtils.toJson(buildTree());
FileIO.toFile(jsonPath, json.getBytes());
return true;
} catch (Exception e) {
error(e);
}
return false;
}
// TODO - need to make thread safe ? JME thread ?
// turn it into a jme msg - put it on the update queue ?
public void scale(String name, float scale) {
UserData node = getUserData(name);
if (node != null) {
node.scale(scale);
// node.thatupdateModelBounds()
} else {
error("scale %s does not exist", name);
}
}
public void setDisplayFps(boolean b) {
app.setDisplayFps(b);
}
public void setDisplayStatView(boolean b) {
app.setDisplayStatView(b);
}
public void setFontColor(String color) {
fontColor = color;
}
public void setFontSize(int size) {
fontSize = size;
}
public Mapper setMapper(String name, int minx, int maxx, int miny, int maxy) {
UserData node = getUserData(name);
if (node == null) {
error("setMapper %s does not exist", name);
return null;
}
node.mapper = new Mapper(minx, maxx, miny, maxy);
return node.mapper;
}
public void setRotation(String name, String rotation) {
UserData o = getUserData(name);
if (o == null) {
error("setRotation %s could not be found", name);
return;
}
o.rotationMask = util.getUnitVector(rotation);
}
public void setSelected(Spatial newSelected) {
// turn off old
if (selectedForView != null) {
enableBoundingBox(selectedForView, false);
enableCoordinateAxes(selectedForView, false);
}
// set selected
selectedForView = newSelected;
// display in menu
menu.putText(newSelected);
// turn on new
if (newSelected != null) {
enableBoundingBox(newSelected, true);
enableCoordinateAxes(newSelected, true);
}
}
public void setVisible(boolean b) {
if (selectedForView != null) {
if (b) {
selectedForView.setCullHint(Spatial.CullHint.Inherit);
} else {
selectedForView.setCullHint(Spatial.CullHint.Always);
}
}
}
public void simpleInitApp() {
stateManager = app.getStateManager();
// GuiGlobals.initialize(app);
// Load the 'glass' style
// BaseStyles.loadGlassStyle();
// Set 'glass' as the default style when not specified
// GuiGlobals.getInstance().getStyles().setDefaultStyle("glass");
setDisplayFps(false);
setDisplayStatView(false);
// guiNode = app.getGuiNode();
// wtf - assetManager == null - another race condition ?!?!?
// after start - these are initialized as "default"
assetManager = app.getAssetManager();
inputManager = app.getInputManager();
// stateManager.attach(state);
// app = jme.getApp();
guiNode = app.getGuiNode();
// Initialize the globals access so that the default
// components can find what they need.
GuiGlobals.initialize(app);
// Load the 'glass' style
BaseStyles.loadGlassStyle();
// Set 'glass' as the default style when not specified
GuiGlobals.getInstance().getStyles().setDefaultStyle("glass");
// disable flycam we are going to use our
// own camera
flyCam = app.getFlyByCamera();
if (flyCam != null) {
flyCam.setEnabled(false);
}
cameraSettings = app.getCamera();
rootNode = app.getRootNode();
rootNode.setName("root");
rootNode.attachChild(camera);
viewPort = app.getViewPort();
// Setting the direction to Spatial to camera, this means the camera will
// copy the movements of the Node
camNode = new CameraNode("cam", cameraSettings);
camNode.setControlDir(ControlDirection.SpatialToCamera);
// camNode.setControlDir(ControlDirection.CameraToSpatial);
// rootNode.attachChild(camNode);
// camNode.attachChild(child)
// camera.setLocation(new Vector3f(0, 1, -1));
// camNode.setLocalTranslation(-1, 1, -1);
// camNode.setLocalTranslation(new Vector3f(1f, 1f, 1f));
// camera.setLocalTranslation(-1, 1, -1);
camera.attachChild(camNode);
// camera.move(0, 1, 2);
// camera.lookAt(rootNode.getLocalTranslation(), Vector3f.UNIT_Y);
// camNode.lookAt(rootNode.getLocalTranslation(), Vector3f.UNIT_Y);
// rootNode.attachChild(camNode);
// rootNode.attachChild(cam);
// personNode.attachChild(camNode);
// Screen screen = nifty.getCurrentScreen();
// loadNiftyGui();
// cam.setFrustum(0, 1000, 0, 0, 0, 0);
// cam.setFrustumNear(1.0f);
inputManager.setCursorVisible(true);
// camNode.setLocalTranslation(0, 0, 2f);
// camera.setLocation(new Vector3f(0f, 0f, 2f));
// cam.setLocation(new Vector3f(0f, 0f, 0f));
// cam.setLocation(new Vector3f(0f, 0f, 900f));
// cam.setLocation(new Vector3f(0f, 0f, 12f));
// cam.setClipPlan);
new File(getDataDir()).mkdirs();
new File(getResourceDir()).mkdirs();
assetManager.registerLocator("./", FileLocator.class);
assetManager.registerLocator(getDataDir(), FileLocator.class);
assetManager.registerLocator(assetsDir, FileLocator.class);
assetManager.registerLocator(getResourceDir(), FileLocator.class);
// FIXME - should be moved under ./data/JMonkeyEngine/
assetManager.registerLocator("InMoov/jm3/assets", FileLocator.class);
assetManager.registerLoader(BlenderLoader.class, "blend");
/**
* <pre>
* Physics related bulletAppState = new BulletAppState();
* bulletAppState.setEnabled(true); stateManager.attach(bulletAppState);
* PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager,
* bulletAppState.getPhysicsSpace()); bulletAppState.setDebugEnabled(true);
*/
// what inputs will jme service handle ?
/**
* <pre>
* LEFT A and left arrow
* RIGHT D and right arrow
* UP W and up arrow
* DOWN S and down arrow
* ZOOM IN J
* ZOOM OUT K
* </pre>
*/
// wheelmouse zoom (check)
// alt+ctrl+lmb - zoom <br>
// alt+lmb - rotate<br>
// alt+shft+lmb - pan
// rotate around selection -
// https://www.youtube.com/watch?v=IVZPm9HAMD4&feature=youtu.be
// wrap text of breadcrumbs
// draggable - resize for menu - what you set is how it stays
// when menu active - inputs(hotkey when non-menu) should be deactive
inputManager.addMapping("mouse-click-left", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
inputManager.addListener(this, "mouse-click-left");
inputManager.addMapping("mouse-click-right", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
inputManager.addListener(this, "mouse-click-right");
inputManager.addMapping("mouse-wheel-up", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false));
inputManager.addListener(analog, "mouse-wheel-up");
inputManager.addMapping("mouse-wheel-down", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true));
inputManager.addListener(analog, "mouse-wheel-down");
inputManager.addMapping("mouse-axis-x", new MouseAxisTrigger(MouseInput.AXIS_X, true));
inputManager.addListener(analog, "mouse-axis-x");
inputManager.addMapping("mouse-axis-x-negative", new MouseAxisTrigger(MouseInput.AXIS_X, false));
inputManager.addListener(analog, "mouse-axis-x-negative");
inputManager.addMapping("mouse-axis-y", new MouseAxisTrigger(MouseInput.AXIS_Y, true));
inputManager.addListener(analog, "mouse-axis-y");
inputManager.addMapping("mouse-axis-y-negative", new MouseAxisTrigger(MouseInput.AXIS_Y, false));
inputManager.addListener(analog, "mouse-axis-y-negative");
inputManager.addMapping("select-root", new KeyTrigger(KeyInput.KEY_R));
inputManager.addListener(this, "select-root");
inputManager.addMapping("camera", new KeyTrigger(KeyInput.KEY_C));
inputManager.addListener(this, "camera");
inputManager.addMapping("menu", new KeyTrigger(KeyInput.KEY_M));
inputManager.addListener(this, "menu");
inputManager.addMapping("full-screen", new KeyTrigger(KeyInput.KEY_F));
inputManager.addListener(this, "full-screen");
inputManager.addMapping("exit-full-screen", new KeyTrigger(KeyInput.KEY_G));
inputManager.addListener(this, "exit-full-screen");
inputManager.addMapping("cycle", new KeyTrigger(KeyInput.KEY_TAB));
inputManager.addListener(this, "cycle");
inputManager.addMapping("shift-left", new KeyTrigger(KeyInput.KEY_LSHIFT));
inputManager.addListener(this, "shift-left");
inputManager.addMapping("ctrl-left", new KeyTrigger(KeyInput.KEY_LCONTROL));
inputManager.addListener(this, "ctrl-left");
inputManager.addMapping("alt-left", new KeyTrigger(KeyInput.KEY_LMENU));
inputManager.addListener(this, "alt-left");
// inputManager.addMapping("mouse-left", new
// KeyTrigger(MouseInput.BUTTON_LEFT));
// inputManager.addListener(this, "mouse-left");
inputManager.addMapping("export", new KeyTrigger(KeyInput.KEY_E));
inputManager.addListener(this, "export");
viewPort.setBackgroundColor(ColorRGBA.Gray);
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f));
rootNode.addLight(sun);
// AmbientLight sun = new AmbientLight();
rootNode.addLight(sun);
// rootNode.scale(.5f);
// rootNode.setLocalTranslation(0, -200, 0);
rootNode.setLocalTranslation(0, 0, 0);
menu = app.getMainMenu();// new MainMenuState(this);
// menu.loadGui();
// load models in the default directory
loadModels();
}
public void simpleUpdate(float tpf) {
// start the clock on how much time we will take
startUpdateTs = System.currentTimeMillis();
for (HudText hudTxt : guiText.values()) {
hudTxt.update();
}
while (jmeMsgQueue.size() > 0) {
Jme3Msg msg = null;
try {
// TODO - support relative & absolute moves
msg = jmeMsgQueue.remove();
util.invoke(msg);
} catch (Exception e) {
log.error("simpleUpdate failed for {} - targetName", msg, e);
}
}
deltaMs = System.currentTimeMillis() - startUpdateTs;
sleepMs = 33 - deltaMs;
if (sleepMs < 0) {
sleepMs = 0;
}
sleep(sleepMs);
}
// FIXME - Possible to have a "default" simple servo app - with default
// service script
public SimpleApplication start() {
return start(defaultAppType, defaultAppType);
}
// dynamic create of type... TODO fix name start --> create
synchronized public SimpleApplication start(String appName, String appType) {
if (app == null) {
// create app
if (!appType.contains(".")) {
appType = String.format("org.myrobotlab.jme3.%s", appType);
}
Jme3App newApp = (Jme3App) Instantiator.getNewInstance(appType, this);
if (newApp == null) {
error("could not instantiate simple application %s", appType);
return null;
}
app = newApp;
// start it with "default" settings
settings = new AppSettings(true);
settings.setResolution(width, height);
// settings.setEmulateMouse(false);
// settings.setUseJoysticks(false);
settings.setUseInput(true);
settings.setAudioRenderer(null);
app.setSettings(settings);
app.setShowSettings(false); // resolution bps etc dialog
app.setPauseOnLostFocus(false);
// the all important "start" - anyone goofing around with the engine
// before this is done will
// will generate error from jmonkey - this should "block"
app.start();
Callable<String> callable = new Callable<String>() {
public String call() throws Exception {
System.out.println("Asynchronous Callable");
return "Callable Result";
}
};
Future<String> future = app.enqueue(callable);
try {
future.get();
} catch (Exception e) {
log.warn("future threw", e);
}
return app;
}
info("already started app %s", appType);
return app;
}
public void startService() {
super.startService();
// start the jmonkey app - if you want a diferent Jme3App
// config should be set at before this time
start();
// notify me if new services are created
subscribe(Runtime.getRuntimeName(), "registered");
if (autoAttach) {
List<ServiceInterface> services = Runtime.getServices();
for (ServiceInterface si : services) {
try {
attach(si);
} catch (Exception e) {
error(e);
}
}
}
}
// FIXME - requirements for "re-start" is everything correctly de-initialized
// ?
public void stop() {
if (app != null) {
// why ?
app.getRootNode().detachAllChildren();
app.getGuiNode().detachAllChildren();
app.stop();
// app.destroy(); not for "us"
app = null;
}
}
@Override
public void stopService() {
super.stopService();
try {
stop();
} catch (Exception e) {
log.error("releasing jme3 app threw", e);
}
}
public void toggleVisible() {
if (Spatial.CullHint.Always == selectedForView.getCullHint()) {
setVisible(true);
} else {
setVisible(false);
}
}
public String toJson(Node node) {
// get absolute position info
return CodecUtils.toJson(node);
// save it out
}
public void lookAt(String viewer, String viewee) {
Jme3Msg msg = new Jme3Msg();
msg.method = "lookAt";
msg.data = new Object[] { viewer, viewee };
addMsg(msg);
}
public List<Spatial> search(String text) {
return search(text, null, null, null);
}
public List<Spatial> search(String text, Node beginNode, Boolean exactMatch, Boolean includeGeometries) {
if (beginNode == null) {
beginNode = rootNode;
}
if (exactMatch == null) {
exactMatch = false;
}
if (includeGeometries == null) {
includeGeometries = true;
}
Search search = new Search(text, exactMatch, includeGeometries);
beginNode.breadthFirstTraversal(search);
return search.getResults();
}
public static void main(String[] args) {
try {
LoggingFactory.init("info");
Runtime.start("gui", "SwingGui");
JMonkeyEngine jme = (JMonkeyEngine) Runtime.start("jme", "JMonkeyEngine");
InMoovHead i01_head = (InMoovHead) Runtime.start("i01.head", "InMoovHead");
// InMoov i01 = (InMoov)Runtime.start("i01", "InMoov");
// i01.startHead("XX");
jme.enableGrid(true);
jme.addBox("floor.box.01", 1.0f, 1.0f, 1.0f, "cccccc", true);
jme.moveTo("floor.box.01", 3, 0, 0);
// camera.move(0, 1, 2);
// jme.rename("i01.head.rollneck", "i01.head.rollNeck");
jme.setRotation("i01.head.rollNeck", "z");
jme.setRotation("i01.head.neck", "x");
jme.moveTo("camera", 0, 1, 4);
jme.lookAt("camera", "i01");
jme.rotateOnAxis("camera", "x", -40);
jme.setMapper("i01.head.neck", 0, 180, -90, 90);
jme.setMapper("i01.head.rollNeck", 0, 180, -90, 90);
jme.setMapper("i01.head.rothead", 0, 180, -90, 90);
Spatial spatial = jme.get("floor.box.01");
log.info("spatial {}", spatial);
Servo servo = (Servo) Runtime.start("i01.head.jaw", "Servo");
jme.setRotation("i01.head.jaw", "x");
Service.sleep(2000);
jme.cameraLookAtRoot();
jme.scale("i01", 0.25f);
jme.save();
boolean test = true;
if (test) {
return;
}
} catch (Exception e) {
log.error("main threw", e);
}
}
public void cameraLookAtRoot() {
cameraLookAt(rootNode);
}
public void enableGrid(boolean b) {
Spatial s = get("floor-grid");
if (s == null) {
addGrid("floor-grid");
s = get("floor-grid");
}
if (b) {
s.setCullHint(CullHint.Never);
} else {
s.setCullHint(CullHint.Always);
}
}
} | src/main/java/org/myrobotlab/service/JMonkeyEngine.java | package org.myrobotlab.service;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.FloatBuffer;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import org.myrobotlab.codec.CodecUtils;
import org.myrobotlab.cv.CvData;
import org.myrobotlab.framework.Instantiator;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.jme3.AnalogHandler;
import org.myrobotlab.jme3.HudText;
import org.myrobotlab.jme3.Jme3App;
import org.myrobotlab.jme3.Jme3Msg;
import org.myrobotlab.jme3.Jme3ServoController;
import org.myrobotlab.jme3.Jme3Util;
import org.myrobotlab.jme3.MainMenuState;
import org.myrobotlab.jme3.Search;
import org.myrobotlab.jme3.UserData;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.math.Mapper;
import org.myrobotlab.math.geometry.Point3df;
import org.myrobotlab.math.geometry.PointCloud;
import org.myrobotlab.service.abstracts.AbstractComputerVision;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.virtual.VirtualMotor;
import org.slf4j.Logger;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.AssetManager;
import com.jme3.asset.plugins.FileLocator;
import com.jme3.bullet.BulletAppState;
// import com.jme3.bullet.animation.DynamicAnimControl;
import com.jme3.collision.CollisionResults;
import com.jme3.export.binary.BinaryExporter;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.input.FlyByCamera;
import com.jme3.input.InputManager;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.AnalogListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseAxisTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.material.RenderState.FaceCullMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Ray;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.renderer.ViewPort;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.CameraNode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.Spatial.CullHint;
import com.jme3.scene.control.BillboardControl;
import com.jme3.scene.control.CameraControl.ControlDirection;
import com.jme3.scene.debug.Grid;
import com.jme3.scene.plugins.blender.BlenderLoader;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Quad;
import com.jme3.system.AppSettings;
import com.jme3.util.BufferUtils;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.lemur.style.BaseStyles;
/**
* A simulator built on JMonkey 3 Engine.
*
* @author GroG, calamity, kwatters, moz4r and many others ...
*
*/
public class JMonkeyEngine extends Service implements ActionListener {
public final static Logger log = LoggerFactory.getLogger(JMonkeyEngine.class);
private static final long serialVersionUID = 1L;
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(JMonkeyEngine.class.getCanonicalName());
meta.addDescription("is a 3d game engine, used for simulators");
meta.setAvailable(true); // false if you do not want it viewable in a gui
// TODO: extract version numbers like this into a constant/enum
String jmeVersion = "3.2.2-stable";
meta.addDependency("org.jmonkeyengine", "jme3-core", jmeVersion);
meta.addDependency("org.jmonkeyengine", "jme3-desktop", jmeVersion);
meta.addDependency("org.jmonkeyengine", "jme3-lwjgl", jmeVersion);
meta.addDependency("org.jmonkeyengine", "jme3-jogg", jmeVersion);
// meta.addDependency("org.jmonkeyengine", "jme3-test-data", jmeVersion);
meta.addDependency("com.simsilica", "lemur", "1.11.0");
meta.addDependency("com.simsilica", "lemur-proto", "1.10.0");
// meta.addDependency("org.jmonkeyengine", "jme3-bullet", jmeVersion);
// meta.addDependency("org.jmonkeyengine", "jme3-bullet-native",
// jmeVersion);
// meta.addDependency("jme3utilities", "Minie", "0.6.2");
// "new" physics - ik forward kinematics ...
// not really supposed to use blender models - export to j3o
meta.addDependency("org.jmonkeyengine", "jme3-blender", jmeVersion);
// jbullet ==> org="net.sf.sociaal" name="jME3-jbullet" rev="3.0.0.20130526"
// audio dependencies
meta.addDependency("de.jarnbjo", "j-ogg-all", "1.0.0");
meta.addCategory("simulator");
return meta;
}
boolean altLeftPressed = false;
transient AnalogListener analog = null;
transient Jme3App app;
transient AssetManager assetManager;
String assetsDir = getDataDir() + File.separator + "assets";
boolean autoAttach = true;
boolean autoAttachAll = true;
transient BulletAppState bulletAppState;
transient Node camera = new Node("camera");
transient Vector3f cameraDirection = new Vector3f();
transient Camera cameraSettings;
transient CameraNode camNode;
boolean ctrlLeftPressed = false;
boolean mouseLeftPressed = false;
String defaultAppType = "Jme3App";
long deltaMs;
transient DisplayMode displayMode = null;
transient FlyByCamera flyCam;
String fontColor = "#66ff66"; // green
int fontSize = 14;
boolean fullscreen = false;
transient Node guiNode;
transient Map<String, HudText> guiText = new TreeMap<>();
int height = 768;
transient AtomicInteger id = new AtomicInteger();
transient InputManager inputManager;
protected Queue<Jme3Msg> jmeMsgQueue = new ConcurrentLinkedQueue<Jme3Msg>();
final public String KEY_SEPERATOR = "/";
transient DisplayMode lastDisplayMode = null;
transient MainMenuState menu;
String modelsDir = assetsDir + File.separator + "Models";
final Map<String, String> nameMappings = new TreeMap<String, String>();
transient Map<String, Spatial> nodesx = new TreeMap<String, Spatial>();
// https://stackoverflow.com/questions/16861727/jmonkey-engine-3-0-drawing-points
FloatBuffer pointCloudBuffer = null;
transient Material pointCloudMat = null;
transient Mesh pointCloudMesh = new Mesh();
transient Node rootNode;
transient Spatial selected = null;
int selectIndex = 0;
transient Jme3ServoController servoController;
transient AppSettings settings;
boolean shiftLeftPressed = false;
long sleepMs;
long startUpdateTs;
transient AppStateManager stateManager;
transient Jme3Util util;
transient ViewPort viewPort;
int width = 1024;
public JMonkeyEngine(String n) {
super(n);
File d = new File(modelsDir);
d.mkdirs();
util = new Jme3Util(this);
analog = new AnalogHandler(this);
servoController = new Jme3ServoController(this);
}
public void addBox(String boxName) {
addBox(boxName, 1f, 1f, 1f); // room box
}
public void addBox(String boxName, float width, float depth, float height) {
addBox(boxName, width, depth, height, null, null);
moveTo(boxName, 0f, height, 0f); // center it on the floor fully above the
// ground
}
// FIXME make method "without" name to be added to the _system_box node ..
public void addBox(String name, Float width, Float depth, Float height, String color, Boolean fill) {
Node boxNode = null;
Spatial check = get(name);
if (check != null && check instanceof Geometry) {
log.error("addBox - scene graph already has {} and it is a Geometry", check);
return;
} else if (check != null && check instanceof Node) {
boxNode = (Node) check;
} else {
boxNode = new Node(name);
}
if (width == null) {
width = 1f;
}
if (depth == null) {
depth = 1f;
}
if (height == null) {
height = 1f;
}
Box box = new Box(width, depth, height); // 1 meter square
// wireCube.setMode(Mesh.Mode.LineLoop);
// box.setMode(Mesh.Mode.Lines);
// FIXME - geom & matterial always xxx-geometry ? & xxx-material ??
Geometry geom = new Geometry(String.format("%s._geometry", name), box);
Material mat1 = null;
if (fill == null || fill.equals(false)) {
// mat1 = new Material(assetManager,
// "Common/MatDefs/Light/Lighting.j3md");
mat1 = new Material(assetManager, "Common/MatDefs/Light/PBRLighting.j3md");
box.setMode(Mesh.Mode.Lines);
} else {
mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat1.setColor("Color", Jme3Util.toColor(color));
}
// mat1 = new Material(assetManager, "Common/MatDefs/Light/Deferred.j3md");
// mat1.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Front);
geom.setMaterial(mat1);
boxNode.attachChild(geom);
// FIXME - optimize rootNode/geom/nodes & jme3Node !
// UserData o = new UserData(this, boxNode);
// nodes.put(name, o);
rootNode.attachChild(boxNode);
moveTo(name, 0.0f, 0.5f * height, 0.0f);
// index(boxNode);
}
public void addGrid(String name) {
addGrid(name, new Vector3f(0, 0, 0), 40, "CCCCCC");
}
public void addGrid(String name, Vector3f pos, int size, String color) {
Spatial s = get(name);
if (s != null) {
log.warn("addGrid {} already exists");
return;
}
Geometry g = new Geometry("wireframe grid", new Grid(size, size, 1.0f));
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.getAdditionalRenderState().setWireframe(true);
mat.setColor("Color", Jme3Util.toColor(color));
g.setMaterial(mat);
g.center().move(pos);
Node n = new Node(name);
n.attachChild(g);
rootNode.attachChild(n);
}
public void addMsg(Jme3Msg msg) {
jmeMsgQueue.add(msg);
}
public void attach(Attachable service) throws Exception {
app.attach(service);
// Cv Publisher ..
if (service instanceof AbstractComputerVision) {
AbstractComputerVision cv = (AbstractComputerVision) service;
subscribe(service.getName(), "publishCvData");
}
if (service instanceof ServoControl) {
servoController.attach(service);
}
// backward attach ?
}
public void attachChild(Spatial node) {
rootNode.attachChild(node);
}
/**
* binds two objects together ...
*
* @param child
* @param parent
*/
public void bind(String child, String parent) {
Jme3Msg msg = new Jme3Msg();
msg.method = "bind";
msg.data = new Object[] { child, parent };
addMsg(msg);
}
public Map<String, UserData> buildTree() {
TreeMap<String, UserData> tree = new TreeMap<String, UserData>();
return buildTree(tree, "", rootNode, false, false);
}
/**
* The buildTree method creates a data structure for quick access and indexing
* of nodes - it can build it in two different ways - one which uses full
* depth for an access key useDepth=true and another that is a flat model.
* Both can have collisions. When the parents of nodes change, the depth model
* "should" change to reflect the changes in branches. The flat model does not
* need to change, but has a higher likelyhood of collisions.
*
* @param tree
* @param path
* @param spatial
* @param useDepthKeys
* @return
*/
public Map<String, UserData> buildTree(Map<String, UserData> tree, String path, Spatial spatial, boolean includeGeometries, boolean useDepthKeys) {
if (useDepthKeys) {
path = path + KEY_SEPERATOR + spatial.getName();
} else {
path = spatial.getName();
}
if (tree.containsKey(path)) {
UserData s = tree.get(path);
log.error("buildTree collision {}", path);
}
// only interested in nodes, since nodes "can" have user data...
// Geometries cannot or (should not?)
if (!includeGeometries && (spatial instanceof Geometry)) {
return tree;
}
// putting both nodes & geometries on the tree
tree.put(path, spatial.getUserData("data"));
if (spatial instanceof Node) {
List<Spatial> children = ((Node) spatial).getChildren();
for (int i = 0; i < children.size(); ++i) {
buildTree(tree, path, children.get(i), includeGeometries, useDepthKeys);
}
}
return tree;
}
public void clone(String name, String newName) {
}
public Geometry createBoundingBox(Spatial spatial) {
return util.createBoundingBox(spatial);
}
public Node createUnitAxis() {
return util.createUnitAxis();
}
public VirtualMotor createVirtualMotor(String name) {
// TODO Auto-generated method stub
return null;
}
/**
* cycles through children at same level
*/
public void cycle() {
if (selected == null) {
Spatial s = rootNode.getChild(0);
setSelected(s);
}
Node parent = selected.getParent();
if (parent == null) {
return;
}
List<Spatial> siblings = parent.getChildren();
if (shiftLeftPressed) {
--selectIndex;
} else {
++selectIndex;
}
if (selectIndex > siblings.size() - 1) {
selectIndex = 0;
} else if (selectIndex < 0) {
selectIndex = siblings.size() - 1;
}
setSelected(siblings.get(selectIndex));
}
public void enableBoundingBox(Spatial spatial, boolean b) {
Node node = getNode(spatial);
UserData data = getUserData(node);
data.enableBoundingBox(b);
}
public void enableBoundingBox(String name, boolean b) {
UserData o = getUserData(name);
enableBoundingBox(o.getSpatial(), b);
}
// FIXME !!!! enableCoodinateAxes - same s bb including parent if geometry
public void enableCoordinateAxes(Spatial spatial, boolean b) {
Node node = getNode(spatial);
UserData data = getUserData(node);
data.enableCoordinateAxes(b);
}
public void enableFlyCam(boolean b) {
flyCam.setEnabled(b);
}
public void enableFullScreen(boolean fullscreen) {
this.fullscreen = fullscreen;
if (fullscreen) {
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
displayMode = device.getDisplayMode();
// DisplayMode[] modes = device.getDisplayModes(); list of possible diplay
// modes
// remember last display mode
displayMode = device.getDisplayMode();
settings = app.getContext().getSettings();
log.info("settings {}", settings);
settings.setTitle(getName());
settings.setResolution(displayMode.getWidth(), displayMode.getHeight());
settings.setFrequency(displayMode.getRefreshRate());
settings.setBitsPerPixel(displayMode.getBitDepth());
// settings.setFullscreen(device.isFullScreenSupported());
settings.setFullscreen(fullscreen);
app.setSettings(settings);
app.restart();
// app.restart(); // restart the context to apply changes
} else {
settings = app.getContext().getSettings();
log.info("settings {}", settings);
/*
* settings.setFrequency(displayMode.getRefreshRate());
* settings.setBitsPerPixel(displayMode.getBitDepth());
*/
settings.setFullscreen(fullscreen);
settings.setResolution(width, height);
app.setSettings(settings);
app.restart();
}
}
public String format(Node node, Integer selected) {
StringBuilder sb = new StringBuilder();
List<Spatial> children = node.getChildren();
sb.append("[");
for (int i = 0; i < children.size(); ++i) {
if (i != 0) {
sb.append(", ");
}
sb.append(node.getChild(i).getName());
}
sb.append("]");
return sb.toString();
}
public Spatial get(String name) {
return get(name, null);
}
/**
* the all purpose get by name method
*
* @param string
* @return
*/
public Spatial get(String name, Node startNode) {
if (startNode == null) {
startNode = rootNode;
}
Spatial child = startNode.getChild(name);
if (child == null) {
error("get(%s) could not find child");
}
return child;
}
public Jme3App getApp() {
return app;
}
public AssetManager getAssetManager() {
return assetManager;
}
private String getExt(String name) {
int pos = name.lastIndexOf(".");
String ext = null;
if (pos != -1) {
ext = name.substring(pos + 1).toLowerCase();
}
return ext;
}
public Geometry getGeometry(String name) {
return getGeometry(name, null);
}
public Geometry getGeometry(String name, Node startNode) {
Spatial spatial = get(name, startNode);
if (spatial instanceof Geometry) {
return (Geometry) spatial;
} else {
log.error("could not find Geometry {}", name);
return null;
}
}
public Queue<Jme3Msg> getjmeMsgQueue() {
return jmeMsgQueue;
}
public String getKeyPath(Spatial spatial) {
if (spatial == null) {
return null;
}
StringBuilder sb = new StringBuilder(spatial.getName());
Node p = spatial.getParent();
while (p != null) {
sb.insert(0, String.format("%s%s", p.getName(), KEY_SEPERATOR));
p = p.getParent();
}
return sb.toString();
}
private String getNameNoExt(String name) {
int pos = name.lastIndexOf(".");
String nameNoExt = name;
if (pos != -1) {
nameNoExt = name.substring(0, pos);
}
return nameNoExt;
}
public Node getNode(Spatial spatial) {
if (spatial instanceof Geometry) {
return spatial.getParent();
}
return (Node) spatial;
}
public Node getNode(String name) {
return getNode(name, null);
}
public Node getNode(String name, Node startNode) {
Spatial spatial = get(name, startNode);
if (spatial instanceof Node) {
return (Node) spatial;
} else {
log.error("could not find Node {}", name);
return null;
}
}
public Spatial getRootChild(Spatial spatial) {
if (spatial == null) {
log.error("spatial is null");
return null;
}
Spatial c = spatial;
Spatial p = c.getParent();
if (spatial == rootNode) {
return null;
}
while (p != null && p != rootNode) {
c = p;
p = c.getParent();
}
if (p != null) {
return c;
}
return spatial;
}
public Node getRootNode() {
return rootNode;
}
public Spatial getSelected() {
return selected;
}
public AppSettings getSettings() {
return settings;
}
public Spatial getTopNode(Spatial spatial) {
if (spatial == null) {
return null;
}
Spatial top = spatial;
while (top.getParent() != null) {
top = top.getParent();
}
return top;
}
// TODO - possibly Geometries
// Unique Naming and map/index
public UserData getUserData(Node node) {
UserData data = node.getUserData("data");
if (data == null) {
data = new UserData(this, node);
// FIXME - add map/index
// getAncestorKey(x) + rootKey if its not root = key
}
return data;
}
/**
* The workhorse - where everyone "searches" for the user data they need. It
* works agains a flat or depth key'd tree. If the node is found but the user
* data has not been created, it creates it and assigns the references... if
* the node cannot be found, it returns null
*
* @param path
* - full path for a depth tree, name for a flat map
* @return
*/
public UserData getUserData(String path /* , boolean useDepth */) {
if (nameMappings.containsKey(path)) {
path = nameMappings.get(path);
}
Spatial spatial = get(path);
if (spatial == null) {
error("geteUserData %s cannot be found", path);
return null;
}
if (spatial instanceof Geometry) {
error("geteUserData %s found but is Geometry not Node", path);
return null;
}
UserData userData = spatial.getUserData("data");
if (userData == null) {
userData = new UserData(this, spatial);
}
return userData;
}
public void initPointCloud(PointCloud pc) {
Point3df[] points = pc.getData();
Vector3f[] lineVerticies = new Vector3f[points.length];
for (int i = 0; i < points.length; ++i) {
Point3df p = points[i];
lineVerticies[i] = new Vector3f(p.x, p.y, p.z);
}
pointCloudBuffer = BufferUtils.createFloatBuffer(lineVerticies);
// pointCloudMesh.setMode(Mesh.Mode.TriangleFan);
pointCloudMesh.setMode(Mesh.Mode.Points);
// pointCloudMesh.setMode(Mesh.Mode.Lines);
// pointCloudMesh.setMode(Mesh.Mode.Triangles);
// https://hub.jmonkeyengine.org/t/how-to-render-a-3d-point-cloud/27341/11
pointCloudMesh.setBuffer(VertexBuffer.Type.Position, 3, pointCloudBuffer);
pointCloudMesh.setBuffer(VertexBuffer.Type.Color, 4, pc.getColors());
pointCloudMesh.updateBound();
pointCloudMesh.updateCounts();
// pointCloudMesh.setPointSize(0.0003);
Geometry geo = new Geometry("line", pointCloudMesh);
pointCloudMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
// pointCloudMat = new Material(assetManager,
// "Common/MatDefs/Misc/Particle.j3md");
pointCloudMat.setColor("Color", ColorRGBA.Green);
pointCloudMat.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Off);
// pointCloudMat.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Front);
pointCloudMat.setBoolean("VertexColor", false); // important for points !!
// pointCloudMat.setBoolean("VertexColor", false); // important for points
// !!
geo.setMaterial(pointCloudMat);
rootNode.attachChild(geo);
}
// FIXME - more parameters - location & rotation (new function "move")
// FIXME - scale should not be in this - scale as one of 3 methods rotate !!!!
// translate
// TODO - must be re-entrant - perhaps even on a schedule ?
// TODO - removeNode
public void load(String inFileName) {
log.info("load({})", inFileName);
// UserData o = null;
try {
if (inFileName == null) {
error("file name cannot be null");
return;
}
File file = getFile(inFileName);
if (!file.exists()) {
error(String.format("file %s does not exits", inFileName));
return;
}
String filename = file.getName();
String ext = getExt(filename);
String simpleName = getNameNoExt(filename);
if (!ext.equals("json")) {
Spatial spatial = assetManager.loadModel(filename);
spatial.setName(simpleName);
Node node = null;
if (spatial instanceof Node) {
node = (Node) spatial;
} else {
node = new Node(spatial.getName());
node.attachChild(spatial);
}
rootNode.attachChild(node);
} else {
// now for the json meta data ....
/*
* String json = FileIO.toString(inFileName); Map<String, Object> list =
* CodecUtils.fromJson(json, nodes.getClass()); for (String name :
* list.keySet()) { String nodePart = CodecUtils.toJson(list.get(name));
* UserData node = CodecUtils.fromJson(nodePart, UserData.class); //
* get/create transient parts //
* node.setService(Runtime.getService(name)); // node.setJme(this); //
* putN // nodes.put(node.getName(), node); }
*/
}
} catch (Exception e) {
error(e);
}
}
public Spatial loadModel(String assetPath) {
return assetManager.loadModel(assetPath);
}
public void loadModels() {
// load the root data dir
loadModels(modelsDir);
loadNodes(modelsDir);
}
public void loadModels(String dirPath) {
File dir = new File(dirPath);
if (!dir.isDirectory()) {
error("%s is not a directory", dirPath);
return;
}
assetManager.registerLocator(dirPath, FileLocator.class);
// get list of files in dir ..
File[] files = dir.listFiles();
// scan for all non json files first ...
// initially set them invisible ...
for (File f : files) {
if (!f.isDirectory() && !"json".equals(getExt(f.getName()))) {
load(f.getAbsolutePath());
}
}
// process structure json files ..
// breadth first search ...
for (File f : files) {
if (f.isDirectory()) {
loadModels(f.getAbsolutePath());
}
}
}
/**
* load a node with all potential children
*
* @param parentDirPath
*/
public void loadNode(String parentDirPath) {
File parentFile = new File(parentDirPath);
if (!parentFile.isDirectory()) {
// parent is not a directory ...
// we are done here ..
return;
}
String parentName = parentFile.getName();
File[] files = parentFile.listFiles();
// depth first search - process all children first
// to build the tree
for (File f : files) {
if (f.isDirectory()) {
loadNode(f.getAbsolutePath());
}
}
Node parentNode = getNode(parentName);
// parent is a dir - we have processed our children - now we process
// the parent "if" we don't already have a reference to a node with the same
// name
if (parentNode == null) {
putNode(parentName);
parentNode = putNode(parentName);
for (File f : files) {
String childname = getNameNoExt(f.getName());
if (getNode(childname) == null) {
log.error("loadNode {} can not attach child to {} not found in nodes", parentDirPath, childname);
} else {
parentNode.attachChild(getNode(childname));
}
}
} else {
// FIXME - it "may" already contain the parent name - but also "may" not
// have all sub-children attached
// possibly implement - attaching children
}
// index(parentNode);
// saveNodes();
}
/**
* based on a directory structure - add missing nodes and bindings top node
* will be bound to root
*
* @param dirPath
*/
public void loadNodes(String dirPath) {
File dir = new File(dirPath);
if (!dir.isDirectory()) {
error("%s is not a directory", dirPath);
return;
}
// get list of files in dir ..
File[] files = dir.listFiles();
// scan for all non json files first ...
// initially set them invisible ...
for (File f : files) {
if (f.isDirectory()) {
loadNode(f.getAbsolutePath());
}
}
}
public void cameraLookAt(String name) {
Spatial s = get(name);
if (s == null) {
log.error("cameraLookAt - cannot find {}", name);
return;
}
cameraLookAt(s);
}
public void cameraLookAt(Spatial spatial) {
camera.lookAt(spatial.getWorldTranslation(), Vector3f.UNIT_Y);
}
// relative move
// favor the xy plane because we are not birds ?
public void move(String name, float x, float y) {
// must "get z"
// move(name, x, y, null);
}
public void moveTo(String name, float x, float y, float z) {
Jme3Msg msg = new Jme3Msg();
msg.method = "moveTo";
msg.data = new Object[] { name, x, y, z };
addMsg(msg);
}
@Override
public void onAction(String name, boolean keyPressed, float tpf) {
log.info("onAction {} {} {}", name, keyPressed, tpf);
if (name.equals("mouse-click-left") && !mouseLeftPressed) {
Geometry target = checkCollision();
setSelected(target);
}
if ("full-screen".equals(name)) {
enableFullScreen(true);
} else if ("menu".equals(name)) {
menu.setEnabled(true);
} else if ("select-root".equals(name)) {
setSelected(rootNode);
} else if ("camera".equals(name)) {
setSelected("camera");
} else if ("exit-full-screen".equals(name)) {
enableFullScreen(false);
} else if ("cycle".equals(name) && keyPressed) {
cycle();
} else if (name.equals("shift-left")) {
shiftLeftPressed = keyPressed;
} else if (name.equals("ctrl-left")) {
ctrlLeftPressed = keyPressed;
} else if (name.equals("alt-left")) {
altLeftPressed = keyPressed;
} else if ("export".equals(name) && keyPressed) {
saveSpatial(selected.getName());
} else if ("mouse-click-left".equals(name)) {
mouseLeftPressed = keyPressed;
} else {
warn("%s - key %b %f not found", name, keyPressed, tpf);
}
}
public void setSelected(String name) {
Spatial s = get(name);
if (s == null) {
log.error("setSelected {} is null", name);
return;
}
setSelected(s);
}
/**
* onAnalog
*
* @param name
* @param keyPressed
* @param tpf
*/
public void onAnalog(String name, float keyPressed, float tpf) {
log.info("onAnalog [{} {} {}]", name, keyPressed, tpf);
if (selected == null) {
selected = camera;// FIXME "new" selectedMove vs selected
}
// wheelmouse zoom (done)
// alt+ctrl+lmb - zoom <br> (done)
// alt+lmb - rotate<br> (done)
// alt+shft+lmb - pan (done)
// rotate around selection -
// https://www.youtube.com/watch?v=IVZPm9HAMD4&feature=youtu.be
// wrap text of breadcrumbs
// draggable - resize for menu - what you set is how it stays
// when menu active - inputs(hotkey when non-menu) should be deactive
log.info("{}", keyPressed);
// ROTATE
if (mouseLeftPressed && !altLeftPressed) {
if (name.equals("mouse-axis-x")) {
selected.rotate(0, -keyPressed, 0);
} else if (name.equals("mouse-axis-x-negative")) {
selected.rotate(0, keyPressed, 0);
} else if (name.equals("mouse-axis-y")) {
selected.rotate(-keyPressed, 0, 0);
} else if (name.equals("mouse-axis-y-negative")) {
selected.rotate(keyPressed, 0, 0);
}
}
// PAN
if (mouseLeftPressed && altLeftPressed && shiftLeftPressed) {
if (name.equals("mouse-axis-x")) {
selected.move(keyPressed*3, 0, 0);
} else if (name.equals("mouse-axis-x-negative")) {
selected.move(-keyPressed*3, 0, 0);
} else if (name.equals("mouse-axis-y")) {
selected.move(0, keyPressed*3, 0);
} else if (name.equals("mouse-axis-y-negative")) {
selected.move(0, -keyPressed*3, 0);
}
}
// ZOOM
if (mouseLeftPressed && altLeftPressed && ctrlLeftPressed) {
if (name.equals("mouse-axis-y")) {
selected.move(0, 0, keyPressed*10);
} else if (name.equals("mouse-axis-y-negative")) {
selected.move(0, 0, -keyPressed*10);
}
}
if (name.equals("mouse-wheel-up") || name.equals("forward")) {
// selected.setLocalScale(selected.getLocalScale().mult(1.0f));
selected.move(0, 0, keyPressed * -1);
} else if (name.equals("mouse-wheel-down") || name.equals("backward")) {
// selected.setLocalScale(selected.getLocalScale().mult(1.0f));
selected.move(0, 0, keyPressed * 1);
} else if (name.equals("up")) {
if (ctrlLeftPressed) {
selected.move(0, 0, keyPressed * 1);
} else {
selected.move(0, keyPressed * 1, 0);
}
} else if (name.equals("down")) {
if (ctrlLeftPressed) {
selected.move(0, 0, keyPressed * -1);
} else {
selected.move(0, -keyPressed * 1, 0);
}
} else if (name.equals("left")) {
if (ctrlLeftPressed) {
selected.rotate(0, -keyPressed, 0);
} else {
selected.move(-keyPressed * 1, 0, 0);
}
} else if (name.equals("right")) {
if (ctrlLeftPressed) {
selected.rotate(0, keyPressed, 0);
} else {
selected.move(keyPressed * 1, 0, 0);
}
}
}
// FIXME make a more general Collision check..
public Geometry checkCollision() {
// Reset results list.
CollisionResults results = new CollisionResults();
// Convert screen click to 3d position
Vector2f click2d = inputManager.getCursorPosition();
Vector3f click3d = cameraSettings.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone();
Vector3f dir = cameraSettings.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 1f).subtractLocal(click3d).normalizeLocal();
// Aim the ray from the clicked spot forwards.
Ray ray = new Ray(click3d, dir);
// Collect intersections between ray and all nodes in results list.
rootNode.collideWith(ray, results);
// (Print the results so we see what is going on:)
for (int i = 0; i < results.size(); i++) {
// (For each “hit”, we know distance, impact point, geometry.)
float dist = results.getCollision(i).getDistance();
Vector3f pt = results.getCollision(i).getContactPoint();
String target = results.getCollision(i).getGeometry().getName();
System.out.println("Selection #" + i + ": " + target + " at " + pt + ", " + dist + " WU away.");
}
// Use the results -- we rotate the selected geometry.
if (results.size() > 0) {
// The closest result is the target that the player picked:
Geometry target = results.getClosestCollision().getGeometry();
// Here comes the action:
log.info("you clicked " + target.getName());
return target;
}
return null;
}
/**
* A method to accept Computer Vision data (from OpenCV or BoofCv) and to
* appropriately delegate it out to more specific methods
*
* @param data
*/
public void onCvData(CvData data) {
onPointCloud(data.getPointCloud());
}
public void onPointCloud(PointCloud pc) {
if (pc == null) {
return;
}
// pointCloudMat.setBoolean("VertexColor", false);
// pointCloudMesh.setPointSize(0.01f);
if (pointCloudBuffer == null) {
initPointCloud(pc);
// addBox("box-1");
}
pointCloudBuffer.rewind();
Point3df[] points = pc.getData();
for (int i = 0; i < points.length; ++i) {
Point3df p = points[i];
// log.info("p {}", p);
// pointCloudBuffer.put(480 - p.y);
// pointCloudBuffer.put(640 - p.x);
pointCloudBuffer.put(p.x);
pointCloudBuffer.put(p.y);
pointCloudBuffer.put(p.z);
// lineVerticies[index] = new Vector3f(480 - p.y, 640 - p.x, p.z);
}
pointCloudMesh.setBuffer(VertexBuffer.Type.Position, 3, pointCloudBuffer);
pointCloudMesh.setBuffer(VertexBuffer.Type.Color, 4, pc.getColors());
}
// auto Register
public void onRegistered(Service service) throws Exception {
// new service - see if we can virtualize it
log.info("{}.onRegistered({})", getName(), service);
if (autoAttach) {
if (autoAttachAll) {
// spin through all apps - attempt to attach
}
attach(service);
}
}
public Node putNode(String name) {
Node check = getNode(name);
if (check != null) {
return check;
}
Node n = new Node(name);
rootNode.attachChild(n);
return n;
}
public void putText(Spatial spatial, int x, int y) {
Vector3f xyz = spatial.getWorldTranslation();
Quaternion q = spatial.getLocalRotation();
float[] angles = new float[3]; // yaw, roll, pitch
q.toAngles(angles);
boolean isNode = (spatial instanceof Node);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s-%s\n", (isNode) ? "node" : "geom", spatial.getName()));
sb.append(String.format("x:%.3f y:%.3f z:%.3f\n", xyz.x, xyz.y, xyz.z));
sb.append(String.format("yaw:%.2f roll:%.2f pitch:%.2f\n", angles[0] * 180 / FastMath.PI, angles[1] * 180 / FastMath.PI, angles[2] * 180 / FastMath.PI));
if (isNode) {
sb.append(format((Node) spatial, 0));
}
putText(sb.toString(), 10, 10);
}
public void putText(String text, int x, int y) {
putText(text, x, y, null, null);
}
// put 2d text into a 3d scene graph
public void putText(String text, int x, int y, int z) {
Node n;
Node n2;
Quad q = new Quad(2, 2);
Geometry g = new Geometry("Quad", q);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", ColorRGBA.Blue);
g.setMaterial(mat);
Quad q2 = new Quad(1, 1);
Geometry g3 = new Geometry("Quad2", q2);
Material mat2 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat2.setColor("Color", ColorRGBA.Yellow);
g3.setMaterial(mat2);
// g3.setLocalTranslation(.5f, .5f, .01f);
// Box b = new Box(.25f, .5f, .25f);
Box b = new Box(1.0f, 1.0f, 1.0f);
Geometry g2 = new Geometry("Box", b);
// g2.setLocalTranslation(0, 0, 3);
g2.setMaterial(mat);
BitmapFont font = assetManager.loadFont("Common/Default.fnt");
BitmapText bmText = new BitmapText(font, false);
bmText.setSize(30);
bmText.setText("Billboard Data");
bmText.setQueueBucket(Bucket.Transparent);
bmText.setColor(ColorRGBA.White);
Node bb = new Node("billboard");
BillboardControl control = new BillboardControl();
control.setAlignment(BillboardControl.Alignment.Screen);
bb.addControl(control);
bb.attachChild(bmText);
bb.attachChild(g);
bb.attachChild(g3);
n = new Node("parent");
n.attachChild(g2);
n.attachChild(bb);
rootNode.attachChild(n);
n2 = new Node("parentParent");
n2.setLocalTranslation(Vector3f.UNIT_X.mult(5));
n2.attachChild(n);
rootNode.attachChild(n2);
}
public void putText(String text, int x, int y, String color) {
putText(text, x, y, color, null);
}
/**
* put text on the guiNode HUD display for jmonkey FIXME - do the same logic
* in OpenCV overlay !
*
* @param text
* @param x
* @param y
*/
public void putText(String text, int x, int y, String color, Integer size) {
HudText hud = null;
if (color == null) {
color = fontColor;
}
if (size == null) {
size = fontSize;
}
String key = String.format("%d-%d", x, y);
if (guiText.containsKey(key)) {
hud = guiText.get(key);
hud.setText(text, color, size);
} else {
hud = new HudText(this, text, x, y);
hud.setText(text, color, size);
guiText.put(key, hud);
app.getGuiNode().attachChild(hud.getNode());
}
}
public void rename(String name, String newName) {
Spatial data = get(name);
if (data == null) {
error("rename(%s, %s) could not find %s", name, newName, name);
return;
}
data.setName(newName);
}
/**
* use default axis
*
* @param object
* @param degrees
*/
public void rotate(String object, float degrees) {
// TODO Auto-generated method stub
}
public void rotateOnAxis(String name, String axis, double degrees) {
Jme3Msg msg = new Jme3Msg();
msg.method = "rotateOnAxis";
msg.data = new Object[] { name, axis, (float) degrees };
addMsg(msg);
}
public void rotateTo(String name, double degrees) {
Jme3Msg msg = new Jme3Msg();
msg.method = "rotateTo";
msg.data = new Object[] { name, degrees };
addMsg(msg);
}
public boolean saveSpatial(String name) {
Spatial spatial = get(name);
return saveSpatial(spatial, spatial.getName());
}
public boolean saveSpatial(Spatial spatial) {
return saveSpatial(spatial, null);
}
// FIXME - fix name - because it can save a Geometry too
public boolean saveSpatial(Spatial spatial, String filename) {
try {
if (spatial == null) {
error("cannot save null spatial");
return false;
}
String name = spatial.getName();
if (filename == null) {
filename = name + ".j3o";
}
filename = FileIO.cleanFileName(filename);
BinaryExporter exporter = BinaryExporter.getInstance();
FileOutputStream out = new FileOutputStream(filename);
exporter.save(spatial, out);
out.close();
/*
* worthless...
*
* out = new FileOutputStream(name + ".xml"); XMLExporter xmlExporter =
* XMLExporter.getInstance(); xmlExporter.save(spatial, out); out.close();
*/
return true;
} catch (Exception e) {
log.error("exporter.save threw", e);
}
return false;
}
public boolean saveNodes() {
return saveSpatial(rootNode, null);
}
// this just saves keys !!!
public void saveKeys(Spatial toSave) {
try {
String filename = FileIO.cleanFileName(toSave.getName()) + ".txt";
TreeMap<String, UserData> tree = new TreeMap<String, UserData>();
buildTree(tree, "", toSave, false, true);
// String ret = CodecUtils.toJson(tree);
FileOutputStream fos = new FileOutputStream(filename);
for (String key : tree.keySet()) {
String type = (tree.get(key) != null && tree.get(key).getSpatial() != null && tree.get(key).getSpatial() instanceof Node) ? " (Node)" : " (Geometry)";
fos.write(String.format("%s\n", key + type).getBytes());
}
fos.close();
} catch (Exception e) {
error(e);
}
}
// FIXME - base64 encoding of j3o file - "all in one file" gltf instead ???
public boolean saveToJson(String jsonPath) {
try {
String json = CodecUtils.toJson(buildTree());
FileIO.toFile(jsonPath, json.getBytes());
return true;
} catch (Exception e) {
error(e);
}
return false;
}
// TODO - need to make thread safe ? JME thread ?
// turn it into a jme msg - put it on the update queue ?
public void scale(String name, float scale) {
UserData node = getUserData(name);
if (node != null) {
node.scale(scale);
// node.thatupdateModelBounds()
} else {
error("scale %s does not exist", name);
}
}
public void setDisplayFps(boolean b) {
app.setDisplayFps(b);
}
public void setDisplayStatView(boolean b) {
app.setDisplayStatView(b);
}
public void setFontColor(String color) {
fontColor = color;
}
public void setFontSize(int size) {
fontSize = size;
}
public Mapper setMapper(String name, int minx, int maxx, int miny, int maxy) {
UserData node = getUserData(name);
if (node == null) {
error("setMapper %s does not exist", name);
return null;
}
node.mapper = new Mapper(minx, maxx, miny, maxy);
return node.mapper;
}
public void setRotation(String name, String rotation) {
UserData o = getUserData(name);
if (o == null) {
error("setRotation %s could not be found", name);
return;
}
o.rotationMask = util.getUnitVector(rotation);
}
public void setSelected(Spatial newSelected) {
// turn off old
if (selected != null) {
enableBoundingBox(selected, false);
enableCoordinateAxes(selected, false);
}
// set selected
selected = newSelected;
// display in menu
menu.putText(newSelected);
// turn on new
if (newSelected != null) {
enableBoundingBox(newSelected, true);
enableCoordinateAxes(newSelected, true);
}
}
public void setVisible(boolean b) {
if (selected != null) {
if (b) {
selected.setCullHint(Spatial.CullHint.Inherit);
} else {
selected.setCullHint(Spatial.CullHint.Always);
}
}
}
public void simpleInitApp() {
stateManager = app.getStateManager();
// GuiGlobals.initialize(app);
// Load the 'glass' style
// BaseStyles.loadGlassStyle();
// Set 'glass' as the default style when not specified
// GuiGlobals.getInstance().getStyles().setDefaultStyle("glass");
setDisplayFps(false);
setDisplayStatView(false);
// guiNode = app.getGuiNode();
// wtf - assetManager == null - another race condition ?!?!?
// after start - these are initialized as "default"
assetManager = app.getAssetManager();
inputManager = app.getInputManager();
// stateManager.attach(state);
// app = jme.getApp();
guiNode = app.getGuiNode();
// Initialize the globals access so that the default
// components can find what they need.
GuiGlobals.initialize(app);
// Load the 'glass' style
BaseStyles.loadGlassStyle();
// Set 'glass' as the default style when not specified
GuiGlobals.getInstance().getStyles().setDefaultStyle("glass");
// disable flycam we are going to use our
// own camera
flyCam = app.getFlyByCamera();
if (flyCam != null) {
flyCam.setEnabled(false);
}
cameraSettings = app.getCamera();
rootNode = app.getRootNode();
rootNode.setName("root");
rootNode.attachChild(camera);
viewPort = app.getViewPort();
// Setting the direction to Spatial to camera, this means the camera will
// copy the movements of the Node
camNode = new CameraNode("cam", cameraSettings);
camNode.setControlDir(ControlDirection.SpatialToCamera);
// camNode.setControlDir(ControlDirection.CameraToSpatial);
// rootNode.attachChild(camNode);
// camNode.attachChild(child)
// camera.setLocation(new Vector3f(0, 1, -1));
// camNode.setLocalTranslation(-1, 1, -1);
// camNode.setLocalTranslation(new Vector3f(1f, 1f, 1f));
// camera.setLocalTranslation(-1, 1, -1);
camera.attachChild(camNode);
// camera.move(0, 1, 2);
// camera.lookAt(rootNode.getLocalTranslation(), Vector3f.UNIT_Y);
// camNode.lookAt(rootNode.getLocalTranslation(), Vector3f.UNIT_Y);
// rootNode.attachChild(camNode);
// rootNode.attachChild(cam);
// personNode.attachChild(camNode);
// Screen screen = nifty.getCurrentScreen();
// loadNiftyGui();
// cam.setFrustum(0, 1000, 0, 0, 0, 0);
// cam.setFrustumNear(1.0f);
inputManager.setCursorVisible(true);
// camNode.setLocalTranslation(0, 0, 2f);
// camera.setLocation(new Vector3f(0f, 0f, 2f));
// cam.setLocation(new Vector3f(0f, 0f, 0f));
// cam.setLocation(new Vector3f(0f, 0f, 900f));
// cam.setLocation(new Vector3f(0f, 0f, 12f));
// cam.setClipPlan);
new File(getDataDir()).mkdirs();
new File(getResourceDir()).mkdirs();
assetManager.registerLocator("./", FileLocator.class);
assetManager.registerLocator(getDataDir(), FileLocator.class);
assetManager.registerLocator(assetsDir, FileLocator.class);
assetManager.registerLocator(getResourceDir(), FileLocator.class);
// FIXME - should be moved under ./data/JMonkeyEngine/
assetManager.registerLocator("InMoov/jm3/assets", FileLocator.class);
assetManager.registerLoader(BlenderLoader.class, "blend");
/**
* <pre>
* Physics related bulletAppState = new BulletAppState();
* bulletAppState.setEnabled(true); stateManager.attach(bulletAppState);
* PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager,
* bulletAppState.getPhysicsSpace()); bulletAppState.setDebugEnabled(true);
*/
// what inputs will jme service handle ?
/**
* <pre>
* LEFT A and left arrow
* RIGHT D and right arrow
* UP W and up arrow
* DOWN S and down arrow
* ZOOM IN J
* ZOOM OUT K
* </pre>
*/
// wheelmouse zoom (check)
// alt+ctrl+lmb - zoom <br>
// alt+lmb - rotate<br>
// alt+shft+lmb - pan
// rotate around selection -
// https://www.youtube.com/watch?v=IVZPm9HAMD4&feature=youtu.be
// wrap text of breadcrumbs
// draggable - resize for menu - what you set is how it stays
// when menu active - inputs(hotkey when non-menu) should be deactive
inputManager.addMapping("mouse-click-left", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
inputManager.addListener(this, "mouse-click-left");
inputManager.addMapping("mouse-click-right", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
inputManager.addListener(this, "mouse-click-right");
inputManager.addMapping("mouse-wheel-up", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false));
inputManager.addListener(analog, "mouse-wheel-up");
inputManager.addMapping("mouse-wheel-down", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true));
inputManager.addListener(analog, "mouse-wheel-down");
inputManager.addMapping("mouse-axis-x", new MouseAxisTrigger(MouseInput.AXIS_X, true));
inputManager.addListener(analog, "mouse-axis-x");
inputManager.addMapping("mouse-axis-x-negative", new MouseAxisTrigger(MouseInput.AXIS_X, false));
inputManager.addListener(analog, "mouse-axis-x-negative");
inputManager.addMapping("mouse-axis-y", new MouseAxisTrigger(MouseInput.AXIS_Y, true));
inputManager.addListener(analog, "mouse-axis-y");
inputManager.addMapping("mouse-axis-y-negative", new MouseAxisTrigger(MouseInput.AXIS_Y, false));
inputManager.addListener(analog, "mouse-axis-y-negative");
inputManager.addMapping("select-root", new KeyTrigger(KeyInput.KEY_R));
inputManager.addListener(this, "select-root");
inputManager.addMapping("camera", new KeyTrigger(KeyInput.KEY_C));
inputManager.addListener(this, "camera");
inputManager.addMapping("menu", new KeyTrigger(KeyInput.KEY_M));
inputManager.addListener(this, "menu");
inputManager.addMapping("full-screen", new KeyTrigger(KeyInput.KEY_F));
inputManager.addListener(this, "full-screen");
inputManager.addMapping("exit-full-screen", new KeyTrigger(KeyInput.KEY_G));
inputManager.addListener(this, "exit-full-screen");
inputManager.addMapping("cycle", new KeyTrigger(KeyInput.KEY_TAB));
inputManager.addListener(this, "cycle");
inputManager.addMapping("shift-left", new KeyTrigger(KeyInput.KEY_LSHIFT));
inputManager.addListener(this, "shift-left");
inputManager.addMapping("ctrl-left", new KeyTrigger(KeyInput.KEY_LCONTROL));
inputManager.addListener(this, "ctrl-left");
inputManager.addMapping("alt-left", new KeyTrigger(KeyInput.KEY_LMENU));
inputManager.addListener(this, "alt-left");
// inputManager.addMapping("mouse-left", new
// KeyTrigger(MouseInput.BUTTON_LEFT));
// inputManager.addListener(this, "mouse-left");
inputManager.addMapping("export", new KeyTrigger(KeyInput.KEY_E));
inputManager.addListener(this, "export");
viewPort.setBackgroundColor(ColorRGBA.Gray);
DirectionalLight sun = new DirectionalLight();
sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f));
rootNode.addLight(sun);
// AmbientLight sun = new AmbientLight();
rootNode.addLight(sun);
// rootNode.scale(.5f);
// rootNode.setLocalTranslation(0, -200, 0);
rootNode.setLocalTranslation(0, 0, 0);
menu = app.getMainMenu();// new MainMenuState(this);
// menu.loadGui();
// load models in the default directory
loadModels();
}
public void simpleUpdate(float tpf) {
// start the clock on how much time we will take
startUpdateTs = System.currentTimeMillis();
for (HudText hudTxt : guiText.values()) {
hudTxt.update();
}
while (jmeMsgQueue.size() > 0) {
Jme3Msg msg = null;
try {
// TODO - support relative & absolute moves
msg = jmeMsgQueue.remove();
util.invoke(msg);
} catch (Exception e) {
log.error("simpleUpdate failed for {} - targetName", msg, e);
}
}
deltaMs = System.currentTimeMillis() - startUpdateTs;
sleepMs = 33 - deltaMs;
if (sleepMs < 0) {
sleepMs = 0;
}
sleep(sleepMs);
}
// FIXME - Possible to have a "default" simple servo app - with default
// service script
public SimpleApplication start() {
return start(defaultAppType, defaultAppType);
}
// dynamic create of type... TODO fix name start --> create
synchronized public SimpleApplication start(String appName, String appType) {
if (app == null) {
// create app
if (!appType.contains(".")) {
appType = String.format("org.myrobotlab.jme3.%s", appType);
}
Jme3App newApp = (Jme3App) Instantiator.getNewInstance(appType, this);
if (newApp == null) {
error("could not instantiate simple application %s", appType);
return null;
}
app = newApp;
// start it with "default" settings
settings = new AppSettings(true);
settings.setResolution(width, height);
// settings.setEmulateMouse(false);
// settings.setUseJoysticks(false);
settings.setUseInput(true);
settings.setAudioRenderer(null);
app.setSettings(settings);
app.setShowSettings(false); // resolution bps etc dialog
app.setPauseOnLostFocus(false);
// the all important "start" - anyone goofing around with the engine
// before this is done will
// will generate error from jmonkey - this should "block"
app.start();
Callable<String> callable = new Callable<String>() {
public String call() throws Exception {
System.out.println("Asynchronous Callable");
return "Callable Result";
}
};
Future<String> future = app.enqueue(callable);
try {
future.get();
} catch (Exception e) {
log.warn("future threw", e);
}
return app;
}
info("already started app %s", appType);
return app;
}
public void startService() {
super.startService();
// start the jmonkey app - if you want a diferent Jme3App
// config should be set at before this time
start();
// notify me if new services are created
subscribe(Runtime.getRuntimeName(), "registered");
if (autoAttach) {
List<ServiceInterface> services = Runtime.getServices();
for (ServiceInterface si : services) {
try {
attach(si);
} catch (Exception e) {
error(e);
}
}
}
}
// FIXME - requirements for "re-start" is everything correctly de-initialized
// ?
public void stop() {
if (app != null) {
// why ?
app.getRootNode().detachAllChildren();
app.getGuiNode().detachAllChildren();
app.stop();
// app.destroy(); not for "us"
app = null;
}
}
@Override
public void stopService() {
super.stopService();
try {
stop();
} catch (Exception e) {
log.error("releasing jme3 app threw", e);
}
}
public void toggleVisible() {
if (Spatial.CullHint.Always == selected.getCullHint()) {
setVisible(true);
} else {
setVisible(false);
}
}
public String toJson(Node node) {
// get absolute position info
return CodecUtils.toJson(node);
// save it out
}
public void lookAt(String viewer, String viewee) {
Jme3Msg msg = new Jme3Msg();
msg.method = "lookAt";
msg.data = new Object[] { viewer, viewee };
addMsg(msg);
}
public List<Spatial> search(String text) {
return search(text, null, null, null);
}
public List<Spatial> search(String text, Node beginNode, Boolean exactMatch, Boolean includeGeometries) {
if (beginNode == null) {
beginNode = rootNode;
}
if (exactMatch == null) {
exactMatch = false;
}
if (includeGeometries == null) {
includeGeometries = true;
}
Search search = new Search(text, exactMatch, includeGeometries);
beginNode.breadthFirstTraversal(search);
return search.getResults();
}
public static void main(String[] args) {
try {
LoggingFactory.init("info");
Runtime.start("gui", "SwingGui");
JMonkeyEngine jme = (JMonkeyEngine) Runtime.start("jme", "JMonkeyEngine");
InMoovHead i01_head = (InMoovHead) Runtime.start("i01.head", "InMoovHead");
// InMoov i01 = (InMoov)Runtime.start("i01", "InMoov");
// i01.startHead("XX");
jme.enableGrid(true);
jme.addBox("floor.box.01", 1.0f, 1.0f, 1.0f, "cccccc", true);
jme.moveTo("floor.box.01", 3, 0, 0);
// camera.move(0, 1, 2);
// jme.rename("i01.head.rollneck", "i01.head.rollNeck");
jme.setRotation("i01.head.rollNeck", "z");
jme.setRotation("i01.head.neck", "x");
jme.moveTo("camera", 0, 1, 4);
jme.lookAt("camera", "i01");
jme.rotateOnAxis("camera", "x", -40);
jme.setMapper("i01.head.neck", 0, 180, -90, 90);
jme.setMapper("i01.head.rollNeck", 0, 180, -90, 90);
jme.setMapper("i01.head.rothead", 0, 180, -90, 90);
Spatial spatial = jme.get("floor.box.01");
log.info("spatial {}", spatial);
Servo servo = (Servo) Runtime.start("i01.head.jaw", "Servo");
jme.setRotation("i01.head.jaw", "x");
Service.sleep(2000);
jme.cameraLookAtRoot();
jme.scale("i01", 0.25f);
jme.save();
boolean test = true;
if (test) {
return;
}
} catch (Exception e) {
log.error("main threw", e);
}
}
public void cameraLookAtRoot() {
cameraLookAt(rootNode);
}
public void enableGrid(boolean b) {
Spatial s = get("floor-grid");
if (s == null) {
addGrid("floor-grid");
s = get("floor-grid");
}
if (b) {
s.setCullHint(CullHint.Never);
} else {
s.setCullHint(CullHint.Always);
}
}
} | blender control update | src/main/java/org/myrobotlab/service/JMonkeyEngine.java | blender control update |
|
Java | apache-2.0 | 40630cc7897fcf556e7587aef98a8ed1524ba093 | 0 | NLeSC/DifferentialEvolution | /*
* Copyrighted 2012-2013 Netherlands eScience Center.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* For details, see the LICENCE.txt file location in the root directory of this
* distribution or obtain the Apache License at the following location:
* 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.
*
* For the full license, see: LICENCE.txt (located in the root folder of this distribution).
* ---
*/
package nl.esciencecenter.diffevo.likelihoodfunctions;
import java.util.Random;
public class LikelihoodFunctionLinearDynamicModel implements LikelihoodFunction {
private static double[] initialState = {30};
private static double[] priorTimes = {
125.5,126.0,126.5,127.0,127.5,
128.0,128.5,129.0,129.5,130.0,
130.5,131.0,131.5,132.0,132.5,
133.0,133.5,134.0,134.5,135.0,
135.5,136.0,136.5,137.0,137.5,
138.0,138.5,139.0,139.5,140.0,
140.5,141.0,141.5,142.0,142.5,
143.0,143.5,144.0,144.5,145.0,
145.5,146.0,146.5,147.0,147.5,
148.0,148.5,149.0,149.5};
private static double[] forcings = {
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,Double.NaN};
private static double[] observedTrue = {
30.000000,29.899600,29.799500,29.699800,29.600400,
29.501300,29.402600,29.304200,29.206100,29.108400,
29.011000,28.913900,28.817100,28.720600,28.624500,
28.528700,28.433200,28.338100,28.243200,28.148700,
28.054500,27.960600,27.867000,27.773800,27.680800,
27.588200,27.495900,27.403800,27.312100,27.220700,
27.129600,27.038800,26.948300,26.858100,26.768200,
26.678700,26.589400,26.500400,26.411700,26.323300,
26.235200,26.147400,26.059900,25.972700,25.885700,
25.799100,25.712800,25.626700,25.540900}; // true state values for parameter = 149.39756262040834
private static int nObs = observedTrue.length;
private static double[] observed = new double[nObs];
private Random generator = new Random();
public LikelihoodFunctionLinearDynamicModel(){
for (int iObs=0;iObs<nObs;iObs++){
observed[iObs] = observedTrue[iObs] + generator.nextDouble()*0.005;
}
}
private double calcSumOfSquaredResiduals(double[] observed,double[] simulated){
double sumOfSquaredResiduals = 0.0;
int nObs = observed.length;
for (int iObs = 0;iObs<nObs-1;iObs++){
sumOfSquaredResiduals = sumOfSquaredResiduals + Math.pow(observed[iObs]-simulated[iObs], 2);
}
//System.out.printf("%10.4f\n\n", sumOfSquaredResiduals);
return sumOfSquaredResiduals;
}
private double[] calcModelPrediction(double[] initialState, double[] parameterVector, double[] forcings, double[] priorTimes){
double[] simulated = new double[nObs];
double[] state = new double[1];
int nPriors = priorTimes.length;
int iPrior = 0;
double resistance = parameterVector[0];
//double time;
double timeStep;
double flow;
state[0] = initialState[0];
simulated[iPrior] = initialState[0];
//System.out.printf("%10.4f\n", parameterVector[0]);
for (;iPrior<nPriors-1;iPrior++){
//time = priorTimes[iPrior];
timeStep = priorTimes[iPrior+1]-priorTimes[iPrior];
flow = -state[0]/resistance;
//System.out.printf("%10.4f %10.4f %10.4f\n", time,state[0],flow);
state[0] = state[0] + flow * timeStep;
simulated[iPrior+1] = state[0];
}
//time = priorTimes[iPrior];
//flow = -state[0]/resistance;
//System.out.printf("%10.4f %10.4f %10.4f\n", time,state[0],Double.NaN);
return simulated;
}
public String getName(){
return LikelihoodFunctionLinearDynamicModel.class.getSimpleName();
}
@Override
public double evaluate(double[][] obs, double[][] sim) {
// TODO Auto-generated method stub
return 0;
}
@Override
public double evaluate(double[] parameterVector) {
// TODO Auto-generated method stub
double[] simulated = calcModelPrediction(initialState,parameterVector,forcings,priorTimes);
double sumOfSquaredResiduals = calcSumOfSquaredResiduals(observed,simulated);
double objScore = -(1.0/2)*nObs*Math.log(sumOfSquaredResiduals);
return objScore;
}
}
| src/nl/esciencecenter/diffevo/likelihoodfunctions/LikelihoodFunctionLinearDynamicModel.java | /*
* Copyrighted 2012-2013 Netherlands eScience Center.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* For details, see the LICENCE.txt file location in the root directory of this
* distribution or obtain the Apache License at the following location:
* 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.
*
* For the full license, see: LICENCE.txt (located in the root folder of this distribution).
* ---
*/
package nl.esciencecenter.diffevo.likelihoodfunctions;
import java.util.Random;
public class LikelihoodFunctionLinearDynamicModel implements LikelihoodFunction {
private static double[] initialState = {30};
private static double[] priorTimes = {
125.5,126.0,126.5,127.0,127.5,
128.0,128.5,129.0,129.5,130.0,
130.5,131.0,131.5,132.0,132.5,
133.0,133.5,134.0,134.5,135.0,
135.5,136.0,136.5,137.0,137.5,
138.0,138.5,139.0,139.5,140.0,
140.5,141.0,141.5,142.0,142.5,
143.0,143.5,144.0,144.5,145.0,
145.5,146.0,146.5,147.0,147.5,
148.0,148.5,149.0,149.5};
private static double[] forcings = {
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,Double.NaN};
private static double[] observedTrue = {
30.000000,29.899600,29.799500,29.699800,29.600400,
29.501300,29.402600,29.304200,29.206100,29.108400,
29.011000,28.913900,28.817100,28.720600,28.624500,
28.528700,28.433200,28.338100,28.243200,28.148700,
28.054500,27.960600,27.867000,27.773800,27.680800,
27.588200,27.495900,27.403800,27.312100,27.220700,
27.129600,27.038800,26.948300,26.858100,26.768200,
26.678700,26.589400,26.500400,26.411700,26.323300,
26.235200,26.147400,26.059900,25.972700,25.885700,
25.799100,25.712800,25.626700,25.540900}; // true state values for parameter = 149.39756262040834
private static int nObs = observedTrue.length;
private static double[] observed = new double[nObs];
private Random generator = new Random();
public LikelihoodFunctionLinearDynamicModel(){
for (int iObs=0;iObs<nObs;iObs++){
observed[iObs] = observedTrue[iObs] + generator.nextDouble()*0.005;
}
}
private double calcSumOfSquaredResiduals(double[] observed,double[] simulated){
double sumOfSquaredResiduals = 0.0;
int nObs = observed.length;
for (int iObs = 0;iObs<nObs-1;iObs++){
sumOfSquaredResiduals = sumOfSquaredResiduals + Math.pow(observed[iObs]-simulated[iObs], 2);
}
//System.out.printf("%10.4f\n\n", sumOfSquaredResiduals);
return sumOfSquaredResiduals;
}
private double[] calcModelPrediction(double[] initialState, double[] parameterVector, double[] forcings, double[] priorTimes){
double[] simulated = new double[nObs];
double[] state = new double[1];
int nPriors = priorTimes.length;
int iPrior = 0;
double resistance = parameterVector[0];
//double time;
double timeStep;
double flow;
state[0] = initialState[0];
simulated[iPrior] = initialState[0];
//System.out.printf("%10.4f\n", parameterVector[0]);
for (;iPrior<nPriors-1;iPrior++){
//time = priorTimes[iPrior];
timeStep = priorTimes[iPrior+1]-priorTimes[iPrior];
flow = -state[0]/resistance;
//System.out.printf("%10.4f %10.4f %10.4f\n", time,state[0],flow);
state[0] = state[0] + flow * timeStep;
simulated[iPrior+1] = state[0];
}
//time = priorTimes[iPrior];
flow = -state[0]/resistance;
//System.out.printf("%10.4f %10.4f %10.4f\n", time,state[0],Double.NaN);
return simulated;
}
public String getName(){
return LikelihoodFunctionLinearDynamicModel.class.getSimpleName();
}
@Override
public double evaluate(double[][] obs, double[][] sim) {
// TODO Auto-generated method stub
return 0;
}
@Override
public double evaluate(double[] parameterVector) {
// TODO Auto-generated method stub
double[] simulated = calcModelPrediction(initialState,parameterVector,forcings,priorTimes);
double sumOfSquaredResiduals = calcSumOfSquaredResiduals(observed,simulated);
double objScore = -(1.0/2)*nObs*Math.log(sumOfSquaredResiduals);
return objScore;
}
}
| fixed sonar issue about dead store to local variable in likelihoodfunctions/LikelihoodFunctionLinearDynamicModel.java
| src/nl/esciencecenter/diffevo/likelihoodfunctions/LikelihoodFunctionLinearDynamicModel.java | fixed sonar issue about dead store to local variable in likelihoodfunctions/LikelihoodFunctionLinearDynamicModel.java |
|
Java | apache-2.0 | 3eceb42feff8f6a290cdf9826e9f4b7a4cef39be | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | package biomodel.gui.sbmlcore;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import main.Gui;
import main.util.MutableBoolean;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Parameter;
import org.sbml.jsbml.SBase;
import org.sbml.jsbml.UnitDefinition;
import org.sbml.jsbml.ext.arrays.ArraysSBasePlugin;
import org.sbml.jsbml.ext.arrays.Index;
import biomodel.annotation.AnnotationUtility;
import biomodel.annotation.SBOLAnnotation;
import biomodel.gui.fba.FBAObjective;
import biomodel.gui.sbol.SBOLField;
import biomodel.gui.schematic.ModelEditor;
import biomodel.parser.BioModel;
import biomodel.util.GlobalConstants;
import biomodel.util.SBMLutilities;
public class ModelPanel extends JButton implements ActionListener, MouseListener {
private static final long serialVersionUID = 1L;
private JTextField modelID; // the model's ID
private JTextField modelName; // the model's Name
private JButton fbaoButton;
private JComboBox substanceUnits, timeUnits, volumeUnits, areaUnits, lengthUnits, extentUnits, conversionFactor;
private JTextField conviIndex;
private SBOLField sbolField;
private BioModel bioModel;
private Model sbmlModel;
private MutableBoolean dirty;
public ModelPanel(BioModel gcm, ModelEditor modelEditor) {
super();
this.bioModel = gcm;
sbolField = new SBOLField(GlobalConstants.SBOL_DNA_COMPONENT, modelEditor, 1, true);
this.sbmlModel = gcm.getSBMLDocument().getModel();
this.dirty = modelEditor.getDirty();
this.setText("Model");
this.setToolTipText("Edit Model Attributes");
this.addActionListener(this);
if (modelEditor.isParamsOnly()) {
this.setEnabled(false);
}
}
/**
* Creates a frame used to edit parameters or create new ones.
*/
private void modelEditor(String option) {
JPanel modelEditorPanel;
modelEditorPanel = new JPanel(new GridLayout(12, 2));
Model model = bioModel.getSBMLDocument().getModel();
modelName = new JTextField(model.getName(), 50);
modelID = new JTextField(model.getId(), 16);
modelName = new JTextField(model.getName(), 40);
JLabel modelIDLabel = new JLabel("Model ID:");
JLabel modelNameLabel = new JLabel("Model Name:");
modelID.setEditable(false);
modelEditorPanel.add(modelIDLabel);
modelEditorPanel.add(modelID);
modelEditorPanel.add(modelNameLabel);
modelEditorPanel.add(modelName);
conviIndex = new JTextField(20);
if (bioModel.getSBMLDocument().getLevel() > 2) {
JLabel substanceUnitsLabel = new JLabel("Substance Units:");
JLabel timeUnitsLabel = new JLabel("Time Units:");
JLabel volumeUnitsLabel = new JLabel("Volume Units:");
JLabel areaUnitsLabel = new JLabel("Area Units:");
JLabel lengthUnitsLabel = new JLabel("Length Units:");
JLabel extentUnitsLabel = new JLabel("Extent Units:");
JLabel conversionFactorLabel = new JLabel("Conversion Factor:");
substanceUnits = new JComboBox();
substanceUnits.addItem("( none )");
timeUnits = new JComboBox();
timeUnits.addItem("( none )");
volumeUnits = new JComboBox();
volumeUnits.addItem("( none )");
areaUnits = new JComboBox();
areaUnits.addItem("( none )");
lengthUnits = new JComboBox();
lengthUnits.addItem("( none )");
extentUnits = new JComboBox();
extentUnits.addItem("( none )");
conversionFactor = new JComboBox();
conversionFactor.addActionListener(this);
conversionFactor.addItem("( none )");
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getUnitDefinitionCount(); i++) {
UnitDefinition unit = bioModel.getSBMLDocument().getModel().getUnitDefinition(i);
if ((unit.getUnitCount() == 1)
&& (unit.getUnit(0).isMole() || unit.getUnit(0).isItem() || unit.getUnit(0).isGram() || unit.getUnit(0).isKilogram())
&& (unit.getUnit(0).getExponent() == 1)) {
substanceUnits.addItem(unit.getId());
extentUnits.addItem(unit.getId());
}
if ((unit.getUnitCount() == 1) && (unit.getUnit(0).isSecond()) && (unit.getUnit(0).getExponent() == 1)) {
timeUnits.addItem(unit.getId());
}
if ((unit.getUnitCount() == 1) && (unit.getUnit(0).isLitre() && unit.getUnit(0).getExponent() == 1)
|| (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 3)) {
volumeUnits.addItem(unit.getId());
}
if ((unit.getUnitCount() == 1) && (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 2)) {
areaUnits.addItem(unit.getId());
}
if ((unit.getUnitCount() == 1) && (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 1)) {
lengthUnits.addItem(unit.getId());
}
}
substanceUnits.addItem("dimensionless");
substanceUnits.addItem("gram");
substanceUnits.addItem("item");
substanceUnits.addItem("kilogram");
substanceUnits.addItem("mole");
timeUnits.addItem("dimensionless");
timeUnits.addItem("second");
volumeUnits.addItem("dimensionless");
volumeUnits.addItem("litre");
areaUnits.addItem("dimensionless");
lengthUnits.addItem("dimensionless");
lengthUnits.addItem("metre");
extentUnits.addItem("dimensionless");
extentUnits.addItem("gram");
extentUnits.addItem("item");
extentUnits.addItem("kilogram");
extentUnits.addItem("mole");
List<URI> sbolURIs = new LinkedList<URI>();
String sbolStrand = AnnotationUtility.parseSBOLAnnotation(sbmlModel, sbolURIs);
sbolField.setSBOLURIs(sbolURIs);
sbolField.setSBOLStrand(sbolStrand);
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getParameterCount(); i++) {
Parameter param = bioModel.getSBMLDocument().getModel().getParameter(i);
if (param.getConstant() && !BioModel.IsDefaultParameter(param.getId())) {
conversionFactor.addItem(param.getId());
}
}
if (option.equals("OK")) {
substanceUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getSubstanceUnits());
timeUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getTimeUnits());
volumeUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getVolumeUnits());
areaUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getAreaUnits());
lengthUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getLengthUnits());
extentUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getExtentUnits());
conversionFactor.setSelectedItem(bioModel.getSBMLDocument().getModel().getConversionFactor());
// TODO: Scott - change for Plugin reading
String freshIndex = "";
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(model);
for(int i = 0; i<sBasePlugin.getIndexCount(); i++){
Index indie = sBasePlugin.getIndex(i);
freshIndex += "[" + SBMLutilities.myFormulaToString(indie.getMath()) + "]";
}
conviIndex.setText(freshIndex);
}
fbaoButton = new JButton("Edit Objectives");
fbaoButton.setActionCommand("fluxObjective");
fbaoButton.addActionListener(this);
modelEditorPanel.add(substanceUnitsLabel);
modelEditorPanel.add(substanceUnits);
modelEditorPanel.add(timeUnitsLabel);
modelEditorPanel.add(timeUnits);
modelEditorPanel.add(volumeUnitsLabel);
modelEditorPanel.add(volumeUnits);
modelEditorPanel.add(areaUnitsLabel);
modelEditorPanel.add(areaUnits);
modelEditorPanel.add(lengthUnitsLabel);
modelEditorPanel.add(lengthUnits);
modelEditorPanel.add(extentUnitsLabel);
modelEditorPanel.add(extentUnits);
modelEditorPanel.add(conversionFactorLabel);
modelEditorPanel.add(conversionFactor);
modelEditorPanel.add(new JLabel("Conversion Factor Indices:"));
modelEditorPanel.add(conviIndex);
modelEditorPanel.add(new JLabel("SBOL DNA Component:"));
modelEditorPanel.add(sbolField);
modelEditorPanel.add(new JLabel("Flux Objective: "));
modelEditorPanel.add(fbaoButton);
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, modelEditorPanel, "Model Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value != JOptionPane.YES_OPTION)
sbolField.resetRemovedBioSimURI();
String[] dex = new String[]{""};
String[] dimensionIds = new String[]{""};
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
if(!error&&!conversionFactor.getSelectedItem().equals("( none )")){
SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), (String)conversionFactor.getSelectedItem());
dex = SBMLutilities.checkIndices(conviIndex.getText(), variable, bioModel.getSBMLDocument(), dimensionIds);
error = (dex==null);
}
// Add SBOL annotation to SBML model itself
if (!error) {
if (sbolField.getSBOLURIs().size() > 0) {
SBOLAnnotation sbolAnnot = new SBOLAnnotation(sbmlModel.getMetaId(), sbolField.getSBOLURIs(),
sbolField.getSBOLStrand());
AnnotationUtility.setSBOLAnnotation(sbmlModel, sbolAnnot);
} else
AnnotationUtility.removeSBOLAnnotation(sbmlModel);
// Deletes iBioSim composite components that have been removed from association panel
// URI deletionURI = sbolField.getDeletionURI();
// if (deletionURI != null)
// for (String filePath : gcmEditor.getGui().getFilePaths(".sbol")) {
// SBOLDocument sbolDoc = SBOLUtility.loadSBOLFile(filePath);
// SBOLUtility.deleteDNAComponent(deletionURI, sbolDoc);
// SBOLUtility.writeSBOLDocument(filePath, sbolDoc);
// }
}
if (!error) {
if (bioModel.getSBMLDocument().getLevel() > 2) {
if (substanceUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetSubstanceUnits();
}
else {
bioModel.getSBMLDocument().getModel().setSubstanceUnits((String) substanceUnits.getSelectedItem());
}
if (timeUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetTimeUnits();
}
else {
bioModel.getSBMLDocument().getModel().setTimeUnits((String) timeUnits.getSelectedItem());
}
if (volumeUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetVolumeUnits();
}
else {
bioModel.getSBMLDocument().getModel().setVolumeUnits((String) volumeUnits.getSelectedItem());
}
if (areaUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetAreaUnits();
}
else {
bioModel.getSBMLDocument().getModel().setAreaUnits((String) areaUnits.getSelectedItem());
}
if (lengthUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetLengthUnits();
}
else {
bioModel.getSBMLDocument().getModel().setLengthUnits((String) lengthUnits.getSelectedItem());
}
if (extentUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetExtentUnits();
}
else {
bioModel.getSBMLDocument().getModel().setExtentUnits((String) extentUnits.getSelectedItem());
}
//TODO indices writing here
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(model);
if (conversionFactor.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetConversionFactor();
sBasePlugin.unsetListOfIndices();
}
else {
bioModel.getSBMLDocument().getModel().setConversionFactor((String) conversionFactor.getSelectedItem());
sBasePlugin.unsetListOfIndices();
for(int i = 0; i<dex.length-1; i++){
Index indexRule = new Index();
indexRule.setArrayDimension(i);
indexRule.setReferencedAttribute("variable");
ASTNode indexMath = SBMLutilities.myParseFormula(dex[i+1].replace("]", "").trim());
indexRule.setMath(indexMath);
sBasePlugin.addIndex(indexRule);
}
}
bioModel.getSBMLDocument().getModel().setName(modelName.getText());
}
dirty.setValue(true);
bioModel.makeUndoPoint();
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, modelEditorPanel, "Model Units Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// if the add unit button is clicked
// if the add function button is clicked
if (e.getSource() == this) {
modelEditor("OK");
} else if (e.getActionCommand().equals("editDescriptors")) {
// if (bioModel.getSBOLDescriptors() != null)
// SBOLDescriptorPanel descriptorPanel = new SBOLDescriptorPanel(sbolField.getSBOLURIs().get(0))
}
else if (e.getActionCommand().equals("fluxObjective")){
FBAObjective fbaObjective = new FBAObjective(bioModel);
fbaObjective.openGui();
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseExited(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseReleased(MouseEvent e) {
}
public SBOLField getSBOLField() {
return sbolField;
}
}
| gui/src/biomodel/gui/sbmlcore/ModelPanel.java | package biomodel.gui.sbmlcore;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import main.Gui;
import main.util.MutableBoolean;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Parameter;
import org.sbml.jsbml.SBase;
import org.sbml.jsbml.UnitDefinition;
import biomodel.annotation.AnnotationUtility;
import biomodel.annotation.SBOLAnnotation;
import biomodel.gui.fba.FBAObjective;
import biomodel.gui.sbol.SBOLField;
import biomodel.gui.schematic.ModelEditor;
import biomodel.parser.BioModel;
import biomodel.util.GlobalConstants;
import biomodel.util.SBMLutilities;
public class ModelPanel extends JButton implements ActionListener, MouseListener {
private static final long serialVersionUID = 1L;
private JTextField modelID; // the model's ID
private JTextField modelName; // the model's Name
private JButton fbaoButton;
private JComboBox substanceUnits, timeUnits, volumeUnits, areaUnits, lengthUnits, extentUnits, conversionFactor;
private JTextField conviIndex, convjIndex;
private SBOLField sbolField;
private BioModel bioModel;
private Model sbmlModel;
private MutableBoolean dirty;
public ModelPanel(BioModel gcm, ModelEditor modelEditor) {
super();
this.bioModel = gcm;
sbolField = new SBOLField(GlobalConstants.SBOL_DNA_COMPONENT, modelEditor, 1, true);
this.sbmlModel = gcm.getSBMLDocument().getModel();
this.dirty = modelEditor.getDirty();
this.setText("Model");
this.setToolTipText("Edit Model Attributes");
this.addActionListener(this);
if (modelEditor.isParamsOnly()) {
this.setEnabled(false);
}
}
/**
* Creates a frame used to edit parameters or create new ones.
*/
private void modelEditor(String option) {
JPanel modelEditorPanel;
modelEditorPanel = new JPanel(new GridLayout(12, 2));
Model model = bioModel.getSBMLDocument().getModel();
modelName = new JTextField(model.getName(), 50);
modelID = new JTextField(model.getId(), 16);
modelName = new JTextField(model.getName(), 40);
JLabel modelIDLabel = new JLabel("Model ID:");
JLabel modelNameLabel = new JLabel("Model Name:");
modelID.setEditable(false);
modelEditorPanel.add(modelIDLabel);
modelEditorPanel.add(modelID);
modelEditorPanel.add(modelNameLabel);
modelEditorPanel.add(modelName);
conviIndex = new JTextField(10);
convjIndex = new JTextField(10);
if (bioModel.getSBMLDocument().getLevel() > 2) {
JLabel substanceUnitsLabel = new JLabel("Substance Units:");
JLabel timeUnitsLabel = new JLabel("Time Units:");
JLabel volumeUnitsLabel = new JLabel("Volume Units:");
JLabel areaUnitsLabel = new JLabel("Area Units:");
JLabel lengthUnitsLabel = new JLabel("Length Units:");
JLabel extentUnitsLabel = new JLabel("Extent Units:");
JLabel conversionFactorLabel = new JLabel("Conversion Factor:");
substanceUnits = new JComboBox();
substanceUnits.addItem("( none )");
timeUnits = new JComboBox();
timeUnits.addItem("( none )");
volumeUnits = new JComboBox();
volumeUnits.addItem("( none )");
areaUnits = new JComboBox();
areaUnits.addItem("( none )");
lengthUnits = new JComboBox();
lengthUnits.addItem("( none )");
extentUnits = new JComboBox();
extentUnits.addItem("( none )");
conversionFactor = new JComboBox();
conversionFactor.addActionListener(this);
conversionFactor.addItem("( none )");
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getUnitDefinitionCount(); i++) {
UnitDefinition unit = bioModel.getSBMLDocument().getModel().getUnitDefinition(i);
if ((unit.getUnitCount() == 1)
&& (unit.getUnit(0).isMole() || unit.getUnit(0).isItem() || unit.getUnit(0).isGram() || unit.getUnit(0).isKilogram())
&& (unit.getUnit(0).getExponent() == 1)) {
substanceUnits.addItem(unit.getId());
extentUnits.addItem(unit.getId());
}
if ((unit.getUnitCount() == 1) && (unit.getUnit(0).isSecond()) && (unit.getUnit(0).getExponent() == 1)) {
timeUnits.addItem(unit.getId());
}
if ((unit.getUnitCount() == 1) && (unit.getUnit(0).isLitre() && unit.getUnit(0).getExponent() == 1)
|| (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 3)) {
volumeUnits.addItem(unit.getId());
}
if ((unit.getUnitCount() == 1) && (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 2)) {
areaUnits.addItem(unit.getId());
}
if ((unit.getUnitCount() == 1) && (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 1)) {
lengthUnits.addItem(unit.getId());
}
}
substanceUnits.addItem("dimensionless");
substanceUnits.addItem("gram");
substanceUnits.addItem("item");
substanceUnits.addItem("kilogram");
substanceUnits.addItem("mole");
timeUnits.addItem("dimensionless");
timeUnits.addItem("second");
volumeUnits.addItem("dimensionless");
volumeUnits.addItem("litre");
areaUnits.addItem("dimensionless");
lengthUnits.addItem("dimensionless");
lengthUnits.addItem("metre");
extentUnits.addItem("dimensionless");
extentUnits.addItem("gram");
extentUnits.addItem("item");
extentUnits.addItem("kilogram");
extentUnits.addItem("mole");
List<URI> sbolURIs = new LinkedList<URI>();
String sbolStrand = AnnotationUtility.parseSBOLAnnotation(sbmlModel, sbolURIs);
sbolField.setSBOLURIs(sbolURIs);
sbolField.setSBOLStrand(sbolStrand);
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getParameterCount(); i++) {
Parameter param = bioModel.getSBMLDocument().getModel().getParameter(i);
if (param.getConstant() && !BioModel.IsDefaultParameter(param.getId())) {
conversionFactor.addItem(param.getId());
}
}
if (option.equals("OK")) {
substanceUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getSubstanceUnits());
timeUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getTimeUnits());
volumeUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getVolumeUnits());
areaUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getAreaUnits());
lengthUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getLengthUnits());
extentUnits.setSelectedItem(bioModel.getSBMLDocument().getModel().getExtentUnits());
conversionFactor.setSelectedItem(bioModel.getSBMLDocument().getModel().getConversionFactor());
String[] indices= new String[2];
// TODO: Scott - change for Plugin reading
indices[0] = AnnotationUtility.parseConversionRowIndexAnnotation(model);
if(indices[0]!=null){
indices[1] = AnnotationUtility.parseConversionColIndexAnnotation(model);
if(indices[1]==null){
conviIndex.setText(indices[0]);
convjIndex.setText("");
}
else{
conviIndex.setText(indices[0]);
convjIndex.setText(indices[1]);
}
}
else{
conviIndex.setText("");
convjIndex.setText("");
}
}
fbaoButton = new JButton("Edit Objectives");
fbaoButton.setActionCommand("fluxObjective");
fbaoButton.addActionListener(this);
JPanel conversionFactorIndices = new JPanel(new GridLayout(1,2));
conversionFactorIndices.add(conviIndex);
conversionFactorIndices.add(convjIndex);
modelEditorPanel.add(substanceUnitsLabel);
modelEditorPanel.add(substanceUnits);
modelEditorPanel.add(timeUnitsLabel);
modelEditorPanel.add(timeUnits);
modelEditorPanel.add(volumeUnitsLabel);
modelEditorPanel.add(volumeUnits);
modelEditorPanel.add(areaUnitsLabel);
modelEditorPanel.add(areaUnits);
modelEditorPanel.add(lengthUnitsLabel);
modelEditorPanel.add(lengthUnits);
modelEditorPanel.add(extentUnitsLabel);
modelEditorPanel.add(extentUnits);
modelEditorPanel.add(conversionFactorLabel);
modelEditorPanel.add(conversionFactor);
modelEditorPanel.add(new JLabel("Conversion Factor Indices:"));
modelEditorPanel.add(conversionFactorIndices);
modelEditorPanel.add(new JLabel("SBOL DNA Component:"));
modelEditorPanel.add(sbolField);
modelEditorPanel.add(new JLabel("Flux Objective: "));
modelEditorPanel.add(fbaoButton);
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, modelEditorPanel, "Model Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value != JOptionPane.YES_OPTION)
sbolField.resetRemovedBioSimURI();
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
// Add SBOL annotation to SBML model itself
if (!error) {
if (sbolField.getSBOLURIs().size() > 0) {
SBOLAnnotation sbolAnnot = new SBOLAnnotation(sbmlModel.getMetaId(), sbolField.getSBOLURIs(),
sbolField.getSBOLStrand());
AnnotationUtility.setSBOLAnnotation(sbmlModel, sbolAnnot);
} else
AnnotationUtility.removeSBOLAnnotation(sbmlModel);
// Deletes iBioSim composite components that have been removed from association panel
// URI deletionURI = sbolField.getDeletionURI();
// if (deletionURI != null)
// for (String filePath : gcmEditor.getGui().getFilePaths(".sbol")) {
// SBOLDocument sbolDoc = SBOLUtility.loadSBOLFile(filePath);
// SBOLUtility.deleteDNAComponent(deletionURI, sbolDoc);
// SBOLUtility.writeSBOLDocument(filePath, sbolDoc);
// }
}
if (!error) {
if (bioModel.getSBMLDocument().getLevel() > 2) {
if (substanceUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetSubstanceUnits();
}
else {
bioModel.getSBMLDocument().getModel().setSubstanceUnits((String) substanceUnits.getSelectedItem());
}
if (timeUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetTimeUnits();
}
else {
bioModel.getSBMLDocument().getModel().setTimeUnits((String) timeUnits.getSelectedItem());
}
if (volumeUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetVolumeUnits();
}
else {
bioModel.getSBMLDocument().getModel().setVolumeUnits((String) volumeUnits.getSelectedItem());
}
if (areaUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetAreaUnits();
}
else {
bioModel.getSBMLDocument().getModel().setAreaUnits((String) areaUnits.getSelectedItem());
}
if (lengthUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetLengthUnits();
}
else {
bioModel.getSBMLDocument().getModel().setLengthUnits((String) lengthUnits.getSelectedItem());
}
if (extentUnits.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetExtentUnits();
}
else {
bioModel.getSBMLDocument().getModel().setExtentUnits((String) extentUnits.getSelectedItem());
}
if (conversionFactor.getSelectedItem().equals("( none )")) {
bioModel.getSBMLDocument().getModel().unsetConversionFactor();
}
else {
bioModel.getSBMLDocument().getModel().setConversionFactor((String) conversionFactor.getSelectedItem());
}
bioModel.getSBMLDocument().getModel().setName(modelName.getText());
// TODO: Scott - change for Plugin writing
if (!conviIndex.getText().equals("")) {
AnnotationUtility.setConversionRowIndexAnnotation(model,conviIndex.getText());
} else {
AnnotationUtility.removeConversionRowIndexAnnotation(model);
}
if (!convjIndex.getText().equals("")) {
AnnotationUtility.setConversionColIndexAnnotation(model,convjIndex.getText());
} else {
AnnotationUtility.removeConversionColIndexAnnotation(model);
}
}
dirty.setValue(true);
bioModel.makeUndoPoint();
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, modelEditorPanel, "Model Units Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// if the add unit button is clicked
// if the add function button is clicked
if (e.getSource() == this) {
modelEditor("OK");
} else if (e.getActionCommand().equals("editDescriptors")) {
// if (bioModel.getSBOLDescriptors() != null)
// SBOLDescriptorPanel descriptorPanel = new SBOLDescriptorPanel(sbolField.getSBOLURIs().get(0))
}
else if (e.getActionCommand().equals("fluxObjective")){
FBAObjective fbaObjective = new FBAObjective(bioModel);
fbaObjective.openGui();
}
// if the variable is changed
else if (e.getSource() == conversionFactor) {
SBase variable = (SBase) SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), (String)conversionFactor.getSelectedItem());
String[] sizes = new String[2];
// TODO: Scott - change for Plugin reading
sizes[0] = AnnotationUtility.parseVectorSizeAnnotation(variable);
if(sizes[0]==null){
sizes = AnnotationUtility.parseMatrixSizeAnnotation(variable);
if(sizes==null){
conviIndex.setEnabled(false);
convjIndex.setEnabled(false);
}
else{
conviIndex.setEnabled(true);
convjIndex.setEnabled(true);
}
}
else{
conviIndex.setEnabled(true);
convjIndex.setEnabled(false);
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseExited(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseReleased(MouseEvent e) {
}
public SBOLField getSBOLField() {
return sbolField;
}
}
| Should be good to go with the conversion factor indices
| gui/src/biomodel/gui/sbmlcore/ModelPanel.java | Should be good to go with the conversion factor indices |
|
Java | apache-2.0 | 07a0f739192818453a149f147f92077dc4ee2464 | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.http.client.core.communication;
import com.google.common.annotations.Beta;
import com.yahoo.vespa.http.client.config.Endpoint;
import com.yahoo.vespa.http.client.core.Document;
import com.yahoo.vespa.http.client.core.operationProcessor.EndPointResultFactory;
import com.yahoo.vespa.http.client.core.EndpointResult;
import com.yahoo.vespa.http.client.core.ServerResponseException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class for handling asynchronous feeding of new documents and processing of results.
* @author <a href="mailto:[email protected]">Einar M R Rosenvinge</a>
* @since 5.1.20
*/
@Beta
class IOThread implements Runnable, AutoCloseable {
private static Logger log = Logger.getLogger(IOThread.class.getName());
private final Endpoint endpoint;
private final GatewayConnection client;
private final DocumentQueue documentQueue;
private final EndpointResultQueue resultQueue;
private final Thread thread;
private final int clusterId;
private final CountDownLatch running = new CountDownLatch(1);
private final CountDownLatch stopSignal = new CountDownLatch(1);
private final int maxChunkSizeBytes;
private final int maxInFlightRequests;
private final long localQueueTimeOut;
private final GatewayThrottler gatewayThrottler;
private enum ThreadState { DISCONNECTED, CONNECTED, SESSION_SYNCED };
private final AtomicInteger wrongSessionDetectedCounter = new AtomicInteger(0);
private final AtomicInteger wrongVersionDetectedCounter = new AtomicInteger(0);
private final AtomicInteger problemStatusCodeFromServerCounter = new AtomicInteger(0);
private final AtomicInteger executeProblemsCounter = new AtomicInteger(0);
private final AtomicInteger docsReceivedCounter = new AtomicInteger(0);
private final AtomicInteger statusReceivedCounter = new AtomicInteger(0);
private final AtomicInteger pendingDocumentStatusCount = new AtomicInteger(0);
private final AtomicInteger successfullHandshakes = new AtomicInteger(0);
private final AtomicInteger lastGatewayProcessTimeMillis = new AtomicInteger(0);
IOThread(
EndpointResultQueue endpointResultQueue,
GatewayConnection client,
int clusterId,
int maxChunkSizeBytes,
int maxInFlightRequests,
long localQueueTimeOut,
DocumentQueue documentQueue,
long maxSleepTimeMs) {
this.documentQueue = documentQueue;
this.endpoint = client.getEndpoint();
this.client = client;
this.resultQueue = endpointResultQueue;
this.clusterId = clusterId;
this.maxChunkSizeBytes = maxChunkSizeBytes;
this.maxInFlightRequests = maxInFlightRequests;
this.gatewayThrottler = new GatewayThrottler(maxSleepTimeMs);
thread = new Thread(this, "IOThread " + endpoint);
thread.setDaemon(true);
this.localQueueTimeOut = localQueueTimeOut;
thread.start();
}
public Endpoint getEndpoint() {
return endpoint;
}
public static class ConnectionStats {
public final int wrongSessionDetectedCounter;
public final int wrongVersionDetectedCounter;
public final int problemStatusCodeFromServerCounter;
public final int executeProblemsCounter;
public final int docsReceivedCounter;
public final int statusReceivedCounter;
public final int pendingDocumentStatusCount;
public final int successfullHandshakes;
public final int lastGatewayProcessTimeMillis;
protected ConnectionStats(
final int wrongSessionDetectedCounter,
final int wrongVersionDetectedCounter,
final int problemStatusCodeFromServerCounter,
final int executeProblemsCounter,
final int docsReceivedCounter,
final int statusReceivedCounter,
final int pendingDocumentStatusCount,
final int successfullHandshakes,
final int lastGatewayProcessTimeMillis) {
this.wrongSessionDetectedCounter = wrongSessionDetectedCounter;
this.wrongVersionDetectedCounter = wrongVersionDetectedCounter;
this.problemStatusCodeFromServerCounter = problemStatusCodeFromServerCounter;
this.executeProblemsCounter = executeProblemsCounter;
this.docsReceivedCounter = docsReceivedCounter;
this.statusReceivedCounter = statusReceivedCounter;
this.pendingDocumentStatusCount = pendingDocumentStatusCount;
this.successfullHandshakes = successfullHandshakes;
this.lastGatewayProcessTimeMillis = lastGatewayProcessTimeMillis;
}
}
/**
* Returns a snapshot of counters. Threadsafe.
*/
public ConnectionStats getConnectionStats() {
return new ConnectionStats(
wrongSessionDetectedCounter.get(),
wrongVersionDetectedCounter.get(),
problemStatusCodeFromServerCounter.get(),
executeProblemsCounter.get(),
docsReceivedCounter.get(),
statusReceivedCounter.get(),
pendingDocumentStatusCount.get(),
successfullHandshakes.get(),
lastGatewayProcessTimeMillis.get());
}
@Override
public void close() {
documentQueue.close();
if (stopSignal.getCount() == 0) {
return;
}
stopSignal.countDown();
log.finer("Closed called.");
try {
if (! running.await(2 * localQueueTimeOut, TimeUnit.MILLISECONDS)) {
log.info("Waited " + 2 * localQueueTimeOut
+ " ms for queue to be empty, did not happen, interrupting thread.");
thread.interrupt();
try {
running.await();
log.info("Now thread finished (after interrupt).");
} catch (InterruptedException e) {
log.log(Level.INFO, "Interrupted while waiting for threads to finish after they were interrupted.", e);
}
}
} catch (InterruptedException e) {
log.log(Level.INFO, "Interrupted while waiting for threads to finish.", e);
}
try {
if (resultQueue.getPendingSize() > 0) {
log.info("We have outstanding operations, maybe we did an interrupt? Draining.");
processResponse(client.drain());
}
} catch (Exception e) {
drainDocumentQueueWhenFailingPermanently(e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
} finally {
try {
client.close();
} finally {
// If there is still documents in the queue, fail them.
drainDocumentQueueWhenFailingPermanently(new Exception(
"Closed call, did not manage to process everything so failing this document."));
}
}
log.fine("Session to " + endpoint + " closed.");
}
public void post(final Document document) throws InterruptedException {
documentQueue.put(document);
}
@Override
public String toString() {
return "I/O thread (for " + endpoint + ")";
}
List<Document> getNextDocsForFeeding(int maxWaitUnits, TimeUnit timeUnit) {
final List<Document> docsForSendChunk = new ArrayList<>();
if (resultQueue.getPendingSize() > maxInFlightRequests) {
// The queue is full do some sleep just to reduce network usage.
try {
stopSignal.await(300, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) { /* Ignore */ }
return docsForSendChunk;
}
int chunkSizeBytes = 0;
try {
drainFirstDocumentInQueueIfOld();
Document doc = documentQueue.poll(maxWaitUnits, timeUnit);
if (doc != null) {
docsForSendChunk.add(doc);
chunkSizeBytes = doc.size();
}
} catch (InterruptedException ie) {
log.fine("Got break signal while waiting for new documents to feed.");
return docsForSendChunk;
}
int pendingSize = 1 + resultQueue.getPendingSize();
// see if we can get more documents without blocking
while (chunkSizeBytes < maxChunkSizeBytes && pendingSize < maxInFlightRequests) {
drainFirstDocumentInQueueIfOld();
Document d = documentQueue.poll();
if (d == null) {
break;
}
docsForSendChunk.add(d);
chunkSizeBytes += d.size();
pendingSize++;
}
log.finest("Chunk has " + docsForSendChunk.size() + " docs with a size " + chunkSizeBytes + " bytes.");
docsReceivedCounter.addAndGet(docsForSendChunk.size());
return docsForSendChunk;
}
private void addDocumentsToResultQueue(List<Document> docs) {
for (Document doc : docs) {
resultQueue.operationSent(doc.getOperationId());
}
}
private void markDocumentAsFailed(
List<Document> docs, ServerResponseException servletException) {
for (Document doc : docs) {
resultQueue.failOperation(
EndPointResultFactory.createTransientError(
endpoint, doc.getOperationId(), servletException), clusterId);
}
}
private InputStream sendAndReceive(List<Document> docs)
throws IOException, ServerResponseException {
try {
// Post the new docs and get async responses for other posts.
return client.writeOperations(docs);
} catch (ServerResponseException ser) {
markDocumentAsFailed(docs, ser);
throw ser;
} catch (Exception e) {
markDocumentAsFailed(docs, new ServerResponseException(e.getMessage()));
throw e;
}
}
// Return number of transient errors.
private int processResponse(InputStream serverResponse) throws IOException {
final Collection<EndpointResult> endpointResults =
EndPointResultFactory.createResult(endpoint, serverResponse);
statusReceivedCounter.addAndGet(endpointResults.size());
int transientErrors = 0;
for (EndpointResult endpointResult : endpointResults) {
if (! endpointResult.getDetail().isSuccess() &&
endpointResult.getDetail().isTransient()) {
transientErrors++;
}
resultQueue.resultReceived(endpointResult, clusterId);
}
return transientErrors;
}
// Returns number of transient errors.
private int feedDocumentAndProcessResults(List<Document> docs)
throws ServerResponseException, IOException {
addDocumentsToResultQueue(docs);
long startTime = System.currentTimeMillis();
InputStream serverResponse = sendAndReceive(docs);
int transientErrors = processResponse(serverResponse);
lastGatewayProcessTimeMillis.set((int) (System.currentTimeMillis() - startTime));
return transientErrors;
}
// Returns number of transient errors.
private int pullAndProcessData(int maxWaitTimeMilliSecs)
throws ServerResponseException, IOException {
List<Document> nextDocsForFeeding = getNextDocsForFeeding(maxWaitTimeMilliSecs, TimeUnit.MILLISECONDS);
final int pendingResultQueueSize = resultQueue.getPendingSize();
pendingDocumentStatusCount.set(pendingResultQueueSize);
if (nextDocsForFeeding.isEmpty() && pendingResultQueueSize == 0) {
//we have no unfinished business with the server now.
log.finest("No document awaiting feeding, not waiting for results.");
return 0;
}
log.finest("Awaiting " + pendingResultQueueSize + " results.");
return feedDocumentAndProcessResults(nextDocsForFeeding);
}
private ThreadState cycle(final ThreadState threadState) {
switch(threadState) {
case DISCONNECTED:
try {
if (! client.connect()) {
log.log(Level.WARNING, "Connect returned null " + endpoint);
drainFirstDocumentInQueueIfOld();
return ThreadState.DISCONNECTED;
}
return ThreadState.CONNECTED;
} catch (Throwable throwable1) {
drainFirstDocumentInQueueIfOld();
log.log(Level.WARNING, "Connect did not work out " + endpoint, throwable1);
executeProblemsCounter.incrementAndGet();
return ThreadState.DISCONNECTED;
}
case CONNECTED:
try {
client.handshake();
successfullHandshakes.getAndIncrement();
} catch (ServerResponseException ser) {
executeProblemsCounter.incrementAndGet();
log.log(Level.WARNING, "Handshake did not work out " + endpoint, ser.getMessage());
drainFirstDocumentInQueueIfOld();
return ThreadState.CONNECTED;
} catch (Throwable throwable) { // This cover IOException as well
executeProblemsCounter.incrementAndGet();
log.log(Level.WARNING, "Problem with Handshake " + endpoint, throwable.getMessage());
drainFirstDocumentInQueueIfOld();
client.close();
return ThreadState.DISCONNECTED;
}
return ThreadState.SESSION_SYNCED;
case SESSION_SYNCED:
final int maxWaitTimeMilliSecs = 100;
try {
int transientErrors = pullAndProcessData(maxWaitTimeMilliSecs);
gatewayThrottler.handleCall(transientErrors);
}
catch (ServerResponseException ser) {
log.severe("Problems while handing data over to gateway " + endpoint + " " + ser.getMessage());
return ThreadState.CONNECTED;
}
catch (Throwable e) { // Covers IOException as well
log.severe("Problems while handing data over to gateway " + endpoint + " " + e.getMessage());
client.close();
return ThreadState.DISCONNECTED;
}
return ThreadState.SESSION_SYNCED;
default: {
log.severe("Should never get here.");
client.close();
return ThreadState.DISCONNECTED;
}
}
}
private void sleepIfProblemsGettingSyncedConnection(ThreadState newState, ThreadState oldState) {
if (newState == ThreadState.SESSION_SYNCED) return;
if (newState == ThreadState.CONNECTED && oldState == ThreadState.DISCONNECTED) return;
try {
// Take it easy we have problems getting a connection up.
if (stopSignal.getCount() > 0 || !documentQueue.isEmpty()) {
Thread.sleep(gatewayThrottler.distribute(3000));
}
} catch (InterruptedException e) {
}
}
@Override
public void run() {
ThreadState threadState = ThreadState.DISCONNECTED;
while (stopSignal.getCount() > 0 || !documentQueue.isEmpty()) {
ThreadState oldState = threadState;
threadState = cycle(threadState);
sleepIfProblemsGettingSyncedConnection(threadState, oldState);
}
log.finer(toString() + " exiting, documentQueue.size()=" + documentQueue.size());
running.countDown();
}
private void drainFirstDocumentInQueueIfOld() {
while (true) {
Document document = documentQueue.peek();
if (document == null) {
return;
}
if (document.timeInQueueMillis() > localQueueTimeOut) {
documentQueue.poll();
EndpointResult endpointResult = EndPointResultFactory.createTransientError(
endpoint, document.getOperationId(),
new Exception("Not sending document operation, timed out in queue after "
+ document.timeInQueueMillis() + " ms."));
resultQueue.failOperation(endpointResult, clusterId);
} else {
return;
}
}
}
private void drainDocumentQueueWhenFailingPermanently(Exception exception) {
//first, clear sentOperations:
resultQueue.failPending(exception);
for (Document document : documentQueue.removeAllDocuments()) {
EndpointResult endpointResult=
EndPointResultFactory.createError(endpoint, document.getOperationId(), exception);
resultQueue.failOperation(endpointResult, clusterId);
}
}
}
| vespa-http-client/src/main/java/com/yahoo/vespa/http/client/core/communication/IOThread.java | // Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.http.client.core.communication;
import com.google.common.annotations.Beta;
import com.yahoo.vespa.http.client.config.Endpoint;
import com.yahoo.vespa.http.client.core.Document;
import com.yahoo.vespa.http.client.core.operationProcessor.EndPointResultFactory;
import com.yahoo.vespa.http.client.core.EndpointResult;
import com.yahoo.vespa.http.client.core.ServerResponseException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class for handling asynchronous feeding of new documents and processing of results.
* @author <a href="mailto:[email protected]">Einar M R Rosenvinge</a>
* @since 5.1.20
*/
@Beta
class IOThread implements Runnable, AutoCloseable {
private static Logger log = Logger.getLogger(IOThread.class.getName());
private final Endpoint endpoint;
private final GatewayConnection client;
private final DocumentQueue documentQueue;
private final EndpointResultQueue resultQueue;
private final Thread thread;
private final int clusterId;
private final CountDownLatch running = new CountDownLatch(1);
private final CountDownLatch stopSignal = new CountDownLatch(1);
private final int maxChunkSizeBytes;
private final int maxInFlightRequests;
private final long localQueueTimeOut;
private final GatewayThrottler gatewayThrottler;
private enum ThreadState { DISCONNECTED, CONNECTED, SESSION_SYNCED };
private final AtomicInteger wrongSessionDetectedCounter = new AtomicInteger(0);
private final AtomicInteger wrongVersionDetectedCounter = new AtomicInteger(0);
private final AtomicInteger problemStatusCodeFromServerCounter = new AtomicInteger(0);
private final AtomicInteger executeProblemsCounter = new AtomicInteger(0);
private final AtomicInteger docsReceivedCounter = new AtomicInteger(0);
private final AtomicInteger statusReceivedCounter = new AtomicInteger(0);
private final AtomicInteger pendingDocumentStatusCount = new AtomicInteger(0);
private final AtomicInteger successfullHandshakes = new AtomicInteger(0);
private final AtomicInteger lastGatewayProcessTimeMillis = new AtomicInteger(0);
IOThread(
EndpointResultQueue endpointResultQueue,
GatewayConnection client,
int clusterId,
int maxChunkSizeBytes,
int maxInFlightRequests,
long localQueueTimeOut,
DocumentQueue documentQueue,
long maxSleepTimeMs) {
this.documentQueue = documentQueue;
this.endpoint = client.getEndpoint();
this.client = client;
this.resultQueue = endpointResultQueue;
this.clusterId = clusterId;
this.maxChunkSizeBytes = maxChunkSizeBytes;
this.maxInFlightRequests = maxInFlightRequests;
this.gatewayThrottler = new GatewayThrottler(maxSleepTimeMs);
thread = new Thread(this, "IOThread " + endpoint);
thread.setDaemon(true);
this.localQueueTimeOut = localQueueTimeOut;
thread.start();
}
public Endpoint getEndpoint() {
return endpoint;
}
public static class ConnectionStats {
public final int wrongSessionDetectedCounter;
public final int wrongVersionDetectedCounter;
public final int problemStatusCodeFromServerCounter;
public final int executeProblemsCounter;
public final int docsReceivedCounter;
public final int statusReceivedCounter;
public final int pendingDocumentStatusCount;
public final int successfullHandshakes;
public final int lastGatewayProcessTimeMillis;
protected ConnectionStats(
final int wrongSessionDetectedCounter,
final int wrongVersionDetectedCounter,
final int problemStatusCodeFromServerCounter,
final int executeProblemsCounter,
final int docsReceivedCounter,
final int statusReceivedCounter,
final int pendingDocumentStatusCount,
final int successfullHandshakes,
final int lastGatewayProcessTimeMillis) {
this.wrongSessionDetectedCounter = wrongSessionDetectedCounter;
this.wrongVersionDetectedCounter = wrongVersionDetectedCounter;
this.problemStatusCodeFromServerCounter = problemStatusCodeFromServerCounter;
this.executeProblemsCounter = executeProblemsCounter;
this.docsReceivedCounter = docsReceivedCounter;
this.statusReceivedCounter = statusReceivedCounter;
this.pendingDocumentStatusCount = pendingDocumentStatusCount;
this.successfullHandshakes = successfullHandshakes;
this.lastGatewayProcessTimeMillis = lastGatewayProcessTimeMillis;
}
}
/**
* Returns a snapshot of counters. Threadsafe.
*/
public ConnectionStats getConnectionStats() {
return new ConnectionStats(
wrongSessionDetectedCounter.get(),
wrongVersionDetectedCounter.get(),
problemStatusCodeFromServerCounter.get(),
executeProblemsCounter.get(),
docsReceivedCounter.get(),
statusReceivedCounter.get(),
pendingDocumentStatusCount.get(),
successfullHandshakes.get(),
lastGatewayProcessTimeMillis.get());
}
@Override
public void close() {
documentQueue.close();
if (stopSignal.getCount() == 0) {
return;
}
stopSignal.countDown();
log.finer("Closed called.");
try {
if (! running.await(2 * localQueueTimeOut, TimeUnit.MILLISECONDS)) {
log.info("Waited " + 2 * localQueueTimeOut
+ " ms for queue to be empty, did not happen, interrupting thread.");
thread.interrupt();
try {
running.await();
log.info("Now thread finished (after interrupt).");
} catch (InterruptedException e) {
log.log(Level.INFO, "Interrupted while waiting for threads to finish after they were interrupted.", e);
}
}
} catch (InterruptedException e) {
log.log(Level.INFO, "Interrupted while waiting for threads to finish.", e);
}
try {
if (resultQueue.getPendingSize() > 0) {
log.info("We have outstanding operations, maybe we did an interrupt? Draining.");
processResponse(client.drain());
}
} catch (Exception e) {
drainDocumentQueueWhenFailingPermanently(e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
} finally {
try {
client.close();
} finally {
// If there is still documents in the queue, fail them.
drainDocumentQueueWhenFailingPermanently(new Exception(
"Closed call, did not manage to process everything so failing this document."));
}
}
log.fine("Session to " + endpoint + " closed.");
}
public void post(final Document document) throws InterruptedException {
documentQueue.put(document);
}
@Override
public String toString() {
return "I/O thread (for " + endpoint + ")";
}
List<Document> getNextDocsForFeeding(int maxWaitUnits, TimeUnit timeUnit) {
final List<Document> docsForSendChunk = new ArrayList<>();
if (resultQueue.getPendingSize() > maxInFlightRequests) {
// The queue is full do some sleep just to reduce network usage.
try {
stopSignal.await(300, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) { /* Ignore */ }
return docsForSendChunk;
}
int chunkSizeBytes = 0;
try {
drainFirstDocumentInQueueIfOld();
Document doc = documentQueue.poll(maxWaitUnits, timeUnit);
if (doc != null) {
docsForSendChunk.add(doc);
chunkSizeBytes = doc.size();
}
} catch (InterruptedException ie) {
log.fine("Got break signal while waiting for new documents to feed.");
return docsForSendChunk;
}
int pendingSize = 1 + resultQueue.getPendingSize();
// see if we can get more documents without blocking
while (chunkSizeBytes < maxChunkSizeBytes && pendingSize < maxInFlightRequests) {
drainFirstDocumentInQueueIfOld();
Document d = documentQueue.poll();
if (d == null) {
break;
}
docsForSendChunk.add(d);
chunkSizeBytes += d.size();
pendingSize++;
}
log.finest("Chunk has " + docsForSendChunk.size() + " docs with a size " + chunkSizeBytes + " bytes.");
docsReceivedCounter.addAndGet(docsForSendChunk.size());
return docsForSendChunk;
}
private void addDocumentsToResultQueue(List<Document> docs) {
for (Document doc : docs) {
resultQueue.operationSent(doc.getOperationId());
}
}
private void markDocumentAsFailed(
List<Document> docs, ServerResponseException servletException) {
for (Document doc : docs) {
resultQueue.failOperation(
EndPointResultFactory.createTransientError(
endpoint, doc.getOperationId(), servletException), clusterId);
}
}
private InputStream sendAndReceive(List<Document> docs)
throws IOException, ServerResponseException {
try {
// Post the new docs and get async responses for other posts.
return client.writeOperations(docs);
} catch (ServerResponseException ser) {
markDocumentAsFailed(docs, ser);
throw ser;
} catch (Exception e) {
markDocumentAsFailed(docs, new ServerResponseException(e.getMessage()));
throw e;
}
}
// Return number of transient errors.
private int processResponse(InputStream serverResponse) throws IOException {
final Collection<EndpointResult> endpointResults =
EndPointResultFactory.createResult(endpoint, serverResponse);
statusReceivedCounter.addAndGet(endpointResults.size());
int transientErrors = 0;
for (EndpointResult endpointResult : endpointResults) {
if (! endpointResult.getDetail().isSuccess() &&
endpointResult.getDetail().isTransient()) {
transientErrors++;
}
resultQueue.resultReceived(endpointResult, clusterId);
}
return transientErrors;
}
// Returns number of transient errors.
private int feedDocumentAndProcessResults(List<Document> docs)
throws ServerResponseException, IOException {
addDocumentsToResultQueue(docs);
long startTime = System.currentTimeMillis();
InputStream serverResponse = sendAndReceive(docs);
int transientErrors = processResponse(serverResponse);
lastGatewayProcessTimeMillis.set((int) (System.currentTimeMillis() - startTime));
return transientErrors;
}
// Returns number of transient errors.
private int pullAndProcessData(int maxWaitTimeMilliSecs)
throws ServerResponseException, IOException {
List<Document> nextDocsForFeeding = getNextDocsForFeeding(maxWaitTimeMilliSecs, TimeUnit.MILLISECONDS);
final int pendingResultQueueSize = resultQueue.getPendingSize();
pendingDocumentStatusCount.set(pendingResultQueueSize);
if (nextDocsForFeeding.isEmpty() && pendingResultQueueSize == 0) {
//we have no unfinished business with the server now.
log.finest("No document awaiting feeding, not waiting for results.");
return 0;
}
log.finest("Awaiting " + pendingResultQueueSize + " results.");
return feedDocumentAndProcessResults(nextDocsForFeeding);
}
private ThreadState cycle(final ThreadState threadState) {
switch(threadState) {
case DISCONNECTED:
try {
if (! client.connect()) {
log.log(Level.WARNING, "Connect returned null " + endpoint);
drainFirstDocumentInQueueIfOld();
return ThreadState.DISCONNECTED;
}
return ThreadState.CONNECTED;
} catch (Exception ex) {
drainFirstDocumentInQueueIfOld();
log.log(Level.WARNING, "Connect did not work out " + endpoint, ex);
return ThreadState.DISCONNECTED;
}
case CONNECTED:
try {
client.handshake();
successfullHandshakes.getAndIncrement();
} catch (ServerResponseException ser) {
log.log(Level.WARNING, "Handshake did not work out " + endpoint, ser.getMessage());
drainFirstDocumentInQueueIfOld();
return ThreadState.CONNECTED;
} catch (Exception ex) { // This cover IOException as well
log.log(Level.WARNING, "Problem with Handshake " + endpoint, ex.getMessage());
drainFirstDocumentInQueueIfOld();
client.close();
return ThreadState.DISCONNECTED;
}
return ThreadState.SESSION_SYNCED;
case SESSION_SYNCED:
final int maxWaitTimeMilliSecs = 100;
try {
int transientErrors = pullAndProcessData(maxWaitTimeMilliSecs);
gatewayThrottler.handleCall(transientErrors);
}
catch (ServerResponseException ser) {
log.severe("Problems while handing data over to gateway " + endpoint + " " + ser.getMessage());
return ThreadState.CONNECTED;
}
catch (Throwable e) { // Covers IOException as well
log.severe("Problems while handing data over to gateway " + endpoint + " " + e.getMessage());
client.close();
return ThreadState.DISCONNECTED;
}
return ThreadState.SESSION_SYNCED;
default: {
log.severe("Should never get here.");
client.close();
return ThreadState.DISCONNECTED;
}
}
}
private void sleepIfProblemsGettingSyncedConnection(ThreadState newState, ThreadState oldState) {
if (newState == ThreadState.SESSION_SYNCED) return;
if (newState == ThreadState.CONNECTED && oldState == ThreadState.DISCONNECTED) return;
try {
// Take it easy we have problems getting a connection up.
if (stopSignal.getCount() > 0 || !documentQueue.isEmpty()) {
Thread.sleep(gatewayThrottler.distribute(3000));
}
} catch (InterruptedException e) {
}
}
@Override
public void run() {
ThreadState threadState = ThreadState.DISCONNECTED;
while (stopSignal.getCount() > 0 || !documentQueue.isEmpty()) {
ThreadState oldState = threadState;
threadState = cycle(threadState);
sleepIfProblemsGettingSyncedConnection(threadState, oldState);
}
log.finer(toString() + " exiting, documentQueue.size()=" + documentQueue.size());
running.countDown();
}
private void drainFirstDocumentInQueueIfOld() {
while (true) {
Document document = documentQueue.peek();
if (document == null) {
return;
}
if (document.timeInQueueMillis() > localQueueTimeOut) {
documentQueue.poll();
EndpointResult endpointResult = EndPointResultFactory.createTransientError(
endpoint, document.getOperationId(),
new Exception("Not sending document operation, timed out in queue after "
+ document.timeInQueueMillis() + " ms."));
resultQueue.failOperation(endpointResult, clusterId);
} else {
return;
}
}
}
private void drainDocumentQueueWhenFailingPermanently(Exception exception) {
//first, clear sentOperations:
resultQueue.failPending(exception);
for (Document document : documentQueue.removeAllDocuments()) {
EndpointResult endpointResult=
EndPointResultFactory.createError(endpoint, document.getOperationId(), exception);
resultQueue.failOperation(endpointResult, clusterId);
}
}
}
| Catch more errors.
| vespa-http-client/src/main/java/com/yahoo/vespa/http/client/core/communication/IOThread.java | Catch more errors. |
|
Java | apache-2.0 | b30f348a1d62ab85a673b4f833a4d7495a922524 | 0 | pmadrigal/Crossdata,gserranojc/Crossdata,miguel0afd/crossdata,luismcl/crossdata,pfcoperez/crossdata,luismcl/crossdata,pfcoperez/crossdata,jjlopezm/crossdata,Stratio/crossdata,pmadrigal/Crossdata,hdominguez1989/Crossdata,jjlopezm/crossdata,ccaballe/crossdata,darroyocazorla/crossdata,hdominguez1989/Crossdata,compae/Crossdata,gserranojc/Crossdata,ccaballe/crossdata,miguel0afd/crossdata,Stratio/crossdata,darroyocazorla/crossdata,compae/Crossdata | /*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) 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.stratio.meta2.core.validator.statements;
import com.stratio.meta.common.exceptions.IgnoreQueryException;
import com.stratio.meta.common.exceptions.ValidationException;
import com.stratio.meta2.common.data.*;
import com.stratio.meta2.common.metadata.ColumnType;
import com.stratio.meta2.common.metadata.IndexMetadata;
import com.stratio.meta2.common.statements.structures.selectors.StringSelector;
import com.stratio.meta2.core.query.BaseQuery;
import com.stratio.meta2.core.query.MetadataParsedQuery;
import com.stratio.meta2.core.query.ParsedQuery;
import com.stratio.meta2.core.statements.CreateTableStatement;
import com.stratio.meta2.core.structures.Property;
import com.stratio.meta2.core.structures.PropertyNameValue;
import com.stratio.meta2.core.validator.BasicValidatorTest;
import com.stratio.meta2.core.validator.Validator;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CreateTableStatementTest extends BasicValidatorTest {
@Test
public void createTable() {
String query = "CREATE TABLE demo.users2 ( name varchar, gender varchar, age int, PRIMARY KEY (name)) ";
Map< ColumnName, ColumnType > columns=new HashMap<>();
ClusterName clusterRef=new ClusterName("cluster");
List<ColumnName> primaryKey=new ArrayList<>();
ColumnName partitionColumn1=new ColumnName("demo","users2","name");
primaryKey.add(partitionColumn1);
List<ColumnName> clusterKey=new ArrayList<>();
Object[] parameters=null;
columns.put(new ColumnName(new TableName("demo","users2"),"name"),ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","users2"),"gender"), ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","users2"),"age"), ColumnType.INT);
Map<IndexName, IndexMetadata> indexes=new HashMap<>();
List<ColumnName> clusterkey=null;
int primaryKeyType=1;
CreateTableStatement createTableStatement=new CreateTableStatement(new TableName("demo","users2"),new ClusterName("cluster"),columns,primaryKey,clusterkey,primaryKeyType,1);
Validator validator=new Validator();
BaseQuery baseQuery=new BaseQuery("CreateTableId",query, new CatalogName("demo"));
ParsedQuery parsedQuery=new MetadataParsedQuery(baseQuery,createTableStatement);
try {
validator.validate(parsedQuery);
Assert.assertTrue(true);
} catch (ValidationException e) {
Assert.fail(e.getMessage());
} catch (IgnoreQueryException e) {
Assert.fail(e.getMessage());
}
}
@Test
public void CreateTableWithOptions() {
String query = "CREATE TABLE demo.users2 ( name varchar, gender varchar, age int, PRIMARY KEY (name)) WITH comment='Users2 table'";
Map< ColumnName, ColumnType > columns=new HashMap<>();
ClusterName clusterRef=new ClusterName("cluster");
List<ColumnName> primaryKey=new ArrayList<>();
ColumnName partitionColumn1=new ColumnName("demo","users2","name");
primaryKey.add(partitionColumn1);
List<ColumnName> clusterKey=new ArrayList<>();
Object[] parameters=null;
columns.put(new ColumnName(new TableName("demo","users2"),"name"),ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","users2"),"gender"), ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","users2"),"age"), ColumnType.INT);
Map<IndexName, IndexMetadata> indexes=new HashMap<>();
List<ColumnName> clusterkey=null;
int primaryKeyType=1;
CreateTableStatement createTableStatement=new CreateTableStatement(new TableName("demo","users2"),new ClusterName("cluster"),columns,primaryKey,clusterkey,primaryKeyType,1);
createTableStatement.setWithProperties(true);
List<Property> properties=new ArrayList<>();
Property prop=new PropertyNameValue(new StringSelector("comment"),new StringSelector("Users2 table"));
properties.add(prop);
createTableStatement.setProperties(properties.toString());
Validator validator=new Validator();
BaseQuery baseQuery=new BaseQuery("CreateTableId",query, new CatalogName("demo"));
ParsedQuery parsedQuery=new MetadataParsedQuery(baseQuery,createTableStatement);
try {
validator.validate(parsedQuery);
Assert.assertTrue(true);
} catch (ValidationException e) {
Assert.fail(e.getMessage());
} catch (IgnoreQueryException e) {
Assert.fail(e.getMessage());
}
}
@Test
public void CreateTableUnknownCatalog() {
String query = "CREATE TABLE unknown.users2 ( name varchar, gender varchar, age int, PRIMARY KEY (name))";
Map< ColumnName, ColumnType > columns=new HashMap<>();
ClusterName clusterRef=new ClusterName("cluster");
List<ColumnName> primaryKey=new ArrayList<>();
ColumnName partitionColumn1=new ColumnName("unknown","users2","name");
primaryKey.add(partitionColumn1);
List<ColumnName> clusterKey=new ArrayList<>();
Object[] parameters=null;
columns.put(new ColumnName(new TableName("unknown","users2"),"name"),ColumnType.TEXT);
columns.put(new ColumnName(new TableName("unknown","users2"),"gender"), ColumnType.TEXT);
columns.put(new ColumnName(new TableName("unknown","users2"),"age"), ColumnType.INT);
Map<IndexName, IndexMetadata> indexes=new HashMap<>();
List<ColumnName> clusterkey=null;
int primaryKeyType=1;
CreateTableStatement createTableStatement=new CreateTableStatement(new TableName("unknown","users2"),new ClusterName("cluster"),columns,primaryKey,clusterkey,primaryKeyType,1);
createTableStatement.setWithProperties(true);
List<Property> properties=new ArrayList<>();
Property prop=new PropertyNameValue(new StringSelector("comment"),new StringSelector("Users2 table"));
properties.add(prop);
createTableStatement.setProperties(properties.toString());
Validator validator=new Validator();
BaseQuery baseQuery=new BaseQuery("CreateTableId",query, new CatalogName("unknown"));
ParsedQuery parsedQuery=new MetadataParsedQuery(baseQuery,createTableStatement);
try {
validator.validate(parsedQuery);
Assert.fail("Catalog must exists");
} catch (ValidationException e) {
Assert.assertTrue(true);
} catch (IgnoreQueryException e) {
Assert.assertTrue(true);
}
}
@Test
public void createDuplicateTable() {
String query = "CREATE TABLE demo.users ( name varchar, gender varchar, age int, PRIMARY KEY (name)) ";
Map< ColumnName, ColumnType > columns=new HashMap<>();
ClusterName clusterRef=new ClusterName("cluster");
List<ColumnName> primaryKey=new ArrayList<>();
ColumnName partitionColumn1=new ColumnName("demo","user","name");
primaryKey.add(partitionColumn1);
List<ColumnName> clusterKey=new ArrayList<>();
Object[] parameters=null;
columns.put(new ColumnName(new TableName("demo","user"),"name"),ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","user"),"gender"), ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","user"),"age"), ColumnType.INT);
Map<IndexName, IndexMetadata> indexes=new HashMap<>();
List<ColumnName> clusterkey=null;
int primaryKeyType=1;
CreateTableStatement createTableStatement=new CreateTableStatement(new TableName("demo","user"),new ClusterName("cluster"),columns,primaryKey,clusterkey,primaryKeyType,1);
Validator validator=new Validator();
BaseQuery baseQuery=new BaseQuery("CreateTableId",query, new CatalogName("demo"));
ParsedQuery parsedQuery=new MetadataParsedQuery(baseQuery,createTableStatement);
try {
validator.validate(parsedQuery);
Assert.fail("The new table must not exists");
} catch (ValidationException e) {
Assert.assertTrue(true);
} catch (IgnoreQueryException e) {
Assert.assertTrue(true);
}
}
}
| meta-core/src/test/java/com/stratio/meta2/core/validator/statements/CreateTableStatementTest.java | /*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) 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.stratio.meta2.core.validator.statements;
import com.stratio.meta.common.exceptions.IgnoreQueryException;
import com.stratio.meta.common.exceptions.ValidationException;
import com.stratio.meta2.common.data.CatalogName;
import com.stratio.meta2.common.data.ClusterName;
import com.stratio.meta2.common.data.ColumnName;
import com.stratio.meta2.common.data.TableName;
import com.stratio.meta2.common.metadata.ColumnType;
import com.stratio.meta2.core.query.BaseQuery;
import com.stratio.meta2.core.query.MetadataParsedQuery;
import com.stratio.meta2.core.query.ParsedQuery;
import com.stratio.meta2.core.statements.CreateTableStatement;
import com.stratio.meta2.core.validator.BasicValidatorTest;
import com.stratio.meta2.core.validator.Validator;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CreateTableStatementTest extends BasicValidatorTest {
@Test
public void createTable() {
String query = "CREATE TABLE demo.users2 ( name varchar, gender varchar, age int, PRIMARY KEY (name)) ";
Map< ColumnName, ColumnType > columns=new HashMap<>();
ClusterName clusterRef=new ClusterName("cluster");
List<ColumnName> primaryKey=new ArrayList<>();
ColumnName partitionColumn1=new ColumnName("demo","users2","name");
primaryKey.add(partitionColumn1);
List<ColumnName> clusterKey=new ArrayList<>();
Object[] parameters=null;
columns.put(new ColumnName(new TableName("demo","users2"),"name"),ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","users2"),"gender"), ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","users2"),"age"), ColumnType.INT);
Map<IndexName, IndexMetadata> indexes=new HashMap<>();
List<ColumnName> clusterkey=null;
int primaryKeyType=1;
CreateTableStatement createTableStatement=new CreateTableStatement(new TableName("demo","users2"),new ClusterName("cluster"),columns,primaryKey,clusterkey,primaryKeyType,1);
Validator validator=new Validator();
BaseQuery baseQuery=new BaseQuery("CreateTableId",query, new CatalogName("demo"));
ParsedQuery parsedQuery=new MetadataParsedQuery(baseQuery,createTableStatement);
try {
validator.validate(parsedQuery);
Assert.assertTrue(true);
} catch (ValidationException e) {
Assert.fail(e.getMessage());
} catch (IgnoreQueryException e) {
Assert.fail(e.getMessage());
}
}
@Test
public void CreateTableWithOptions() {
String query = "CREATE TABLE demo.users2 ( name varchar, gender varchar, age int, PRIMARY KEY (name)) WITH comment='Users2 table'";
Map< ColumnName, ColumnType > columns=new HashMap<>();
ClusterName clusterRef=new ClusterName("cluster");
List<ColumnName> primaryKey=new ArrayList<>();
ColumnName partitionColumn1=new ColumnName("demo","users2","name");
primaryKey.add(partitionColumn1);
List<ColumnName> clusterKey=new ArrayList<>();
Object[] parameters=null;
columns.put(new ColumnName(new TableName("demo","users2"),"name"),ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","users2"),"gender"), ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","users2"),"age"), ColumnType.INT);
Map<IndexName, IndexMetadata> indexes=new HashMap<>();
List<ColumnName> clusterkey=null;
int primaryKeyType=1;
CreateTableStatement createTableStatement=new CreateTableStatement(new TableName("demo","users2"),new ClusterName("cluster"),columns,primaryKey,clusterkey,primaryKeyType,1);
createTableStatement.setWithProperties(true);
List<Property> properties=new ArrayList<>();
Property prop=new PropertyNameValue(new StringSelector("comment"),new StringSelector("Users2 table"));
properties.add(prop);
createTableStatement.setProperties(properties);
Validator validator=new Validator();
BaseQuery baseQuery=new BaseQuery("CreateTableId",query, new CatalogName("demo"));
ParsedQuery parsedQuery=new MetadataParsedQuery(baseQuery,createTableStatement);
try {
validator.validate(parsedQuery);
Assert.assertTrue(true);
} catch (ValidationException e) {
Assert.fail(e.getMessage());
} catch (IgnoreQueryException e) {
Assert.fail(e.getMessage());
}
}
@Test
public void CreateTableUnknownCatalog() {
String query = "CREATE TABLE unknown.users2 ( name varchar, gender varchar, age int, PRIMARY KEY (name))";
Map< ColumnName, ColumnType > columns=new HashMap<>();
ClusterName clusterRef=new ClusterName("cluster");
List<ColumnName> primaryKey=new ArrayList<>();
ColumnName partitionColumn1=new ColumnName("unknown","users2","name");
primaryKey.add(partitionColumn1);
List<ColumnName> clusterKey=new ArrayList<>();
Object[] parameters=null;
columns.put(new ColumnName(new TableName("unknown","users2"),"name"),ColumnType.TEXT);
columns.put(new ColumnName(new TableName("unknown","users2"),"gender"), ColumnType.TEXT);
columns.put(new ColumnName(new TableName("unknown","users2"),"age"), ColumnType.INT);
Map<IndexName, IndexMetadata> indexes=new HashMap<>();
List<ColumnName> clusterkey=null;
int primaryKeyType=1;
CreateTableStatement createTableStatement=new CreateTableStatement(new TableName("unknown","users2"),new ClusterName("cluster"),columns,primaryKey,clusterkey,primaryKeyType,1);
createTableStatement.setWithProperties(true);
List<Property> properties=new ArrayList<>();
Property prop=new PropertyNameValue(new StringSelector("comment"),new StringSelector("Users2 table"));
properties.add(prop);
createTableStatement.setProperties(properties);
Validator validator=new Validator();
BaseQuery baseQuery=new BaseQuery("CreateTableId",query, new CatalogName("unknown"));
ParsedQuery parsedQuery=new MetadataParsedQuery(baseQuery,createTableStatement);
try {
validator.validate(parsedQuery);
Assert.fail("Catalog must exists");
} catch (ValidationException e) {
Assert.assertTrue(true);
} catch (IgnoreQueryException e) {
Assert.assertTrue(true);
}
}
@Test
public void createDuplicateTable() {
String query = "CREATE TABLE demo.users ( name varchar, gender varchar, age int, PRIMARY KEY (name)) ";
Map< ColumnName, ColumnType > columns=new HashMap<>();
ClusterName clusterRef=new ClusterName("cluster");
List<ColumnName> primaryKey=new ArrayList<>();
ColumnName partitionColumn1=new ColumnName("demo","user","name");
primaryKey.add(partitionColumn1);
List<ColumnName> clusterKey=new ArrayList<>();
Object[] parameters=null;
columns.put(new ColumnName(new TableName("demo","user"),"name"),ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","user"),"gender"), ColumnType.TEXT);
columns.put(new ColumnName(new TableName("demo","user"),"age"), ColumnType.INT);
Map<IndexName, IndexMetadata> indexes=new HashMap<>();
List<ColumnName> clusterkey=null;
int primaryKeyType=1;
CreateTableStatement createTableStatement=new CreateTableStatement(new TableName("demo","user"),new ClusterName("cluster"),columns,primaryKey,clusterkey,primaryKeyType,1);
Validator validator=new Validator();
BaseQuery baseQuery=new BaseQuery("CreateTableId",query, new CatalogName("demo"));
ParsedQuery parsedQuery=new MetadataParsedQuery(baseQuery,createTableStatement);
try {
validator.validate(parsedQuery);
Assert.fail("The new table must not exists");
} catch (ValidationException e) {
Assert.assertTrue(true);
} catch (IgnoreQueryException e) {
Assert.assertTrue(true);
}
}
}
| Fix import errors
| meta-core/src/test/java/com/stratio/meta2/core/validator/statements/CreateTableStatementTest.java | Fix import errors |
|
Java | apache-2.0 | babf7ea3282eb90b5a9977c806082fd0fc2ede61 | 0 | anchela/jackrabbit-oak,alexkli/jackrabbit-oak,alexkli/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,stillalex/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,stillalex/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexkli/jackrabbit-oak,catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,anchela/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,stillalex/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexparvulescu/jackrabbit-oak,catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,alexparvulescu/jackrabbit-oak,catholicon/jackrabbit-oak,stillalex/jackrabbit-oak,francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,stillalex/jackrabbit-oak,alexparvulescu/jackrabbit-oak,francescomari/jackrabbit-oak,alexparvulescu/jackrabbit-oak,catholicon/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.document;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.Ignore;
import org.junit.Test;
import static com.google.common.collect.Sets.newHashSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class RevisionVectorTest {
@Test(expected = IllegalArgumentException.class)
public void illegalArgument() {
Revision rev1 = new Revision(1, 0, 1);
new RevisionVector(rev1, rev1);
}
@Test
public void construct() {
RevisionVector rv = new RevisionVector();
assertEquals(newHashSet(), newHashSet(rv));
Revision rev1 = new Revision(1, 0, 1);
Revision rev2 = new Revision(1, 0, 2);
rv = new RevisionVector(newHashSet(rev1, rev2));
assertEquals(newHashSet(rev1, rev2), newHashSet(rv));
rv = new RevisionVector(Lists.newArrayList(rev1, rev2));
assertEquals(newHashSet(rev1, rev2), newHashSet(rv));
}
@Test
public void update() {
Revision rev1 = new Revision(1, 0, 1);
RevisionVector rv = new RevisionVector(rev1);
assertEquals(1, Iterables.size(rv));
assertSame(rv, rv.update(rev1));
Revision rev2 = new Revision(2, 0, 1);
rv = rv.update(rev2);
assertEquals(newHashSet(rev2), newHashSet(rv));
Revision rev3 = new Revision(3, 0, 2);
rv = rv.update(rev3);
assertEquals(newHashSet(rev2, rev3), newHashSet(rv));
rev3 = rev3.asBranchRevision();
rv = rv.update(rev3);
assertEquals(newHashSet(rev2, rev3), newHashSet(rv));
}
@Test
public void remove() {
RevisionVector rv = new RevisionVector();
assertSame(rv, rv.remove(1));
Revision rev1 = new Revision(1, 0, 1);
Revision rev2 = new Revision(1, 0, 2);
Revision rev3 = new Revision(1, 0, 3);
rv = new RevisionVector(rev1);
assertSame(rv, rv.remove(2));
assertEquals(new RevisionVector(), rv.remove(rev1.getClusterId()));
rv = new RevisionVector(rev1, rev2, rev3);
assertEquals(new RevisionVector(rev2, rev3), rv.remove(rev1.getClusterId()));
assertEquals(new RevisionVector(rev1, rev3), rv.remove(rev2.getClusterId()));
assertEquals(new RevisionVector(rev1, rev2), rv.remove(rev3.getClusterId()));
}
@Test
public void isNewer() {
Revision rev1 = new Revision(1, 0, 1);
Revision rev2 = new Revision(1, 0, 2);
Revision rev3 = new Revision(1, 0, 3);
RevisionVector rv = new RevisionVector(rev1, rev2);
assertFalse(rv.isRevisionNewer(rev1));
assertFalse(rv.isRevisionNewer(rev2));
assertTrue(rv.isRevisionNewer(rev3));
assertTrue(rv.isRevisionNewer(new Revision(2, 0, 1)));
assertTrue(rv.isRevisionNewer(new Revision(2, 0, 2)));
assertFalse(rv.isRevisionNewer(new Revision(0, 0, 1)));
assertFalse(rv.isRevisionNewer(new Revision(0, 0, 2)));
}
@Test
public void pmin() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(newHashSet(), newHashSet(rv1.pmin(rv2)));
Revision rev11 = new Revision(1, 0, 1);
Revision rev21 = new Revision(2, 0, 1);
Revision rev12 = new Revision(1, 0, 2);
Revision rev22 = new Revision(2, 0, 2);
rv1 = rv1.update(rev11);
// rv1: [r1-0-1], rv2: []
assertEquals(newHashSet(), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(), newHashSet(rv2.pmin(rv1)));
rv2 = rv2.update(rev12);
// rv1: [r1-0-1], rv2: [r1-0-2]
assertEquals(newHashSet(), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(), newHashSet(rv2.pmin(rv1)));
rv1 = rv1.update(rev12);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-2]
assertEquals(newHashSet(rev12), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev12), newHashSet(rv2.pmin(rv1)));
rv2 = rv2.update(rev22);
// rv1: [r1-0-1, r1-0-2], rv2: [r2-0-2]
assertEquals(newHashSet(rev12), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev12), newHashSet(rv2.pmin(rv1)));
rv2 = rv2.update(rev11);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev11, rev12), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev11, rev12), newHashSet(rv2.pmin(rv1)));
rv1 = rv1.update(rev21);
// rv1: [r2-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev11, rev12), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev11, rev12), newHashSet(rv2.pmin(rv1)));
rv1 = rv1.update(rev22);
// rv1: [r2-0-1, r2-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev11, rev22), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev11, rev22), newHashSet(rv2.pmin(rv1)));
rv2 = rv2.update(rev21);
// rv1: [r2-0-1, r2-0-2], rv2: [r2-0-1, r2-0-2]
assertEquals(newHashSet(rev21, rev22), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev21, rev22), newHashSet(rv2.pmin(rv1)));
}
@Test
public void pmax() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(newHashSet(), newHashSet(rv1.pmax(rv2)));
Revision rev11 = new Revision(1, 0, 1);
Revision rev21 = new Revision(2, 0, 1);
Revision rev12 = new Revision(1, 0, 2);
Revision rev22 = new Revision(2, 0, 2);
rv1 = rv1.update(rev11);
// rv1: [r1-0-1], rv2: []
assertEquals(newHashSet(rev11), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11), newHashSet(rv2.pmax(rv1)));
rv2 = rv2.update(rev12);
// rv1: [r1-0-1], rv2: [r1-0-2]
assertEquals(newHashSet(rev11, rev12), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11, rev12), newHashSet(rv2.pmax(rv1)));
rv1 = rv1.update(rev12);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-2]
assertEquals(newHashSet(rev11, rev12), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11, rev12), newHashSet(rv2.pmax(rv1)));
rv2 = rv2.update(rev22);
// rv1: [r1-0-1, r1-0-2], rv2: [r2-0-2]
assertEquals(newHashSet(rev11, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11, rev22), newHashSet(rv2.pmax(rv1)));
rv2 = rv2.update(rev11);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev11, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11, rev22), newHashSet(rv2.pmax(rv1)));
rv1 = rv1.update(rev21);
// rv1: [r2-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev21, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev21, rev22), newHashSet(rv2.pmax(rv1)));
rv1 = rv1.update(rev22);
// rv1: [r2-0-1, r2-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev21, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev21, rev22), newHashSet(rv2.pmax(rv1)));
rv2 = rv2.update(rev21);
// rv1: [r2-0-1, r2-0-2], rv2: [r2-0-1, r2-0-2]
assertEquals(newHashSet(rev21, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev21, rev22), newHashSet(rv2.pmax(rv1)));
}
@Test
public void difference() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(new RevisionVector(), rv1.difference(rv2));
Revision r11 = new Revision(1, 0, 1);
rv1 = rv1.update(r11);
// rv1: [r1-0-1]
assertEquals(new RevisionVector(r11), rv1.difference(rv2));
assertEquals(new RevisionVector(), rv2.difference(rv1));
rv2 = rv2.update(r11);
// rv1: [r1-0-1], rv2: [r1-0-1]
assertEquals(new RevisionVector(), rv1.difference(rv2));
assertEquals(new RevisionVector(), rv2.difference(rv1));
Revision r12 = new Revision(1, 0, 2);
rv1 = rv1.update(r12);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-1]
assertEquals(new RevisionVector(r12), rv1.difference(rv2));
assertEquals(new RevisionVector(), rv2.difference(rv1));
Revision r22 = new Revision(2, 0, 2);
rv2 = rv2.update(r22);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(new RevisionVector(r12), rv1.difference(rv2));
assertEquals(new RevisionVector(r22), rv2.difference(rv1));
Revision r21 = new Revision(2, 0, 1);
rv1 = rv1.update(r21);
// rv1: [r2-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(new RevisionVector(r21, r12), rv1.difference(rv2));
assertEquals(new RevisionVector(r11, r22), rv2.difference(rv1));
}
@Test
public void isBranch() {
RevisionVector rv = new RevisionVector();
assertFalse(rv.isBranch());
Revision r1 = new Revision(1, 0, 1);
rv = rv.update(r1);
assertFalse(rv.isBranch());
Revision r2 = new Revision(1, 0, 2, true);
rv = rv.update(r2);
assertTrue(rv.isBranch());
}
@Test
public void getBranchRevision() {
Revision r1 = new Revision(1, 0, 1);
Revision r2 = new Revision(1, 0, 2, true);
RevisionVector rv = new RevisionVector(r1, r2);
assertEquals(r2, rv.getBranchRevision());
}
@Test(expected = IllegalStateException.class)
public void exceptionOnGetBranchRevision() {
RevisionVector rv = new RevisionVector();
rv.getBranchRevision();
}
@Test
public void compareTo() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(0, rv1.compareTo(rv2));
Revision r11 = new Revision(1, 0, 1);
rv1 = rv1.update(r11); // [r1-0-1]
assertTrue(rv1.compareTo(rv2) > 0);
assertTrue(rv2.compareTo(rv1) < 0);
Revision r12 = new Revision(1, 0, 2);
rv2 = rv2.update(r12); // [r1-0-2]
assertTrue(rv1.compareTo(rv2) > 0);
assertTrue(rv2.compareTo(rv1) < 0);
rv2 = rv2.update(r11); // [r1-0-1, r1-0-2]
assertTrue(rv1.compareTo(rv2) < 0);
assertTrue(rv2.compareTo(rv1) > 0);
rv1 = rv1.update(r12); // [r1-0-1, r1-0-2]
assertEquals(0, rv1.compareTo(rv2));
assertEquals(0, rv2.compareTo(rv1));
Revision r22 = new Revision(2, 0, 2);
rv2 = rv2.update(r22); // [r1-0-1, r2-0-2]
assertTrue(rv1.compareTo(rv2) < 0);
assertTrue(rv2.compareTo(rv1) > 0);
Revision rb22 = r22.asBranchRevision();
rv1 = rv1.update(rb22);
assertTrue(rv1.compareTo(rv2) < 0);
assertTrue(rv2.compareTo(rv1) > 0);
}
@Test
public void equals() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(rv1, rv2);
Revision r11 = new Revision(1, 0, 1);
rv1 = rv1.update(r11);
assertNotEquals(rv1, rv2);
rv2 = rv2.update(r11);
assertEquals(rv1, rv2);
Revision r12 = new Revision(1, 0, 2);
rv1 = rv1.update(r12);
assertNotEquals(rv1, rv2);
rv2 = rv2.update(r12);
assertEquals(rv1, rv2);
//Check basic cases which are short circuited
assertEquals(rv1, rv1);
assertNotEquals(rv1, null);
assertNotEquals(rv1, new Object());
}
@Test
public void hashCodeTest() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(rv1.hashCode(), rv2.hashCode());
//Check again once lazily initialized hash is initialized
assertEquals(rv1.hashCode(), rv2.hashCode());
Revision r11 = new Revision(1, 0, 1);
rv1 = rv1.update(r11);
rv2 = rv2.update(r11);
assertEquals(rv1.hashCode(), rv2.hashCode());
Revision r12 = new Revision(1, 0, 2);
rv1 = rv1.update(r12);
rv2 = rv2.update(r12);
assertEquals(rv1.hashCode(), rv2.hashCode());
}
@Test
public void getRevision() {
RevisionVector rv = new RevisionVector();
assertNull(rv.getRevision(1));
Revision r11 = new Revision(1, 0, 1);
rv = rv.update(r11);
assertEquals(r11, rv.getRevision(1));
assertNull(rv.getRevision(2));
Revision r13 = new Revision(1, 0, 3);
rv = rv.update(r13);
assertEquals(r13, rv.getRevision(3));
assertNull(rv.getRevision(2));
}
@Test
public void asTrunkRevision() {
RevisionVector rv = new RevisionVector();
assertFalse(rv.asTrunkRevision().isBranch());
rv = rv.update(new Revision(1, 0, 1, true));
assertTrue(rv.isBranch());
assertFalse(rv.asTrunkRevision().isBranch());
}
@Test(expected = IllegalArgumentException.class)
public void asBranchRevision1() {
new RevisionVector().asBranchRevision(1);
}
@Test(expected = IllegalArgumentException.class)
public void asBranchRevision2() {
new RevisionVector(new Revision(1, 0, 1)).asBranchRevision(2);
}
@Test
public void asBranchRevision3() {
Revision r11 = new Revision(1, 0, 1);
Revision br11 = r11.asBranchRevision();
RevisionVector rv = new RevisionVector(r11);
assertEquals(new RevisionVector(br11), rv.asBranchRevision(1));
rv = rv.asTrunkRevision();
Revision r12 = new Revision(1, 0, 2);
rv = rv.update(r12);
assertEquals(new RevisionVector(br11, r12), rv.asBranchRevision(1));
}
@Test
public void fromString() throws Exception{
RevisionVector rv = new RevisionVector(
new Revision(1, 0, 1),
new Revision(2, 0, 2)
);
String rvstr = rv.asString();
RevisionVector rvFromStr = RevisionVector.fromString(rvstr);
assertEquals(rv, rvFromStr);
}
@Test
public void toStringBuilder() throws Exception {
RevisionVector rv = new RevisionVector();
StringBuilder sb = new StringBuilder();
rv.toStringBuilder(sb);
assertEquals("", sb.toString());
rv = new RevisionVector(
new Revision(1, 0, 1),
new Revision(2, 0, 2)
);
rv.toStringBuilder(sb);
assertEquals(rv.toString(), sb.toString());
}
@Test
public void getDimensions() throws Exception {
RevisionVector rv = new RevisionVector();
assertEquals(0, rv.getDimensions());
rv = new RevisionVector(
new Revision(1, 0, 1),
new Revision(2, 0, 2)
);
assertEquals(2, rv.getDimensions());
rv = rv.remove(1);
assertEquals(1, rv.getDimensions());
}
@Ignore
@Test
public void emptyAsFromString() {
RevisionVector empty = new RevisionVector();
assertEquals(empty, RevisionVector.fromString(empty.asString()));
}
}
| oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/RevisionVectorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.document;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.Test;
import static com.google.common.collect.Sets.newHashSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class RevisionVectorTest {
@Test(expected = IllegalArgumentException.class)
public void illegalArgument() {
Revision rev1 = new Revision(1, 0, 1);
new RevisionVector(rev1, rev1);
}
@Test
public void construct() {
RevisionVector rv = new RevisionVector();
assertEquals(newHashSet(), newHashSet(rv));
Revision rev1 = new Revision(1, 0, 1);
Revision rev2 = new Revision(1, 0, 2);
rv = new RevisionVector(newHashSet(rev1, rev2));
assertEquals(newHashSet(rev1, rev2), newHashSet(rv));
rv = new RevisionVector(Lists.newArrayList(rev1, rev2));
assertEquals(newHashSet(rev1, rev2), newHashSet(rv));
}
@Test
public void update() {
Revision rev1 = new Revision(1, 0, 1);
RevisionVector rv = new RevisionVector(rev1);
assertEquals(1, Iterables.size(rv));
assertSame(rv, rv.update(rev1));
Revision rev2 = new Revision(2, 0, 1);
rv = rv.update(rev2);
assertEquals(newHashSet(rev2), newHashSet(rv));
Revision rev3 = new Revision(3, 0, 2);
rv = rv.update(rev3);
assertEquals(newHashSet(rev2, rev3), newHashSet(rv));
rev3 = rev3.asBranchRevision();
rv = rv.update(rev3);
assertEquals(newHashSet(rev2, rev3), newHashSet(rv));
}
@Test
public void remove() {
RevisionVector rv = new RevisionVector();
assertSame(rv, rv.remove(1));
Revision rev1 = new Revision(1, 0, 1);
Revision rev2 = new Revision(1, 0, 2);
Revision rev3 = new Revision(1, 0, 3);
rv = new RevisionVector(rev1);
assertSame(rv, rv.remove(2));
assertEquals(new RevisionVector(), rv.remove(rev1.getClusterId()));
rv = new RevisionVector(rev1, rev2, rev3);
assertEquals(new RevisionVector(rev2, rev3), rv.remove(rev1.getClusterId()));
assertEquals(new RevisionVector(rev1, rev3), rv.remove(rev2.getClusterId()));
assertEquals(new RevisionVector(rev1, rev2), rv.remove(rev3.getClusterId()));
}
@Test
public void isNewer() {
Revision rev1 = new Revision(1, 0, 1);
Revision rev2 = new Revision(1, 0, 2);
Revision rev3 = new Revision(1, 0, 3);
RevisionVector rv = new RevisionVector(rev1, rev2);
assertFalse(rv.isRevisionNewer(rev1));
assertFalse(rv.isRevisionNewer(rev2));
assertTrue(rv.isRevisionNewer(rev3));
assertTrue(rv.isRevisionNewer(new Revision(2, 0, 1)));
assertTrue(rv.isRevisionNewer(new Revision(2, 0, 2)));
assertFalse(rv.isRevisionNewer(new Revision(0, 0, 1)));
assertFalse(rv.isRevisionNewer(new Revision(0, 0, 2)));
}
@Test
public void pmin() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(newHashSet(), newHashSet(rv1.pmin(rv2)));
Revision rev11 = new Revision(1, 0, 1);
Revision rev21 = new Revision(2, 0, 1);
Revision rev12 = new Revision(1, 0, 2);
Revision rev22 = new Revision(2, 0, 2);
rv1 = rv1.update(rev11);
// rv1: [r1-0-1], rv2: []
assertEquals(newHashSet(), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(), newHashSet(rv2.pmin(rv1)));
rv2 = rv2.update(rev12);
// rv1: [r1-0-1], rv2: [r1-0-2]
assertEquals(newHashSet(), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(), newHashSet(rv2.pmin(rv1)));
rv1 = rv1.update(rev12);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-2]
assertEquals(newHashSet(rev12), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev12), newHashSet(rv2.pmin(rv1)));
rv2 = rv2.update(rev22);
// rv1: [r1-0-1, r1-0-2], rv2: [r2-0-2]
assertEquals(newHashSet(rev12), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev12), newHashSet(rv2.pmin(rv1)));
rv2 = rv2.update(rev11);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev11, rev12), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev11, rev12), newHashSet(rv2.pmin(rv1)));
rv1 = rv1.update(rev21);
// rv1: [r2-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev11, rev12), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev11, rev12), newHashSet(rv2.pmin(rv1)));
rv1 = rv1.update(rev22);
// rv1: [r2-0-1, r2-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev11, rev22), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev11, rev22), newHashSet(rv2.pmin(rv1)));
rv2 = rv2.update(rev21);
// rv1: [r2-0-1, r2-0-2], rv2: [r2-0-1, r2-0-2]
assertEquals(newHashSet(rev21, rev22), newHashSet(rv1.pmin(rv2)));
assertEquals(newHashSet(rev21, rev22), newHashSet(rv2.pmin(rv1)));
}
@Test
public void pmax() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(newHashSet(), newHashSet(rv1.pmax(rv2)));
Revision rev11 = new Revision(1, 0, 1);
Revision rev21 = new Revision(2, 0, 1);
Revision rev12 = new Revision(1, 0, 2);
Revision rev22 = new Revision(2, 0, 2);
rv1 = rv1.update(rev11);
// rv1: [r1-0-1], rv2: []
assertEquals(newHashSet(rev11), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11), newHashSet(rv2.pmax(rv1)));
rv2 = rv2.update(rev12);
// rv1: [r1-0-1], rv2: [r1-0-2]
assertEquals(newHashSet(rev11, rev12), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11, rev12), newHashSet(rv2.pmax(rv1)));
rv1 = rv1.update(rev12);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-2]
assertEquals(newHashSet(rev11, rev12), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11, rev12), newHashSet(rv2.pmax(rv1)));
rv2 = rv2.update(rev22);
// rv1: [r1-0-1, r1-0-2], rv2: [r2-0-2]
assertEquals(newHashSet(rev11, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11, rev22), newHashSet(rv2.pmax(rv1)));
rv2 = rv2.update(rev11);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev11, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev11, rev22), newHashSet(rv2.pmax(rv1)));
rv1 = rv1.update(rev21);
// rv1: [r2-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev21, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev21, rev22), newHashSet(rv2.pmax(rv1)));
rv1 = rv1.update(rev22);
// rv1: [r2-0-1, r2-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(newHashSet(rev21, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev21, rev22), newHashSet(rv2.pmax(rv1)));
rv2 = rv2.update(rev21);
// rv1: [r2-0-1, r2-0-2], rv2: [r2-0-1, r2-0-2]
assertEquals(newHashSet(rev21, rev22), newHashSet(rv1.pmax(rv2)));
assertEquals(newHashSet(rev21, rev22), newHashSet(rv2.pmax(rv1)));
}
@Test
public void difference() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(new RevisionVector(), rv1.difference(rv2));
Revision r11 = new Revision(1, 0, 1);
rv1 = rv1.update(r11);
// rv1: [r1-0-1]
assertEquals(new RevisionVector(r11), rv1.difference(rv2));
assertEquals(new RevisionVector(), rv2.difference(rv1));
rv2 = rv2.update(r11);
// rv1: [r1-0-1], rv2: [r1-0-1]
assertEquals(new RevisionVector(), rv1.difference(rv2));
assertEquals(new RevisionVector(), rv2.difference(rv1));
Revision r12 = new Revision(1, 0, 2);
rv1 = rv1.update(r12);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-1]
assertEquals(new RevisionVector(r12), rv1.difference(rv2));
assertEquals(new RevisionVector(), rv2.difference(rv1));
Revision r22 = new Revision(2, 0, 2);
rv2 = rv2.update(r22);
// rv1: [r1-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(new RevisionVector(r12), rv1.difference(rv2));
assertEquals(new RevisionVector(r22), rv2.difference(rv1));
Revision r21 = new Revision(2, 0, 1);
rv1 = rv1.update(r21);
// rv1: [r2-0-1, r1-0-2], rv2: [r1-0-1, r2-0-2]
assertEquals(new RevisionVector(r21, r12), rv1.difference(rv2));
assertEquals(new RevisionVector(r11, r22), rv2.difference(rv1));
}
@Test
public void isBranch() {
RevisionVector rv = new RevisionVector();
assertFalse(rv.isBranch());
Revision r1 = new Revision(1, 0, 1);
rv = rv.update(r1);
assertFalse(rv.isBranch());
Revision r2 = new Revision(1, 0, 2, true);
rv = rv.update(r2);
assertTrue(rv.isBranch());
}
@Test
public void getBranchRevision() {
Revision r1 = new Revision(1, 0, 1);
Revision r2 = new Revision(1, 0, 2, true);
RevisionVector rv = new RevisionVector(r1, r2);
assertEquals(r2, rv.getBranchRevision());
}
@Test(expected = IllegalStateException.class)
public void exceptionOnGetBranchRevision() {
RevisionVector rv = new RevisionVector();
rv.getBranchRevision();
}
@Test
public void compareTo() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(0, rv1.compareTo(rv2));
Revision r11 = new Revision(1, 0, 1);
rv1 = rv1.update(r11); // [r1-0-1]
assertTrue(rv1.compareTo(rv2) > 0);
assertTrue(rv2.compareTo(rv1) < 0);
Revision r12 = new Revision(1, 0, 2);
rv2 = rv2.update(r12); // [r1-0-2]
assertTrue(rv1.compareTo(rv2) > 0);
assertTrue(rv2.compareTo(rv1) < 0);
rv2 = rv2.update(r11); // [r1-0-1, r1-0-2]
assertTrue(rv1.compareTo(rv2) < 0);
assertTrue(rv2.compareTo(rv1) > 0);
rv1 = rv1.update(r12); // [r1-0-1, r1-0-2]
assertEquals(0, rv1.compareTo(rv2));
assertEquals(0, rv2.compareTo(rv1));
Revision r22 = new Revision(2, 0, 2);
rv2 = rv2.update(r22); // [r1-0-1, r2-0-2]
assertTrue(rv1.compareTo(rv2) < 0);
assertTrue(rv2.compareTo(rv1) > 0);
Revision rb22 = r22.asBranchRevision();
rv1 = rv1.update(rb22);
assertTrue(rv1.compareTo(rv2) < 0);
assertTrue(rv2.compareTo(rv1) > 0);
}
@Test
public void equals() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(rv1, rv2);
Revision r11 = new Revision(1, 0, 1);
rv1 = rv1.update(r11);
assertNotEquals(rv1, rv2);
rv2 = rv2.update(r11);
assertEquals(rv1, rv2);
Revision r12 = new Revision(1, 0, 2);
rv1 = rv1.update(r12);
assertNotEquals(rv1, rv2);
rv2 = rv2.update(r12);
assertEquals(rv1, rv2);
//Check basic cases which are short circuited
assertEquals(rv1, rv1);
assertNotEquals(rv1, null);
assertNotEquals(rv1, new Object());
}
@Test
public void hashCodeTest() {
RevisionVector rv1 = new RevisionVector();
RevisionVector rv2 = new RevisionVector();
assertEquals(rv1.hashCode(), rv2.hashCode());
//Check again once lazily initialized hash is initialized
assertEquals(rv1.hashCode(), rv2.hashCode());
Revision r11 = new Revision(1, 0, 1);
rv1 = rv1.update(r11);
rv2 = rv2.update(r11);
assertEquals(rv1.hashCode(), rv2.hashCode());
Revision r12 = new Revision(1, 0, 2);
rv1 = rv1.update(r12);
rv2 = rv2.update(r12);
assertEquals(rv1.hashCode(), rv2.hashCode());
}
@Test
public void getRevision() {
RevisionVector rv = new RevisionVector();
assertNull(rv.getRevision(1));
Revision r11 = new Revision(1, 0, 1);
rv = rv.update(r11);
assertEquals(r11, rv.getRevision(1));
assertNull(rv.getRevision(2));
Revision r13 = new Revision(1, 0, 3);
rv = rv.update(r13);
assertEquals(r13, rv.getRevision(3));
assertNull(rv.getRevision(2));
}
@Test
public void asTrunkRevision() {
RevisionVector rv = new RevisionVector();
assertFalse(rv.asTrunkRevision().isBranch());
rv = rv.update(new Revision(1, 0, 1, true));
assertTrue(rv.isBranch());
assertFalse(rv.asTrunkRevision().isBranch());
}
@Test(expected = IllegalArgumentException.class)
public void asBranchRevision1() {
new RevisionVector().asBranchRevision(1);
}
@Test(expected = IllegalArgumentException.class)
public void asBranchRevision2() {
new RevisionVector(new Revision(1, 0, 1)).asBranchRevision(2);
}
@Test
public void asBranchRevision3() {
Revision r11 = new Revision(1, 0, 1);
Revision br11 = r11.asBranchRevision();
RevisionVector rv = new RevisionVector(r11);
assertEquals(new RevisionVector(br11), rv.asBranchRevision(1));
rv = rv.asTrunkRevision();
Revision r12 = new Revision(1, 0, 2);
rv = rv.update(r12);
assertEquals(new RevisionVector(br11, r12), rv.asBranchRevision(1));
}
@Test
public void fromString() throws Exception{
RevisionVector rv = new RevisionVector(
new Revision(1, 0, 1),
new Revision(2, 0, 2)
);
String rvstr = rv.asString();
RevisionVector rvFromStr = RevisionVector.fromString(rvstr);
assertEquals(rv, rvFromStr);
}
@Test
public void toStringBuilder() throws Exception {
RevisionVector rv = new RevisionVector();
StringBuilder sb = new StringBuilder();
rv.toStringBuilder(sb);
assertEquals("", sb.toString());
rv = new RevisionVector(
new Revision(1, 0, 1),
new Revision(2, 0, 2)
);
rv.toStringBuilder(sb);
assertEquals(rv.toString(), sb.toString());
}
@Test
public void getDimensions() throws Exception {
RevisionVector rv = new RevisionVector();
assertEquals(0, rv.getDimensions());
rv = new RevisionVector(
new Revision(1, 0, 1),
new Revision(2, 0, 2)
);
assertEquals(2, rv.getDimensions());
rv = rv.remove(1);
assertEquals(1, rv.getDimensions());
}
}
| OAK-7176: RevisionVector from empty string throws StringIndexOutOfBoundsException
Add ignored test
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1821477 13f79535-47bb-0310-9956-ffa450edef68
| oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/RevisionVectorTest.java | OAK-7176: RevisionVector from empty string throws StringIndexOutOfBoundsException |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.