answer
stringlengths 17
10.2M
|
|---|
package team.creative.creativecore.common.util.math.box;
import com.mojang.math.Vector3d;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Vec3i;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import team.creative.creativecore.common.util.math.base.Axis;
import team.creative.creativecore.common.util.math.base.Facing;
import team.creative.creativecore.common.util.math.matrix.Matrix3;
import team.creative.creativecore.common.util.math.transformation.Rotation;
import team.creative.creativecore.common.util.math.vec.Vec3f;
public class AlignedBox {
public float minX;
public float minY;
public float minZ;
public float maxX;
public float maxY;
public float maxZ;
public AlignedBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
this.minX = minX;
this.minY = minY;
this.minZ = minZ;
this.maxX = maxX;
this.maxY = maxY;
this.maxZ = maxZ;
}
public AlignedBox(AABB box) {
this((float) box.minX, (float) box.minY, (float) box.minZ, (float) box.maxX, (float) box.maxY, (float) box.maxZ);
}
public AlignedBox() {
this(0, 0, 0, 1, 1, 1);
}
public AlignedBox(AlignedBox cube) {
this(cube.minX, cube.minY, cube.minZ, cube.maxX, cube.maxY, cube.maxZ);
}
public void add(float x, float y, float z) {
this.minX += x;
this.minY += y;
this.minZ += z;
this.maxX += x;
this.maxY += y;
this.maxZ += z;
}
public void sub(float x, float y, float z) {
this.minX -= x;
this.minY -= y;
this.minZ -= z;
this.maxX -= x;
this.maxY -= y;
this.maxZ -= z;
}
public void add(Vector3d vec) {
add((float) vec.x, (float) vec.y, (float) vec.z);
}
public void sub(Vector3d vec) {
sub((float) vec.x, (float) vec.y, (float) vec.z);
}
public void add(Vec3i vec) {
add(vec.getX(), vec.getY(), vec.getZ());
}
public void sub(Vec3i vec) {
sub(vec.getX(), vec.getY(), vec.getZ());
}
public void scale(float scale) {
this.minX *= scale;
this.minY *= scale;
this.minZ *= scale;
this.maxX *= scale;
this.maxY *= scale;
this.maxZ *= scale;
}
public Vector3d getSize() {
return new Vector3d(maxX - minX, maxY - minY, maxZ - minZ);
}
public Vector3d getCenter() {
return new Vector3d((maxX + minX) * 0.5, (maxY + minY) * 0.5, (maxZ + minZ) * 0.5);
}
@Override
public String toString() {
return "cube[" + this.minX + ", " + this.minY + ", " + this.minZ + " -> " + this.maxX + ", " + this.maxY + ", " + this.maxZ + "]";
}
public Vec3f getCorner(BoxCorner corner) {
return new Vec3f(get(corner.x), get(corner.y), get(corner.z));
}
public AABB getBB() {
return new AABB(minX, minY, minZ, maxX, maxY, maxZ);
}
public AABB getBB(BlockPos pos) {
return new AABB(minX + pos.getX(), minY + pos.getY(), minZ + pos.getZ(), maxX + pos.getX(), maxY + pos.getY(), maxZ + pos.getZ());
}
public VoxelShape voxelShape() {
return Shapes.box(minX, minY, minZ, maxX, maxY, maxZ);
}
public VoxelShape voxelShape(BlockPos pos) {
return Shapes.box(minX + pos.getX(), minY + pos.getY(), minZ + pos.getZ(), maxX + pos.getX(), maxY + pos.getY(), maxZ + pos.getZ());
}
public void rotate(Rotation rotation, Vec3f center) {
Vec3f low = new Vec3f(minX, minY, minZ);
Vec3f high = new Vec3f(maxX, maxY, maxZ);
low.sub(center);
high.sub(center);
rotation.getMatrix().transform(low);
rotation.getMatrix().transform(high);
low.add(center);
high.add(center);
set(low.x, low.y, low.z, high.x, high.y, high.z);
}
public void rotate(Matrix3 matrix, Vec3f center) {
Vec3f low = new Vec3f(minX, minY, minZ);
Vec3f high = new Vec3f(maxX, maxY, maxZ);
low.sub(center);
high.sub(center);
matrix.transform(low);
matrix.transform(high);
low.add(center);
high.add(center);
set(low.x, low.y, low.z, high.x, high.y, high.z);
}
public void set(float x, float y, float z, float x2, float y2, float z2) {
this.minX = Math.min(x, x2);
this.minY = Math.min(y, y2);
this.minZ = Math.min(z, z2);
this.maxX = Math.max(x, x2);
this.maxY = Math.max(y, y2);
this.maxZ = Math.max(z, z2);
}
public BlockPos getOffset() {
return new BlockPos(minX, minY, minZ);
}
public float get(Facing facing) {
switch (facing) {
case EAST:
return maxX;
case WEST:
return minX;
case UP:
return maxY;
case DOWN:
return minY;
case SOUTH:
return maxZ;
case NORTH:
return minZ;
}
return 0;
}
public float getSize(Axis axis) {
switch (axis) {
case X:
return maxX - minX;
case Y:
return maxY - minY;
case Z:
return maxZ - minZ;
}
return 0;
}
public void setMin(Axis axis, float value) {
switch (axis) {
case X:
minX = value;
break;
case Y:
minY = value;
break;
case Z:
minZ = value;
break;
}
}
public float getMin(Axis axis) {
switch (axis) {
case X:
return minX;
case Y:
return minY;
case Z:
return minZ;
}
return 0;
}
public void setMax(Axis axis, float value) {
switch (axis) {
case X:
maxX = value;
break;
case Y:
maxY = value;
break;
case Z:
maxZ = value;
break;
}
}
public float getMax(Axis axis) {
switch (axis) {
case X:
return maxX;
case Y:
return maxY;
case Z:
return maxZ;
}
return 0;
}
public void grow(Axis axis, float value) {
value /= 2;
setMin(axis, getMin(axis) - value);
setMax(axis, getMax(axis) + value);
}
public void shrink(Axis axis, float value) {
value /= 2;
setMin(axis, getMin(axis) + value);
setMax(axis, getMax(axis) - value);
}
}
|
package modules;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import extras.urlparsers.YoutubeParser;
import bot.Message;
import bot.config.Config;
public class Youtube implements Module {
@Override
public void parse(Message m) {
String target = m.param();
if(!m.param().startsWith("#")) target = m.sender();
if(m.botCommand().equals("yt") || m.botCommand().equals("youtube")){
if(m.botParamsArray().length == 0)return;
String query = m.botParams().replace(" ", "_");
try {
URL url = new URL("https:
InputStream in = url.openStream();
Scanner scan = new Scanner(in);
String jsonstring = "";
while(scan.hasNext()){
jsonstring += scan.next() + " ";
}
scan.close();
Gson gson = new GsonBuilder().create();
JsonObject json = gson.fromJson(jsonstring, JsonElement.class).getAsJsonObject();
JsonObject items = json.get("items").getAsJsonArray().get(0).getAsJsonObject();
JsonObject id = items.get("id").getAsJsonObject();
String videoId = id.get("videoId").getAsString();
String title = "https://youtu.be/" + videoId + " | " + YoutubeParser.findById(videoId);
m.say(target, title);
} catch (IOException e) {
e.printStackTrace();
}
catch(IndexOutOfBoundsException e){
m.say(target,"No results found for " + m.botParams());
}
}
}
}
|
package org.openspaces.admin.internal.gsm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import net.jini.core.discovery.LookupLocator;
import net.jini.core.lookup.ServiceID;
import org.jini.rio.core.OperationalString;
import org.jini.rio.monitor.DeployAdmin;
import org.jini.rio.monitor.ProvisionMonitorAdmin;
import org.jini.rio.resources.servicecore.ServiceAdmin;
import org.openspaces.admin.AdminException;
import org.openspaces.admin.dump.DumpResult;
import org.openspaces.admin.gsc.GridServiceContainer;
import org.openspaces.admin.internal.admin.InternalAdmin;
import org.openspaces.admin.internal.dump.InternalDumpResult;
import org.openspaces.admin.internal.esm.InternalElasticServiceManager;
import org.openspaces.admin.internal.gsc.InternalGridServiceContainer;
import org.openspaces.admin.internal.pu.InternalProcessingUnitInstance;
import org.openspaces.admin.internal.support.AbstractAgentGridComponent;
import org.openspaces.admin.internal.support.NetworkExceptionHelper;
import org.openspaces.admin.memcached.MemcachedDeployment;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.pu.ProcessingUnitAlreadyDeployedException;
import org.openspaces.admin.pu.ProcessingUnitDeployment;
import org.openspaces.admin.pu.ProcessingUnitInstance;
import org.openspaces.admin.pu.elastic.ElasticStatefulProcessingUnitDeployment;
import org.openspaces.admin.pu.events.ProcessingUnitAddedEventListener;
import org.openspaces.admin.space.ElasticDataGridDeployment;
import org.openspaces.admin.space.SpaceDeployment;
import org.openspaces.pu.container.servicegrid.deploy.Deploy;
import com.gigaspaces.grid.gsm.GSM;
import com.gigaspaces.internal.jvm.JVMDetails;
import com.gigaspaces.internal.jvm.JVMStatistics;
import com.gigaspaces.internal.os.OSDetails;
import com.gigaspaces.internal.os.OSStatistics;
import com.gigaspaces.log.LogEntries;
import com.gigaspaces.log.LogEntryMatcher;
import com.gigaspaces.log.LogProcessType;
import com.gigaspaces.lrmi.nio.info.NIODetails;
import com.gigaspaces.lrmi.nio.info.NIOStatistics;
import com.gigaspaces.security.SecurityException;
/**
* @author kimchy
*/
public class DefaultGridServiceManager extends AbstractAgentGridComponent implements InternalGridServiceManager {
private final ServiceID serviceID;
private final GSM gsm;
private final ProvisionMonitorAdmin gsmAdmin;
public DefaultGridServiceManager(ServiceID serviceID, GSM gsm, InternalAdmin admin, int agentId, String agentUid)
throws RemoteException {
super(admin, agentId, agentUid);
this.serviceID = serviceID;
this.gsm = gsm;
this.gsmAdmin = (ProvisionMonitorAdmin) gsm.getAdmin();
}
public String getUid() {
return serviceID.toString();
}
public ServiceID getServiceID() {
return this.serviceID;
}
public GSM getGSM() {
return this.gsm;
}
public ProvisionMonitorAdmin getGSMAdmin() {
return gsmAdmin;
}
public ProcessingUnit deploy(SpaceDeployment deployment) {
return deploy(deployment, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit());
}
public ProcessingUnit deploy(SpaceDeployment deployment, long timeout, TimeUnit timeUnit) {
return deploy(deployment.toProcessingUnitDeployment(), timeout, timeUnit);
}
public ProcessingUnit deploy(ProcessingUnitDeployment deployment) {
return deploy(deployment, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit());
}
public ProcessingUnit deploy(MemcachedDeployment deployment) {
return deploy(deployment, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit());
}
public ProcessingUnit deploy(MemcachedDeployment deployment, long timeout, TimeUnit timeUnit) {
return deploy(deployment.toProcessingUnitDeployment(), timeout, timeUnit);
}
public ProcessingUnit deploy(ProcessingUnitDeployment deployment, long timeout, TimeUnit timeUnit) {
Deploy deploy = new Deploy();
Deploy.setDisableInfoLogging(true);
deploy.setGroups(getAdmin().getGroups());
StringBuilder locatorsString = new StringBuilder();
for (LookupLocator locator : getAdmin().getLocators()) {
locatorsString.append(locator).append(',');
}
deploy.setLocators(locatorsString.toString());
deploy.initializeDiscovery(gsm);
if (deployment.isSecured() != null) {
deploy.setSecured(deployment.isSecured());
}
deploy.setUserDetails(deployment.getUserDetails());
final OperationalString operationalString;
try {
operationalString = deploy.buildOperationalString(deployment.getDeploymentOptions());
} catch (Exception e) {
throw new AdminException("Failed to deploy [" + deployment.getProcessingUnit() + "]", e);
}
try {
if (getGSMAdmin().hasDeployed(operationalString.getName())) {
throw new ProcessingUnitAlreadyDeployedException(operationalString.getName());
}
}
catch (ProcessingUnitAlreadyDeployedException e) {
throw e;
}
catch (Exception e) {
throw new AdminException("Failed to check if processing unit [" + operationalString.getName() + "] is deployed", e);
}
final AtomicReference<ProcessingUnit> ref = new AtomicReference<ProcessingUnit>();
ref.set(getAdmin().getProcessingUnits().getProcessingUnit(operationalString.getName()));
if (ref.get() != null) {
return ref.get();
}
final CountDownLatch latch = new CountDownLatch(1);
ProcessingUnitAddedEventListener added = new ProcessingUnitAddedEventListener() {
public void processingUnitAdded(ProcessingUnit processingUnit) {
if (operationalString.getName().equals(processingUnit.getName())) {
ref.set(processingUnit);
latch.countDown();
}
}
};
getAdmin().getProcessingUnits().getProcessingUnitAdded().add(added);
ProcessingUnit pu = null;
try {
getGSMAdmin().deploy(operationalString);
latch.await(timeout, timeUnit);
pu = ref.get();
} catch (SecurityException se) {
throw new AdminException("No privileges to deploy a processing unit", se);
} catch (Exception e) {
throw new AdminException("Failed to deploy [" + deployment.getProcessingUnit() + "]", e);
} finally {
Deploy.setDisableInfoLogging(false);
getAdmin().getProcessingUnits().getProcessingUnitAdded().remove(added);
}
// set dynamic properties
Map<String,String> elasticConfig = deployment.getElasticProperties();
if (elasticConfig.size() > 0) {
setProcessingUnitElasticProperties(pu, elasticConfig);
}
return pu;
}
public void undeploy(String processingUnitName) {
undeployProcessingUnit(processingUnitName);
}
public void undeployProcessingUnit(String processingUnitName) {
try {
getGSMAdmin().undeploy(processingUnitName);
} catch (SecurityException se) {
throw new AdminException("No privileges to undeploy a processing unit", se);
} catch (Exception e) {
throw new AdminException("Failed to undeploy processing unit [" + processingUnitName + "]", e);
}
}
public void destroyInstance(ProcessingUnitInstance processingUnitInstance) {
try {
gsm.destroy(processingUnitInstance.getProcessingUnit().getName(), ((InternalProcessingUnitInstance) processingUnitInstance).getServiceID());
} catch (SecurityException se) {
throw new AdminException("No privileges to destroy a processing unit instance", se);
} catch (Exception e) {
if (NetworkExceptionHelper.isConnectOrCloseException(e)) {
// all is well
} else {
throw new AdminException("Failed to destroy processing unit instance", e);
}
}
}
public void decrementInstance(ProcessingUnitInstance processingUnitInstance) {
if (!processingUnitInstance.getProcessingUnit().canDecrementInstance()) {
throw new AdminException("Processing unit does not allow to decrement instances on it");
}
try {
gsm.decrement(processingUnitInstance.getProcessingUnit().getName(), ((InternalProcessingUnitInstance) processingUnitInstance).getServiceID(), true);
} catch (SecurityException se) {
throw new AdminException("No privileges to decrement a processing unit instance", se);
} catch (Exception e) {
if (NetworkExceptionHelper.isConnectOrCloseException(e)) {
// all is well
} else {
throw new AdminException("Failed to destroy processing unit instance", e);
}
}
}
public void incrementInstance(ProcessingUnit processingUnit) {
if (!processingUnit.canIncrementInstance()) {
throw new AdminException("Processing unit does not allow to increment instances on it");
}
try {
gsm.increment(processingUnit.getName(), null);
} catch (SecurityException se) {
throw new AdminException("No privileges to increment a processing unit instance", se);
} catch (Exception e) {
if (NetworkExceptionHelper.isConnectOrCloseException(e)) {
// all is well
} else {
throw new AdminException("Failed to destroy processing unit instance", e);
}
}
}
/**
* @param processingUnitInstance The processing unit instance to relocate
* @param gridServiceContainer The GSC to relocate to, or <code>null</code> if the GSM should decide on a
* suitable GSC to relocate to.
*/
public void relocate(ProcessingUnitInstance processingUnitInstance, GridServiceContainer gridServiceContainer) {
try {
gsm.relocate(
processingUnitInstance.getProcessingUnit().getName(),
((InternalProcessingUnitInstance) processingUnitInstance).getServiceID(),
(gridServiceContainer == null ? null : ((InternalGridServiceContainer) gridServiceContainer).getServiceID()),
null);
} catch (SecurityException se) {
throw new AdminException("No privileges to relocate a processing unit instance", se);
} catch (Exception e) {
throw new AdminException("Failed to relocate processing unit instance to grid service container", e);
}
}
public LogEntries logEntries(LogEntryMatcher matcher) throws AdminException {
if (getGridServiceAgent() != null) {
return getGridServiceAgent().logEntries(LogProcessType.GSM, getVirtualMachine().getDetails().getPid(), matcher);
}
return logEntriesDirect(matcher);
}
public LogEntries logEntriesDirect(LogEntryMatcher matcher) throws AdminException {
try {
return gsm.logEntriesDirect(matcher);
} catch (IOException e) {
throw new AdminException("Failed to get log", e);
}
}
public DumpResult generateDump(String cause, Map<String, Object> context) throws AdminException {
try {
return new InternalDumpResult(this, gsm, gsm.generateDump(cause, context));
} catch (Exception e) {
throw new AdminException("Failed to generate dump", e);
}
}
public DumpResult generateDump(String cause, Map<String, Object> context, String... processors) throws AdminException {
try {
return new InternalDumpResult(this, gsm, gsm.generateDump(cause, context, processors));
} catch (Exception e) {
throw new AdminException("Failed to generate dump", e);
}
}
// NIO, OS, and JVM stats
public NIODetails getNIODetails() throws RemoteException {
return gsm.getNIODetails();
}
public NIOStatistics getNIOStatistics() throws RemoteException {
return gsm.getNIOStatistics();
}
public long getCurrentTimeInMillis() throws RemoteException {
return gsm.getCurrentTimestamp();
}
public OSDetails getOSDetails() throws RemoteException {
return gsm.getOSDetails();
}
public OSStatistics getOSStatistics() throws RemoteException {
return gsm.getOSStatistics();
}
public JVMDetails getJVMDetails() throws RemoteException {
return gsm.getJVMDetails();
}
public JVMStatistics getJVMStatistics() throws RemoteException {
return gsm.getJVMStatistics();
}
public void runGc() throws RemoteException {
gsm.runGc();
}
public String[] listDeployDir() {
List<String> result = new ArrayList<String>();
try{
URL listPU = new URL( new URL(getCodebase( gsmAdmin )), "list-pu" );
BufferedReader reader =
new BufferedReader( new InputStreamReader( listPU.openStream() ) );
String line;
while ((line = reader.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(line, "\t");
String puName = tokenizer.nextToken();
result.add( puName );
}
}
catch( IOException io ){
throw new AdminException( "Failed to retrive processing units available " +
"under [GS ROOT]/deploy directory", io );
}
return result.toArray( new String[ 0 ] );
}
private String getCodebase(DeployAdmin deployAdmin) throws MalformedURLException, RemoteException {
URL url = ((ServiceAdmin) deployAdmin).getServiceElement().getExportURLs()[0];
return url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + "/";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DefaultGridServiceManager that = (DefaultGridServiceManager) o;
return serviceID.equals(that.serviceID);
}
@Override
public int hashCode() {
return serviceID.hashCode();
}
public boolean isDeployed(String processingUnitName) {
try{
return gsmAdmin.hasDeployed( processingUnitName );
}
catch (Exception e) {
throw new AdminException( "Failed to check if processing unit [" +
processingUnitName + "] deployed", e);
}
}
public ProcessingUnit deploy(ElasticDataGridDeployment deployment) throws ProcessingUnitAlreadyDeployedException {
return deploy(deployment.toElasticStatefulProcessingUnitDeployment());
}
public ProcessingUnit deploy(ElasticDataGridDeployment deployment, long timeout, TimeUnit timeUnit)
throws ProcessingUnitAlreadyDeployedException {
return deploy(deployment.toElasticStatefulProcessingUnitDeployment(),timeout,timeUnit);
}
public ProcessingUnit deploy(ElasticStatefulProcessingUnitDeployment deployment)
throws ProcessingUnitAlreadyDeployedException {
return deploy(deployment,admin.getDefaultTimeout(),admin.getDefaultTimeoutTimeUnit());
}
public ProcessingUnit deploy(ElasticStatefulProcessingUnitDeployment deployment, long timeout, TimeUnit timeUnit)
throws ProcessingUnitAlreadyDeployedException {
throw new UnsupportedOperationException("Feature not supported in RC1");
//return deploy(deployment.toProcessingUnitDeployment(),timeout,timeUnit);
}
public boolean isRunning() {
return admin.getGridServiceManagers().getManagerByUID(getUid()) != null;
}
public Map<String,String> getProcessingUnitElasticProperties(ProcessingUnit pu) {
//TODO: Read the data from the gsm server.
return getElasticServiceManager().getProcessingUnitElasticProperties(pu);
}
public void setProcessingUnitElasticProperties(ProcessingUnit pu, Map<String,String> properties) {
//TODO: Store the data in the gsm server.
getElasticServiceManager().setProcessingUnitElasticProperties(pu, properties);
}
private InternalElasticServiceManager getElasticServiceManager() {
if (admin.getElasticServiceManagers().getSize() != 1) {
throw new AdminException("ElasticScaleHandler requires exactly one ESM server running.");
}
final InternalElasticServiceManager esm = (InternalElasticServiceManager) admin.getElasticServiceManagers().getManagers()[0];
return esm;
}
}
|
package org.openspaces.admin.internal.gsm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import net.jini.core.discovery.LookupLocator;
import net.jini.core.lookup.ServiceID;
import org.jini.rio.core.OperationalString;
import org.jini.rio.monitor.DeployAdmin;
import org.jini.rio.monitor.ProvisionMonitorAdmin;
import org.jini.rio.resources.servicecore.ServiceAdmin;
import org.openspaces.admin.AdminException;
import org.openspaces.admin.dump.DumpResult;
import org.openspaces.admin.gsc.GridServiceContainer;
import org.openspaces.admin.internal.admin.InternalAdmin;
import org.openspaces.admin.internal.dump.InternalDumpResult;
import org.openspaces.admin.internal.esm.InternalElasticServiceManager;
import org.openspaces.admin.internal.gsc.InternalGridServiceContainer;
import org.openspaces.admin.internal.pu.InternalProcessingUnitInstance;
import org.openspaces.admin.internal.support.AbstractAgentGridComponent;
import org.openspaces.admin.internal.support.NetworkExceptionHelper;
import org.openspaces.admin.memcached.MemcachedDeployment;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.pu.ProcessingUnitAlreadyDeployedException;
import org.openspaces.admin.pu.ProcessingUnitDeployment;
import org.openspaces.admin.pu.ProcessingUnitInstance;
import org.openspaces.admin.pu.elastic.ElasticStatefulProcessingUnitDeployment;
import org.openspaces.admin.pu.events.ProcessingUnitAddedEventListener;
import org.openspaces.admin.space.ElasticDataGridDeployment;
import org.openspaces.admin.space.SpaceDeployment;
import org.openspaces.pu.container.servicegrid.deploy.Deploy;
import com.gigaspaces.grid.gsm.GSM;
import com.gigaspaces.internal.jvm.JVMDetails;
import com.gigaspaces.internal.jvm.JVMStatistics;
import com.gigaspaces.internal.os.OSDetails;
import com.gigaspaces.internal.os.OSStatistics;
import com.gigaspaces.log.LogEntries;
import com.gigaspaces.log.LogEntryMatcher;
import com.gigaspaces.log.LogProcessType;
import com.gigaspaces.lrmi.nio.info.NIODetails;
import com.gigaspaces.lrmi.nio.info.NIOStatistics;
import com.gigaspaces.security.SecurityException;
/**
* @author kimchy
*/
public class DefaultGridServiceManager extends AbstractAgentGridComponent implements InternalGridServiceManager {
private final ServiceID serviceID;
private final GSM gsm;
private final ProvisionMonitorAdmin gsmAdmin;
public DefaultGridServiceManager(ServiceID serviceID, GSM gsm, InternalAdmin admin, int agentId, String agentUid)
throws RemoteException {
super(admin, agentId, agentUid);
this.serviceID = serviceID;
this.gsm = gsm;
this.gsmAdmin = (ProvisionMonitorAdmin) gsm.getAdmin();
}
public String getUid() {
return serviceID.toString();
}
public ServiceID getServiceID() {
return this.serviceID;
}
public GSM getGSM() {
return this.gsm;
}
public ProvisionMonitorAdmin getGSMAdmin() {
return gsmAdmin;
}
public ProcessingUnit deploy(SpaceDeployment deployment) {
return deploy(deployment, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit());
}
public ProcessingUnit deploy(SpaceDeployment deployment, long timeout, TimeUnit timeUnit) {
return deploy(deployment.toProcessingUnitDeployment(), timeout, timeUnit);
}
public ProcessingUnit deploy(ProcessingUnitDeployment deployment) {
return deploy(deployment, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit());
}
public ProcessingUnit deploy(MemcachedDeployment deployment) {
return deploy(deployment, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit());
}
public ProcessingUnit deploy(MemcachedDeployment deployment, long timeout, TimeUnit timeUnit) {
return deploy(deployment.toProcessingUnitDeployment(), timeout, timeUnit);
}
public ProcessingUnit deploy(ProcessingUnitDeployment deployment, long timeout, TimeUnit timeUnit) {
Deploy deploy = new Deploy();
Deploy.setDisableInfoLogging(true);
deploy.setGroups(getAdmin().getGroups());
StringBuilder locatorsString = new StringBuilder();
for (LookupLocator locator : getAdmin().getLocators()) {
locatorsString.append(locator).append(',');
}
deploy.setLocators(locatorsString.toString());
deploy.initializeDiscovery(gsm);
if (deployment.isSecured() != null) {
deploy.setSecured(deployment.isSecured());
}
deploy.setUserDetails(deployment.getUserDetails());
final OperationalString operationalString;
try {
operationalString = deploy.buildOperationalString(deployment.getDeploymentOptions());
} catch (Exception e) {
throw new AdminException("Failed to deploy [" + deployment.getProcessingUnit() + "]", e);
}
try {
if (getGSMAdmin().hasDeployed(operationalString.getName())) {
throw new ProcessingUnitAlreadyDeployedException(operationalString.getName());
}
}
catch (ProcessingUnitAlreadyDeployedException e) {
// re-set dynamic properties (ESM)
Map<String,String> elasticConfig = deployment.getElasticProperties();
ProcessingUnit pu = admin.getProcessingUnits().getProcessingUnit(operationalString.getName());
if (pu != null && elasticConfig.size() > 0) {
setProcessingUnitElasticProperties(pu, elasticConfig);
}
throw e;
}
catch (Exception e) {
throw new AdminException("Failed to check if processing unit [" + operationalString.getName() + "] is deployed", e);
}
final AtomicReference<ProcessingUnit> ref = new AtomicReference<ProcessingUnit>();
ref.set(getAdmin().getProcessingUnits().getProcessingUnit(operationalString.getName()));
if (ref.get() != null) {
return ref.get();
}
final CountDownLatch latch = new CountDownLatch(1);
ProcessingUnitAddedEventListener added = new ProcessingUnitAddedEventListener() {
public void processingUnitAdded(ProcessingUnit processingUnit) {
if (operationalString.getName().equals(processingUnit.getName())) {
ref.set(processingUnit);
latch.countDown();
}
}
};
getAdmin().getProcessingUnits().getProcessingUnitAdded().add(added);
ProcessingUnit pu = null;
try {
getGSMAdmin().deploy(operationalString);
latch.await(timeout, timeUnit);
pu = ref.get();
} catch (SecurityException se) {
throw new AdminException("No privileges to deploy a processing unit", se);
} catch (Exception e) {
throw new AdminException("Failed to deploy [" + deployment.getProcessingUnit() + "]", e);
} finally {
Deploy.setDisableInfoLogging(false);
getAdmin().getProcessingUnits().getProcessingUnitAdded().remove(added);
}
// set dynamic properties
Map<String,String> elasticConfig = deployment.getElasticProperties();
if (elasticConfig.size() > 0) {
setProcessingUnitElasticProperties(pu, elasticConfig);
}
return pu;
}
public void undeploy(String processingUnitName) {
undeployProcessingUnit(processingUnitName);
}
public void undeployProcessingUnit(String processingUnitName) {
try {
getGSMAdmin().undeploy(processingUnitName);
} catch (SecurityException se) {
throw new AdminException("No privileges to undeploy a processing unit", se);
} catch (Exception e) {
throw new AdminException("Failed to undeploy processing unit [" + processingUnitName + "]", e);
}
}
public void destroyInstance(ProcessingUnitInstance processingUnitInstance) {
try {
gsm.destroy(processingUnitInstance.getProcessingUnit().getName(), ((InternalProcessingUnitInstance) processingUnitInstance).getServiceID());
} catch (SecurityException se) {
throw new AdminException("No privileges to destroy a processing unit instance", se);
} catch (Exception e) {
if (NetworkExceptionHelper.isConnectOrCloseException(e)) {
// all is well
} else {
throw new AdminException("Failed to destroy processing unit instance", e);
}
}
}
public void decrementInstance(ProcessingUnitInstance processingUnitInstance) {
if (!processingUnitInstance.getProcessingUnit().canDecrementInstance()) {
throw new AdminException("Processing unit does not allow to decrement instances on it");
}
try {
gsm.decrement(processingUnitInstance.getProcessingUnit().getName(), ((InternalProcessingUnitInstance) processingUnitInstance).getServiceID(), true);
} catch (SecurityException se) {
throw new AdminException("No privileges to decrement a processing unit instance", se);
} catch (Exception e) {
if (NetworkExceptionHelper.isConnectOrCloseException(e)) {
// all is well
} else {
throw new AdminException("Failed to destroy processing unit instance", e);
}
}
}
public void incrementInstance(ProcessingUnit processingUnit) {
if (!processingUnit.canIncrementInstance()) {
throw new AdminException("Processing unit does not allow to increment instances on it");
}
try {
gsm.increment(processingUnit.getName(), null);
} catch (SecurityException se) {
throw new AdminException("No privileges to increment a processing unit instance", se);
} catch (Exception e) {
if (NetworkExceptionHelper.isConnectOrCloseException(e)) {
// all is well
} else {
throw new AdminException("Failed to destroy processing unit instance", e);
}
}
}
/**
* @param processingUnitInstance The processing unit instance to relocate
* @param gridServiceContainer The GSC to relocate to, or <code>null</code> if the GSM should decide on a
* suitable GSC to relocate to.
*/
public void relocate(ProcessingUnitInstance processingUnitInstance, GridServiceContainer gridServiceContainer) {
try {
gsm.relocate(
processingUnitInstance.getProcessingUnit().getName(),
((InternalProcessingUnitInstance) processingUnitInstance).getServiceID(),
(gridServiceContainer == null ? null : ((InternalGridServiceContainer) gridServiceContainer).getServiceID()),
null);
} catch (SecurityException se) {
throw new AdminException("No privileges to relocate a processing unit instance", se);
} catch (Exception e) {
throw new AdminException("Failed to relocate processing unit instance to grid service container", e);
}
}
public LogEntries logEntries(LogEntryMatcher matcher) throws AdminException {
if (getGridServiceAgent() != null) {
return getGridServiceAgent().logEntries(LogProcessType.GSM, getVirtualMachine().getDetails().getPid(), matcher);
}
return logEntriesDirect(matcher);
}
public LogEntries logEntriesDirect(LogEntryMatcher matcher) throws AdminException {
try {
return gsm.logEntriesDirect(matcher);
} catch (IOException e) {
throw new AdminException("Failed to get log", e);
}
}
public DumpResult generateDump(String cause, Map<String, Object> context) throws AdminException {
try {
return new InternalDumpResult(this, gsm, gsm.generateDump(cause, context));
} catch (Exception e) {
throw new AdminException("Failed to generate dump", e);
}
}
public DumpResult generateDump(String cause, Map<String, Object> context, String... processors) throws AdminException {
try {
return new InternalDumpResult(this, gsm, gsm.generateDump(cause, context, processors));
} catch (Exception e) {
throw new AdminException("Failed to generate dump", e);
}
}
// NIO, OS, and JVM stats
public NIODetails getNIODetails() throws RemoteException {
return gsm.getNIODetails();
}
public NIOStatistics getNIOStatistics() throws RemoteException {
return gsm.getNIOStatistics();
}
public long getCurrentTimeInMillis() throws RemoteException {
return gsm.getCurrentTimestamp();
}
public OSDetails getOSDetails() throws RemoteException {
return gsm.getOSDetails();
}
public OSStatistics getOSStatistics() throws RemoteException {
return gsm.getOSStatistics();
}
public JVMDetails getJVMDetails() throws RemoteException {
return gsm.getJVMDetails();
}
public JVMStatistics getJVMStatistics() throws RemoteException {
return gsm.getJVMStatistics();
}
public void runGc() throws RemoteException {
gsm.runGc();
}
public String[] listDeployDir() {
List<String> result = new ArrayList<String>();
try{
URL listPU = new URL( new URL(getCodebase( gsmAdmin )), "list-pu" );
BufferedReader reader =
new BufferedReader( new InputStreamReader( listPU.openStream() ) );
String line;
while ((line = reader.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(line, "\t");
String puName = tokenizer.nextToken();
result.add( puName );
}
}
catch( IOException io ){
throw new AdminException( "Failed to retrive processing units available " +
"under [GS ROOT]/deploy directory", io );
}
return result.toArray( new String[ 0 ] );
}
private String getCodebase(DeployAdmin deployAdmin) throws MalformedURLException, RemoteException {
URL url = ((ServiceAdmin) deployAdmin).getServiceElement().getExportURLs()[0];
return url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + "/";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DefaultGridServiceManager that = (DefaultGridServiceManager) o;
return serviceID.equals(that.serviceID);
}
@Override
public int hashCode() {
return serviceID.hashCode();
}
public boolean isDeployed(String processingUnitName) {
try{
return gsmAdmin.hasDeployed( processingUnitName );
}
catch (Exception e) {
throw new AdminException( "Failed to check if processing unit [" +
processingUnitName + "] deployed", e);
}
}
public ProcessingUnit deploy(ElasticDataGridDeployment deployment) throws ProcessingUnitAlreadyDeployedException {
return deploy(deployment.toElasticStatefulProcessingUnitDeployment());
}
public ProcessingUnit deploy(ElasticDataGridDeployment deployment, long timeout, TimeUnit timeUnit)
throws ProcessingUnitAlreadyDeployedException {
return deploy(deployment.toElasticStatefulProcessingUnitDeployment(),timeout,timeUnit);
}
public ProcessingUnit deploy(ElasticStatefulProcessingUnitDeployment deployment)
throws ProcessingUnitAlreadyDeployedException {
return deploy(deployment,admin.getDefaultTimeout(),admin.getDefaultTimeoutTimeUnit());
}
public ProcessingUnit deploy(ElasticStatefulProcessingUnitDeployment deployment, long timeout, TimeUnit timeUnit)
throws ProcessingUnitAlreadyDeployedException {
return deploy(deployment.toProcessingUnitDeployment(admin),timeout,timeUnit);
}
public Map<String,String> getProcessingUnitElasticProperties(ProcessingUnit pu) {
//TODO: Read the data from the gsm server.
return getElasticServiceManager().getProcessingUnitElasticProperties(pu);
}
public void setProcessingUnitElasticProperties(ProcessingUnit pu, Map<String,String> properties) {
//TODO: Store the data in the gsm server.
getElasticServiceManager().setProcessingUnitElasticProperties(pu, properties);
}
private InternalElasticServiceManager getElasticServiceManager() {
if (admin.getElasticServiceManagers().getSize() != 1) {
throw new AdminException("ElasticScaleHandler requires exactly one ESM server running.");
}
final InternalElasticServiceManager esm = (InternalElasticServiceManager) admin.getElasticServiceManagers().getManagers()[0];
return esm;
}
}
|
package net.idlesoft.android.apps.github.ui.activities;
import com.google.gson.reflect.TypeToken;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
import com.github.eddieringle.android.libs.undergarment.widgets.DrawerGarment;
import net.idlesoft.android.apps.github.R;
import net.idlesoft.android.apps.github.services.GitHubApiService;
import net.idlesoft.android.apps.github.ui.activities.app.EventsActivity;
import net.idlesoft.android.apps.github.ui.activities.app.HomeActivity;
import net.idlesoft.android.apps.github.ui.activities.app.ProfileActivity;
import net.idlesoft.android.apps.github.ui.activities.app.RepositoriesActivity;
import net.idlesoft.android.apps.github.ui.adapters.ContextListAdapter;
import net.idlesoft.android.apps.github.ui.adapters.DashboardListAdapter;
import net.idlesoft.android.apps.github.ui.widgets.OcticonView;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GsonUtils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static net.idlesoft.android.apps.github.HubroidConstants.ARG_TARGET_USER;
import static net.idlesoft.android.apps.github.HubroidConstants.PREF_CURRENT_USER_LOGIN;
import static net.idlesoft.android.apps.github.services.GitHubApiService.ACTION_ORGS_SELF_MEMBERSHIPS;
import static net.idlesoft.android.apps.github.services.GitHubApiService.ARG_ACCOUNT;
import static net.idlesoft.android.apps.github.services.GitHubApiService.EXTRA_RESULT_JSON;
import static net.idlesoft.android.apps.github.ui.fragments.app.EventListFragment.ARG_EVENT_LIST_TYPE;
import static net.idlesoft.android.apps.github.ui.fragments.app.EventListFragment.LIST_USER_PRIVATE;
import static net.idlesoft.android.apps.github.ui.fragments.app.RepositoryListFragment.ARG_LIST_TYPE;
import static net.idlesoft.android.apps.github.ui.fragments.app.RepositoryListFragment.LIST_USER;
import static net.idlesoft.android.apps.github.ui.fragments.app.RepositoryListFragment.LIST_STARRED;
public class BaseDashboardActivity extends BaseActivity {
public static final String EXTRA_CONTEXTS = "extra_contexts";
public static final String ARG_FROM_DASHBOARD = "extra_from_dashboard";
public static final String EXTRA_SHOWING_DASH = "extra_showing_dash";
private boolean mFromDashboard;
private boolean mReadyForContext = false;
private boolean mShowingDash;
private DrawerGarment mDrawerGarment;
private ListView mDashboardListView;
private DashboardListAdapter mDashboardListAdapter;
private Spinner mContextSpinner;
private ContextListAdapter mContextListAdapter;
private Intent mTargetIntent;
private AdapterView.OnItemSelectedListener mOnContextItemSelectedListener;
private BroadcastReceiver mContextReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (context == null || intent == null) {
return;
}
if (intent.getAction().equals(ACTION_ORGS_SELF_MEMBERSHIPS)) {
final ArrayList<User> contexts = new ArrayList<User>();
contexts.add(getCurrentUser());
final String orgsJson = intent.getStringExtra(EXTRA_RESULT_JSON);
if (orgsJson != null) {
TypeToken<List<User>> token = new TypeToken<List<User>>() {
};
List<User> orgs = GsonUtils.fromJson(orgsJson, token.getType());
contexts.addAll(orgs);
}
/*
* Loop through the list of users/organizations to find the
* current context the user is browsing as and rearrange the
* list so that it's at the top.
*/
int len = contexts.size();
for (int i = 0; i < len; i++) {
if (contexts.get(i).getLogin().equals(getCurrentContextLogin())) {
Collections.swap(contexts, i, 0);
break;
}
}
mContextListAdapter = new ContextListAdapter(BaseDashboardActivity.this);
mContextListAdapter.fillWithItems(contexts);
mContextSpinner.setAdapter(mContextListAdapter);
mContextSpinner.setOnItemSelectedListener(mOnContextItemSelectedListener);
mContextSpinner.setEnabled(true);
}
}
};
public DrawerGarment getDrawerGarment() {
return mDrawerGarment;
}
public boolean isDrawerOpened() {
if (getDrawerGarment() != null) {
return getDrawerGarment().isDrawerOpened();
}
return false;
}
public boolean isFromDashboard() {
return mFromDashboard;
}
@Override
protected void onCreate(Bundle icicle, int layout) {
super.onCreate(icicle, layout);
if (icicle != null) {
mShowingDash = icicle.getBoolean(EXTRA_SHOWING_DASH, false);
}
mDrawerGarment = new DrawerGarment(this, R.layout.dashboard);
mDrawerGarment.setDrawerMaxWidth(Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 250, getResources().getDisplayMetrics())));
mDrawerGarment.setSlideTarget(DrawerGarment.SLIDE_TARGET_CONTENT);
mDrawerGarment.setDrawerCallbacks(new DrawerGarment.IDrawerCallbacks() {
@Override
public void onDrawerOpened() {
mShowingDash = true;
supportInvalidateOptionsMenu();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void onDrawerClosed() {
if (mTargetIntent == null) {
mShowingDash = false;
supportInvalidateOptionsMenu();
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
} else {
startActivity(mTargetIntent);
overridePendingTransition(0, 0);
finish();
}
}
});
if (getIntent() != null) {
mFromDashboard = getIntent().getBooleanExtra(ARG_FROM_DASHBOARD, false);
if (!mFromDashboard) {
getDrawerGarment().setDrawerEnabled(false);
mShowingDash = false;
} else if (getIntent().hasExtra(EXTRA_SHOWING_DASH)) {
mShowingDash = getIntent().getBooleanExtra(EXTRA_SHOWING_DASH, mShowingDash);
}
}
mTargetIntent = null;
final ArrayList<DashboardListAdapter.DashboardEntry> dashboardEntries =
new ArrayList<DashboardListAdapter.DashboardEntry>();
DashboardListAdapter.DashboardEntry entry = new DashboardListAdapter.DashboardEntry();
entry.label = getString(R.string.dash_events);
entry.icon = (new OcticonView(this)).setOcticon(OcticonView.IC_FEED)
.setGlyphColor(Color.parseColor("#2c2c2c"))
.setGlyphSize(72.0f)
.toDrawable();
entry.selected = false;
if (this instanceof EventsActivity) {
entry.selected = true;
}
entry.onEntryClickListener = new DashboardListAdapter.DashboardEntry.OnEntryClickListener() {
@Override
public void onClick(DashboardListAdapter.DashboardEntry entry, int i) {
final Intent eventsIntent = new Intent(BaseDashboardActivity.this,
EventsActivity.class);
eventsIntent.setFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_NEW_TASK);
eventsIntent.putExtra(ARG_FROM_DASHBOARD, true);
eventsIntent.putExtra(ARG_TARGET_USER,
GsonUtils.toJson(new User().setLogin(getCurrentContextLogin())));
eventsIntent.putExtra(ARG_EVENT_LIST_TYPE, LIST_USER_PRIVATE);
mTargetIntent = eventsIntent;
getDrawerGarment().closeDrawer();
}
};
dashboardEntries.add(entry);
entry = new DashboardListAdapter.DashboardEntry();
entry.label = getString(R.string.dash_profile);
entry.icon = (new OcticonView(this)).setOcticon(OcticonView.IC_PERSON)
.setGlyphColor(Color.parseColor("#2c2c2c"))
.setGlyphSize(72.0f)
.toDrawable();
entry.selected = false;
if (this instanceof ProfileActivity) {
entry.selected = true;
}
entry.onEntryClickListener = new DashboardListAdapter.DashboardEntry.OnEntryClickListener() {
@Override
public void onClick(DashboardListAdapter.DashboardEntry entry, int i) {
final Intent profileIntent = new Intent(BaseDashboardActivity.this,
ProfileActivity.class);
profileIntent.setFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_NEW_TASK);
profileIntent.putExtra(ARG_FROM_DASHBOARD, true);
profileIntent.putExtra(ARG_TARGET_USER,
GsonUtils.toJson(new User().setLogin(getCurrentContextLogin())));
mTargetIntent = profileIntent;
getDrawerGarment().closeDrawer();
}
};
dashboardEntries.add(entry);
mDashboardListAdapter = new DashboardListAdapter(this);
mDashboardListAdapter.fillWithItems(dashboardEntries);
final LinearLayout headerLayout = (LinearLayout) getLayoutInflater()
.inflate(R.layout.dashboard_account_header, null);
mContextSpinner = (Spinner) headerLayout.findViewById(R.id.context_spinner);
mContextSpinner.setEnabled(false);
mOnContextItemSelectedListener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i,
long l) {
if (mReadyForContext) {
/* Remove the listener so we don't handle any more events */
mContextSpinner.setOnItemSelectedListener(null);
/*
* Reboot the app with the new context loaded
*/
final User target = mContextListAdapter.getItem(i);
setCurrentContextLogin(target.getLogin());
final Intent rebootIntent = new Intent(BaseDashboardActivity.this,
HomeActivity.class);
rebootIntent.setFlags(FLAG_ACTIVITY_CLEAR_TOP
| FLAG_ACTIVITY_NEW_TASK);
startActivity(rebootIntent);
finish();
} else {
mReadyForContext = true;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
};
mDashboardListView = (ListView) mDrawerGarment.findViewById(R.id.list);
if (isLoggedIn()) {
mDashboardListView.addHeaderView(headerLayout);
}
mDashboardListView.setAdapter(mDashboardListAdapter);
mDashboardListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (isLoggedIn()) {
if (i == 0) {
return;
} else {
i
}
}
final DashboardListAdapter.DashboardEntry entry = mDashboardListAdapter.getItem(i);
if (entry != null) {
if (entry.onEntryClickListener != null) {
entry.onEntryClickListener.onClick(entry, i);
}
}
}
});
if (isLoggedIn()) {
final IntentFilter contextFilter = new IntentFilter(ACTION_ORGS_SELF_MEMBERSHIPS);
registerReceiver(mContextReceiver, contextFilter);
if (icicle == null) {
final Intent getContextsIntent = new Intent(this, GitHubApiService.class);
getContextsIntent.setAction(ACTION_ORGS_SELF_MEMBERSHIPS);
getContextsIntent.putExtra(ARG_ACCOUNT, getCurrentUserAccount());
startService(getContextsIntent);
} else {
if (icicle.containsKey(EXTRA_CONTEXTS)) {
final String contextsJson = icicle.getString(EXTRA_CONTEXTS);
if (contextsJson != null) {
TypeToken<List<User>> token = new TypeToken<List<User>>() {
};
List<User> contexts = GsonUtils.fromJson(contextsJson, token.getType());
/*
* Loop through the list of users/organizations to find the
* current context the user is browsing as and rearrange the
* list so that it's at the top.
*/
int len = contexts.size();
for (int i = 0; i < len; i++) {
if (contexts.get(i).getLogin().equals(getCurrentContextLogin())) {
Collections.swap(contexts, i, 0);
break;
}
}
mContextListAdapter = new ContextListAdapter(BaseDashboardActivity.this);
mContextListAdapter.fillWithItems(contexts);
mContextSpinner.setAdapter(mContextListAdapter);
mContextSpinner.setOnItemSelectedListener(mOnContextItemSelectedListener);
mContextSpinner.setEnabled(true);
}
}
}
}
}
@Override
protected void onStart() {
super.onStart();
if (mShowingDash) {
mDrawerGarment.openDrawer(false);
}
}
@Override
protected void onPause() {
super.onPause();
mReadyForContext = false;
mContextSpinner.setEnabled(false);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mContextReceiver != null) {
try {
unregisterReceiver(mContextReceiver);
} catch (IllegalArgumentException e) {
/* Ignore this. */
}
}
}
@Override
public void onCreateActionBar(ActionBar bar) {
super.onCreateActionBar(bar);
if (getDrawerGarment().isDrawerEnabled()) {
if (isFromDashboard()) {
bar.setIcon(R.drawable.ic_launcher_white_dashboard);
}
if (getDrawerGarment().isDrawerOpened()) {
bar.setDisplayHomeAsUpEnabled(true);
} else {
bar.setDisplayHomeAsUpEnabled(false);
}
}
if (!isFromDashboard()) {
bar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mContextListAdapter != null && mContextListAdapter.getAll() != null) {
outState.putString(EXTRA_CONTEXTS, GsonUtils.toJson(mContextListAdapter.getAll()));
}
outState.putBoolean(EXTRA_SHOWING_DASH, mShowingDash);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerGarment.isDrawerEnabled()) {
mDrawerGarment.toggleDrawer();
return true;
}
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (mDrawerGarment.isDrawerOpened()) {
mDrawerGarment.closeDrawer();
} else {
super.onBackPressed();
}
}
}
|
package net.java.sip.communicator.impl.gui.main.contactlist;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import net.java.sip.communicator.impl.gui.main.MainFrame;
import net.java.sip.communicator.impl.gui.main.message.ChatMessage;
import net.java.sip.communicator.impl.gui.main.message.ChatPanel;
import net.java.sip.communicator.impl.gui.main.message.ChatWindow;
import net.java.sip.communicator.impl.gui.main.utils.Constants;
import net.java.sip.communicator.service.contactlist.MetaContact;
import net.java.sip.communicator.service.contactlist.MetaContactGroup;
import net.java.sip.communicator.service.contactlist.MetaContactListService;
import net.java.sip.communicator.service.protocol.Message;
import net.java.sip.communicator.service.protocol.OperationSetBasicInstantMessaging;
import net.java.sip.communicator.service.protocol.event.MessageDeliveredEvent;
import net.java.sip.communicator.service.protocol.event.MessageDeliveryFailedEvent;
import net.java.sip.communicator.service.protocol.event.MessageListener;
import net.java.sip.communicator.service.protocol.event.MessageReceivedEvent;
/**
* Creates the contactlist panel. The contactlist panel not only contains the contact list
* but it has the role of a message dispatcher by implementing the MessageListener.
*
* @author Yana Stamcheva
*/
public class ContactListPanel extends JScrollPane
implements MouseListener, MessageListener {
private MainFrame mainFrame;
private ContactList contactList;
private JPanel treePanel = new JPanel(new BorderLayout());
private Hashtable contactMsgWindows = new Hashtable();
private ChatWindow tabbedChatWindow;
/**
* Creates the contactlist scroll panel defining the parent frame.
*
* @param parent The parent frame.
*/
public ContactListPanel(MainFrame mainFrame) {
this.mainFrame = mainFrame;
this.getViewport().add(treePanel);
this.treePanel.setBackground(Color.WHITE);
this.setHorizontalScrollBarPolicy
(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
public void initTree(MetaContactListService contactListService) {
this.contactList = new ContactList(contactListService);
this.contactList.addMouseListener(this);
this.treePanel.add(contactList, BorderLayout.NORTH);
this.addKeyListener(new CListKeySearchListener(this.contactList));
}
public ContactList getContactList(){
return this.contactList;
}
public void mouseClicked(MouseEvent e) {
//Expand and collapse groups on double click.
if(e.getClickCount() > 1){
int selectedIndex
= this.contactList.locationToIndex(e.getPoint());
ContactListModel listModel = (ContactListModel)this.contactList.getModel();
Object element
= listModel.getElementAt(selectedIndex);
if(element instanceof MetaContactGroup){
MetaContactGroup group = (MetaContactGroup)element;
if(listModel.isGroupClosed(group)){
listModel.openGroup(group);
}
else{
listModel.closeGroup(group);
}
}
}
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
// Open message window, right button menu or contact info when
// mouse is pressed. Distinguish on which component was pressed
// the mouse and make the appropriate work.
if (this.contactList.getSelectedValue() instanceof MetaContact){
MetaContact contact
= (MetaContact) this.contactList.getSelectedValue();
int selectedIndex = this.contactList.getSelectedIndex();
ContactListCellRenderer renderer = (ContactListCellRenderer)
this.contactList.getCellRenderer()
.getListCellRendererComponent(
this.contactList,
contact,
selectedIndex,
true, true);
Point selectedCellPoint
= this.contactList.indexToLocation(selectedIndex);
int translatedX = e.getX()
- selectedCellPoint.x;
int translatedY = e.getY()
- selectedCellPoint.y;
//get the component under the mouse
Component component
= renderer.getComponentAt(translatedX, translatedY);
if (component instanceof JLabel) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK)
== InputEvent.BUTTON1_MASK) {
//Left click on the contact label opens Chat window
SwingUtilities.invokeLater(new RunMessageWindow(
contact));
} else if ((e.getModifiers() & InputEvent.BUTTON3_MASK)
== InputEvent.BUTTON3_MASK) {
//Right click on the contact label opens Popup menu
ContactRightButtonMenu popupMenu
= new ContactRightButtonMenu(
mainFrame, contact);
popupMenu.setInvoker(this.contactList);
popupMenu.setLocation(popupMenu.getPopupLocation());
popupMenu.setVisible(true);
}
} else if (component instanceof JButton) {
//Click on the info button opens the info popup panel
SwingUtilities.invokeLater
(new RunInfoWindow(selectedCellPoint,
contact));
}
}
}
public void mouseReleased(MouseEvent e) {
}
/**
* Runs the chat window for the specified contact.
*
* @author Yana Stamcheva
*/
private class RunMessageWindow implements Runnable {
private MetaContact contactItem;
private RunMessageWindow(MetaContact contactItem) {
this.contactItem = contactItem;
}
public void run() {
if(!Constants.TABBED_CHAT_WINDOW){
//If in mode "open all messages in new window"
if (contactMsgWindows.containsKey(this.contactItem)) {
/*
* If a chat window for this contact is already opened
* show it.
*/
ChatWindow msgWindow = (ChatWindow) contactMsgWindows
.get(this.contactItem);
if (msgWindow.getExtendedState() == JFrame.ICONIFIED)
msgWindow.setExtendedState(JFrame.NORMAL);
if(!msgWindow.isVisible())
msgWindow.setVisible(true);
} else {
/*
* If there's no chat window for the contact
* create it and show it.
*/
ChatWindow msgWindow = new ChatWindow(mainFrame);
contactMsgWindows.put(this.contactItem, msgWindow);
msgWindow.addChat(this.contactItem);
msgWindow.setVisible(true);
msgWindow.getWriteMessagePanel()
.getEditorPane().requestFocus();
}
}
else{
// If in mode "group messages in one chat window"
if(tabbedChatWindow == null){
// If there's no open chat window
tabbedChatWindow = new ChatWindow(mainFrame);
tabbedChatWindow.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
tabbedChatWindow = null;
}
});
}
/*
* Get the hashtable containg all tabs and corresponding
* chat panels.
*/
Hashtable contactTabsTable
= tabbedChatWindow.getContactTabsTable();
if(contactTabsTable.get(this.contactItem.getDisplayName())
== null){
// If there's no open tab for the given contact.
tabbedChatWindow.addChatTab(this.contactItem);
if(tabbedChatWindow.getTabCount() > 1)
tabbedChatWindow.setSelectedContactTab(this.contactItem);
if (tabbedChatWindow.getExtendedState() == JFrame.ICONIFIED)
tabbedChatWindow.setExtendedState(JFrame.NORMAL);
if(!tabbedChatWindow.isVisible())
tabbedChatWindow.setVisible(true);
tabbedChatWindow.getWriteMessagePanel()
.getEditorPane().requestFocus();
}
else{
if(tabbedChatWindow.getTabCount() > 1){
// If a tab fot the given contact already exists.
tabbedChatWindow.setSelectedContactTab(this.contactItem);
}
if (tabbedChatWindow.getExtendedState() == JFrame.ICONIFIED)
tabbedChatWindow.setExtendedState(JFrame.NORMAL);
tabbedChatWindow.setVisible(true);
tabbedChatWindow.getWriteMessagePanel()
.getEditorPane().requestFocus();
}
}
}
}
/**
* Runs the info window for the specified contact at the
* appropriate position.
*
* @author Yana Stamcheva
*/
private class RunInfoWindow implements Runnable {
private MetaContact contactItem;
private Point p;
private RunInfoWindow(Point p, MetaContact contactItem) {
this.p = p;
this.contactItem = contactItem;
}
public void run() {
ContactInfoPanel contactInfoPanel = new ContactInfoPanel(mainFrame, contactItem);
SwingUtilities.convertPointToScreen(p, contactList);
// TODO: to calculate popup window posititon properly.
contactInfoPanel.setPopupLocation(p.x - 140, p.y - 15);
contactInfoPanel.setVisible(true);
contactInfoPanel.requestFocusInWindow();
}
}
public void messageReceived(MessageReceivedEvent evt) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(evt.getTimestamp());
MetaContact metaContact
= mainFrame.getContactList().findMetaContactByContact(evt.getSourceContact());
if(!Constants.TABBED_CHAT_WINDOW){
//If in mode "open all messages in new window"
if (contactMsgWindows.containsKey(metaContact)) {
/*
* If a chat window for this contact is already opened
* show it.
*/
ChatWindow msgWindow = (ChatWindow) contactMsgWindows
.get(metaContact);
msgWindow.getCurrentChatPanel().getConversationPanel()
.processMessage(evt.getSourceContact().getDisplayName(),
calendar,
ChatMessage.INCOMING_MESSAGE,
evt.getSourceMessage().getContent());
if(!msgWindow.isVisible())
msgWindow.setVisible(true);
} else {
/*
* If there's no chat window for the contact
* create it and show it.
*/
ChatWindow msgWindow = new ChatWindow(mainFrame);
contactMsgWindows.put(metaContact, msgWindow);
msgWindow.addChat(metaContact);
msgWindow.getCurrentChatPanel().getConversationPanel()
.processMessage(evt.getSourceContact().getDisplayName(),
calendar, ChatMessage.INCOMING_MESSAGE,
evt.getSourceMessage().getContent());
msgWindow.setVisible(true);
}
}
else{
// If in mode "group messages in one chat window"
if(tabbedChatWindow == null){
// If there's no open chat window
tabbedChatWindow = new ChatWindow(mainFrame);
tabbedChatWindow.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
tabbedChatWindow = null;
}
});
}
/*
* Get the hashtable containg all tabs and corresponding
* chat panels.
*/
Hashtable contactTabsTable
= tabbedChatWindow.getContactTabsTable();
if(contactTabsTable.get(metaContact.getDisplayName())
== null){
// If there's no open tab for the given contact.
tabbedChatWindow.addChatTab(metaContact);
tabbedChatWindow.getCurrentChatPanel().getConversationPanel()
.processMessage(evt.getSourceContact().getDisplayName(),
calendar, ChatMessage.INCOMING_MESSAGE,
evt.getSourceMessage().getContent());
if(!tabbedChatWindow.isVisible())
tabbedChatWindow.setVisible(true);
tabbedChatWindow.getWriteMessagePanel()
.getEditorPane().requestFocus();
}
else{
tabbedChatWindow.getChatPanel(metaContact).getConversationPanel()
.processMessage(evt.getSourceContact().getDisplayName(),
calendar, ChatMessage.INCOMING_MESSAGE,
evt.getSourceMessage().getContent());
if(!tabbedChatWindow.isVisible())
tabbedChatWindow.setVisible(true);
tabbedChatWindow.getWriteMessagePanel()
.getEditorPane().requestFocus();
}
if(tabbedChatWindow.getTabCount() > 1){
// If a tab fot the given contact already exists.
tabbedChatWindow.highlightTab(metaContact);
}
}
}
public void messageDelivered(MessageDeliveredEvent evt) {
Message msg = evt.getSourceMessage();
Hashtable waitToBeDelivered = this.mainFrame.getWaitToBeDeliveredMsgs();
String msgUID = msg.getMessageUID();
if(waitToBeDelivered.containsKey(msgUID)){
ChatPanel chatPanel = (ChatPanel)waitToBeDelivered.get(msgUID);
JEditorPane messagePane = chatPanel.getWriteMessagePanel()
.getEditorPane();
Calendar calendar = Calendar.getInstance();
calendar.setTime(evt.getTimestamp());
chatPanel.getConversationPanel().processMessage(
this.mainFrame.getAccount().getIdentifier(),
calendar,
ChatMessage.OUTGOING_MESSAGE,
msg.getContent());
messagePane.setText("");
messagePane.requestFocus();
}
}
public void messageDeliveryFailed(MessageDeliveryFailedEvent evt) {
}
}
|
package org.ensembl.healthcheck.testcase.generic;
import org.ensembl.healthcheck.DatabaseRegistry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase;
/**
* Check that the assembly table is the same in all necessary databases.
*/
public class AssemblyTablesAcrossSpecies extends MultiDatabaseTestCase {
private DatabaseType[] types = {DatabaseType.CORE, DatabaseType.EST, DatabaseType.ESTGENE, DatabaseType.VEGA, DatabaseType.OTHERFEATURES};
/**
* Creates a new instance of AssemblyTablesAcrossSpecies
*/
public AssemblyTablesAcrossSpecies() {
addToGroup("release");
setDescription("Check that the assembly table contains the same information for all databases with the same species.");
}
/**
* Make sure that the assembly tables are all the same.
*
* @param dbr
* The database registry containing all the specified databases.
* @return True if the assembly table is the same across all the species in
* the registry.
*/
public boolean run(DatabaseRegistry dbr) {
return checkTableAcrossSpecies("assembly", dbr, types, "assembly tables all the same", "assembly tables different");
} // run
} // AssemblyTablesAcrossSpecies
|
package org.jetbrains.plugins.scala.lift.runner;
import com.intellij.execution.junit.RuntimeConfigurationProducer;
import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl;
import com.intellij.execution.Location;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.RunManager;
import com.intellij.execution.configurations.ConfigurationTypeUtil;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.SourceFolder;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.util.xml.GenericDomValue;
import org.jetbrains.idea.maven.runner.*;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.project.MavenGeneralSettings;
import org.jetbrains.idea.maven.project.MavenProjectModel;
import org.jetbrains.idea.maven.project.MavenArtifact;
import org.jetbrains.idea.maven.utils.MavenUtil;
import org.jetbrains.idea.maven.dom.model.MavenModel;
import org.jetbrains.idea.maven.dom.model.Dependencies;
import org.jetbrains.idea.maven.dom.model.Dependency;
import org.jetbrains.plugins.scala.util.ScalaUtils;
import java.util.List;
import java.util.ArrayList;
/**
* @author ilyas
*/
public class LiftRunConfigurationProducer extends RuntimeConfigurationProducer implements Cloneable {
private PsiElement mySourceElement;
private static final String GROUP_ID_LIFT = "net.liftweb";
private static final String ARTIFACT_ID_LIDT = "lift-webkit";
private static final String JETTY_RUN = "jetty:run";
public LiftRunConfigurationProducer() {
super(ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class));
}
public PsiElement getSourceElement() {
return mySourceElement;
}
private MavenRunnerParameters createBuildParameters(Location l) {
final PsiElement element = l.getPsiElement();
final Project project = l.getProject();
final Module module = ModuleUtil.findModuleForPsiElement(element);
if (module == null) return null;
final MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(project);
final MavenProjectModel mavenProjectModel = mavenProjectsManager.findProject(module);
if (mavenProjectModel == null) return null;
final MavenArtifact artifact = mavenProjectModel.findDependency(GROUP_ID_LIFT, ARTIFACT_ID_LIDT);
if (artifact == null) return null;
mySourceElement = element;
List<String> profiles = MavenProjectsManager.getInstance(project).getActiveProfiles();
List<String> goals = new ArrayList<String>();
goals.add(JETTY_RUN);
final VirtualFile file = module.getModuleFile();
if (file == null) return null;
final VirtualFile parent = file.getParent();
if (parent == null) return null;
return new MavenRunnerParameters(true, parent.getPath(), goals, profiles);
}
private static RunnerAndConfigurationSettingsImpl createRunnerAndConfigurationSettings(MavenGeneralSettings generalSettings,
MavenRunnerSettings runnerSettings,
MavenRunnerParameters params,
Project project) {
MavenRunConfigurationType type = ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class);
final RunnerAndConfigurationSettingsImpl settings = RunManagerEx.getInstanceEx(project)
.createConfiguration(MavenRunConfigurationType.generateName(project, params), type.getConfigurationFactories()[0]);
MavenRunConfiguration runConfiguration = (MavenRunConfiguration) settings.getConfiguration();
runConfiguration.setRunnerParameters(params);
if (generalSettings != null) runConfiguration.setGeneralSettings(generalSettings);
if (runnerSettings != null) runConfiguration.setRunnerSettings(runnerSettings);
return settings;
}
protected RunnerAndConfigurationSettingsImpl createConfigurationByElement(final Location location, final ConfigurationContext context) {
final Module module = context.getModule();
if (module == null || !ScalaUtils.isSuitableModule(module)) return null;
final MavenRunnerParameters params = createBuildParameters(location);
if (params == null) return null;
return createRunnerAndConfigurationSettings(null, null, params, location.getProject());
}
private static boolean isTestDirectory(final Module module, final PsiElement element) {
final PsiDirectory dir = (PsiDirectory) element;
final ModuleRootManager manager = ModuleRootManager.getInstance(module);
final ContentEntry[] entries = manager.getContentEntries();
for (ContentEntry entry : entries) {
for (SourceFolder folder : entry.getSourceFolders()) {
if (folder.isTestSource() && folder.getFile() == dir.getVirtualFile()) {
return true;
}
}
}
return false;
}
public int compareTo(final Object o) {
return PREFERED;
}
}
|
package org.pentaho.di.job.entries.evalfilesmetrics;
import static org.pentaho.di.job.entry.validator.AbstractFileValidator.putVariableSpace;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator;
import org.w3c.dom.Node;
import org.apache.commons.vfs.FileSelectInfo;
import org.apache.commons.vfs.AllFileSelector;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileType;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.simpleeval.JobEntrySimpleEval;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.job.entry.validator.ValidatorContext;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
/**
* This defines a 'evaluate files metrics' job entry.
*
* @author Samatar Hassan
* @since 26-02-2010
*/
public class JobEntryEvalFilesMetrics extends JobEntryBase implements Cloneable, JobEntryInterface
{
private static Class<?> PKG = JobEntryEvalFilesMetrics.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
public static final BigDecimal ONE = new BigDecimal(1);
public static final String[] IncludeSubFoldersDesc = new String[] { BaseMessages.getString(PKG, "System.Combo.No"), BaseMessages.getString(PKG, "System.Combo.Yes") };
public static final String[] IncludeSubFoldersCodes = new String[] {"N", "Y"};
private static final String YES = "Y";
private static final String NO = "N";
public static final String[] scaleDesc = new String[] {
BaseMessages.getString(PKG, "JobEvalFilesMetrics.Bytes.Label"),
BaseMessages.getString(PKG, "JobEvalFilesMetrics.KBytes.Label"),
BaseMessages.getString(PKG, "JobEvalFilesMetrics.MBytes.Label"),
BaseMessages.getString(PKG, "JobEvalFilesMetrics.GBytes.Label")
};
public static final String[] scaleCodes = new String[] {
"bytes",
"kbytes",
"mbytes",
"gbytes"
};
public static final int SCALE_BYTES=0;
public static final int SCALE_KBYTES=1;
public static final int SCALE_MBYTES=2;
public static final int SCALE_GBYTES=3;
public int scale;
public static final String[] SourceFilesDesc = new String[] {
BaseMessages.getString(PKG, "JobEvalFilesMetrics.SourceFiles.Files.Label"),
BaseMessages.getString(PKG, "JobEvalFilesMetrics.SourceFiles.FilenamesResult.Label"),
BaseMessages.getString(PKG, "JobEvalFilesMetrics.SourceFiles.PreviousResult.Label"),
};
public static final String[] SourceFilesCodes = new String[] {
"files",
"filenamesresult",
"previousresult"
};
public static final int SOURCE_FILES_FILES=0;
public static final int SOURCE_FILES_FILENAMES_RESULT=1;
public static final int SOURCE_FILES_PREVIOUS_RESULT=2;
public int sourceFiles;
public static final String[] EvaluationTypeDesc = new String[] {
BaseMessages.getString(PKG, "JobEvalFilesMetrics.EvaluationType.Size.Label"),
BaseMessages.getString(PKG, "JobEvalFilesMetrics.EvaluationType.Count.Label"),
};
public static final String[] EvaluationTypeCodes= new String[] {
"size",
"count",
};
public static final int EVALUATE_TYPE_SIZE=0;
public static final int EVALUATE_TYPE_COUNT=1;
public int evaluationType;
private String comparevalue;
private String minvalue;
private String maxvalue;
public int successnumbercondition;
private String resultFilenamesWildcard;
public boolean arg_from_previous;
public String source_filefolder[];
public String wildcard[];
public String includeSubFolders[];
private BigDecimal evaluationValue;
private BigDecimal filesCount;
private long nrErrors;
private String ResultFieldFile;
private String ResultFieldWildcard;
private String ResultFieldIncludesubFolders;
private BigDecimal compareValue;
private BigDecimal minValue;
private BigDecimal maxValue;
public JobEntryEvalFilesMetrics(String n)
{
super(n, "");
source_filefolder=null;
wildcard=null;
includeSubFolders=null;
scale = SCALE_BYTES;
sourceFiles = SOURCE_FILES_FILES;
evaluationType = EVALUATE_TYPE_SIZE;
successnumbercondition = JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_GREATER;
resultFilenamesWildcard=null;
ResultFieldFile=null;
ResultFieldWildcard=null;
ResultFieldIncludesubFolders=null;
setID(-1L);
}
public JobEntryEvalFilesMetrics()
{
this("");
}
public Object clone()
{
JobEntryEvalFilesMetrics je = (JobEntryEvalFilesMetrics) super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(300);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("result_filenames_wildcard", resultFilenamesWildcard));
retval.append(" ").append(XMLHandler.addTagValue("Result_field_file", ResultFieldFile));
retval.append(" ").append(XMLHandler.addTagValue("Result_field_wildcard", ResultFieldWildcard));
retval.append(" ").append(XMLHandler.addTagValue("Result_field_includesubfolders", ResultFieldIncludesubFolders));
retval.append(" <fields>").append(Const.CR);
if (source_filefolder!=null)
{
for (int i=0;i<source_filefolder.length;i++)
{
retval.append(" <field>").append(Const.CR);
retval.append(" ").append(XMLHandler.addTagValue("source_filefolder", source_filefolder[i]));
retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard[i]));
retval.append(" ").append(XMLHandler.addTagValue("include_subFolders", includeSubFolders[i]));
retval.append(" </field>").append(Const.CR);
}
}
retval.append(" </fields>").append(Const.CR);
retval.append(" ").append(XMLHandler.addTagValue("comparevalue", comparevalue));
retval.append(" ").append(XMLHandler.addTagValue("minvalue", minvalue));
retval.append(" ").append(XMLHandler.addTagValue("maxvalue", maxvalue));
retval.append(" ").append(XMLHandler.addTagValue("successnumbercondition",JobEntrySimpleEval.getSuccessNumberConditionCode(successnumbercondition)));
retval.append(" ").append(XMLHandler.addTagValue("source_files",getSourceFilesCode(sourceFiles)));
retval.append(" ").append(XMLHandler.addTagValue("evaluation_type",getEvaluationTypeCode(evaluationType)));
retval.append(" ").append(XMLHandler.addTagValue("scale",getScaleCode(scale)));
return retval.toString();
}
public static String getIncludeSubFolders(String tt) {
if(tt==null) return IncludeSubFoldersCodes[0];
if(tt.equals(IncludeSubFoldersDesc[1]))
return IncludeSubFoldersCodes[1];
else
return IncludeSubFoldersCodes[0];
}
public static String getIncludeSubFoldersDesc(String tt) {
if(tt==null) return IncludeSubFoldersDesc[0];
if(tt.equals(IncludeSubFoldersCodes[1]))
return IncludeSubFoldersDesc[1];
else
return IncludeSubFoldersDesc[0];
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases, slaveServers);
Node fields = XMLHandler.getSubNode(entrynode, "fields");
// How many field arguments?
int nrFields = XMLHandler.countNodes(fields, "field");
source_filefolder = new String[nrFields];
wildcard = new String[nrFields];
includeSubFolders = new String[nrFields];
// Read them all...
for (int i = 0; i < nrFields; i++)
{
Node fnode = XMLHandler.getSubNodeByNr(fields, "field", i);
source_filefolder[i] = XMLHandler.getTagValue(fnode, "source_filefolder");
wildcard[i] = XMLHandler.getTagValue(fnode, "wildcard");
includeSubFolders[i] = XMLHandler.getTagValue(fnode, "include_subFolders");
}
resultFilenamesWildcard = XMLHandler.getTagValue(entrynode, "result_filenames_wildcard");
ResultFieldFile = XMLHandler.getTagValue(entrynode, "result_field_file");
ResultFieldWildcard = XMLHandler.getTagValue(entrynode, "result_field_wildcard");
ResultFieldIncludesubFolders = XMLHandler.getTagValue(entrynode, "result_field_includesubfolders");
comparevalue = XMLHandler.getTagValue(entrynode, "comparevalue");
minvalue = XMLHandler.getTagValue(entrynode, "minvalue");
maxvalue = XMLHandler.getTagValue(entrynode, "maxvalue");
successnumbercondition = JobEntrySimpleEval.getSuccessNumberConditionByCode(Const.NVL(XMLHandler.getTagValue(entrynode, "successnumbercondition"), ""));
sourceFiles =getSourceFilesByCode(Const.NVL(XMLHandler.getTagValue(entrynode, "source_files"), ""));
evaluationType =getEvaluationTypeByCode(Const.NVL(XMLHandler.getTagValue(entrynode, "evaluation_type"), ""));
scale =getScaleByCode(Const.NVL(XMLHandler.getTagValue(entrynode, "scale"), ""));
}
catch(KettleXMLException xe)
{
throw new KettleXMLException(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.Exception.UnableLoadXML"), xe);
}
}
public void loadRep(Repository rep, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException
{
try
{
// How many arguments?
int argnr = rep.countNrJobEntryAttributes(id_jobentry, "source_filefolder");
source_filefolder = new String[argnr];
wildcard = new String[argnr];
includeSubFolders = new String[argnr];
// Read them all...
for (int a=0;a<argnr;a++)
{
source_filefolder[a]= rep.getJobEntryAttributeString(id_jobentry, a, "source_filefolder");
wildcard[a]= rep.getJobEntryAttributeString(id_jobentry, a, "wildcard");
includeSubFolders[a]= rep.getJobEntryAttributeString(id_jobentry, a, "include_subFolders");
}
resultFilenamesWildcard = rep.getJobEntryAttributeString(id_jobentry, "result_filenames_wildcard");
ResultFieldFile = rep.getJobEntryAttributeString(id_jobentry, "result_field_file");
ResultFieldWildcard = rep.getJobEntryAttributeString(id_jobentry, "result_field_wildcard");
ResultFieldIncludesubFolders = rep.getJobEntryAttributeString(id_jobentry, "result_field_includesubfolders");
comparevalue = rep.getJobEntryAttributeString(id_jobentry, "comparevalue");
minvalue = rep.getJobEntryAttributeString(id_jobentry, "minvalue");
maxvalue = rep.getJobEntryAttributeString(id_jobentry, "maxvalue");
successnumbercondition = JobEntrySimpleEval.getSuccessNumberConditionByCode(Const.NVL(rep.getJobEntryAttributeString(id_jobentry,"successnumbercondition"), ""));
sourceFiles = getSourceFilesByCode(Const.NVL(rep.getJobEntryAttributeString(id_jobentry,"source_files"), ""));
evaluationType = getEvaluationTypeByCode(Const.NVL(rep.getJobEntryAttributeString(id_jobentry,"evaluation_type"), ""));
scale = getScaleByCode(Const.NVL(rep.getJobEntryAttributeString(id_jobentry,"scale"), ""));
}
catch(KettleException dbe)
{
throw new KettleException(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.Exception.UnableLoadRep")+id_jobentry, dbe);
}
}
public void saveRep(Repository rep, ObjectId id_job) throws KettleException
{
try
{
// save the arguments...
if (source_filefolder!=null)
{
for (int i=0;i<source_filefolder.length;i++)
{
rep.saveJobEntryAttribute(id_job, getObjectId(), i, "source_filefolder", source_filefolder[i]);
rep.saveJobEntryAttribute(id_job, getObjectId(), i, "wildcard", wildcard[i]);
rep.saveJobEntryAttribute(id_job, getObjectId(), i, "include_subFolders", includeSubFolders[i]);
}
}
rep.saveJobEntryAttribute(id_job, getObjectId(), "result_filenames_wildcard", resultFilenamesWildcard);
rep.saveJobEntryAttribute(id_job, getObjectId(), "result_field_file", ResultFieldFile);
rep.saveJobEntryAttribute(id_job, getObjectId(), "result_field_wild", ResultFieldWildcard);
rep.saveJobEntryAttribute(id_job, getObjectId(), "result_field_includesubfolders", ResultFieldIncludesubFolders);
rep.saveJobEntryAttribute(id_job, getObjectId(), "comparevalue", comparevalue);
rep.saveJobEntryAttribute(id_job, getObjectId(), "minvalue", minvalue);
rep.saveJobEntryAttribute(id_job, getObjectId(), "maxvalue", maxvalue);
rep.saveJobEntryAttribute(id_job, getObjectId(),"successnumbercondition", JobEntrySimpleEval.getSuccessNumberConditionCode(successnumbercondition));
rep.saveJobEntryAttribute(id_job, getObjectId(),"scale", getScaleCode(scale));
rep.saveJobEntryAttribute(id_job, getObjectId(),"source_files", getSourceFilesCode(sourceFiles));
rep.saveJobEntryAttribute(id_job, getObjectId(),"evaluation_type", getEvaluationTypeCode(evaluationType));
}
catch(KettleDatabaseException dbe)
{
throw new KettleException(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.Exception.UnableSaveRep")+id_job, dbe);
}
}
public Result execute(Result previousResult, int nr) throws KettleException
{
Result result = previousResult;
result.setNrErrors(1);
result.setResult(false);
List<RowMetaAndData> rows = result.getRows();
RowMetaAndData resultRow = null;
try {
initMetrics();
}catch(Exception e) {
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.Init", e.toString()));
return result;
}
// Get source and destination files, also wildcard
String vsourcefilefolder[] = source_filefolder;
String vwildcard[] = wildcard;
String vincludeSubFolders[] = includeSubFolders;
switch (getSourceFiles()){
case SOURCE_FILES_PREVIOUS_RESULT:
// Filenames are retrieved from previous result rows
String realResultFieldFile= environmentSubstitute(getResultFieldFile());
String realResultFieldWildcard= environmentSubstitute(getResultFieldWildcard());
String realResultFieldIncluseSubfolders= environmentSubstitute(getResultFieldIncludeSubfolders());
int indexOfResultFieldFile=-1;
if(Const.isEmpty(realResultFieldFile)) {
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.ResultFieldsFileMissing"));
return result;
}
int indexOfResultFieldWildcard=-1;
int indexOfResultFieldIncludeSubfolders=-1;
// as such we must get rows
if (log.isDetailed()) logDetailed( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.ArgFromPrevious.Found",(rows!=null?rows.size():0)+ ""));
if (rows!=null && rows.size()>0) {
// We get rows
RowMetaAndData firstRow = rows.get(0);
indexOfResultFieldFile= firstRow.getRowMeta().indexOfValue(realResultFieldFile);
if(indexOfResultFieldFile==-1) {
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.CanNotFindField", realResultFieldFile));
return result;
}
if(!Const.isEmpty(realResultFieldWildcard)) {
indexOfResultFieldWildcard= firstRow.getRowMeta().indexOfValue(realResultFieldWildcard);
if(indexOfResultFieldWildcard==-1) {
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.CanNotFindField", realResultFieldWildcard));
return result;
}
}
if(!Const.isEmpty(realResultFieldIncluseSubfolders)) {
indexOfResultFieldIncludeSubfolders= firstRow.getRowMeta().indexOfValue(realResultFieldIncluseSubfolders);
if(indexOfResultFieldIncludeSubfolders==-1) {
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.CanNotFindField", realResultFieldIncluseSubfolders));
return result;
}
}
for (int iteration=0;iteration<rows.size() && !parentJob.isStopped();iteration++) {
resultRow = rows.get(iteration);
// Get source and destination file names, also wildcard
String vsourcefilefolder_previous = resultRow.getString(indexOfResultFieldFile, null);
String vwildcard_previous = null;
if(indexOfResultFieldWildcard>-1) {
vwildcard_previous = resultRow.getString(indexOfResultFieldWildcard, null);
}
String vincludeSubFolders_previous = NO;
if(indexOfResultFieldIncludeSubfolders>-1) {
vincludeSubFolders_previous = resultRow.getString(indexOfResultFieldIncludeSubfolders, NO);
}
if(isDetailed()) logDetailed( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.ProcessingRow",vsourcefilefolder_previous,vwildcard_previous));
ProcessFileFolder(vsourcefilefolder_previous, vwildcard_previous,vincludeSubFolders_previous,parentJob,result);
}
}
break;
case SOURCE_FILES_FILENAMES_RESULT:
List<ResultFile> resultFiles = result.getResultFilesList();
if (log.isDetailed()) logDetailed( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.ResultFilenames.Found",(resultFiles!=null?resultFiles.size():0)+ ""));
if(resultFiles != null && resultFiles.size() > 0) {
// Let's check wildcard
Pattern pattern = null;
String realPattern=environmentSubstitute(getResultFilenamesWildcard());
if (!Const.isEmpty(realPattern)){
pattern = Pattern.compile(realPattern);
}
for (Iterator<ResultFile> it = resultFiles.iterator(); it.hasNext() && !parentJob.isStopped();){
ResultFile resultFile = (ResultFile) it.next();
FileObject file = resultFile.getFile();
try {
if (file != null && file.exists()) {
boolean getIt=true;
if(pattern!=null) {
Matcher matcher = pattern.matcher(file.getName().getBaseName());
getIt = matcher.matches();
}
if(getIt) {
getFileSize(file,result, parentJob);
}
}
}catch(Exception e) {
incrementErrors();
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.GettingFileFromResultFilenames", file.toString(), e.toString()));
}finally {
if(file!=null) { try{file.close();}catch(Exception e){};};
}
}
}
break;
default:
// static files/folders
// from grid entered by user
if (vsourcefilefolder!=null && vsourcefilefolder.length>0) {
for (int i=0;i<vsourcefilefolder.length && !parentJob.isStopped();i++) {
if(isDetailed()) logDetailed( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.ProcessingRow",vsourcefilefolder[i],vwildcard[i]));
ProcessFileFolder(vsourcefilefolder[i], vwildcard[i],vincludeSubFolders[i],parentJob,result);
}
}else {
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.FilesGridEmpty"));
return result;
}
break;
}
result.setResult(isSuccess());
result.setNrErrors(getNrError());
displayResults();
return result;
}
private void displayResults() {
if(isDetailed()) {
logDetailed( "=======================================");
logDetailed( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.Info.FilesCount",String.valueOf(getFilesCount())));
if(evaluationType==EVALUATE_TYPE_SIZE) {
logDetailed( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.Info.FilesSize",String.valueOf(getEvaluationValue())));
}
logDetailed( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.Info.NrErrors",String.valueOf(getNrError())));
logDetailed( "=======================================");
}
}
private long getNrError() {
return this.nrErrors;
}
private BigDecimal getEvaluationValue() {
return this.evaluationValue;
}
private BigDecimal getFilesCount() {
return this.filesCount;
}
private boolean isSuccess() {
boolean retval=false;
switch (successnumbercondition) {
case JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_EQUAL: // equal
if(isDebug()) logDebug( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.CompareWithValue",String.valueOf(evaluationValue),String.valueOf(compareValue)));
retval=(getEvaluationValue().compareTo(compareValue)==0);
break;
case JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_DIFFERENT: // different
if(isDebug()) logDebug( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.CompareWithValue",String.valueOf(evaluationValue),String.valueOf(compareValue)));
retval=(getEvaluationValue().compareTo(compareValue)!=0);
break;
case JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_SMALLER: // smaller
if(isDebug()) logDebug( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.CompareWithValue",String.valueOf(evaluationValue),String.valueOf(compareValue)));
retval=(getEvaluationValue().compareTo(compareValue)<0);
break;
case JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_SMALLER_EQUAL: // smaller or equal
if(isDebug()) logDebug( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.CompareWithValue",String.valueOf(evaluationValue),String.valueOf(compareValue)));
retval=(getEvaluationValue().compareTo(compareValue)<=0);
break;
case JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_GREATER: // greater
if(isDebug()) logDebug( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.CompareWithValue",String.valueOf(evaluationValue),String.valueOf(compareValue)));
retval=(getEvaluationValue().compareTo(compareValue)>0);
break;
case JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_GREATER_EQUAL: // greater or equal
if(isDebug()) logDebug( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.CompareWithValue",String.valueOf(evaluationValue),String.valueOf(compareValue)));
retval=(getEvaluationValue().compareTo(compareValue)>=0);
break;
case JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_BETWEEN: // between min and max
if(isDebug()) logDebug( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.CompareWithValues",String.valueOf(evaluationValue), String.valueOf(minValue),String.valueOf(maxValue)));
retval=(getEvaluationValue().compareTo(minValue)>=0 && getEvaluationValue().compareTo(maxValue)<=0);
break;
default:
break;
}
return retval;
}
private void initMetrics() throws Exception {
evaluationValue=new BigDecimal(0);
filesCount=new BigDecimal(0);
nrErrors=0;
if(successnumbercondition==JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_BETWEEN) {
minValue= new BigDecimal(environmentSubstitute(getMinValue()));
maxValue= new BigDecimal(environmentSubstitute(getMaxValue()));
}else {
compareValue= new BigDecimal(environmentSubstitute(getCompareValue()));
}
if(evaluationType== EVALUATE_TYPE_SIZE) {
int multyply=1;
switch (getScale()){
case SCALE_KBYTES:
multyply=1024;
break;
case SCALE_MBYTES:
multyply=1048576;
break;
case SCALE_GBYTES:
multyply=1073741824;
break;
default:
break;
}
if(successnumbercondition==JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_BETWEEN) {
minValue=minValue.multiply(BigDecimal.valueOf(multyply));
maxValue=maxValue.multiply(BigDecimal.valueOf(multyply));
}else {
compareValue=compareValue.multiply(BigDecimal.valueOf(multyply));
}
}
arg_from_previous= (getSourceFiles()== SOURCE_FILES_PREVIOUS_RESULT);
}
private void incrementErrors() {
nrErrors++;
}
public int getSourceFiles() {
return this.sourceFiles;
}
private void incrementFilesCount() {
filesCount=filesCount.add(ONE);
}
public String getResultFieldFile() {
return this.ResultFieldFile;
}
public void setResultFieldFile(String field) {
this.ResultFieldFile=field;
}
public String getResultFieldWildcard() {
return this.ResultFieldWildcard;
}
public void setResultFieldWildcard(String field) {
this.ResultFieldWildcard=field;
}
public String getResultFieldIncludeSubfolders() {
return this.ResultFieldIncludesubFolders;
}
public void setResultFieldIncludeSubfolders(String field) {
this.ResultFieldIncludesubFolders=field;
}
private void ProcessFileFolder(String sourcefilefoldername,String wildcard,
String includeSubfolders,Job parentJob, Result result) {
FileObject sourcefilefolder = null;
FileObject CurrentFile = null;
// Get real source file and wildcard
String realSourceFilefoldername = environmentSubstitute(sourcefilefoldername);
if(Const.isEmpty(realSourceFilefoldername)) {
// Filename is empty!
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.log.FileFolderEmpty"));
incrementErrors();
return;
}
String realWildcard=environmentSubstitute(wildcard);
final boolean include_subfolders=YES.equalsIgnoreCase(includeSubfolders);
try {
sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername);
if (sourcefilefolder.exists()) {
// File exists
if(isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.FileExists",sourcefilefolder.toString()));
if(sourcefilefolder.getType() == FileType.FILE) {
// We deals here with a file
// let's get file size
getFileSize(sourcefilefolder,result,parentJob);
}else if(sourcefilefolder.getType() == FileType.FOLDER) {
// We have a folder
// we will fetch and extract files
FileObject[] fileObjects = sourcefilefolder.findFiles(
new AllFileSelector() {
public boolean traverseDescendents(FileSelectInfo info) {
return info.getDepth()==0 || include_subfolders;
}
public boolean includeFile(FileSelectInfo info) {
FileObject fileObject = info.getFile();
try {
if ( fileObject == null) return false;
if(fileObject.getType() != FileType.FILE) return false;
} catch (Exception ex) {
// Upon error don't process the file.
return false;
} finally {
if ( fileObject != null ) {
try {fileObject.close();} catch ( IOException ex ) {};
}
}
return true;
}
}
);
if (fileObjects != null) {
for (int j = 0; j < fileObjects.length && !parentJob.isStopped(); j++) {
// Fetch files in list one after one ...
CurrentFile=fileObjects[j];
if (!CurrentFile.getParent().toString().equals(sourcefilefolder.toString())){
// Not in the Base Folder..Only if include sub folders
if (include_subfolders) {
if(GetFileWildcard(CurrentFile.getName().getBaseName(),realWildcard)) {
getFileSize(CurrentFile,result,parentJob);
}
}
}else {
// In the base folder
if (GetFileWildcard(CurrentFile.getName().getBaseName(),realWildcard)){
getFileSize(CurrentFile,result,parentJob);
}
}
}
}
}else {
incrementErrors();
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.UnknowFileFormat",sourcefilefolder.toString()));
}
} else {
incrementErrors();
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.SourceFileNotExists",realSourceFilefoldername));
}
} catch (Exception e) {
incrementErrors();
logError( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.Exception.Processing",realSourceFilefoldername.toString(),e.getMessage()));
} finally {
if ( sourcefilefolder != null ){
try{
sourcefilefolder.close();
}catch ( IOException ex ) {};
} if ( CurrentFile != null ){
try {
CurrentFile.close();
}catch ( IOException ex ) {};
}
}
}
private void getFileSize(FileObject file, Result result,Job parentJob) {
try{
incrementFilesCount();
if(isDetailed()) logDetailed( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.GetFile",file.toString(), String.valueOf(getFilesCount())));
switch(evaluationType) {
case EVALUATE_TYPE_SIZE :
BigDecimal fileSize=BigDecimal.valueOf(file.getContent().getSize());
evaluationValue=evaluationValue.add(fileSize);
if(isDebug()) logDebug( BaseMessages.getString(PKG, "JobEvalFilesMetrics.Log.AddedFileSize", String.valueOf(fileSize), file.toString()));
break;
default:
evaluationValue=evaluationValue.add(ONE);
break;
}
}catch (Exception e) {
incrementErrors();
logError(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Error.GettingFileSize", file.toString(),e.toString()));
}
}
private boolean GetFileWildcard(String selectedfile, String wildcard) {
Pattern pattern = null;
boolean getIt=true;
if (!Const.isEmpty(wildcard)) {
pattern = Pattern.compile(wildcard);
// First see if the file matches the regular expression!
if (pattern!=null) {
Matcher matcher = pattern.matcher(selectedfile);
getIt = matcher.matches();
}
}
return getIt;
}
public void setMinValue(String minvalue) {
this.minvalue=minvalue;
}
public String getMinValue(){
return minvalue;
}
public void setCompareValue(String comparevalue){
this.comparevalue=comparevalue;
}
public String getCompareValue(){
return comparevalue;
}
public void setResultFilenamesWildcard(String resultwildcard) {
this.resultFilenamesWildcard=resultwildcard;
}
public String getResultFilenamesWildcard() {
return this.resultFilenamesWildcard;
}
public void setMaxValue(String maxvalue)
{
this.maxvalue=maxvalue;
}
public String getMaxValue(){
return maxvalue;
}
public static int getScaleByDesc(String tt) {
if (tt == null)
return 0;
for (int i = 0; i < scaleDesc.length; i++) {
if (scaleDesc[i].equalsIgnoreCase(tt))
return i;
}
// If this fails, try to match using the code.
return getScaleByCode(tt);
}
public static int getSourceFilesByDesc(String tt) {
if (tt == null)
return 0;
for (int i = 0; i < SourceFilesDesc.length; i++) {
if (SourceFilesDesc[i].equalsIgnoreCase(tt))
return i;
}
// If this fails, try to match using the code.
return getSourceFilesByCode(tt);
}
public static int getEvaluationTypeByDesc(String tt) {
if (tt == null)
return 0;
for (int i = 0; i < EvaluationTypeDesc.length; i++) {
if (EvaluationTypeDesc[i].equalsIgnoreCase(tt))
return i;
}
// If this fails, try to match using the code.
return getEvaluationTypeByCode(tt);
}
private static int getScaleByCode(String tt) {
if (tt == null)
return 0;
for (int i = 0; i < scaleCodes.length; i++) {
if (scaleCodes[i].equalsIgnoreCase(tt))
return i;
}
return 0;
}
private static int getSourceFilesByCode(String tt) {
if (tt == null)
return 0;
for (int i = 0; i < SourceFilesCodes.length; i++) {
if (SourceFilesCodes[i].equalsIgnoreCase(tt))
return i;
}
return 0;
}
private static int getEvaluationTypeByCode(String tt) {
if (tt == null)
return 0;
for (int i = 0; i < EvaluationTypeCodes.length; i++) {
if (EvaluationTypeCodes[i].equalsIgnoreCase(tt))
return i;
}
return 0;
}
public static String getScaleDesc(int i) {
if (i < 0 || i >= scaleDesc.length)
return scaleDesc[0];
return scaleDesc[i];
}
public static String getEvaluationTypeDesc(int i) {
if (i < 0 || i >= EvaluationTypeDesc.length)
return EvaluationTypeDesc[0];
return EvaluationTypeDesc[i];
}
public static String getSourceFilesDesc(int i) {
if (i < 0 || i >= SourceFilesDesc.length)
return SourceFilesDesc[0];
return SourceFilesDesc[i];
}
public static String getScaleCode(int i) {
if (i < 0 || i >= scaleCodes.length)
return scaleCodes[0];
return scaleCodes[i];
}
public static String getSourceFilesCode(int i) {
if (i < 0 || i >= SourceFilesCodes.length)
return SourceFilesCodes[0];
return SourceFilesCodes[i];
}
public static String getEvaluationTypeCode(int i) {
if (i < 0 || i >= EvaluationTypeCodes.length)
return EvaluationTypeCodes[0];
return EvaluationTypeCodes[i];
}
public int getScale() {
return this.scale;
}
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
{
boolean res = andValidator().validate(this, "arguments", remarks, putValidators(notNullValidator()));
if (res == false)
{
return;
}
ValidatorContext ctx = new ValidatorContext();
putVariableSpace(ctx, getVariables());
putValidators(ctx, notNullValidator(), fileExistsValidator());
for (int i = 0; i < source_filefolder.length; i++)
{
andValidator().validate(this, "arguments[" + i + "]", remarks, ctx);
}
}
public boolean evaluates() {
return true;
}
}
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc2083.TeamBlitzRobot2015.subsystems;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.CANJaguar.ControlMode;
import edu.wpi.first.wpilibj.can.CANTimeoutException;
import edu.wpi.first.wpilibj.command.*;
import edu.wpi.first.wpilibj.smartdashboard.*;
import org.usfirst.frc2083.TeamBlitzRobot2015.RobotMap;
import org.usfirst.frc2083.TeamBlitzRobot2015.commands.*;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.command.Subsystem;
public class LeftDriveSubsystem extends Subsystem {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
SpeedController leftFrontMotor = RobotMap.leftDriveSubsystemLeftFrontMotor;
SpeedController leftRearMotor = RobotMap.leftDriveSubsystemLeftRearMotor;
public LeftDriveSubsystem() {
super("Left Drive");
this.enable();
this.leftFrontMotor).setOutputRange(-12,12);
}
protected void initDefaultCommand() {
}
public void enableControl() {
try {
leftBack.enableControl();
leftFront.enableControl();
ex.printStackTrace();
"Finally}
}
public void disableControl() {
try {
leftBack.disableControl();
leftFront.disableControl();
ex.printStackTrace();
"Finally}
}
public double returnPIDInput() {
try {
return leftFront.getSpeed();
ex.printStackTrace();
"Finally}
}
public void usePIDOutput(double d) {
try {
System.out.println("Left " + getSetpoint() + " " + returnPIDInput() + " " + d + " " + leftFront.getOutputCurrent() + " " + leftBack.getOutputCurrent());
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}
try {
leftBack.setX(-d);
leftFront.setX(-d);
CANTimeoutException ex;
ex.printStackTrace();"finally";
"Finally}
super("Left Drive");
this.enable();
this.leftRearMotor).setOutputRange(-12,12)"Finally;
}
}
protected void initDefaultCommand() {
}
public void enableControl() {
try {
leftBack.enableControl();
leftFront.enableControl();
ex.printStackTrace();
"Finally}
}
public void disableControl() {
try {
leftBack.disableControl();
leftFront.disableControl();
ex.printStackTrace();
"Finally}
}
public double returnPIDInput() {
try {
return leftFront.getSpeed();
ex.printStackTrace();
"Finally}
}
public void usePIDOutput(double d) {
try {
System.out.println("Left " + getSetpoint() + " " + returnPIDInput() + " " + d + " " + leftFront.getOutputCurrent() + " " + leftBack.getOutputCurrent());
} catch (CANTimeoutException ex) {
ex.printStackTrace();
}
try {
leftBack.setX(-d);
leftFront.setX(-d);
CANTimeoutException ex;
ex.printStackTrace();"finally";}
private void enable() {
// TODO Auto-generated method stub
}
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand1() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
}
|
package ibis.ipl.impl.registry.central;
import ibis.ipl.impl.IbisIdentifier;
import ibis.ipl.impl.Location;
import ibis.util.ThreadPool;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
final class Pool implements Runnable {
static final int PING_THREADS = 5;
static final long GOSSIP_INTERVAL = 120 * 60 * 1000;
static final int GOSSIP_THREADS = 10;
static final int PUSH_THREADS = 10;
private static final Logger logger = Logger.getLogger(Pool.class);
// list of all joins, leaves, elections, etc.
private final ArrayList<Event> events;
// cache of election results we've seen. Optimization over searching all the
// events each time an election result is requested.
// map<election name, winner>
private final Map<String, IbisIdentifier> elections;
private final MemberSet members;
// List of "suspect" ibisses we must ping
private final Set<IbisIdentifier> checkList;
private final boolean keepNodeState;
private final String name;
private final ConnectionFactory connectionFactory;
private final boolean printEvents;
private int nextID;
private long nextSequenceNr;
private boolean ended = false;
Pool(String name, ConnectionFactory connectionFactory, boolean gossip,
boolean keepNodeState, long pingInterval, boolean printEvents) {
this.name = name;
this.connectionFactory = connectionFactory;
this.keepNodeState = keepNodeState;
this.printEvents = printEvents;
nextID = 0;
nextSequenceNr = 0;
events = new ArrayList<Event>();
elections = new HashMap<String, IbisIdentifier>();
members = new MemberSet();
checkList = new LinkedHashSet<IbisIdentifier>();
if (gossip) {
// ping iteratively
new PeriodicNodeContactor(this, false, false, pingInterval,
PING_THREADS);
// gossip randomly
new PeriodicNodeContactor(this, true, true, GOSSIP_INTERVAL,
GOSSIP_THREADS);
} else { // central
// ping iteratively
new PeriodicNodeContactor(this, false, false, pingInterval,
PING_THREADS);
new EventPusher(this, PUSH_THREADS);
}
ThreadPool.createNew(this, "pool management thread");
}
synchronized int getEventTime() {
return events.size();
}
synchronized void waitForEventTime(int time) {
while (getEventTime() < time) {
if (ended()) {
return;
}
try {
wait();
} catch (InterruptedException e) {
// IGNORE
}
}
}
synchronized int getSize() {
return members.size();
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.impl.registry.central.SuperPool#ended()
*/
synchronized boolean ended() {
return ended;
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.impl.registry.central.SuperPool#getName()
*/
String getName() {
return name;
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.impl.registry.central.SuperPool#join(byte[], byte[],
* ibis.ipl.impl.Location)
*/
synchronized IbisIdentifier join(byte[] implementationData,
byte[] clientAddress, Location location) throws Exception {
if (ended()) {
throw new Exception("Pool already ended");
}
String id = Integer.toString(nextID);
nextID++;
IbisIdentifier identifier = new IbisIdentifier(id, implementationData,
clientAddress, location, name);
members.add(new Member(identifier));
if (printEvents) {
System.out.println("Central Registry: " + identifier
+ " joined pool \"" + name + "\" now " + members.size()
+ " members");
}
events.add(new Event(events.size(), Event.JOIN, identifier, null));
notifyAll();
return identifier;
}
void writeBootstrap(DataOutputStream out) throws IOException {
Member[] peers = getRandomMembers(Protocol.BOOTSTRAP_LIST_SIZE);
out.writeInt(peers.length);
for (Member member : peers) {
member.ibis().writeTo(out);
}
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.impl.registry.central.SuperPool#leave(ibis.ipl.impl.IbisIdentifier)
*/
synchronized void leave(IbisIdentifier identifier) throws Exception {
if (!members.remove(identifier.myId)) {
logger.error("unknown ibis " + identifier + " tried to leave");
throw new Exception("ibis unknown: " + identifier);
}
if (printEvents) {
System.out.println("Central Registry: " + identifier
+ " left pool \"" + name + "\" now " + members.size()
+ " members");
}
events.add(new Event(events.size(), Event.LEAVE, identifier, null));
notifyAll();
Iterator<Entry<String, IbisIdentifier>> iterator = elections.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, IbisIdentifier> entry = iterator.next();
if (entry.getValue().equals(identifier)) {
iterator.remove();
events.add(new Event(events.size(), Event.UN_ELECT, identifier,
entry.getKey()));
notifyAll();
}
}
if (members.size() == 0) {
ended = true;
if (printEvents) {
System.err.println("Central Registry: " + "pool \"" + name
+ "\" ended");
} else {
logger.info("Central Registry: " + "pool \"" + name
+ "\" ended");
}
notifyAll();
}
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.impl.registry.central.SuperPool#dead(ibis.ipl.impl.IbisIdentifier)
*/
synchronized void dead(IbisIdentifier identifier) {
if (!members.remove(identifier.myId)) {
return;
}
if (printEvents) {
System.out.println("Central Registry: " + identifier
+ " died in pool \"" + name + "\" now " + members.size()
+ " members");
}
events.add(new Event(events.size(), Event.DIED, identifier, null));
notifyAll();
Iterator<Map.Entry<String, IbisIdentifier>> iterator = elections
.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, IbisIdentifier> entry = iterator.next();
if (entry.getValue().equals(identifier)) {
iterator.remove();
events.add(new Event(events.size(), Event.UN_ELECT, identifier,
entry.getKey()));
notifyAll();
}
}
if (members.size() == 0) {
ended = true;
if (printEvents) {
System.out.println("Central Registry: " + "pool " + name
+ " ended");
} else {
logger.info("Central Registry: " + "pool \"" + name
+ "\" ended");
}
notifyAll();
}
}
synchronized Event[] getEvents(int startTime, int maxSize) {
// logger.debug("getting events, startTime = " + startTime
// + ", maxSize = " + maxSize +
// ", event time = " + events.size());
int resultSize = events.size() - startTime;
if (resultSize > maxSize) {
resultSize = maxSize;
}
if (resultSize < 0) {
return new Event[0];
}
return events.subList(startTime, startTime + resultSize).toArray(
new Event[0]);
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.impl.registry.central.SuperPool#elect(java.lang.String,
* ibis.ipl.impl.IbisIdentifier)
*/
synchronized IbisIdentifier elect(String election, IbisIdentifier candidate) {
IbisIdentifier winner = elections.get(election);
if (winner == null) {
// Do the election now. The caller WINS! :)
winner = candidate;
elections.put(election, winner);
if (printEvents) {
System.out.println("Central Registry: " + winner
+ " won election \"" + election + "\" in pool \""
+ name + "\"");
}
events.add(new Event(events.size(), Event.ELECT, winner, election));
notifyAll();
}
return winner;
}
synchronized long getSequenceNumber() {
return nextSequenceNr++;
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.impl.registry.central.SuperPool#maybeDead(ibis.ipl.impl.IbisIdentifier)
*/
synchronized void maybeDead(IbisIdentifier identifier) {
// add to todo list :)
checkList.add(identifier);
notifyAll();
}
/*
* (non-Javadoc)
*
* @see ibis.ipl.impl.registry.central.SuperPool#signal(java.lang.String,
* ibis.ipl.impl.IbisIdentifier[])
*/
synchronized void signal(String signal, IbisIdentifier[] victims) {
ArrayList<IbisIdentifier> result = new ArrayList<IbisIdentifier>();
for (IbisIdentifier victim : victims) {
if (members.contains(victim.myId)) {
result.add(victim);
}
}
events.add(new Event(events.size(), Event.SIGNAL, result
.toArray(new IbisIdentifier[result.size()]), signal));
notifyAll();
}
void ping(IbisIdentifier ibis) {
if (ended()) {
return;
}
if (!isMember(ibis)) {
return;
}
logger.debug("pinging " + ibis);
Connection connection = null;
try {
logger.debug("creating connection to " + ibis);
connection = connectionFactory.connect(ibis, false);
logger.debug("connection created to " + ibis
+ ", send opcode, checking for reply");
connection.out().writeByte(Protocol.CLIENT_MAGIC_BYTE);
connection.out().writeByte(Protocol.OPCODE_PING);
connection.out().flush();
// get reply
connection.getAndCheckReply();
IbisIdentifier result = new IbisIdentifier(connection.in());
connection.close();
if (!result.equals(ibis)) {
throw new Exception("ping ended up at wrong ibis");
}
logger.debug("ping to " + ibis + " successful");
} catch (Exception e) {
logger.debug("error on pinging ibis " + ibis, e);
if (connection != null) {
connection.close();
}
dead(ibis);
}
}
void push(Member member) {
if (ended()) {
return;
}
if (!isMember(member.ibis())) {
return;
}
logger.debug("pushing entries to " + member);
Connection connection = null;
try {
int peerTime = 0;
if (keepNodeState) {
peerTime = member.getCurrentTime();
int localTime = getEventTime();
if (peerTime >= localTime) {
logger.debug("NOT pushing entries to " + member
+ ", nothing to do");
return;
}
}
logger.debug("creating connection to push events to "
+ member.ibis());
connection = connectionFactory.connect(member.ibis(), false);
logger.debug("connection to " + member.ibis() + " created");
connection.out().writeByte(Protocol.CLIENT_MAGIC_BYTE);
connection.out().writeByte(Protocol.OPCODE_PUSH);
connection.out().writeUTF(getName());
connection.out().flush();
if (!keepNodeState) {
logger.debug("waiting for peer time of peer " + member.ibis());
peerTime = connection.in().readInt();
}
int localTime = getEventTime();
logger.debug("peer " + member.ibis() + ", peer time = " + peerTime
+ ", localtime = " + localTime);
int sendEntries = localTime - peerTime;
if (sendEntries < 0) {
logger.debug("sendEntries " + sendEntries
+ " is negative, not sending events");
sendEntries = 0;
}
logger.debug("sending " + sendEntries + " entries to " + member.ibis());
connection.out().writeInt(sendEntries);
Event[] events = getEvents(peerTime, peerTime + sendEntries);
for (int i = 0; i < events.length; i++) {
events[i].writeTo(connection.out());
}
connection.getAndCheckReply();
if (keepNodeState) {
member.setCurrentTime(localTime);
}
connection.close();
logger.debug("connection to " + member.ibis() + " closed");
} catch (IOException e) {
logger.debug("cannot reach " + member.ibis(), e);
dead(member.ibis());
if (connection != null) {
connection.close();
}
}
}
private synchronized IbisIdentifier getSuspectMember() {
while (true) {
// wait for the list to become non-empty
while (checkList.size() == 0 && !ended()) {
try {
wait();
} catch (InterruptedException e) {
// IGNORE
}
}
// return if this pool ended anyway
if (ended()) {
return null;
}
IbisIdentifier result = checkList.iterator().next();
checkList.remove(result);
// return if still in pool
if (members.contains(result.myId)) {
return result;
}
}
}
/**
* contacts any suspect nodes when asked
*/
public void run() {
while (!ended()) {
IbisIdentifier suspect = getSuspectMember();
if (suspect != null) {
ping(suspect);
}
}
}
synchronized Member[] getRandomMembers(int size) {
return members.getRandom(size);
}
synchronized Member getRandomMember() {
return members.getRandom();
}
synchronized boolean isMember(IbisIdentifier ibis) {
return members.contains(ibis.myId);
}
synchronized Member getMember(int index) {
return members.get(index);
}
synchronized List<Member> getMemberList() {
return members.asList();
}
public String toString() {
return "Pool " + name + ": size = " + getSize() + ", event time = "
+ getEventTime();
}
}
|
package info.guardianproject.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.util.Log;
public class AssetUtil {
/** Read a properties file from /assets. Returns null if it does not exist. */
public static Properties getProperties(String name, Context context) {
Resources resources = context.getResources();
AssetManager assetManager = resources.getAssets();
// Read from the /assets directory
try {
InputStream inputStream = assetManager.open(name);
Properties properties = new Properties();
properties.load(inputStream);
return properties;
} catch (IOException e) {
Log.i("ChatSecure", "no chatsecure.properties available");
return null;
}
}
}
|
package info.tregmine.commands;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import static org.bukkit.ChatColor.*;
import info.tregmine.events.TregminePortalEvent;
import org.bukkit.Server;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginManager;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import info.tregmine.Tregmine;
import info.tregmine.api.Badge;
import info.tregmine.api.TregminePlayer;
import info.tregmine.database.DAOException;
import info.tregmine.database.IContext;
import info.tregmine.database.IWalletDAO;
import info.tregmine.database.ITradeDAO;
import info.tregmine.database.IEnchantmentDAO;
import info.tregmine.listeners.ExpListener;
import info.tregmine.api.math.MathUtil;
public class TradeCommand extends AbstractCommand implements Listener
{
String tradePre = YELLOW + "[Trade] ";
String type = "";
boolean isIllegal = false;
private enum TradeState {
ITEM_SELECT, BID, CONSIDER_BID;
};
private static class TradeContext
{
Inventory inventory;
TregminePlayer firstPlayer;
TregminePlayer secondPlayer;
TradeState state;
int bid;
}
private Map<TregminePlayer, TradeContext> activeTrades;
public TradeCommand(Tregmine tregmine)
{
super(tregmine, "trade");
activeTrades = new HashMap<TregminePlayer, TradeContext>();
PluginManager pluginMgm = tregmine.getServer().getPluginManager();
pluginMgm.registerEvents(this, tregmine);
}
@Override
public boolean handlePlayer(TregminePlayer player, String[] args)
{
if (args.length != 1) {
return false;
}
if (player.getChatState() != TregminePlayer.ChatState.CHAT) {
player.sendMessage(RED + "A trade is already in progress!");
return true;
}
Server server = tregmine.getServer();
String pattern = args[0];
List<TregminePlayer> candidates = tregmine.matchPlayer(pattern);
if (candidates.size() != 1) {
// TODO: error message
return true;
}
TregminePlayer target = candidates.get(0);
if (target.getChatState() != TregminePlayer.ChatState.CHAT) {
player.sendMessage(RED + target.getName() + "is in a trade!");
return true;
}
if (target.getId() == player.getId()) {
player.sendMessage(RED + "You cannot trade with yourself!");
return true;
}
double distance = MathUtil.calcDistance2d(player.getLocation(), target.getLocation());
if (!target.hasFlag(TregminePlayer.Flags.INVISIBLE) &&
(distance > player.getRank().getTradeDistance(player))) {
player.sendMessage(RED + "You can only trade with people less than " +
player.getRank().getTradeDistance(player) + " blocks away.");
return true;
}
Inventory inv = server.createInventory(null, InventoryType.CHEST);
player.openInventory(inv);
TradeContext ctx = new TradeContext();
ctx.inventory = inv;
ctx.firstPlayer = player;
ctx.secondPlayer = target;
ctx.state = TradeState.ITEM_SELECT;
activeTrades.put(player, ctx);
activeTrades.put(target, ctx);
player.setChatState(TregminePlayer.ChatState.TRADE);
target.setChatState(TregminePlayer.ChatState.TRADE);
player.sendMessage(YELLOW + "[Trade] You are now trading with "
+ target.getChatName() + YELLOW + ". What do you want "
+ "to offer?");
String extra = "";
if(isIllegal){
extra = ChatColor.RED + "[Trade] Warning! " + player.getChatName() + " has sent an item that has the " + type + " flag! This means you cannot sell it, use it to buy tools, and using it to craft will result in the product being flagged as well.";
}
target.sendMessage(YELLOW + "[Trade] You are now in a trade with "
+ player.getChatName() + YELLOW + ". To exit, type \"quit\".");
if(isIllegal){
target.sendMessage(extra);
}
return true;
}
@EventHandler
public void onInventoryClose(InventoryCloseEvent event)
{
TregminePlayer player = tregmine.getPlayer((Player) event.getPlayer());
TradeContext ctx = activeTrades.get(player);
if (ctx == null) {
return;
}
TregminePlayer target = ctx.secondPlayer;
target.sendMessage(tradePre + player.getChatName() + " "
+ YELLOW + " is offering: ");
player.sendMessage("[Trade] You are offering: ");
ItemStack[] contents = ctx.inventory.getContents();
for(ItemStack i : contents){
if(i == null){
//ABORT!
}
if(!isIllegal && i.getType() != Material.AIR){
ItemMeta im = i.getItemMeta();
List<String> lore = im.getLore();
if(lore.get(0).contains("CREATIVE") || lore.get(0).contains("SURVIVAL")){
isIllegal = true;
type = lore.get(0);
}
}
}
for (ItemStack stack : contents) {
if (stack == null) {
continue;
}
Material material = stack.getType();
int amount = stack.getAmount();
ItemMeta materialMeta = stack.getItemMeta();
int xpValue;
try{
String[] materialLore = materialMeta.getLore().toString().split(" ");
xpValue = Integer.parseInt(materialLore[2]);
} catch (NullPointerException e) {
xpValue = 0;
} catch (NumberFormatException e) {
xpValue = 0;
}
Map<Enchantment, Integer> enchantments = stack.getEnchantments();
if (material == Material.EXP_BOTTLE &&
xpValue > 0 &&
ExpListener.ITEM_NAME.equals(materialMeta.getDisplayName())) {
target.sendMessage(tradePre + amount + " XP Bottle holding "
+ xpValue + " levels");
player.sendMessage(tradePre + amount + " XP Bottle holding "
+ xpValue + " levels");
} else if (enchantments.size() > 0) {
target.sendMessage(tradePre + " Enchanted " + material.toString() + " with: ");
player.sendMessage(tradePre + " Enchanted " + material.toString() + " with: ");
try (IContext dbCtx = tregmine.createContext()) {
IEnchantmentDAO enchantDAO = dbCtx.getEnchantmentDAO();
for (Enchantment i : enchantments.keySet()) {
String enchantName = enchantDAO.localize(i.getName());
target.sendMessage("- " + enchantName +
" Level: " + enchantments.get(i).toString());
player.sendMessage("- " + enchantName +
" Level: " + enchantments.get(i).toString());
}
} catch (DAOException e) {
throw new RuntimeException(e);
}
} else {
target.sendMessage(tradePre + amount + " "
+ material.toString());
player.sendMessage(tradePre + amount + " "
+ material.toString());
}
}
target.sendMessage(YELLOW
+ "[Trade] To make a bid, type \"bid <tregs>\". "
+ "For example: bid 1000");
player.sendMessage(YELLOW + "[Trade] Waiting for "
+ target.getChatName() + YELLOW
+ " to make a bid. Type \"change\" to modify " + "your offer.");
ctx.state = TradeState.BID;
}
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event)
{
TregminePlayer player = tregmine.getPlayer(event.getPlayer());
if (player.getChatState() != TregminePlayer.ChatState.TRADE) {
return;
}
event.setCancelled(true);
TradeContext ctx = activeTrades.get(player);
if (ctx == null) {
return;
}
TregminePlayer first = ctx.firstPlayer;
TregminePlayer second = ctx.secondPlayer;
String text = event.getMessage();
String[] args = text.split(" ");
Tregmine.LOGGER.info("[TRADE " + first.getName() + ":" + second.getName() +
"] <" + player.getName() + "> " + text);
//Tregmine.LOGGER.info("state: " + ctx.state);
if ("quit".equals(args[0]) && args.length == 1) {
first.setChatState(TregminePlayer.ChatState.CHAT);
second.setChatState(TregminePlayer.ChatState.CHAT);
activeTrades.remove(first);
activeTrades.remove(second);
if (ctx.state == TradeState.ITEM_SELECT) {
first.closeInventory();
}
// Restore contents to player inventory
ItemStack[] contents = ctx.inventory.getContents();
Inventory firstInv = first.getInventory();
for (ItemStack stack : contents) {
if (stack == null) {
continue;
}
firstInv.addItem(stack);
}
first.sendMessage(YELLOW + "[Trade] Trade ended.");
second.sendMessage(YELLOW + "[Trade] Trade ended.");
}
else if ("bid".equalsIgnoreCase(args[0]) && args.length == 2) {
if (second != player) {
player.sendMessage(RED + "[Trade] You can't make a bid!");
return;
}
if (ctx.state != TradeState.BID) {
player.sendMessage(RED
+ "[Trade] You can't make a bid right now.");
return;
}
int amount = 0;
try {
amount = Integer.parseInt(args[1]);
if (amount < 0) {
player.sendMessage(RED
+ "[Trade] You have to bid an integer "
+ "number of tregs.");
return;
}
} catch (NumberFormatException e) {
player.sendMessage(RED + "[Trade] You have to bid an integer "
+ "number of tregs.");
return;
}
try (IContext dbCtx = tregmine.createContext()) {
IWalletDAO walletDAO = dbCtx.getWalletDAO();
long balance = walletDAO.balance(second);
if (amount > balance) {
player.sendMessage(RED + "[Trade] You only have " + balance
+ " tregs!");
return;
}
} catch (DAOException e) {
throw new RuntimeException(e);
}
first.sendMessage(tradePre + second.getChatName() + YELLOW
+ " bid " + amount + " tregs. Type \"accept\" to "
+ "proceed with the trade. Type \"change\" to modify "
+ "your offer. Type \"quit\" to stop trading.");
second.sendMessage(YELLOW + "[Trade] You bid " + amount + " tregs.");
ctx.bid = amount;
ctx.state = TradeState.CONSIDER_BID;
}
else if ("change".equalsIgnoreCase(args[0]) && args.length == 1) {
if (first != player) {
player.sendMessage(RED + "[Trade] You can't change the offer!");
return;
}
player.openInventory(ctx.inventory);
ctx.state = TradeState.ITEM_SELECT;
}
else if ("accept".equals(args[0]) && args.length == 1) {
if (first != player) {
player.sendMessage(RED + "[Trade] You can't accept an offer!");
return;
}
ItemStack[] contents = ctx.inventory.getContents();
int t = 0;
for (ItemStack tis : contents) {
if (tis == null) {
continue;
}
t++;
}
int p = 0;
Inventory secondInv = second.getInventory();
for (ItemStack pis : secondInv.getContents()) {
if (pis != null) {
continue;
}
p++;
}
if (p < t) {
int diff = t - p;
first.sendMessage(tradePre + second.getChatName() + YELLOW +
" doesn't have enough inventory space, please wait a " +
"minute and try again :)");
second.sendMessage(tradePre + "You need to remove " + diff +
" item stack(s) from your inventory to be able to recieve " +
"the items!");
return;
}
// Withdraw ctx.bid tregs from second players wallet
// Add ctx.bid tregs from first players wallet
try (IContext dbCtx = tregmine.createContext()) {
IWalletDAO walletDAO = dbCtx.getWalletDAO();
ITradeDAO tradeDAO = dbCtx.getTradeDAO();
if (walletDAO.take(second, ctx.bid)) {
walletDAO.add(first, ctx.bid);
walletDAO.insertTransaction(second.getId(), first.getId(),
ctx.bid);
int tradeId = tradeDAO.insertTrade(first.getId(),
second.getId(),
ctx.bid);
tradeDAO.insertStacks(tradeId, contents);
first.sendMessage(tradePre + ctx.bid
+ " tregs was " + "added to your wallet!");
second.sendMessage(tradePre + ctx.bid
+ " tregs was " + "withdrawn to your wallet!");
if ((tradeDAO.getAmountofTrades(first.getId()) > 100) &&
!(first.getBadgeLevel(Badge.MERCHANT) == 0)){
first.awardBadgeLevel(Badge.MERCHANT, "For completing 100 transactions!");
}
}
else {
first.sendMessage(RED + "[Trade] Failed to withdraw "
+ ctx.bid + " from the wallet of "
+ second.getChatName() + "!");
return;
}
} catch (DAOException e) {
throw new RuntimeException(e);
}
// Move items to second players inventory
for (ItemStack stack : contents) {
if (stack == null) {
continue;
}
secondInv.addItem(stack);
}
// Finalize
first.setChatState(TregminePlayer.ChatState.CHAT);
second.setChatState(TregminePlayer.ChatState.CHAT);
activeTrades.remove(first);
activeTrades.remove(second);
first.giveExp(5);
second.giveExp(5);
}
else {
first.sendMessage(tradePre + WHITE + "<"
+ player.getChatName() + WHITE + "> " + text);
second.sendMessage(tradePre + WHITE + "<"
+ player.getChatName() + WHITE + "> " + text);
}
}
@EventHandler
public void onPortalUsage(TregminePortalEvent event)
{
TradeContext ctx = activeTrades.get(event.getPlayer());
if (ctx == null) {
return;
}
TregminePlayer first = ctx.firstPlayer;
TregminePlayer second = ctx.secondPlayer;
first.setChatState(TregminePlayer.ChatState.CHAT);
second.setChatState(TregminePlayer.ChatState.CHAT);
activeTrades.remove(first);
activeTrades.remove(second);
if (ctx.state == TradeState.ITEM_SELECT) {
first.closeInventory();
}
first.sendMessage(YELLOW + "[Trade] Trade ended due to portal use! Now that was silly...");
second.sendMessage(YELLOW + "[Trade] Trade ended due to portal use! Now that was silly...");
}
}
|
package org.commcare.suite.model;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapList;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;
/**
* An action defines a user interface element that can be
* triggered by the user to fire off one or more stack operations
* in the current session
*
* @author ctsims
*/
public class Action implements Externalizable {
private DisplayUnit display;
private Vector<StackOperation> stackOps;
/**
* Serialization only!!!
*/
public Action() {
}
/**
* Creates an Action model with the associated display details and stack
* operations set.
*/
public Action(DisplayUnit display, Vector<StackOperation> stackOps) {
this.display = display;
this.stackOps = stackOps;
}
/**
* @return The Display model for showing this action to the user
*/
public DisplayUnit getDisplay() {
return display;
}
/**
* @return A vector of the StackOperation models which
* should be processed sequentially upon this action
* being triggered by the user.
*/
public Vector<StackOperation> getStackOperations() {
return stackOps;
}
@Override
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
this.display = (DisplayUnit)ExtUtil.read(in, DisplayUnit.class, pf);
this.stackOps = (Vector<StackOperation>)ExtUtil.read(in, new ExtWrapList(StackOperation.class), pf);
}
@Override
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.write(out, display);
ExtUtil.write(out, new ExtWrapList(stackOps));
}
}
|
package verification;
import javax.swing.*;
import verification.platu.project.Project;
import verification.platu.stategraph.StateGraph;
import verification.timed_state_exploration.StateExploration;
import biomodel.gui.PropertyList;
import biomodel.util.Utility;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Properties;
import java.util.prefs.Preferences;
import java.util.regex.*;
import java.util.HashMap;
import lpn.parser.Abstraction;
import lpn.parser.LhpnFile;
import main.*;
/**
* This class creates a GUI front end for the Verification tool. It provides the
* necessary options to run an atacs simulation of the circuit and manage the
* results from the BioSim GUI.
*
* @author Kevin Jones
*/
public class Verification extends JPanel implements ActionListener, Runnable {
private static final long serialVersionUID = -5806315070287184299L;
private JButton save, run, viewCircuit, viewTrace, viewLog, addComponent,
removeComponent, addSFile;
private JLabel algorithm, timingMethod, timingOptions, otherOptions,
otherOptions2, compilation, bddSizeLabel, advTiming, abstractLabel,
listLabel;
public JRadioButton untimed, geometric, posets, bag, bap, baptdc, verify,
vergate, orbits, search, trace, bdd, dbm, smt, untimedStateSearch, untimedPOR, lhpn, view, none,
simplify, abstractLhpn, dbm2;
private JCheckBox abst, partialOrder, dot, verbose, graph, genrg,
timsubset, superset, infopt, orbmatch, interleav, prune, disabling,
nofail, noproj, keepgoing, explpn, nochecks, reduction, newTab,
postProc, redCheck, xForm2, expandRate;
private JTextField bddSize, backgroundField, componentField, preprocStr;
private JList sList;
private DefaultListModel sListModel;
private ButtonGroup timingMethodGroup, algorithmGroup, abstractionGroup;
private String directory, separator, root, verFile, oldBdd,
sourceFileNoPath;
public String verifyFile;
private boolean change, atacs, lema;
private PropertyList componentList;
private AbstPane abstPane;
private Log log;
private Gui biosim;
/**
* This is the constructor for the Verification class. It initializes all
* the input fields, puts them on panels, adds the panels to the frame, and
* then displays the frame.
*/
public Verification(String directory, String verName, String filename,
Log log, Gui biosim, boolean lema, boolean atacs) {
if (File.separator.equals("\\")) {
separator = "\\\\";
} else {
separator = File.separator;
}
this.atacs = atacs;
this.lema = lema;
this.biosim = biosim;
this.log = log;
this.directory = directory;
verFile = verName + ".ver";
String[] tempArray = filename.split("\\.");
String traceFilename = tempArray[0] + ".trace";
File traceFile = new File(traceFilename);
String[] tempDir = directory.split(separator);
root = tempDir[0];
for (int i = 1; i < tempDir.length - 1; i++) {
root = root + separator + tempDir[i];
}
this.setMaximumSize(new Dimension(300,300));
this.setMinimumSize(new Dimension(300,300));
JPanel abstractionPanel = new JPanel();
abstractionPanel.setMaximumSize(new Dimension(1000, 35));
JPanel timingRadioPanel = new JPanel();
timingRadioPanel.setMaximumSize(new Dimension(1000, 35));
JPanel timingCheckBoxPanel = new JPanel();
timingCheckBoxPanel.setMaximumSize(new Dimension(1000, 30));
JPanel otherPanel = new JPanel();
otherPanel.setMaximumSize(new Dimension(1000, 35));
JPanel preprocPanel = new JPanel();
preprocPanel.setMaximumSize(new Dimension(1000, 700));
JPanel algorithmPanel = new JPanel();
algorithmPanel.setMaximumSize(new Dimension(1000, 35));
JPanel buttonPanel = new JPanel();
JPanel compilationPanel = new JPanel();
compilationPanel.setMaximumSize(new Dimension(1000, 35));
JPanel advancedPanel = new JPanel();
advancedPanel.setMaximumSize(new Dimension(1000, 35));
JPanel bddPanel = new JPanel();
bddPanel.setMaximumSize(new Dimension(1000, 35));
JPanel pruningPanel = new JPanel();
pruningPanel.setMaximumSize(new Dimension(1000, 35));
JPanel advTimingPanel = new JPanel();
advTimingPanel.setMaximumSize(new Dimension(1000, 62));
advTimingPanel.setPreferredSize(new Dimension(1000, 62));
bddSize = new JTextField("");
bddSize.setPreferredSize(new Dimension(40, 18));
oldBdd = bddSize.getText();
componentField = new JTextField("");
componentList = new PropertyList("");
abstractLabel = new JLabel("Abstraction:");
algorithm = new JLabel("Verification Algorithm:");
timingMethod = new JLabel("Timing Method:");
timingOptions = new JLabel("Timing Options:");
otherOptions = new JLabel("Other Options:");
otherOptions2 = new JLabel("Other Options:");
compilation = new JLabel("Compilation Options:");
bddSizeLabel = new JLabel("BDD Linkspace Size:");
advTiming = new JLabel("Timing Options:");
//preprocLabel = new JLabel("Preprocess Command:");
listLabel = new JLabel("Assembly Files:");
JPanel labelPane = new JPanel();
labelPane.add(listLabel);
sListModel = new DefaultListModel();
sList = new JList(sListModel);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 200));
scroll.setPreferredSize(new Dimension(276, 132));
scroll.setViewportView(sList);
JPanel scrollPane = new JPanel();
scrollPane.add(scroll);
addSFile = new JButton("Add File");
addSFile.addActionListener(this);
JPanel buttonPane = new JPanel();
buttonPane.add(addSFile);
//preprocStr = new JTextField();
//preprocStr.setPreferredSize(new Dimension(500, 18));
// Initializes the radio buttons and check boxes
// Abstraction Options
none = new JRadioButton("None");
simplify = new JRadioButton("Simplification");
abstractLhpn = new JRadioButton("Abstraction");
// Timing Methods
if (atacs) {
untimed = new JRadioButton("Untimed");
geometric = new JRadioButton("Geometric");
posets = new JRadioButton("POSETs");
bag = new JRadioButton("BAG");
bap = new JRadioButton("BAP");
baptdc = new JRadioButton("BAPTDC");
untimed.addActionListener(this);
geometric.addActionListener(this);
posets.addActionListener(this);
bag.addActionListener(this);
bap.addActionListener(this);
baptdc.addActionListener(this);
} else {
untimedStateSearch = new JRadioButton("Untimed");
untimedPOR = new JRadioButton("UntimedPOR");
bdd = new JRadioButton("BDD");
dbm = new JRadioButton("DBM");
smt = new JRadioButton("SMT");
dbm2 = new JRadioButton("DBM2");
bdd.addActionListener(this);
dbm.addActionListener(this);
smt.addActionListener(this);
dbm2.addActionListener(this);
}
lhpn = new JRadioButton("LPN");
view = new JRadioButton("View");
lhpn.addActionListener(this);
view.addActionListener(this);
// Basic Timing Options
abst = new JCheckBox("Abstract");
partialOrder = new JCheckBox("Partial Order");
abst.addActionListener(this);
partialOrder.addActionListener(this);
// Other Basic Options
dot = new JCheckBox("Dot");
verbose = new JCheckBox("Verbose");
graph = new JCheckBox("Show State Graph");
dot.addActionListener(this);
verbose.addActionListener(this);
graph.addActionListener(this);
// Verification Algorithms
verify = new JRadioButton("Verify");
vergate = new JRadioButton("Verify Gates");
orbits = new JRadioButton("Orbits");
search = new JRadioButton("Search");
trace = new JRadioButton("Trace");
verify.addActionListener(this);
vergate.addActionListener(this);
orbits.addActionListener(this);
search.addActionListener(this);
trace.addActionListener(this);
// Compilations Options
newTab = new JCheckBox("New Tab");
postProc = new JCheckBox("Post Processing");
redCheck = new JCheckBox("Redundancy Check");
xForm2 = new JCheckBox("Don't Use Transform 2");
expandRate = new JCheckBox("Expand Rate");
newTab.addActionListener(this);
postProc.addActionListener(this);
redCheck.addActionListener(this);
xForm2.addActionListener(this);
expandRate.addActionListener(this);
// Advanced Timing Options
genrg = new JCheckBox("Generate RG");
timsubset = new JCheckBox("Subsets");
superset = new JCheckBox("Supersets");
infopt = new JCheckBox("Infinity Optimization");
orbmatch = new JCheckBox("Orbits Match");
interleav = new JCheckBox("Interleave");
prune = new JCheckBox("Prune");
disabling = new JCheckBox("Disabling");
nofail = new JCheckBox("No fail");
noproj = new JCheckBox("No project");
keepgoing = new JCheckBox("Keep going");
explpn = new JCheckBox("Expand LPN");
genrg.addActionListener(this);
timsubset.addActionListener(this);
superset.addActionListener(this);
infopt.addActionListener(this);
orbmatch.addActionListener(this);
interleav.addActionListener(this);
prune.addActionListener(this);
disabling.addActionListener(this);
nofail.addActionListener(this);
noproj.addActionListener(this);
keepgoing.addActionListener(this);
explpn.addActionListener(this);
// Other Advanced Options
nochecks = new JCheckBox("No checks");
reduction = new JCheckBox("Reduction");
nochecks.addActionListener(this);
reduction.addActionListener(this);
// Component List
addComponent = new JButton("Add Component");
removeComponent = new JButton("Remove Component");
GridBagConstraints constraints = new GridBagConstraints();
JPanel componentPanel = Utility.createPanel(this, "Components",
componentList, addComponent, removeComponent, null);
constraints.gridx = 0;
constraints.gridy = 1;
abstractionGroup = new ButtonGroup();
timingMethodGroup = new ButtonGroup();
algorithmGroup = new ButtonGroup();
none.setSelected(true);
if (lema) {
dbm.setSelected(true);
} else {
untimed.setSelected(true);
}
verify.setSelected(true);
// Groups the radio buttons
abstractionGroup.add(none);
abstractionGroup.add(simplify);
abstractionGroup.add(abstractLhpn);
if (lema) {
timingMethodGroup.add(untimedStateSearch);
timingMethodGroup.add(untimedPOR);
timingMethodGroup.add(bdd);
timingMethodGroup.add(dbm);
timingMethodGroup.add(smt);
timingMethodGroup.add(dbm2);
} else {
timingMethodGroup.add(untimed);
timingMethodGroup.add(geometric);
timingMethodGroup.add(posets);
timingMethodGroup.add(bag);
timingMethodGroup.add(bap);
timingMethodGroup.add(baptdc);
}
timingMethodGroup.add(lhpn);
timingMethodGroup.add(view);
algorithmGroup.add(verify);
algorithmGroup.add(vergate);
algorithmGroup.add(orbits);
algorithmGroup.add(search);
algorithmGroup.add(trace);
JPanel basicOptions = new JPanel();
JPanel advOptions = new JPanel();
// Adds the buttons to their panels
abstractionPanel.add(abstractLabel);
abstractionPanel.add(none);
abstractionPanel.add(simplify);
abstractionPanel.add(abstractLhpn);
timingRadioPanel.add(timingMethod);
if (lema) {
timingRadioPanel.add(untimedStateSearch);
timingRadioPanel.add(untimedPOR);
timingRadioPanel.add(bdd);
timingRadioPanel.add(dbm);
timingRadioPanel.add(smt);
timingRadioPanel.add(dbm2);
} else {
timingRadioPanel.add(untimed);
timingRadioPanel.add(geometric);
timingRadioPanel.add(posets);
timingRadioPanel.add(bag);
timingRadioPanel.add(bap);
timingRadioPanel.add(baptdc);
}
timingRadioPanel.add(lhpn);
timingRadioPanel.add(view);
timingCheckBoxPanel.add(timingOptions);
timingCheckBoxPanel.add(abst);
timingCheckBoxPanel.add(partialOrder);
otherPanel.add(otherOptions);
otherPanel.add(dot);
otherPanel.add(verbose);
otherPanel.add(graph);
preprocPanel.add(labelPane);
preprocPanel.add(scrollPane);
preprocPanel.add(buttonPane);
algorithmPanel.add(algorithm);
algorithmPanel.add(verify);
algorithmPanel.add(vergate);
algorithmPanel.add(orbits);
algorithmPanel.add(search);
algorithmPanel.add(trace);
compilationPanel.add(compilation);
compilationPanel.add(newTab);
compilationPanel.add(postProc);
compilationPanel.add(redCheck);
compilationPanel.add(xForm2);
compilationPanel.add(expandRate);
advTimingPanel.add(advTiming);
advTimingPanel.add(genrg);
advTimingPanel.add(timsubset);
advTimingPanel.add(superset);
advTimingPanel.add(infopt);
advTimingPanel.add(orbmatch);
advTimingPanel.add(interleav);
advTimingPanel.add(prune);
advTimingPanel.add(disabling);
advTimingPanel.add(nofail);
advTimingPanel.add(noproj);
advTimingPanel.add(keepgoing);
advTimingPanel.add(explpn);
advancedPanel.add(otherOptions2);
advancedPanel.add(nochecks);
advancedPanel.add(reduction);
bddPanel.add(bddSizeLabel);
bddPanel.add(bddSize);
// load parameters
Properties load = new Properties();
verifyFile = "";
try {
FileInputStream in = new FileInputStream(new File(directory
+ separator + verFile));
load.load(in);
in.close();
if (load.containsKey("verification.file")) {
verifyFile = load.getProperty("verification.file");
}
if (load.containsKey("verification.bddSize")) {
bddSize.setText(load.getProperty("verification .bddSize"));
}
if (load.containsKey("verification.component")) {
componentField.setText(load
.getProperty("verification.component"));
}
Integer i = 0;
while (load.containsKey("verification.compList" + i.toString())) {
componentList.addItem(load.getProperty("verification.compList"
+ i.toString()));
i++;
}
if (load.containsKey("verification.abstraction")) {
if (load.getProperty("verification.abstraction").equals("none")) {
none.setSelected(true);
} else if (load.getProperty("verification.abstraction").equals(
"simplify")) {
simplify.setSelected(true);
} else {
abstractLhpn.setSelected(true);
}
}
abstPane = new AbstPane(root + separator + verName, this, log,
lema, atacs);
if (load.containsKey("verification.timing.methods")) {
if (atacs) {
if (load.getProperty("verification.timing.methods").equals(
"untimed")) {
untimed.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("geometric")) {
geometric.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("posets")) {
posets.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("bag")) {
bag.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("bap")) {
bap.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("baptdc")) {
baptdc.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("lhpn")) {
lhpn.setSelected(true);
} else {
view.setSelected(true);
}
} else {
if (load.getProperty("verification.timing.methods").equals(
"bdd")) {
bdd.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("dbm")) {
dbm.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("smt")) {
smt.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("untimedStateSearch")) {
untimedStateSearch.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("untimedPOR")) {
untimedPOR.setSelected(true);
} else if (load.getProperty("verification.timing.methods")
.equals("lhpn")) {
lhpn.setSelected(true);
} else {
view.setSelected(true);
}
}
}
if (load.containsKey("verification.Abst")) {
if (load.getProperty("verification.Abst").equals("true")) {
abst.setSelected(true);
}
}
if (load.containsKey("verification.partial.order")) {
if (load.getProperty("verification.partial.order").equals(
"true")) {
partialOrder.setSelected(true);
}
}
if (load.containsKey("verification.Dot")) {
if (load.getProperty("verification.Dot").equals("true")) {
dot.setSelected(true);
}
}
if (load.containsKey("verification.Verb")) {
if (load.getProperty("verification.Verb").equals("true")) {
verbose.setSelected(true);
}
}
if (load.containsKey("verification.Graph")) {
if (load.getProperty("verification.Graph").equals("true")) {
graph.setSelected(true);
}
}
if (load.containsKey("verification.partial.order")) {
if (load.getProperty("verification.partial.order").equals(
"true")) {
partialOrder.setSelected(true);
}
}
if (load.containsKey("verification.partial.order")) {
if (load.getProperty("verification.partial.order").equals(
"true")) {
partialOrder.setSelected(true);
}
}
if (load.containsKey("verification.algorithm")) {
if (load.getProperty("verification.algorithm").equals("verify")) {
verify.setSelected(true);
} else if (load.getProperty("verification.algorithm").equals(
"vergate")) {
vergate.setSelected(true);
} else if (load.getProperty("verification.algorithm").equals(
"orbits")) {
orbits.setSelected(true);
} else if (load.getProperty("verification.algorithm").equals(
"search")) {
search.setSelected(true);
} else if (load.getProperty("verification.algorithm").equals(
"trace")) {
trace.setSelected(true);
}
}
if (load.containsKey("verification.compilation.newTab")) {
if (load.getProperty("verification.compilation.newTab").equals(
"true")) {
newTab.setSelected(true);
}
}
if (load.containsKey("verification.compilation.postProc")) {
if (load.getProperty("verification.compilation.postProc")
.equals("true")) {
postProc.setSelected(true);
}
}
if (load.containsKey("verification.compilation.redCheck")) {
if (load.getProperty("verification.compilation.redCheck")
.equals("true")) {
redCheck.setSelected(true);
}
}
if (load.containsKey("verification.compilation.xForm2")) {
if (load.getProperty("verification.compilation.xForm2").equals(
"true")) {
xForm2.setSelected(true);
}
}
if (load.containsKey("verification.compilation.expandRate")) {
if (load.getProperty("verification.compilation.expandRate")
.equals("true")) {
expandRate.setSelected(true);
}
}
if (load.containsKey("verification.timing.genrg")) {
if (load.getProperty("verification.timing.genrg")
.equals("true")) {
genrg.setSelected(true);
}
}
if (load.containsKey("verification.timing.subset")) {
if (load.getProperty("verification.timing.subset").equals(
"true")) {
timsubset.setSelected(true);
}
}
if (load.containsKey("verification.timing.superset")) {
if (load.getProperty("verification.timing.superset").equals(
"true")) {
superset.setSelected(true);
}
}
if (load.containsKey("verification.timing.infopt")) {
if (load.getProperty("verification.timing.infopt").equals(
"true")) {
infopt.setSelected(true);
}
}
if (load.containsKey("verification.timing.orbmatch")) {
if (load.getProperty("verification.timing.orbmatch").equals(
"true")) {
orbmatch.setSelected(true);
}
}
if (load.containsKey("verification.timing.interleav")) {
if (load.getProperty("verification.timing.interleav").equals(
"true")) {
interleav.setSelected(true);
}
}
if (load.containsKey("verification.timing.prune")) {
if (load.getProperty("verification.timing.prune")
.equals("true")) {
prune.setSelected(true);
}
}
if (load.containsKey("verification.timing.disabling")) {
if (load.getProperty("verification.timing.disabling").equals(
"true")) {
disabling.setSelected(true);
}
}
if (load.containsKey("verification.timing.nofail")) {
if (load.getProperty("verification.timing.nofail").equals(
"true")) {
nofail.setSelected(true);
}
}
if (load.containsKey("verification.timing.noproj")) {
if (load.getProperty("verification.timing.noproj").equals(
"true")) {
nofail.setSelected(true);
}
}
if (load.containsKey("verification.timing.explpn")) {
if (load.getProperty("verification.timing.explpn").equals(
"true")) {
explpn.setSelected(true);
}
}
if (load.containsKey("verification.nochecks")) {
if (load.getProperty("verification.nochecks").equals("true")) {
nochecks.setSelected(true);
}
}
if (load.containsKey("verification.reduction")) {
if (load.getProperty("verification.reduction").equals("true")) {
reduction.setSelected(true);
}
}
if (verifyFile.endsWith(".s")) {
sListModel.addElement(verifyFile);
}
if (load.containsKey("verification.sList")) {
String concatList = load.getProperty("verification.sList");
String[] list = concatList.split("\\s");
for (String s : list) {
sListModel.addElement(s);
}
}
if (load.containsKey("abstraction.interesting")) {
String intVars = load.getProperty("abstraction.interesting");
String[] array = intVars.split(" ");
for (String s : array) {
if (!s.equals("")) {
abstPane.addIntVar(s);
}
}
}
HashMap<Integer, String> preOrder = new HashMap<Integer, String>();
HashMap<Integer, String> loopOrder = new HashMap<Integer, String>();
HashMap<Integer, String> postOrder = new HashMap<Integer, String>();
boolean containsAbstractions = false;
for (String s : abstPane.transforms) {
if (load.containsKey(s)) {
containsAbstractions = true;
}
}
for (String s : abstPane.transforms) {
if (load.containsKey("abstraction.transform." + s)) {
if (load.getProperty("abstraction.transform." + s).contains("preloop")) {
Pattern prePattern = Pattern.compile("preloop(\\d+)");
Matcher intMatch = prePattern.matcher(load
.getProperty("abstraction.transform." + s));
if (intMatch.find()) {
Integer index = Integer.parseInt(intMatch.group(1));
preOrder.put(index, s);
} else {
abstPane.addPreXform(s);
}
}
else {
abstPane.preAbsModel.removeElement(s);
}
if (load.getProperty("abstraction.transform." + s).contains("mainloop")) {
Pattern loopPattern = Pattern
.compile("mainloop(\\d+)");
Matcher intMatch = loopPattern.matcher(load
.getProperty("abstraction.transform." + s));
if (intMatch.find()) {
Integer index = Integer.parseInt(intMatch.group(1));
loopOrder.put(index, s);
} else {
abstPane.addLoopXform(s);
}
}
else {
abstPane.loopAbsModel.removeElement(s);
}
if (load.getProperty("abstraction.transform." + s).contains("postloop")) {
Pattern postPattern = Pattern
.compile("postloop(\\d+)");
Matcher intMatch = postPattern.matcher(load
.getProperty("abstraction.transform." + s));
if (intMatch.find()) {
Integer index = Integer.parseInt(intMatch.group(1));
postOrder.put(index, s);
} else {
abstPane.addPostXform(s);
}
}
else {
abstPane.postAbsModel.removeElement(s);
}
}
else if (containsAbstractions) {
abstPane.preAbsModel.removeElement(s);
abstPane.loopAbsModel.removeElement(s);
abstPane.postAbsModel.removeElement(s);
}
}
if (preOrder.size() > 0) {
abstPane.preAbsModel.removeAllElements();
}
for (Integer j = 0; j < preOrder.size(); j++) {
abstPane.preAbsModel.addElement(preOrder.get(j));
}
if (loopOrder.size() > 0) {
abstPane.loopAbsModel.removeAllElements();
}
for (Integer j = 0; j < loopOrder.size(); j++) {
abstPane.loopAbsModel.addElement(loopOrder.get(j));
}
if (postOrder.size() > 0) {
abstPane.postAbsModel.removeAllElements();
}
for (Integer j = 0; j < postOrder.size(); j++) {
abstPane.postAbsModel.addElement(postOrder.get(j));
}
abstPane.preAbs.setListData(abstPane.preAbsModel.toArray());
abstPane.loopAbs.setListData(abstPane.loopAbsModel.toArray());
abstPane.postAbs.setListData(abstPane.postAbsModel.toArray());
if (load.containsKey("abstraction.transforms")) {
String xforms = load.getProperty("abstraction.transforms");
String[] array = xforms.split(", ");
for (String s : array) {
if (!s.equals("")) {
abstPane.addLoopXform(s.replace(",", ""));
}
}
}
if (load.containsKey("abstraction.factor")) {
abstPane.factorField.setText(load
.getProperty("abstraction.factor"));
}
if (load.containsKey("abstraction.iterations")) {
abstPane.iterField.setText(load
.getProperty("abstraction.iterations"));
}
tempArray = verifyFile.split(separator);
sourceFileNoPath = tempArray[tempArray.length - 1];
backgroundField = new JTextField(sourceFileNoPath);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
// Creates the run button
run = new JButton("Save and Verify");
run.addActionListener(this);
buttonPanel.add(run);
run.setMnemonic(KeyEvent.VK_S);
// Creates the save button
save = new JButton("Save Parameters");
save.addActionListener(this);
buttonPanel.add(save);
save.setMnemonic(KeyEvent.VK_P);
// Creates the view circuit button
viewCircuit = new JButton("View Circuit");
viewCircuit.addActionListener(this);
viewCircuit.setMnemonic(KeyEvent.VK_C);
// Creates the view trace button
viewTrace = new JButton("View Trace");
viewTrace.addActionListener(this);
buttonPanel.add(viewTrace);
if (!traceFile.exists()) {
viewTrace.setEnabled(false);
}
viewTrace.setMnemonic(KeyEvent.VK_T);
// Creates the view log button
viewLog = new JButton("View Log");
viewLog.addActionListener(this);
buttonPanel.add(viewLog);
viewLog.setMnemonic(KeyEvent.VK_V);
viewLog.setEnabled(false);
JPanel backgroundPanel = new JPanel();
JLabel backgroundLabel = new JLabel("Model File:");
tempArray = verifyFile.split(separator);
JLabel componentLabel = new JLabel("Component:");
componentField.setPreferredSize(new Dimension(200, 20));
String sourceFile = tempArray[tempArray.length - 1];
backgroundField = new JTextField(sourceFile);
backgroundField.setMaximumSize(new Dimension(200, 20));
backgroundField.setEditable(false);
backgroundPanel.add(backgroundLabel);
backgroundPanel.add(backgroundField);
if (verifyFile.endsWith(".vhd")) {
backgroundPanel.add(componentLabel);
backgroundPanel.add(componentField);
}
backgroundPanel.setMaximumSize(new Dimension(500, 30));
basicOptions.add(backgroundPanel);
basicOptions.add(abstractionPanel);
basicOptions.add(timingRadioPanel);
if (!lema) {
basicOptions.add(timingCheckBoxPanel);
}
basicOptions.add(otherPanel);
//if (lema) {
// basicOptions.add(preprocPanel);
if (!lema) {
basicOptions.add(algorithmPanel);
}
if (verifyFile.endsWith(".vhd")) {
basicOptions.add(componentPanel);
}
basicOptions.setLayout(new BoxLayout(basicOptions, BoxLayout.Y_AXIS));
basicOptions.add(Box.createVerticalGlue());
advOptions.add(compilationPanel);
advOptions.add(advTimingPanel);
advOptions.add(advancedPanel);
advOptions.add(bddPanel);
advOptions.setLayout(new BoxLayout(advOptions, BoxLayout.Y_AXIS));
advOptions.add(Box.createVerticalGlue());
JTabbedPane tab = new JTabbedPane();
tab.addTab("Basic Options", basicOptions);
tab.addTab("Advanced Options", advOptions);
tab.addTab("Abstraction Options", abstPane);
tab.setPreferredSize(new Dimension(1000, 480));
this.setLayout(new BorderLayout());
this.add(tab, BorderLayout.PAGE_START);
change = false;
}
/**
* This method performs different functions depending on what menu items or
* buttons are selected.
*
* @throws
* @throws
*/
public void actionPerformed(ActionEvent e) {
change = true;
if (e.getSource() == run) {
save(verFile);
new Thread(this).start();
} else if (e.getSource() == save) {
log.addText("Saving:\n" + directory + separator + verFile + "\n");
save(verFile);
} else if (e.getSource() == viewCircuit) {
viewCircuit();
} else if (e.getSource() == viewTrace) {
viewTrace();
} else if (e.getSource() == viewLog) {
viewLog();
} else if (e.getSource() == addComponent) {
String[] vhdlFiles = new File(root).list();
ArrayList<String> tempFiles = new ArrayList<String>();
for (int i = 0; i < vhdlFiles.length; i++) {
if (vhdlFiles[i].endsWith(".vhd")
&& !vhdlFiles[i].equals(sourceFileNoPath)) {
tempFiles.add(vhdlFiles[i]);
}
}
vhdlFiles = new String[tempFiles.size()];
for (int i = 0; i < vhdlFiles.length; i++) {
vhdlFiles[i] = tempFiles.get(i);
}
String filename = (String) JOptionPane.showInputDialog(this, "",
"Select Component", JOptionPane.PLAIN_MESSAGE, null,
vhdlFiles, vhdlFiles[0]);
if (filename != null) {
String[] comps = componentList.getItems();
boolean contains = false;
for (int i = 0; i < comps.length; i++) {
if (comps[i].equals(filename)) {
contains = true;
}
}
if (!filename.endsWith(".vhd")) {
JOptionPane.showMessageDialog(Gui.frame,
"You must select a valid VHDL file.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
} else if (new File(directory + separator + filename).exists()
|| filename.equals(sourceFileNoPath) || contains) {
JOptionPane
.showMessageDialog(
Gui.frame,
"This component is already contained in this tool.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
componentList.addItem(filename);
return;
}
} else if (e.getSource() == removeComponent) {
if (componentList.getSelectedValue() != null) {
String selected = componentList.getSelectedValue().toString();
componentList.removeItem(selected);
new File(directory + separator + selected).delete();
}
} else if (e.getSource() == addSFile) {
String sFile = JOptionPane.showInputDialog(this, "Enter Assembly File Name:",
"Assembly File Name", JOptionPane.PLAIN_MESSAGE);
if ((!sFile.endsWith(".s") && !sFile.endsWith(".inst")) || !(new File(sFile).exists())) {
JOptionPane.showMessageDialog(this, "Invalid filename entered.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public void run() {
copyFile();
String[] array = directory.split(separator);
String tempDir = "";
String lpnFile = "";
if (!verifyFile.endsWith("lpn")) {
String[] temp = verifyFile.split("\\.");
lpnFile = temp[0] + ".lpn";
} else {
lpnFile = verifyFile;
}
if (untimedStateSearch.isSelected()) {
LhpnFile lpn = new LhpnFile();
lpn.load(directory + separator + lpnFile);
String graphFileName = verifyFile.replace(".lpn", "") + "_sg.dot";
Project untimedStateSearch = new Project(lpn);
StateGraph stateGraph = untimedStateSearch.search(false);
if (dot.isSelected()) {
stateGraph.outputStateGraph(directory + separator + graphFileName);
}
return;
}
if (untimedPOR.isSelected()) {
LhpnFile lpn = new LhpnFile();
lpn.load(directory + separator + lpnFile);
String graphFileName = verifyFile.replace(".lpn", "") + "POR_sg.dot";
Project untimedStateSearchPOR = new Project(lpn);
StateGraph stateGraph = untimedStateSearchPOR.search(true);
if (dot.isSelected()) {
stateGraph.outputStateGraph(directory + separator + graphFileName);
}
return;
}
long time1 = System.nanoTime();
File work = new File(directory);
/*
if (!preprocStr.getText().equals("")) {
try {
String preprocCmd = preprocStr.getText();
Runtime exec = Runtime.getRuntime();
Process preproc = exec.exec(preprocCmd, null, work);
log.addText("Executing:\n" + preprocCmd + "\n");
preproc.waitFor();
} catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame,
"Error with preprocessing.", "Error",
JOptionPane.ERROR_MESSAGE);
//e.printStackTrace();
}
}
*/
try {
if (verifyFile.endsWith(".lpn")) {
Runtime.getRuntime().exec("atacs -llsl " + verifyFile, null,
work);
} else if (verifyFile.endsWith(".vhd")) {
Runtime.getRuntime().exec("atacs -lvsl " + verifyFile, null,
work);
} else if (verifyFile.endsWith(".g")) {
Runtime.getRuntime().exec("atacs -lgsl " + verifyFile, null,
work);
} else if (verifyFile.endsWith(".hse")) {
Runtime.getRuntime().exec("atacs -lhsl " + verifyFile, null,
work); }
} catch (Exception e) {
}
for (int i = 0; i < array.length - 1; i++) {
tempDir = tempDir + array[i] + separator;
}
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(directory + separator + lpnFile);
Abstraction abstraction = lhpnFile.abstractLhpn(this);
String abstFilename;
if(dbm2.isSelected())
{
try {
verification.timed_state_exploration.StateExploration.findStateGraph(lhpnFile, directory+separator, lpnFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
if (lhpn.isSelected()) {
abstFilename = (String) JOptionPane.showInputDialog(this,
"Please enter the file name for the abstracted LPN.",
"Enter Filename", JOptionPane.PLAIN_MESSAGE);
if (abstFilename != null) {
if (!abstFilename.endsWith(".lpn")) {
while (abstFilename.contains("\\.")) {
abstFilename = (String) JOptionPane.showInputDialog(this,
"Please enter a valid file name for the abstracted LPN.",
"Invalid Filename", JOptionPane.PLAIN_MESSAGE);
}
abstFilename = abstFilename + ".lpn";
}
}
} else {
abstFilename = lpnFile.replace(".lpn", "_abs.lpn");
}
String sourceFile;
if (simplify.isSelected() || abstractLhpn.isSelected()) {
String[] boolVars = lhpnFile.getBooleanVars();
String[] contVars = lhpnFile.getContVars();
String[] intVars = lhpnFile.getIntVars();
String[] variables = new String[boolVars.length + contVars.length
+ intVars.length];
int k = 0;
for (int j = 0; j < contVars.length; j++) {
variables[k] = contVars[j];
k++;
}
for (int j = 0; j < intVars.length; j++) {
variables[k] = intVars[j];
k++;
}
for (int j = 0; j < boolVars.length; j++) {
variables[k] = boolVars[j];
k++;
}
if (abstFilename != null) {
if (!abstFilename.endsWith(".lpn"))
abstFilename = abstFilename + ".lpn";
if (abstPane.loopAbsModel.contains("Remove Variables")) {
abstraction.abstractVars(abstPane.getIntVars());
}
abstraction.abstractSTG(true);
}
if (!lhpn.isSelected() && !view.isSelected()) {
abstraction.save(directory + separator + abstFilename);
}
sourceFile = abstFilename;
} else {
String[] tempArray = verifyFile.split(separator);
sourceFile = tempArray[tempArray.length - 1];
}
if (!lhpn.isSelected() && !view.isSelected()) {
abstraction.save(directory + separator + abstFilename);
}
if (!lhpn.isSelected() && !view.isSelected()) {
String[] tempArray = verifyFile.split("\\.");
String traceFilename = tempArray[0] + ".trace";
File traceFile = new File(traceFilename);
String pargName = "";
String dotName = "";
if (componentField.getText().trim().equals("")) {
if (verifyFile.endsWith(".g")) {
pargName = directory + separator
+ sourceFile.replace(".g", ".prg");
dotName = directory + separator
+ sourceFile.replace(".g", ".dot");
} else if (verifyFile.endsWith(".lpn")) {
pargName = directory + separator
+ sourceFile.replace(".lpn", ".prg");
dotName = directory + separator
+ sourceFile.replace(".lpn", ".dot");
} else if (verifyFile.endsWith(".vhd")) {
pargName = directory + separator
+ sourceFile.replace(".vhd", ".prg");
dotName = directory + separator
+ sourceFile.replace(".vhd", ".dot");
}
} else {
pargName = directory + separator
+ componentField.getText().trim() + ".prg";
dotName = directory + separator
+ componentField.getText().trim() + ".dot";
}
File pargFile = new File(pargName);
File dotFile = new File(dotName);
if (traceFile.exists()) {
traceFile.delete();
}
if (pargFile.exists()) {
pargFile.delete();
}
if (dotFile.exists()) {
dotFile.delete();
}
for (String s : componentList.getItems()) {
try {
FileInputStream in = new FileInputStream(new File(root
+ separator + s));
FileOutputStream out = new FileOutputStream(new File(
directory + separator + s));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
} catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Cannot update the file " + s + ".", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
String options = "";
// BDD Linkspace Size
if (!bddSize.getText().equals("") && !bddSize.getText().equals("0")) {
options = options + "-L" + bddSize.getText() + " ";
}
options = options + "-oq";
// Timing method
if (atacs) {
if (untimed.isSelected()) {
options = options + "tu";
} else if (geometric.isSelected()) {
options = options + "tg";
} else if (posets.isSelected()) {
options = options + "ts";
} else if (bag.isSelected()) {
options = options + "tg";
} else if (bap.isSelected()) {
options = options + "tp";
} else {
options = options + "tt";
}
} else {
if (bdd.isSelected()) {
options = options + "tB";
} else if (dbm.isSelected()) {
options = options + "tL";
} else if (smt.isSelected()) {
options = options + "tM";
}
}
// Timing Options
if (abst.isSelected()) {
options = options + "oa";
}
if (partialOrder.isSelected()) {
options = options + "op";
}
// Other Options
if (dot.isSelected()) {
options = options + "od";
}
if (verbose.isSelected()) {
options = options + "ov";
}
// Advanced Timing Options
if (genrg.isSelected()) {
options = options + "oG";
}
if (timsubset.isSelected()) {
options = options + "oS";
}
if (superset.isSelected()) {
options = options + "oU";
}
if (infopt.isSelected()) {
options = options + "oF";
}
if (orbmatch.isSelected()) {
options = options + "oO";
}
if (interleav.isSelected()) {
options = options + "oI";
}
if (prune.isSelected()) {
options = options + "oP";
}
if (disabling.isSelected()) {
options = options + "oD";
}
if (nofail.isSelected()) {
options = options + "of";
}
if (noproj.isSelected()) {
options = options + "oj";
}
if (keepgoing.isSelected()) {
options = options + "oK";
}
if (explpn.isSelected()) {
options = options + "oL";
}
// Other Advanced Options
if (nochecks.isSelected()) {
options = options + "on";
}
if (reduction.isSelected()) {
options = options + "oR";
}
// Compilation Options
if (newTab.isSelected()) {
options = options + "cN";
}
if (postProc.isSelected()) {
options = options + "cP";
}
if (redCheck.isSelected()) {
options = options + "cR";
}
if (xForm2.isSelected()) {
options = options + "cT";
}
if (expandRate.isSelected()) {
options = options + "cE";
}
// Load file type
if (verifyFile.endsWith(".g")) {
options = options + "lg";
} else if (verifyFile.endsWith(".lpn")) {
options = options + "ll";
} else if (verifyFile.endsWith(".vhd")
|| verifyFile.endsWith(".vhdl")) {
options = options + "lvslll";
}
// Verification Algorithms
if (verify.isSelected()) {
options = options + "va";
} else if (vergate.isSelected()) {
options = options + "vg";
} else if (orbits.isSelected()) {
options = options + "vo";
} else if (search.isSelected()) {
options = options + "vs";
} else if (trace.isSelected()) {
options = options + "vt";
}
if (graph.isSelected()) {
options = options + "ps";
}
String cmd = "atacs " + options;
String[] components = componentList.getItems();
for (String s : components) {
cmd = cmd + " " + s;
}
cmd = cmd + " " + sourceFile;
if (!componentField.getText().trim().equals("")) {
cmd = cmd + " " + componentField.getText().trim();
}
final JButton cancel = new JButton("Cancel");
final JFrame running = new JFrame("Progress");
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
cancel.doClick();
running.dispose();
}
public void windowOpened(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowActivated(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
};
running.addWindowListener(w);
JPanel text = new JPanel();
JPanel progBar = new JPanel();
JPanel button = new JPanel();
JPanel all = new JPanel(new BorderLayout());
JLabel label = new JLabel("Running...");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
text.add(label);
progBar.add(progress);
button.add(cancel);
all.add(text, "North");
all.add(progBar, "Center");
all.add(button, "South");
all.setOpaque(true);
running.setContentPane(all);
running.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
} catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = running.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
running.setLocation(x, y);
running.setVisible(true);
running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
work = new File(directory);
Runtime exec = Runtime.getRuntime();
try {
Preferences biosimrc = Preferences.userRoot();
String output = "";
int exitValue = 0;
if (biosimrc.get("biosim.verification.command", "").equals("")) {
final Process ver = exec.exec(cmd, null, work);
cancel.setActionCommand("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ver.destroy();
running.setCursor(null);
running.dispose();
}
});
biosim.getExitButton().setActionCommand("Exit program");
biosim.getExitButton().addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
ver.destroy();
running.setCursor(null);
running.dispose();
}
});
log.addText("Executing:\n" + cmd + "\n");
InputStream reb = ver.getInputStream();
InputStreamReader isr = new InputStreamReader(reb);
BufferedReader br = new BufferedReader(isr);
FileWriter out = new FileWriter(new File(directory
+ separator + "run.log"));
while ((output = br.readLine()) != null) {
out.write(output);
out.write("\n");
}
out.close();
br.close();
isr.close();
reb.close();
viewLog.setEnabled(true);
exitValue = ver.waitFor();
} else {
cmd = biosimrc.get("biosim.verification.command", "") + " "
+ options + " " + sourceFile.replaceAll(".lpn", "");
final Process ver = exec.exec(cmd, null, work);
cancel.setActionCommand("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ver.destroy();
running.setCursor(null);
running.dispose();
}
});
biosim.getExitButton().setActionCommand("Exit program");
biosim.getExitButton().addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
ver.destroy();
running.setCursor(null);
running.dispose();
}
});
log.addText("Executing:\n" + cmd + "\n");
InputStream reb = ver.getInputStream();
InputStreamReader isr = new InputStreamReader(reb);
BufferedReader br = new BufferedReader(isr);
FileWriter out = new FileWriter(new File(directory
+ separator + "run.log"));
while ((output = br.readLine()) != null) {
out.write(output);
out.write("\n");
}
out.close();
br.close();
isr.close();
reb.close();
viewLog.setEnabled(true);
exitValue = ver.waitFor();
}
long time2 = System.nanoTime();
long minutes;
long hours;
long days;
double secs = ((time2 - time1) / 1000000000.0);
long seconds = ((time2 - time1) / 1000000000);
secs = secs - seconds;
minutes = seconds / 60;
secs = seconds % 60 + secs;
hours = minutes / 60;
minutes = minutes % 60;
days = hours / 24;
hours = hours % 60;
String time;
String dayLabel;
String hourLabel;
String minuteLabel;
String secondLabel;
if (days == 1) {
dayLabel = " day ";
} else {
dayLabel = " days ";
}
if (hours == 1) {
hourLabel = " hour ";
} else {
hourLabel = " hours ";
}
if (minutes == 1) {
minuteLabel = " minute ";
} else {
minuteLabel = " minutes ";
}
if (seconds == 1) {
secondLabel = " second";
} else {
secondLabel = " seconds";
}
if (days != 0) {
time = days + dayLabel + hours + hourLabel + minutes
+ minuteLabel + secs + secondLabel;
} else if (hours != 0) {
time = hours + hourLabel + minutes + minuteLabel + secs
+ secondLabel;
} else if (minutes != 0) {
time = minutes + minuteLabel + secs + secondLabel;
} else {
time = secs + secondLabel;
}
log.addText("Total Verification Time: " + time + "\n\n");
running.setCursor(null);
running.dispose();
FileInputStream atacsLog = new FileInputStream(new File(
directory + separator + "atacs.log"));
InputStreamReader atacsReader = new InputStreamReader(atacsLog);
BufferedReader atacsBuffer = new BufferedReader(atacsReader);
boolean success = false;
while ((output = atacsBuffer.readLine()) != null) {
if (output.contains("Verification succeeded.")) {
JOptionPane.showMessageDialog(Gui.frame,
"Verification succeeded!", "Success",
JOptionPane.INFORMATION_MESSAGE);
success = true;
break;
}
}
if (exitValue == 143) {
JOptionPane.showMessageDialog(Gui.frame,
"Verification was" + " canceled by the user.",
"Canceled Verification", JOptionPane.ERROR_MESSAGE);
}
if (!success) {
if (new File(pargName).exists()) {
Process parg = exec.exec("parg " + pargName);
log.addText("parg " + pargName + "\n");
parg.waitFor();
} else if (new File(dotName).exists()) {
String command;
if (System.getProperty("os.name")
.contentEquals("Linux")) {
command = "gnome-open ";
} else if (System.getProperty("os.name").toLowerCase()
.startsWith("mac os")) {
command = "open ";
} else {
command = "dotty ";
}
Process dot = exec.exec("open " + dotName);
log.addText(command + dotName + "\n");
dot.waitFor();
} else {
viewLog();
}
}
if (graph.isSelected()) {
if (dot.isSelected()) {
String command;
if (System.getProperty("os.name")
.contentEquals("Linux")) {
command = "gnome-open ";
} else if (System.getProperty("os.name").toLowerCase()
.startsWith("mac os")) {
command = "open ";
} else {
command = "dotty ";
}
exec.exec(command + dotName);
log.addText("Executing:\n" + command + dotName + "\n");
} else {
exec.exec("parg " + pargName);
log.addText("Executing:\nparg " + pargName + "\n");
}
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Unable to verify model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} else {
if (lhpn.isSelected()) {
abstraction.save(tempDir + separator + abstFilename);
biosim.addToTree(abstFilename);
} else if (view.isSelected()) {
abstraction.save(directory + separator + abstFilename);
work = new File(directory + separator);
try {
String dotName = abstFilename.replace(".lpn", ".dot");
new File(directory + separator + dotName).delete();
Runtime exec = Runtime.getRuntime();
abstraction.printDot(directory + separator + dotName);
if (new File(directory + separator + dotName).exists()) {
String command;
if (System.getProperty("os.name")
.contentEquals("Linux")) {
command = "gnome-open ";
} else if (System.getProperty("os.name").toLowerCase()
.startsWith("mac os")) {
command = "open ";
} else {
command = "dotty ";
}
Process dot = exec.exec(command + dotName, null, work);
log.addText(command + dotName + "\n");
dot.waitFor();
} else {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to view LHPN.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void saveAs() {
String newName = JOptionPane.showInputDialog(Gui.frame,
"Enter Verification name:", "Verification Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".ver")) {
newName = newName + ".ver";
}
save(newName);
}
public void save() {
save(verFile);
}
public void save(String filename) {
try {
Properties prop = new Properties();
FileInputStream in = new FileInputStream(new File(directory
+ separator + filename));
prop.load(in);
in.close();
prop.setProperty("verification.file", verifyFile);
if (!bddSize.equals("")) {
prop.setProperty("verification.bddSize", this.bddSize.getText()
.trim());
}
if (!componentField.getText().trim().equals("")) {
prop.setProperty("verification.component", componentField
.getText().trim());
} else {
prop.remove("verification.component");
}
String[] components = componentList.getItems();
if (components.length == 0) {
for (Object s : prop.keySet()) {
if (s.toString().startsWith("verification.compList")) {
prop.remove(s);
}
}
} else {
for (Integer i = 0; i < components.length; i++) {
prop.setProperty("verification.compList" + i.toString(),
components[i]);
}
}
if (none.isSelected()) {
prop.setProperty("verification.abstraction", "none");
} else if (simplify.isSelected()) {
prop.setProperty("verification.abstraction", "simplify");
} else {
prop.setProperty("verification.abstraction", "abstract");
}
if (atacs) {
if (untimed.isSelected()) {
prop.setProperty("verification.timing.methods", "untimed");
} else if (geometric.isSelected()) {
prop
.setProperty("verification.timing.methods",
"geometric");
} else if (posets.isSelected()) {
prop.setProperty("verification.timing.methods", "posets");
} else if (bag.isSelected()) {
prop.setProperty("verification.timing.methods", "bag");
} else if (bap.isSelected()) {
prop.setProperty("verification.timing.methods", "bap");
} else if (baptdc.isSelected()) {
prop.setProperty("verification.timing.methods", "baptdc");
} else if (lhpn.isSelected()) {
prop.setProperty("verification.timing.methods", "lhpn");
} else {
prop.setProperty("verification.timing.methods", "view");
}
} else {
if (bdd.isSelected()) {
prop.setProperty("verification.timing.methods", "bdd");
} else if (dbm.isSelected()) {
prop.setProperty("verification.timing.methods", "dbm");
} else if (smt.isSelected()) {
prop.setProperty("verification.timing.methods", "smt");
} else if (untimedStateSearch.isSelected()) {
prop.setProperty("verification.timing.methods", "untimedStateSearch");
} else if (untimedPOR.isSelected()) {
prop.setProperty("verification.timing.methods", "untimedPOR");
}
else if (lhpn.isSelected()) {
prop.setProperty("verification.timing.methods", "lhpn");
} else {
prop.setProperty("verification.timing.methods", "view");
}
}
if (abst.isSelected()) {
prop.setProperty("verification.Abst", "true");
} else {
prop.setProperty("verification.Abst", "false");
}
if (partialOrder.isSelected()) {
prop.setProperty("verification.partial.order", "true");
} else {
prop.setProperty("verification.partial.order", "false");
}
if (dot.isSelected()) {
prop.setProperty("verification.Dot", "true");
} else {
prop.setProperty("verification.Dot", "false");
}
if (verbose.isSelected()) {
prop.setProperty("verification.Verb", "true");
} else {
prop.setProperty("verification.Verb", "false");
}
if (graph.isSelected()) {
prop.setProperty("verification.Graph", "true");
} else {
prop.setProperty("verification.Graph", "false");
}
if (verify.isSelected()) {
prop.setProperty("verification.algorithm", "verify");
} else if (vergate.isSelected()) {
prop.setProperty("verification.algorithm", "vergate");
} else if (orbits.isSelected()) {
prop.setProperty("verification.algorithm", "orbits");
} else if (search.isSelected()) {
prop.setProperty("verification.algorithm", "search");
} else if (trace.isSelected()) {
prop.setProperty("verification.algorithm", "trace");
}
if (newTab.isSelected()) {
prop.setProperty("verification.compilation.newTab", "true");
} else {
prop.setProperty("verification.compilation.newTab", "false");
}
if (postProc.isSelected()) {
prop.setProperty("verification.compilation.postProc", "true");
} else {
prop.setProperty("verification.compilation.postProc", "false");
}
if (redCheck.isSelected()) {
prop.setProperty("verification.compilation.redCheck", "true");
} else {
prop.setProperty("verification.compilation.redCheck", "false");
}
if (xForm2.isSelected()) {
prop.setProperty("verification.compilation.xForm2", "true");
} else {
prop.setProperty("verification.compilation.xForm2", "false");
}
if (expandRate.isSelected()) {
prop.setProperty("verification.compilation.expandRate", "true");
} else {
prop
.setProperty("verification.compilation.expandRate",
"false");
}
if (genrg.isSelected()) {
prop.setProperty("verification.timing.genrg", "true");
} else {
prop.setProperty("verification.timing.genrg", "false");
}
if (timsubset.isSelected()) {
prop.setProperty("verification.timing.subset", "true");
} else {
prop.setProperty("verification.timing.subset", "false");
}
if (superset.isSelected()) {
prop.setProperty("verification.timing.superset", "true");
} else {
prop.setProperty("verification.timing.superset", "false");
}
if (infopt.isSelected()) {
prop.setProperty("verification.timing.infopt", "true");
} else {
prop.setProperty("verification.timing.infopt", "false");
}
if (orbmatch.isSelected()) {
prop.setProperty("verification.timing.orbmatch", "true");
} else {
prop.setProperty("verification.timing.orbmatch", "false");
}
if (interleav.isSelected()) {
prop.setProperty("verification.timing.interleav", "true");
} else {
prop.setProperty("verification.timing.interleav", "false");
}
if (prune.isSelected()) {
prop.setProperty("verification.timing.prune", "true");
} else {
prop.setProperty("verification.timing.prune", "false");
}
if (disabling.isSelected()) {
prop.setProperty("verification.timing.disabling", "true");
} else {
prop.setProperty("verification.timing.disabling", "false");
}
if (nofail.isSelected()) {
prop.setProperty("verification.timing.nofail", "true");
} else {
prop.setProperty("verification.timing.nofail", "false");
}
if (nofail.isSelected()) {
prop.setProperty("verification.timing.noproj", "true");
} else {
prop.setProperty("verification.timing.noproj", "false");
}
if (keepgoing.isSelected()) {
prop.setProperty("verification.timing.keepgoing", "true");
} else {
prop.setProperty("verification.timing.keepgoing", "false");
}
if (explpn.isSelected()) {
prop.setProperty("verification.timing.explpn", "true");
} else {
prop.setProperty("verification.timing.explpn", "false");
}
if (nochecks.isSelected()) {
prop.setProperty("verification.nochecks", "true");
} else {
prop.setProperty("verification.nochecks", "false");
}
if (reduction.isSelected()) {
prop.setProperty("verification.reduction", "true");
} else {
prop.setProperty("verification.reduction", "false");
}
String intVars = "";
for (int i = 0; i < abstPane.listModel.getSize(); i++) {
if (abstPane.listModel.getElementAt(i) != null) {
intVars = intVars + abstPane.listModel.getElementAt(i)
+ " ";
}
}
if (sListModel.size() > 0) {
String list = "";
for (Object o : sListModel.toArray()) {
list = list + o + " ";
}
list.trim();
prop.put("verification.sList", list);
} else {
prop.remove("verification.sList");
}
if (!intVars.equals("")) {
prop.setProperty("abstraction.interesting", intVars.trim());
} else {
prop.remove("abstraction.interesting");
}
for (Integer i=0; i<abstPane.preAbsModel.size(); i++) {
prop.setProperty("abstraction.transform." + abstPane.preAbsModel.getElementAt(i).toString(), "preloop" + i.toString());
}
for (Integer i=0; i<abstPane.loopAbsModel.size(); i++) {
if (abstPane.preAbsModel.contains(abstPane.loopAbsModel.getElementAt(i))) {
String value = prop.getProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString());
value = value + "mainloop" + i.toString();
prop.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), value);
}
else {
prop.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), "mainloop" + i.toString());
}
}
for (Integer i=0; i<abstPane.postAbsModel.size(); i++) {
if (abstPane.preAbsModel.contains(abstPane.postAbsModel.getElementAt(i)) || abstPane.preAbsModel.contains(abstPane.postAbsModel.get(i))) {
String value = prop.getProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString());
value = value + "postloop" + i.toString();
prop.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), value);
}
else {
prop.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), "postloop" + i.toString());
}
}
for (String s : abstPane.transforms) {
if (!abstPane.preAbsModel.contains(s)
&& !abstPane.loopAbsModel.contains(s)
&& !abstPane.postAbsModel.contains(s)) {
prop.remove(s);
}
}
if (!abstPane.factorField.getText().equals("")) {
prop.setProperty("abstraction.factor", abstPane.factorField
.getText());
}
if (!abstPane.iterField.getText().equals("")) {
prop.setProperty("abstraction.iterations", abstPane.iterField
.getText());
}
FileOutputStream out = new FileOutputStream(new File(directory
+ separator + verFile));
prop.store(out, verifyFile);
out.close();
log.addText("Saving Parameter File:\n" + directory + separator
+ verFile + "\n");
change = false;
oldBdd = bddSize.getText();
} catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Unable to save parameter file!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
}
for (String s : componentList.getItems()) {
try {
new File(directory + separator + s).createNewFile();
FileInputStream in = new FileInputStream(new File(root
+ separator + s));
FileOutputStream out = new FileOutputStream(new File(directory
+ separator + s));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
} catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(Gui.frame,
"Cannot add the selected component.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void reload(String newname) {
}
public void viewCircuit() {
String[] getFilename;
if (componentField.getText().trim().equals("")) {
getFilename = verifyFile.split("\\.");
} else {
getFilename = new String[1];
getFilename[0] = componentField.getText().trim();
}
String circuitFile = getFilename[0] + ".prs";
try {
if (new File(circuitFile).exists()) {
File log = new File(circuitFile);
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls,
"Circuit View", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(Gui.frame,
"No circuit view exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to view circuit.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public boolean getViewTraceEnabled() {
return viewTrace.isEnabled();
}
public boolean getViewLogEnabled() {
return viewLog.isEnabled();
}
public void viewTrace() {
String[] getFilename = verifyFile.split("\\.");
String traceFilename = getFilename[0] + ".trace";
try {
if (new File(directory + separator + traceFilename).exists()) {
File log = new File(directory + separator + traceFilename);
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls,
"Trace View", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(Gui.frame,
"No trace file exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane
.showMessageDialog(Gui.frame, "Unable to view trace.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public void viewLog() {
try {
if (new File(directory + separator + "run.log").exists()) {
File log = new File(directory + separator + "run.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Run Log",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(Gui.frame,
"No run log exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to view run log.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public boolean hasChanged() {
if (!oldBdd.equals(bddSize.getText())) {
return true;
}
return change;
}
public boolean isSimplify() {
if (simplify.isSelected())
return true;
return false;
}
public void copyFile() {
String[] tempArray = verifyFile.split(separator);
String sourceFile = tempArray[tempArray.length - 1];
String[] workArray = directory.split(separator);
String workDir = "";
for (int i = 0; i < (workArray.length - 1); i++) {
workDir = workDir + workArray[i] + separator;
}
try {
File newFile = new File(directory + separator + sourceFile);
newFile.createNewFile();
FileOutputStream copyin = new FileOutputStream(newFile);
FileInputStream copyout = new FileInputStream(new File(workDir
+ separator + sourceFile));
int read = copyout.read();
while (read != -1) {
copyin.write(read);
read = copyout.read();
}
copyin.close();
copyout.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(Gui.frame, "Cannot copy file "
+ sourceFile, "Copy Error", JOptionPane.ERROR_MESSAGE);
}
/* TODO Test Assembly File compilation */
if (sourceFile.endsWith(".s") || sourceFile.endsWith(".inst")) {
biosim.copySFiles(verifyFile, directory);
try {
String preprocCmd;
if (lema) {
preprocCmd = System.getenv("LEMA") + "/bin/s2lpn " + verifyFile;
}
else if (atacs) {
preprocCmd = System.getenv("ATACS") + "/bin/s2lpn " + verifyFile;
}
else {
preprocCmd = System.getenv("BIOSIM") + "/bin/s2lpn " + verifyFile;
}
//for (Object o : sListModel.toArray()) {
// preprocCmd = preprocCmd + " " + o.toString();
File work = new File(directory);
Runtime exec = Runtime.getRuntime();
Process preproc = exec.exec(preprocCmd, null, work);
log.addText("Executing:\n" + preprocCmd + "\n");
preproc.waitFor();
if (verifyFile.endsWith(".s")) {
verifyFile.replace(".s", ".lpn");
}
else {
verifyFile.replace(".inst", ".lpn");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame,
"Error with preprocessing.", "Error",
JOptionPane.ERROR_MESSAGE);
//e.printStackTrace();
}
}
}
public String getVerName() {
String verName = verFile.replace(".ver", "");
return verName;
}
public AbstPane getAbstPane() {
return abstPane;
}
}
|
package team316;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.math.Fraction;
import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.RobotController;
import battlecode.common.RobotInfo;
import battlecode.common.RobotType;
import battlecode.common.Signal;
import battlecode.common.Team;
import team316.navigation.ChargedParticle;
import team316.navigation.ParticleType;
import team316.navigation.PotentialField;
import team316.navigation.motion.MotionController;
import team316.utils.Battle;
import team316.utils.EncodedMessage;
import team316.utils.EncodedMessage.MessageType;
import team316.utils.Encoding;
import team316.utils.Grid;
import team316.utils.Probability;
import team316.utils.RCWrapper;
import team316.utils.Turn;
public class Archon implements Player {
// For archonRank;
// 1 is the leader.
// 0 is unassigned
// -1 is dead archon: an archon that can't build anymore;
private int archonRank = 0;
private ArrayList<ArrayList<Integer>> toBroadcastNextTurnList = new ArrayList<>();
// private RobotType lastBuilt = RobotType.ARCHON;
private Map<RobotType, Double> buildDistribution = new HashMap<>();
private RobotType toBuild = null;
private int healthyArchonCount = 0;
private final int ARCHON_UNHEALTHY_HP_THRESHOLD = 100;
private int leaderID;
private boolean isDying = false;
private final PotentialField field;
private final MotionController mc;
private boolean inDanger = false;
private MapLocation myCurrentLocation = null;
// maps Locations with parts to the turns they were added at.
private Set<MapLocation> consideredPartsBeforeFrom = new HashSet<>();
private Set<MapLocation> partsAdded = new HashSet<>();
private int helpMessageDelay = 0;
private int gatherMessageDelay = 0;
private final RCWrapper rcWrapper;
private MapLocation targetLocation = null;
private int HELP_MESSASGE_MAX_DELAY = 15;
private int GATHER_MESSASGE_MAX_DELAY = 15;
private LinkedList<MapLocation> densLocations = new LinkedList<>();
private LinkedList<MapLocation> neutralArchonLocations = new LinkedList<>();
private Signal[] IncomingSignals;
static int[] tryDirections = {0, -1, 1, -2, 2};
private final static int MAX_RADIUS = GameConstants.MAP_MAX_HEIGHT
* GameConstants.MAP_MAX_HEIGHT
+ GameConstants.MAP_MAX_WIDTH * GameConstants.MAP_MAX_WIDTH;
private boolean isTopArchon = false;
public enum GameMode {
FREEPLAY, GATHER, ACTIVATE, ATTACK, DEFENSE
}
private GameMode myMode = GameMode.FREEPLAY;
private boolean reachedTarget;
private static int emptyMessage = EncodedMessage.makeMessage(
MessageType.EMPTY_MESSAGE, new MapLocation(0, 0));
int modeMessage;
//private boolean defenseMode = false;
//private boolean gatherMode = false;
//private boolean activationMode = false;
//private boolean attackMode = false;
//private MapLocation gatherLocation = null;
//private MapLocation attackLocation = null;
public Archon(PotentialField field, MotionController mc,
RobotController rc) {
this.field = field;
this.mc = mc;
this.rcWrapper = new RCWrapper(rc);
}
private boolean attemptBuild(RobotController rc)
throws GameActionException {
Direction proposedBuildDirection = null;
if (rc.isCoreReady()) {
if (myMode.equals(GameMode.DEFENSE) ) {
toBuild = RobotType.TURRET;
for (int i = 0; i < 4; i++) {
proposedBuildDirection = Grid.mainDirections[i]
.rotateRight();
if (rc.canBuild(proposedBuildDirection, RobotType.TURRET)) {
break;
}
}
}
if (toBuild == null) {
toBuild = (new Probability<RobotType>())
.getRandomSample(buildDistribution);
if (toBuild == null) {
return false;
}
}
if (rc.hasBuildRequirements(toBuild)) {
if (proposedBuildDirection == null) {
proposedBuildDirection = RobotPlayer.randomDirection();
}
Direction buildDirection = closestToForwardToBuild(rc,
proposedBuildDirection, toBuild);
final double acceptProbability = 1.0
/ (healthyArchonCount - archonRank + 1);
// will equal to 1.0 if healthyArchonCount = 0 and archonRank =
// 0 (not assigned).
if (buildDirection != null
&& rc.canBuild(buildDirection, toBuild)) {
boolean isFairResourcesDistribution = Probability
.acceptWithProbability(acceptProbability)
|| rc.getTeamParts() > 120;
if (!isFairResourcesDistribution) {
return false;
}
rc.build(buildDirection, toBuild);
// lastBuilt = toBuild;
toBuild = null;
if(!myMode.equals(GameMode.FREEPLAY)){
addNextTurnMessage(modeMessage, emptyMessage, 2);
}
return true;
}
}
}
return false;
}
/**
* Sends a message next turn. Useful with communicating with a unit just
* built.
*
* @param message1
* @param message2
* @param radius
*/
private void addNextTurnMessage(Integer firstInteger, Integer secondInteger,
int radius) {
ArrayList<Integer> message = new ArrayList<>();
message.add(firstInteger);
message.add(secondInteger);
message.add(radius);
toBroadcastNextTurnList.add(message);
}
/**
* Broadcasts all messages that are on the queue.
*/
private void broadcastLateMessages(RobotController rc)
throws GameActionException {
for (ArrayList<Integer> message : toBroadcastNextTurnList) {
if (message.get(0) == null) {
rc.broadcastSignal(message.get(2));
} else {
rc.broadcastMessageSignal(message.get(0), message.get(1),
message.get(2));
}
}
toBroadcastNextTurnList.clear();
}
private void seekHelpIfNeeded(RobotController rc)
throws GameActionException {
boolean isAttacked = rcWrapper.isUnderAttack();
boolean canBeAttacked = false;
RobotInfo[] enemiesSensed = rc.senseHostileRobots(myCurrentLocation,
RobotType.ARCHON.sensorRadiusSquared);
if (!isAttacked) {
for (RobotInfo enemy : enemiesSensed) {
/*
* if (myCurrentLocation.distanceSquaredTo( enemy.location) <=
* enemy.type.attackRadiusSquared) { canBeAttacked = true;
* break; }
*/
if (enemy.type != RobotType.ARCHON
&& enemy.type != RobotType.SCOUT) {
canBeAttacked = true;
break;
}
}
}
if (isAttacked || canBeAttacked) {
inDanger = true;
if (helpMessageDelay == 0 && rc.getRobotCount() > 1) {
int message = EncodedMessage.makeMessage(
MessageType.MESSAGE_HELP_ARCHON,
rcWrapper.getCurrentLocation());
rc.broadcastMessageSignal(message, emptyMessage, 1000);
helpMessageDelay = this.HELP_MESSASGE_MAX_DELAY;
}
}
isDying = rc.getHealth() < ARCHON_UNHEALTHY_HP_THRESHOLD;
// TODO fix this:
/*
* if (isDying && !isAttacked && !canBeAttacked) {
* rc.broadcastMessageSignal(RobotPlayer.MESSAGE_BYE_ARCHON, archonRank,
* MAX_RADIUS); archonRank = -1; healthyArchonCount--; }
*/
}
public void figureOutDistribution() {
if (Turn.currentTurn() == 1) {
buildDistribution.clear();
// buildDistribution.put(RobotType.GUARD, 5.0);
buildDistribution.put(RobotType.SCOUT, 10.0);
buildDistribution.put(RobotType.SOLDIER, 90.0);
}
}
/**
* Returns the build direction closest to a given direction Returns null if
* it can't build anywhere.
*/
private Direction closestToForwardToBuild(RobotController rc,
Direction forward, RobotType toBuild) {
for (int deltaD : tryDirections) {
Direction currentDirection = Direction
.values()[(forward.ordinal() + deltaD + 8) % 8];
if (rc.canBuild(currentDirection, toBuild)) {
return currentDirection;
}
}
return null;
}
private void attemptRepairingWeakest(RobotController rc)
throws GameActionException {
RobotInfo[] alliesToHelp = rc.senseNearbyRobots(
RobotType.ARCHON.attackRadiusSquared, rcWrapper.myTeam);
MapLocation weakestOneLocation = null;
double weakestWeakness = -(1e9);
for (RobotInfo ally : alliesToHelp) {
if (!ally.type.equals(RobotType.ARCHON)
&& Battle.weakness(ally) > weakestWeakness
&& ally.health < ally.maxHealth) {
weakestOneLocation = ally.location;
weakestWeakness = Battle.weakness(ally);
}
}
if (weakestOneLocation != null) {
rc.repair(weakestOneLocation);
}
}
private void figureOutRank(RobotController rc) throws GameActionException {
// Get all incoming archon signals who were initialized before me.
for (Signal s : IncomingSignals) {
if (s.getTeam().equals(rcWrapper.myTeam)
&& s.getMessage() != null) {
if (EncodedMessage.getMessageType(s.getMessage()[0])
.equals(MessageType.MESSAGE_HELLO_ARCHON)) {
archonRank++;
if (archonRank == 1) {
leaderID = s.getID();
}
}
}
}
archonRank++;
// Find farthest archon from me and broadcast that I'm initialized.
MapLocation[] archonLocations = rc
.getInitialArchonLocations(rcWrapper.myTeam);
int furthestArchonDistance = 0;
if (Turn.currentTurn() == 1) {
for (MapLocation location : archonLocations) {
int distance = myCurrentLocation.distanceSquaredTo(location);
if (distance > furthestArchonDistance) {
furthestArchonDistance = distance;
}
}
} else {
furthestArchonDistance = MAX_RADIUS;
}
// TODO furthestArchonDistance doesn't work.
int message = EncodedMessage.makeMessage(
MessageType.MESSAGE_HELLO_ARCHON,
rcWrapper.getCurrentLocation());
rc.broadcastMessageSignal(message, 0, MAX_RADIUS);
rc.setIndicatorString(0, "My archon rank is: " + archonRank);
if (archonRank == 1) {
leaderID = rc.getID();
}
}
private void startGather(MapLocation location) {
myMode = GameMode.GATHER;
targetLocation = location;
}
private boolean processMessage(int message) throws GameActionException {
MapLocation location = EncodedMessage.getMessageLocation(message);
boolean success = false;
switch (EncodedMessage.getMessageType(message)) {
case EMPTY_MESSAGE :
break;
case ZOMBIE_DEN_LOCATION :
if(!densLocations.contains(location)){
densLocations.add(location);
}
// field.addParticle(ParticleType.DEN, location, 100);
break;
case MESSAGE_HELP_ARCHON :
field.addParticle(ParticleType.ARCHON_ATTACKED, location, 5);
break;
case NEUTRAL_ARCHON_LOCATION :
neutralArchonLocations.add(location);
// field.addParticle(new ChargedParticle(1000, location, 500));
break;
case NEUTRAL_NON_ARCHON_LOCATION :
field.addParticle(new ChargedParticle(30, location, 100));
break;
case Y_BORDER :
int coordinateY = location.y;
if (coordinateY <= rcWrapper.getCurrentLocation().y) {
rcWrapper.setMaxCoordinate(Direction.NORTH, coordinateY);
} else {
rcWrapper.setMaxCoordinate(Direction.SOUTH, coordinateY);
}
break;
case X_BORDER :
int coordinateX = location.x;
if (coordinateX <= rcWrapper.getCurrentLocation().x) {
rcWrapper.setMaxCoordinate(Direction.WEST, coordinateX);
} else {
rcWrapper.setMaxCoordinate(Direction.EAST, coordinateX);
}
break;
case DEFENSE_MODE_ON :
myMode = GameMode.DEFENSE;
targetLocation = location;
//isTopArchon = false;
break;
case ACTIVATE :
myMode = GameMode.ACTIVATE;
targetLocation = location;
//isTopArchon = false;
break;
case ATTACK :
myMode = GameMode.ATTACK;
targetLocation = location;
//isTopArchon = false;
break;
case GATHER :
System.out.println("Gather Message received!");
startGather(location);
//isTopArchon = false;
break;
default :
success = false;
break;
}
return success;
}
private void checkInbox(RobotController rc) throws GameActionException {
for (Signal s : IncomingSignals) {
if (s.getTeam() == rcWrapper.myTeam && s.getMessage() != null) {
processMessage(s.getMessage()[0]);
processMessage(s.getMessage()[1]);
/*
* if (!processMessage(s.getMessage()[0]) &&
* processMessage(s.getMessage()[1])) { /// switch
* (s.getMessage()[0]) { case RobotPlayer.MESSAGE_BYE_ARCHON :
* if (archonRank > s.getMessage()[1]) { archonRank--; if
* (archonRank == 1) { rc.broadcastMessageSignal(
* RobotPlayer.MESSAGE_DECLARE_LEADER, 0, MAX_RADIUS); } }
* healthyArchonCount--; break; case
* RobotPlayer.MESSAGE_WELCOME_ACTIVATED_ARCHON : if
* (healthyArchonCount == 0) { healthyArchonCount =
* s.getMessage()[1]; archonRank = healthyArchonCount; } else {
* healthyArchonCount++; } break; case
* RobotPlayer.MESSAGE_DECLARE_LEADER : leaderID = s.getID();
* break; default : break; } /// }
*/
}
}
}
private int activationProfit(RobotType type) {
switch (type) {
case ARCHON :
return 100;
case GUARD :
return 5;
case SOLDIER :
return 50;
case SCOUT :
return 1;
case VIPER :
return 20;
case TTM :
return 10;
case TURRET :
return 11;
default :
throw new RuntimeException("UNKNOWN ROBOT TYPE!");
}
}
private void attemptActivateRobots(RobotController rc)
throws GameActionException {
if (!rc.isCoreReady())
return;
RobotInfo[] neutralRobots = rc.senseNearbyRobots(2, Team.NEUTRAL);
int bestProfit = 0;
RobotInfo neutralRobotToActivate = null;
for (RobotInfo neutralRobot : neutralRobots) {
if (activationProfit(neutralRobot.type) > bestProfit
&& myCurrentLocation.isAdjacentTo(neutralRobot.location)) {
neutralRobotToActivate = neutralRobot;
bestProfit = activationProfit(neutralRobot.type);
}
}
if (neutralRobotToActivate != null) {
rc.activate(neutralRobotToActivate.location);
/*
* if (neutralRobotToActivate.type.equals(RobotType.ARCHON)) { int
* distanceToRobot = myCurrentLocation
* .distanceSquaredTo(neutralRobotToActivate.location);
* addNextTurnMessage(RobotPlayer.MESSAGE_WELCOME_ACTIVATED_ARCHON,
* healthyArchonCount + 1, distanceToRobot); }
*/
}
}
private void switchModes(RobotController rc) throws GameActionException{
MapLocation closestArchonLocation = rcWrapper
.getClosestLocation(neutralArchonLocations);
int emptyMessage = EncodedMessage.makeMessage(
MessageType.EMPTY_MESSAGE, new MapLocation(0, 0));
if (closestArchonLocation != null) {
targetLocation = closestArchonLocation;
myMode = GameMode.ACTIVATE;
int activateMessage = EncodedMessage.makeMessage(
MessageType.ACTIVATE, targetLocation);
//rc.broadcastMessageSignal(activateMessage, emptyMessage, MAX_RADIUS);
return;
}
MapLocation closestDenLocation = rcWrapper
.getClosestLocation(densLocations);
if (closestDenLocation != null && Turn.currentTurn() > 600) {
targetLocation = closestDenLocation;
myMode = GameMode.ATTACK;
int attackMessage = EncodedMessage.makeMessage(
MessageType.ATTACK, targetLocation);
System.out.println("Den message!");
//rc.broadcastMessageSignal(attackMessage, emptyMessage, MAX_RADIUS);
return;
}
if(Turn.currentTurn() > 1000){
targetLocation = rcWrapper.getCurrentLocation();
int defenseMessage = EncodedMessage.makeMessage(
MessageType.DEFENSE_MODE_ON, targetLocation);
myMode = GameMode.DEFENSE;
System.out.println("Defense message!");
//rc.broadcastMessageSignal(defenseMessage, emptyMessage, MAX_RADIUS);
}
}
// High level logic here.
private void checkMode(RobotController rc) throws GameActionException {
boolean finishedMission = false;
reachedTarget = false;
Integer distance = null;
if(targetLocation != null){
distance = rcWrapper.getCurrentLocation().distanceSquaredTo(targetLocation);
}
MessageType messageType = null;
switch (myMode){
case FREEPLAY:
rc.setIndicatorString(1, "FreePlay");
reachedTarget = true;
//finishedMission = Turn.currentTurn() > 200;
break;
case GATHER:
rc.setIndicatorString(1, "Gather");
if(distance <= 10){
reachedTarget = true;
finishedMission = true;
}
messageType = MessageType.GATHER;
break;
case ACTIVATE:
rc.setIndicatorString(1, "Activate");
if(distance <= 1){
reachedTarget = true;
}
if(rc.senseNearbyRobots(targetLocation, 0, Team.NEUTRAL).length == 0){
finishedMission = true;
}
messageType = MessageType.ACTIVATE;
break;
case ATTACK:
rc.setIndicatorString(1, "Attack: " + densLocations);
if(distance <= 35){
reachedTarget = true;
if(rc.senseNearbyRobots(targetLocation, 0, Team.ZOMBIE).length == 0){
finishedMission = true;
densLocations.remove(targetLocation);
}
}
messageType = MessageType.ATTACK;
break;
case DEFENSE:
rc.setIndicatorString(1, "Defense");
reachedTarget = true;
messageType = MessageType.DEFENSE_MODE_ON;
break;
default:
break;
}
if(finishedMission && Turn.currentTurn() > 500){
switchModes(rc);
}
if(!myMode.equals(GameMode.FREEPLAY)){
modeMessage = EncodedMessage.makeMessage(messageType, targetLocation);
}
if(!myMode.equals(GameMode.FREEPLAY) && gatherMessageDelay == 0 && !inDanger){
int message = modeMessage;
rc.broadcastMessageSignal(message, emptyMessage, 1000);
gatherMessageDelay = GATHER_MESSASGE_MAX_DELAY;
}
if (!reachedTarget && !inDanger) {
field.addParticle(new ChargedParticle(1000, targetLocation, 1));
return;
}
}
private void initializeArchon(RobotController rc)
throws GameActionException {
rcWrapper.initOnNewTurn();
myCurrentLocation = rcWrapper.getCurrentLocation();
inDanger = false;
IncomingSignals = rc.emptySignalQueue();
if (helpMessageDelay > 0) {
helpMessageDelay
}
if (gatherMessageDelay > 0) {
gatherMessageDelay
}
checkInbox(rc);
seekHelpIfNeeded(rc);
checkMode(rc);
if (Turn.currentTurn() == 1) {
figureOutRank(rc);
healthyArchonCount = rc
.getInitialArchonLocations(rcWrapper.myTeam).length;
}
}
@Override
public void play(RobotController rc) throws GameActionException {
initializeArchon(rc);
broadcastLateMessages(rc);
figureOutDistribution();
attemptActivateRobots(rc);
if (!inDanger) {
attemptBuild(rc);
}
attemptRepairingWeakest(rc);
adjustBattle(rc);
// If not necessary move with a probability.
if (inDanger || myMode.equals(GameMode.GATHER)
|| (Probability.acceptWithProbability(.10) && !myMode.equals(GameMode.DEFENSE))) {
attempMoving(rc);
}
if (!inDanger && myMode.equals(GameMode.FREEPLAY)
&& Turn.currentTurn() > 200) {
int gatherMessage = EncodedMessage.makeMessage(MessageType.GATHER,
rcWrapper.getCurrentLocation());
int emptyMessage = EncodedMessage.makeMessage(
MessageType.EMPTY_MESSAGE, new MapLocation(0, 0));
rc.broadcastMessageSignal(gatherMessage, emptyMessage, MAX_RADIUS);
//System.out.println("Gather Message sent");
startGather(rcWrapper.getCurrentLocation());
}
}
private void attempMoving(RobotController rc) throws GameActionException {
if (rc.isCoreReady()) {
mc.tryToMove(rc);
}
}
private void adjustBattle(RobotController rc) throws GameActionException {
RobotInfo[] enemyArray = rc.senseHostileRobots(myCurrentLocation,
RobotType.ARCHON.sensorRadiusSquared);
Battle.addEnemyParticles(enemyArray, field, 1);
RobotInfo[] allyArray = rc.senseNearbyRobots(
RobotType.ARCHON.sensorRadiusSquared, rcWrapper.myTeam);
Battle.addAllyParticles(allyArray, field, 1);
// if (!consideredPartsBeforeFrom.contains(myCurrentLocation)) {
MapLocation[] partsLocations = rc
.sensePartLocations(RobotType.ARCHON.sensorRadiusSquared);
for (MapLocation partsLocation : partsLocations) {
// if (!partsAdded.contains(partsLocations)) {
double amount = rc.senseParts(partsLocation);
field.addParticle(new ChargedParticle(amount / 100.0,
partsLocation, 1));
// partsAdded.add(partsLocation);
}
// consideredPartsBeforeFrom.add(myCurrentLocation);
if (inDanger) {
Battle.addBorderParticles(rcWrapper, field);
}
}
/**
* Gets an unmarried turret or scout or null if there is not.
*
* @param robots
* @param targetType
* @param married
* @return
*/
private static RobotInfo getLonelyRobot(RobotInfo[] robots,
RobotType targetType, Set<Integer> married) {
for (RobotInfo robot : robots) {
if (robot.type == targetType && !married.contains(robot.ID)) {
return robot;
}
}
return null;
}
}
|
package net.minecraftforge.gradle.patcher.task;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputDirectory;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import com.cloudbees.diff.PatchException;
import net.minecraftforge.gradle.common.diff.ContextualPatch;
import net.minecraftforge.gradle.common.diff.HunkReport;
import net.minecraftforge.gradle.common.diff.PatchFile;
import net.minecraftforge.gradle.common.diff.ZipContext;
import net.minecraftforge.gradle.common.diff.ContextualPatch.PatchReport;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.zip.ZipFile;
public class TaskApplyPatches extends DefaultTask {
private File clean;
private File patches;
private File output = getProject().file("build/" + getName() + "/output.zip");
private int maxFuzz = 0;
private boolean canonicalizeAccess = true;
private boolean canonicalizeWhitespace = true;
@TaskAction
public void applyPatches() {
try (ZipFile zip = new ZipFile(getClean())) {
ZipContext context = new ZipContext(zip);
if (getPatches() == null) {
context.save(getOutput());
return;
}
boolean all_success = Files.walk(getPatches().toPath())
.filter(p -> Files.isRegularFile(p) && p.getFileName().toString().endsWith(".patch"))
.map(p -> {
boolean success = true;
ContextualPatch patch = ContextualPatch.create(PatchFile.from(p.toFile()), context);
patch.setCanonialization(getCanonicalizeAccess(), getCanonicalizeWhitespace());
patch.setMaxFuzz(getMaxFuzz());
String name = p.toFile().getAbsolutePath().substring(getPatches().getAbsolutePath().length() + 1);
try {
getLogger().info("Apply Patch: " + name);
List<PatchReport> result = patch.patch(false);
for (int x = 0; x < result.size(); x++) {
PatchReport report = result.get(x);
if (!report.getStatus().isSuccess()) {
success = false;
for (int y = 0; y < report.hunkReports().size(); y++) {
HunkReport hunk = report.hunkReports().get(y);
if (hunk.hasFailed()) {
if (hunk.failure == null) {
getLogger().error(" Hunk #" + hunk.hunkID + " Failed @" + hunk.index + " Fuzz: " + hunk.fuzz);
} else {
getLogger().error(" Hunk #" + hunk.hunkID + " Failed: " + hunk.failure.getMessage());
}
}
}
}
}
} catch (PatchException e) {
getLogger().error(" " + e.getMessage());
} catch (IOException e) {
throw new RuntimeException(e);
}
return success;
}).reduce(true, (a,b) -> a && b);
if (all_success) {
context.save(getOutput());
} else {
throw new RuntimeException("Failed to apply patches. See log for details.");
}
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
@InputFile
public File getClean() {
return clean;
}
@Optional
@InputDirectory
public File getPatches() {
return patches;
}
@Input
public int getMaxFuzz() {
return maxFuzz;
}
@Input
public boolean getCanonicalizeWhitespace() {
return canonicalizeWhitespace;
}
@Input
public boolean getCanonicalizeAccess() {
return canonicalizeAccess;
}
@OutputFile
public File getOutput() {
return output;
}
public void setClean(File clean) {
this.clean = clean;
}
public void setPatches(File value) {
patches = value;
}
public void setMaxFuzz(int value) {
maxFuzz = value;
}
public void setCanonicalizeWhitespace(boolean value) {
canonicalizeWhitespace = value;
}
public void setCanonicalizeAccess(boolean value) {
canonicalizeAccess = value;
}
public void setOutput(File value) {
output = value;
}
}
|
package net.hyperic.sigar.cmd;
import java.util.Date;
import java.text.SimpleDateFormat;
import net.hyperic.sigar.SigarException;
public class Who extends SigarCommandBase {
public Who(Shell shell) {
super(shell);
}
public Who() {
super();
}
public String getUsageShort() {
return "Show who is logged on";
}
private String getTime(long time) {
if (time == 0) {
return "unknown";
}
String fmt = "MMM dd HH:mm";
return new SimpleDateFormat(fmt).format(new Date(time));
}
public void output(String[] args) throws SigarException {
net.hyperic.sigar.Who[] who = this.sigar.getWhoList();
for (int i=0; i<who.length; i++) {
String host = who[i].getHost();
if (host.length() != 0) {
host = "(" + host + ")";
}
printf(new String[] {
who[i].getUser(),
who[i].getDevice(),
getTime(who[i].getTime() * 1000),
host
});
}
}
public static void main(String[] args) throws Exception {
new Who().processCommand(args);
}
}
|
package bitronix.tm.twopc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bitronix.tm.BitronixTransaction;
import bitronix.tm.utils.Decoder;
import bitronix.tm.twopc.executor.Executor;
import bitronix.tm.twopc.executor.Job;
import bitronix.tm.internal.*;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.Status;
import javax.transaction.xa.XAException;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Collections;
/**
* Phase 2 Commit logic engine.
*
* @author lorban
*/
public class Committer extends AbstractPhaseEngine {
private final static Logger log = LoggerFactory.getLogger(Committer.class);
private boolean onePhase;
private List interestedResources;
// this list has to be thread-safe as the CommitJobs can be executed in parallel (when async 2PC is configured)
private final List committedResources = Collections.synchronizedList(new ArrayList());
public Committer(Executor executor) {
super(executor);
}
/**
* Execute phase 2 commit.
* @param transaction the transaction wanting to commit phase 2
* @param interestedResources a map of phase 1 prepared resources wanting to participate in phase 2 using Xids as keys
* @throws HeuristicRollbackException when all resources committed instead.
* @throws HeuristicMixedException when some resources committed and some rolled back.
* @throws bitronix.tm.internal.BitronixSystemException when an internal error occured.
*/
public void commit(BitronixTransaction transaction, List interestedResources) throws HeuristicMixedException, HeuristicRollbackException, BitronixSystemException {
XAResourceManager resourceManager = transaction.getResourceManager();
if (resourceManager.size() == 0) {
transaction.setStatus(Status.STATUS_COMMITTING); //TODO: there is a disk force here that could be avoided
transaction.setStatus(Status.STATUS_COMMITTED);
if (log.isDebugEnabled()) log.debug("phase 2 commit succeeded with no interested resource");
return;
}
transaction.setStatus(Status.STATUS_COMMITTING);
this.interestedResources = Collections.unmodifiableList(interestedResources);
this.onePhase = resourceManager.size() == 1;
try {
executePhase(resourceManager, true);
} catch (PhaseException ex) {
logFailedResources(ex);
transaction.setStatus(Status.STATUS_UNKNOWN);
throwException("transaction failed during commit of " + transaction, ex, interestedResources.size());
}
if (log.isDebugEnabled()) log.debug("phase 2 commit executed on resources " + Decoder.collectResourcesNames(committedResources));
// Some resources might have failed the 2nd phase of 2PC.
// Only resources which successfully committed should be registered in the journal, the other
// ones should be picked up by the recoverer.
// Not interested resources have to be included as well since they returned XA_RDONLY and they
// don't participate in phase 2: the TX succeded for them.
List committedAndNotInterestedUniqueNames = new ArrayList();
committedAndNotInterestedUniqueNames.addAll(collectResourcesUniqueNames(committedResources));
List notInterestedResources = collectNotInterestedResources(resourceManager.getAllResources(), interestedResources);
committedAndNotInterestedUniqueNames.addAll(collectResourcesUniqueNames(notInterestedResources));
if (log.isDebugEnabled()) {
List committedAndNotInterestedResources = new ArrayList();
committedAndNotInterestedResources.addAll(committedResources);
committedAndNotInterestedResources.addAll(notInterestedResources);
log.debug("phase 2 commit succeeded on resources " + Decoder.collectResourcesNames(committedAndNotInterestedResources));
}
transaction.setStatus(Status.STATUS_COMMITTED, new HashSet(committedAndNotInterestedUniqueNames));
}
private void throwException(String message, PhaseException phaseException, int totalResourceCount) throws HeuristicMixedException, HeuristicRollbackException {
List exceptions = phaseException.getExceptions();
List resources = phaseException.getResourceStates();
boolean hazard = false;
List heuristicResources = new ArrayList();
List errorResources = new ArrayList();
for (int i = 0; i < exceptions.size(); i++) {
Exception ex = (Exception) exceptions.get(i);
XAResourceHolderState resourceHolder = (XAResourceHolderState) resources.get(i);
if (ex instanceof XAException) {
XAException xaEx = (XAException) ex;
switch (xaEx.errorCode) {
case XAException.XA_HEURHAZ:
hazard = true;
case XAException.XA_HEURCOM:
case XAException.XA_HEURRB:
case XAException.XA_HEURMIX:
heuristicResources.add(resourceHolder);
break;
default:
errorResources.add(resourceHolder);
}
}
else
errorResources.add(resourceHolder);
}
if (!hazard && heuristicResources.size() == totalResourceCount)
throw new BitronixHeuristicRollbackException(message + ":" +
" all resource(s) " + Decoder.collectResourcesNames(heuristicResources) +
" improperly unilaterally rolled back", phaseException);
else
throw new BitronixHeuristicMixedException(message + ":" +
(errorResources.size() > 0 ? " resource(s) " + Decoder.collectResourcesNames(errorResources) + " threw unexpected exception" : "") +
(errorResources.size() > 0 && heuristicResources.size() > 0 ? " and" : "") +
(heuristicResources.size() > 0 ? " resource(s) " + Decoder.collectResourcesNames(heuristicResources) + " improperly unilaterally rolled back" + (hazard ? " (or hazard happened)" : "") : ""), phaseException);
}
protected Job createJob(XAResourceHolderState resourceHolder) {
return new CommitJob(resourceHolder);
}
protected boolean isParticipating(XAResourceHolderState xaResourceHolderState) {
for (int i = 0; i < interestedResources.size(); i++) {
XAResourceHolderState resourceHolderState = (XAResourceHolderState) interestedResources.get(i);
if (xaResourceHolderState == resourceHolderState)
return true;
}
return false;
}
private class CommitJob extends Job {
public CommitJob(XAResourceHolderState resourceHolder) {
super(resourceHolder);
}
public XAException getXAException() {
return xaException;
}
public RuntimeException getRuntimeException() {
return runtimeException;
}
public void execute() {
try {
commitResource(getResource(), onePhase);
} catch (RuntimeException ex) {
runtimeException = ex;
} catch (XAException ex) {
xaException = ex;
}
}
private void commitResource(XAResourceHolderState resourceHolder, boolean onePhase) throws XAException {
try {
if (log.isDebugEnabled()) log.debug("committing resource " + resourceHolder + (onePhase ? " (with one-phase optimization)" : ""));
resourceHolder.getXAResource().commit(resourceHolder.getXid(), onePhase);
committedResources.add(resourceHolder);
if (log.isDebugEnabled()) log.debug("committed resource " + resourceHolder);
} catch (XAException ex) {
handleXAException(resourceHolder, ex);
}
}
private void handleXAException(XAResourceHolderState failedResourceHolder, XAException xaException) throws XAException {
switch (xaException.errorCode) {
case XAException.XA_HEURCOM:
forgetHeuristicCommit(failedResourceHolder);
return;
case XAException.XAER_NOTA:
throw new BitronixXAException("unknown heuristic termination, global state of this transaction is unknown - guilty: " + failedResourceHolder, XAException.XA_HEURHAZ, xaException);
case XAException.XA_HEURHAZ:
case XAException.XA_HEURMIX:
case XAException.XA_HEURRB:
case XAException.XA_RBCOMMFAIL:
case XAException.XA_RBDEADLOCK:
case XAException.XA_RBINTEGRITY:
case XAException.XA_RBOTHER:
case XAException.XA_RBPROTO:
case XAException.XA_RBROLLBACK:
case XAException.XA_RBTIMEOUT:
case XAException.XA_RBTRANSIENT:
log.error("heuristic rollback is incompatible with the global state of this transaction - guilty: " + failedResourceHolder);
throw xaException;
default:
log.warn("resource '" + failedResourceHolder.getUniqueName() + "' reported " + Decoder.decodeXAExceptionErrorCode(xaException) +
" when asked to commit transaction branch. Transaction is prepared and will commit via recovery service when resource availability allows.", xaException);
}
}
private void forgetHeuristicCommit(XAResourceHolderState resourceHolder) {
try {
if (log.isDebugEnabled()) log.debug("handling heuristic commit on resource " + resourceHolder.getXAResource());
resourceHolder.getXAResource().forget(resourceHolder.getXid());
if (log.isDebugEnabled()) log.debug("forgotten heuristically committed resource " + resourceHolder.getXAResource());
} catch (XAException ex) {
log.error("cannot forget " + resourceHolder.getXid() + " assigned to " + resourceHolder.getXAResource() + ", error=" + Decoder.decodeXAExceptionErrorCode(ex), ex);
}
}
public String toString() {
return "a CommitJob " + (onePhase ? "(one phase) " : "") + "with " + getResource();
}
}
}
|
package arjdbc.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Array;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Date;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Savepoint;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.joda.time.DateTime;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyException;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyIO;
import org.jruby.RubyInteger;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
import org.jruby.RubyTime;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.bigdecimal.RubyBigDecimal;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.Block;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.backtrace.RubyStackTraceElement;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.TypeConverter;
/**
* Most of our ActiveRecord::ConnectionAdapters::JdbcConnection implementation.
*/
public class RubyJdbcConnection extends RubyObject {
private static final String[] TABLE_TYPE = new String[] { "TABLE" };
private static final String[] TABLE_TYPES = new String[] { "TABLE", "VIEW", "SYNONYM" };
private JdbcConnectionFactory connectionFactory;
protected RubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
}
private static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyJdbcConnection(runtime, klass);
}
};
public static RubyClass createJdbcConnectionClass(final Ruby runtime) {
RubyClass jdbcConnection = getConnectionAdapters(runtime).
defineClassUnder("JdbcConnection", runtime.getObject(), ALLOCATOR);
jdbcConnection.defineAnnotatedMethods(RubyJdbcConnection.class);
return jdbcConnection;
}
public static RubyClass getJdbcConnectionClass(final Ruby runtime) {
return getConnectionAdapters(runtime).getClass("JdbcConnection");
}
protected static RubyModule ActiveRecord(ThreadContext context) {
return context.runtime.getModule("ActiveRecord");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters</code>
*/
protected static RubyModule getConnectionAdapters(final Ruby runtime) {
return (RubyModule) runtime.getModule("ActiveRecord").getConstant("ConnectionAdapters");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters::IndexDefinition</code>
*/
protected static RubyClass getIndexDefinition(final Ruby runtime) {
return getConnectionAdapters(runtime).getClass("IndexDefinition");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters::ForeignKeyDefinition</code>
* @note only since AR 4.2
*/
protected static RubyClass getForeignKeyDefinition(final Ruby runtime) {
return getConnectionAdapters(runtime).getClass("ForeignKeyDefinition");
}
/**
* @param runtime
* @return <code>ActiveRecord::JDBCError</code>
*/
protected static RubyClass getJDBCError(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("JDBCError");
}
public static int mapTransactionIsolationLevel(IRubyObject isolation) {
if ( ! ( isolation instanceof RubySymbol ) ) {
isolation = isolation.asString().callMethod("intern");
}
final Object isolationString = isolation.toString(); // RubySymbol.toString
if ( isolationString == "read_uncommitted" ) return Connection.TRANSACTION_READ_UNCOMMITTED;
if ( isolationString == "read_committed" ) return Connection.TRANSACTION_READ_COMMITTED;
if ( isolationString == "repeatable_read" ) return Connection.TRANSACTION_REPEATABLE_READ;
if ( isolationString == "serializable" ) return Connection.TRANSACTION_SERIALIZABLE;
throw new IllegalArgumentException(
"unexpected isolation level: " + isolation + " (" + isolationString + ")"
);
}
@JRubyMethod(name = "supports_transaction_isolation?", optional = 1)
public IRubyObject supports_transaction_isolation_p(final ThreadContext context,
final IRubyObject[] args) throws SQLException {
final IRubyObject isolation = args.length > 0 ? args[0] : null;
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final DatabaseMetaData metaData = connection.getMetaData();
final boolean supported;
if ( isolation != null && ! isolation.isNil() ) {
final int level = mapTransactionIsolationLevel(isolation);
supported = metaData.supportsTransactionIsolationLevel(level);
}
else {
final int level = metaData.getDefaultTransactionIsolation();
supported = level > Connection.TRANSACTION_NONE;
}
return context.getRuntime().newBoolean(supported);
}
});
}
@JRubyMethod(name = {"begin", "transaction"}, required = 1) // optional isolation argument for AR-4.0
public IRubyObject begin(final ThreadContext context, final IRubyObject isolation) {
try { // handleException == false so we can handle setTXIsolation
return withConnection(context, false, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
return beginTransaction(context, connection, isolation.isNil() ? null : isolation);
}
});
} catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = {"begin", "transaction"}) // optional isolation argument for AR-4.0
public IRubyObject begin(final ThreadContext context) {
try { // handleException == false so we can handle setTXIsolation
return withConnection(context, false, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
return beginTransaction(context, connection, null);
}
});
} catch (SQLException e) {
return handleException(context, e);
}
}
protected IRubyObject beginTransaction(final ThreadContext context, final Connection connection,
final IRubyObject isolation) throws SQLException {
if ( isolation != null ) {
setTransactionIsolation(context, connection, isolation);
}
if ( connection.getAutoCommit() ) connection.setAutoCommit(false);
return context.nil;
}
protected final void setTransactionIsolation(final ThreadContext context, final Connection connection,
final IRubyObject isolation) throws SQLException {
final int level = mapTransactionIsolationLevel(isolation);
try {
connection.setTransactionIsolation(level);
}
catch (SQLException e) {
RubyClass txError = ActiveRecord(context).getClass("TransactionIsolationError");
if ( txError != null ) throw wrapException(context, txError, e);
throw e; // let it roll - will be wrapped into a JDBCError (non 4.0)
}
}
@JRubyMethod(name = "commit")
public IRubyObject commit(final ThreadContext context) {
final Connection connection = getConnection(context, true);
try {
if ( ! connection.getAutoCommit() ) {
try {
connection.commit();
resetSavepoints(context); // if any
return context.getRuntime().newBoolean(true);
}
finally {
connection.setAutoCommit(true);
}
}
return context.getRuntime().getNil();
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "rollback")
public IRubyObject rollback(final ThreadContext context) {
final Connection connection = getConnection(context, true);
try {
if ( ! connection.getAutoCommit() ) {
try {
connection.rollback();
resetSavepoints(context); // if any
return context.runtime.getTrue();
} finally {
connection.setAutoCommit(true);
}
}
return context.getRuntime().getNil();
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "supports_savepoints?")
public IRubyObject supports_savepoints_p(final ThreadContext context) throws SQLException {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final DatabaseMetaData metaData = connection.getMetaData();
return context.getRuntime().newBoolean( metaData.supportsSavepoints() );
}
});
}
@JRubyMethod(name = "create_savepoint", optional = 1)
public IRubyObject create_savepoint(final ThreadContext context, final IRubyObject[] args) {
IRubyObject name = args.length > 0 ? args[0] : null;
final Connection connection = getConnection(context, true);
try {
connection.setAutoCommit(false);
final Savepoint savepoint ;
// NOTE: this will auto-start a DB transaction even invoked outside
// of a AR (Ruby) transaction (`transaction { ... create_savepoint }`)
// it would be nice if AR knew about this TX although that's kind of
// "really advanced" functionality - likely not to be implemented ...
if ( name != null && ! name.isNil() ) {
savepoint = connection.setSavepoint(name.toString());
}
else {
savepoint = connection.setSavepoint();
name = RubyString.newString( context.getRuntime(),
Integer.toString( savepoint.getSavepointId() )
);
}
getSavepoints(context).put(name, savepoint);
return name;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "rollback_savepoint", required = 1)
public IRubyObject rollback_savepoint(final ThreadContext context, final IRubyObject name) {
if ( name == null || name.isNil() ) {
throw context.getRuntime().newArgumentError("nil savepoint name given");
}
final Connection connection = getConnection(context, true);
try {
Savepoint savepoint = getSavepoints(context).get(name);
if ( savepoint == null ) {
throw context.getRuntime().newRuntimeError("could not rollback savepoint: '" + name + "' (not set)");
}
connection.rollback(savepoint);
return context.getRuntime().getNil();
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "release_savepoint", required = 1)
public IRubyObject release_savepoint(final ThreadContext context, final IRubyObject name) {
Ruby runtime = context.runtime;
if ( name == null || name.isNil() ) throw runtime.newArgumentError("nil savepoint name given");
try {
Object savepoint = getSavepoints(context).remove(name);
if (savepoint == null) {
RubyClass invalidStatement = ActiveRecord(context).getClass("StatementInvalid");
throw runtime.newRaiseException(invalidStatement, "could not release savepoint: '" + name + "' (not set)");
}
// NOTE: RubyHash.remove does not convert to Java as get does :
if (!( savepoint instanceof Savepoint )) {
savepoint = ((IRubyObject) savepoint).toJava(Savepoint.class);
}
getConnection(context, true).releaseSavepoint((Savepoint) savepoint);
return runtime.getNil();
} catch (SQLException e) {
return handleException(context, e);
}
}
@SuppressWarnings("unchecked")
protected Map<IRubyObject, Savepoint> getSavepoints(final ThreadContext context) {
if ( hasInstanceVariable("@savepoints") ) {
IRubyObject savepoints = getInstanceVariable("@savepoints");
return (Map<IRubyObject, Savepoint>) savepoints.toJava(Map.class);
}
else { // not using a RubyHash to preserve order on Ruby 1.8 as well :
Map<IRubyObject, Savepoint> savepoints = new LinkedHashMap<IRubyObject, Savepoint>(4);
setInstanceVariable("@savepoints", convertJavaToRuby(savepoints));
return savepoints;
}
}
protected boolean resetSavepoints(final ThreadContext context) {
if ( hasInstanceVariable("@savepoints") ) {
removeInstanceVariable("@savepoints");
return true;
}
return false;
}
@JRubyMethod(name = "connection_factory")
public IRubyObject connection_factory(final ThreadContext context) {
return convertJavaToRuby( getConnectionFactory() );
}
@JRubyMethod(name = "connection_factory=", required = 1)
public IRubyObject set_connection_factory(final ThreadContext context, final IRubyObject factory) {
setConnectionFactory( (JdbcConnectionFactory) factory.toJava(JdbcConnectionFactory.class) );
return context.getRuntime().getNil();
}
/**
* Called during <code>initialize</code> after the connection factory
* has been set to check if we can connect and/or perform any initialization
* necessary.
* <br/>
* NOTE: connection has not been configured at this point,
* nor should we retry - we're creating a brand new JDBC connection
*
* @param context
* @return connection
*/
@JRubyMethod(name = "init_connection")
public synchronized IRubyObject init_connection(final ThreadContext context) {
try {
return initConnection(context);
}
catch (SQLException e) {
return handleException(context, e); // throws
}
}
private IRubyObject initConnection(final ThreadContext context) throws SQLException {
final IRubyObject jdbcConnection = setConnection(context, newConnection());
final IRubyObject adapter = callMethod("adapter"); // self.adapter
if ( ! adapter.isNil() ) {
if ( adapter.respondsTo("init_connection") ) {
adapter.callMethod(context, "init_connection", jdbcConnection);
}
}
else {
warn(context, "WARN: adapter not set for: " + inspect() +
" make sure you pass it on initialize(config, adapter)");
}
return jdbcConnection;
}
@JRubyMethod(name = "connection")
public IRubyObject connection(final ThreadContext context) {
if (getConnection(context, false) == null) {
synchronized (this) {
if (getConnection(context, false) == null) reconnect(context);
}
}
return getInstanceVariable("@connection");
}
@JRubyMethod(name = "active?", alias = "valid?")
public IRubyObject active_p(final ThreadContext context) {
IRubyObject connection = getInstanceVariable("@connection");
if (connection != null && ! connection.isNil()) {
return context.runtime.newBoolean(isConnectionValid(context, getConnection(context, false)));
}
return context.runtime.getFalse();
}
@JRubyMethod(name = "disconnect!")
public synchronized IRubyObject disconnect(final ThreadContext context) {
// TODO: only here to try resolving multi-thread issues :
if ( Boolean.getBoolean("arjdbc.disconnect.debug") ) {
final List<?> backtrace = createCallerBacktrace(context);
final Ruby runtime = context.getRuntime();
runtime.getOut().println(this + " connection.disconnect! occured: ");
for ( Object element : backtrace ) {
runtime.getOut().println(element);
}
runtime.getOut().flush();
}
return setConnection(context, null);
}
@JRubyMethod(name = "reconnect!")
public synchronized IRubyObject reconnect(final ThreadContext context) {
try {
final Connection connection = newConnection();
final IRubyObject result = setConnection(context, connection);
final IRubyObject adapter = callMethod("adapter");
if ( ! adapter.isNil() ) {
if ( adapter.respondsTo("configure_connection") ) {
adapter.callMethod(context, "configure_connection");
}
}
else {
// NOTE: we warn on init_connection - should be enough
}
return result;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = { "open?" /* "conn?" */ })
public IRubyObject open_p(final ThreadContext context) {
final Connection connection = getConnection(context, false);
if (connection == null) return context.runtime.getFalse();
try {
// NOTE: isClosed method generally cannot be called to determine
// whether a connection to a database is valid or invalid ...
return context.getRuntime().newBoolean(!connection.isClosed());
} catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "close")
public IRubyObject close(final ThreadContext context) {
final Connection connection = getConnection(context, false);
if (connection == null) return context.runtime.getFalse();
try {
if (connection.isClosed()) return context.runtime.getFalse();
setConnection(context, null); // does connection.close();
} catch (Exception e) {
debugStackTrace(context, e);
return context.runtime.getNil();
}
return context.runtime.getTrue();
}
@JRubyMethod(name = "database_name")
public IRubyObject database_name(final ThreadContext context) throws SQLException {
final Connection connection = getConnection(context, true);
String name = connection.getCatalog();
if (name == null) {
name = connection.getMetaData().getUserName();
if (name == null) name = "db1"; // TODO why ?
}
return context.getRuntime().newString(name);
}
@JRubyMethod(name = "execute", required = 1)
public IRubyObject execute(final ThreadContext context, final IRubyObject sql) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
Statement statement = null;
final String query = sql.convertToString().getUnicodeValue();
try {
statement = createStatement(context, connection);
// For DBs that do support multiple statements, lets return the last result set
// to be consistent with AR
boolean hasResultSet = doExecute(statement, query);
int updateCount = statement.getUpdateCount();
ColumnData[] columns = null;
IRubyObject result = null;
ResultSet resultSet = null;
while (hasResultSet || updateCount != -1) {
if (hasResultSet) {
resultSet = statement.getResultSet();
// Unfortunately the result set gets closed when getMoreResults()
// is called, so we have to process the result sets as we get them
// this shouldn't be an issue in most cases since we're only getting 1 result set anyways
columns = extractColumns(context.runtime, connection, resultSet, false);
result = mapToResult(context, context.runtime, connection, resultSet, columns);
} else {
resultSet = null;
}
// Check to see if there is another result set
hasResultSet = statement.getMoreResults();
updateCount = statement.getUpdateCount();
}
// Need to check resultSet instead of result because result
// may have been populated in a previous iteration of the loop
if (resultSet == null) {
return context.runtime.newEmptyArray();
} else {
return result;
}
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
}
});
}
protected Statement createStatement(final ThreadContext context, final Connection connection)
throws SQLException {
final Statement statement = connection.createStatement();
IRubyObject statementEscapeProcessing = getConfigValue(context, "statement_escape_processing");
// NOTE: disable (driver) escape processing by default, it's not really
// needed for AR statements ... if users need it they might configure :
if ( statementEscapeProcessing.isNil() ) {
statement.setEscapeProcessing(false);
}
else {
statement.setEscapeProcessing(statementEscapeProcessing.isTrue());
}
return statement;
}
/**
* Execute a query using the given statement.
* @param statement
* @param query
* @return true if the first result is a <code>ResultSet</code>;
* false if it is an update count or there are no results
* @throws SQLException
*/
protected boolean doExecute(final Statement statement, final String query) throws SQLException {
return statement.execute(query);
}
@JRubyMethod(name = "execute_insert", required = 1)
public IRubyObject execute_insert(final ThreadContext context, final IRubyObject sql)
throws SQLException {
final String query = sql.convertToString().getUnicodeValue();
return executeUpdate(context, query, true);
}
@JRubyMethod(name = "execute_insert", required = 2)
public IRubyObject execute_insert(final ThreadContext context,
final IRubyObject sql, final IRubyObject binds) throws SQLException {
final String query = sql.convertToString().getUnicodeValue();
if ( binds == null || binds.isNil() ) { // no prepared statements
return executeUpdate(context, query, true);
}
else { // we allow prepared statements with empty binds parameters
return executePreparedUpdate(context, query, (RubyArray) binds, true);
}
}
/**
* Executes an UPDATE (DELETE) SQL statement.
* @param context
* @param sql
* @return affected row count
* @throws SQLException
*/
@JRubyMethod(name = {"execute_update", "execute_delete"}, required = 1)
public IRubyObject execute_update(final ThreadContext context, final IRubyObject sql)
throws SQLException {
final String query = sql.convertToString().getUnicodeValue();
return executeUpdate(context, query, false);
}
/**
* Executes an UPDATE (DELETE) SQL (prepared - if binds provided) statement.
* @param context
* @param sql
* @return affected row count
* @throws SQLException
*
* @see #execute_update(ThreadContext, IRubyObject)
*/
@JRubyMethod(name = {"execute_update", "execute_delete"}, required = 2)
public IRubyObject execute_update(final ThreadContext context,
final IRubyObject sql, final IRubyObject binds) throws SQLException {
final String query = sql.convertToString().getUnicodeValue();
if ( binds == null || binds.isNil() ) { // no prepared statements
return executeUpdate(context, query, false);
}
else { // we allow prepared statements with empty binds parameters
return executePreparedUpdate(context, query, (RubyArray) binds, false);
}
}
@JRubyMethod(name = {"execute_prepared_update"}, required = 2)
public IRubyObject execute_prepared_update(final ThreadContext context,
final IRubyObject sql, final IRubyObject binds) throws SQLException {
final String query = sql.convertToString().getUnicodeValue();
return executePreparedUpdate(context, query, (RubyArray) binds, false);
}
/**
* @param context
* @param query
* @param returnGeneratedKeys
* @return row count or generated keys
*
* @see #execute_insert(ThreadContext, IRubyObject)
* @see #execute_update(ThreadContext, IRubyObject)
*/
protected IRubyObject executeUpdate(final ThreadContext context, final String query,
final boolean returnGeneratedKeys) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
Statement statement = null;
try {
statement = createStatement(context, connection);
if ( returnGeneratedKeys ) {
statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
IRubyObject keys = mapGeneratedKeys(context.getRuntime(), connection, statement);
return keys == null ? context.getRuntime().getNil() : keys;
}
else {
final int rowCount = statement.executeUpdate(query);
return context.getRuntime().newFixnum(rowCount);
}
}
catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
}
finally { close(statement); }
}
});
}
private IRubyObject executePreparedUpdate(final ThreadContext context, final String query,
final RubyArray binds, final boolean returnGeneratedKeys) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
PreparedStatement statement = null;
try {
if ( returnGeneratedKeys ) {
statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
setStatementParameters(context, connection, statement, binds);
statement.executeUpdate();
IRubyObject keys = mapGeneratedKeys(context.getRuntime(), connection, statement);
return keys == null ? context.getRuntime().getNil() : keys;
}
else {
statement = connection.prepareStatement(query);
setStatementParameters(context, connection, statement, binds);
final int rowCount = statement.executeUpdate();
return context.getRuntime().newFixnum(rowCount);
}
}
catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
}
finally { close(statement); }
}
});
}
/**
* This is the same as execute_query but it will return a list of hashes.
*
* @see RubyJdbcConnection#execute_query(ThreadContext, IRubyObject[])
* @param context which context this method is executing on.
* @param args arguments being supplied to this method.
* @param block (optional) block to yield row values (Hash(name: value))
* @return List of Hash(name: value) unless block is given.
* @throws SQLException when a database error occurs
*/
@JRubyMethod(required = 1, optional = 2)
public IRubyObject execute_query_raw(final ThreadContext context,
final IRubyObject[] args, final Block block) throws SQLException {
final String query = args[0].convertToString().getUnicodeValue(); // sql
final RubyArray binds;
final int maxRows;
// args: (sql), (sql, max_rows), (sql, binds), (sql, max_rows, binds)
switch (args.length) {
case 2:
if (args[1] instanceof RubyNumeric) { // (sql, max_rows)
maxRows = RubyNumeric.fix2int(args[1]);
binds = null;
} else { // (sql, binds)
maxRows = 0;
binds = (RubyArray) TypeConverter.checkArrayType(args[1]);
}
break;
case 3: // (sql, max_rows, binds)
maxRows = RubyNumeric.fix2int(args[1]);
binds = (RubyArray) TypeConverter.checkArrayType(args[2]);
break;
default: // (sql) 1-arg
maxRows = 0;
binds = null;
break;
}
return doExecuteQueryRaw(context, query, maxRows, block, binds);
}
private IRubyObject doExecuteQueryRaw(final ThreadContext context,
final String query, final int maxRows, final Block block, final RubyArray binds) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final Ruby runtime = context.getRuntime();
Statement statement = null; ResultSet resultSet = null;
try {
if ( binds == null ) { // plain statement
statement = createStatement(context, connection);
statement.setMaxRows(maxRows); // zero means there is no limit
resultSet = statement.executeQuery(query);
}
else {
final PreparedStatement prepStatement;
statement = prepStatement = connection.prepareStatement(query);
statement.setMaxRows(maxRows); // zero means there is no limit
setStatementParameters(context, connection, prepStatement, binds);
resultSet = prepStatement.executeQuery();
}
if (block.isGiven()) {
// yield(id1, name1) ... row 1 result data
// yield(id2, name2) ... row 2 result data
return yieldResultRows(context, runtime, connection, resultSet, block);
} else {
return mapToRawResult(context, runtime, connection, resultSet, false);
}
}
catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
}
finally { close(resultSet); close(statement); }
}
});
}
/**
* Executes a query and returns the (AR) result. There are three parameters:
* <ul>
* <li>sql - String of sql</li>
* <li>max_rows - Integer of how many rows to return</li>
* <li>binds - Array of bindings for a prepared statement</li>
* </ul>
*
* In true Ruby fashion if there are only two arguments then the last argument
* may be either max_rows or binds. Note: If you want to force the query to be
* done using a prepared statement then you must provide an empty array to binds.
*
* @param context which context this method is executing on.
* @param args arguments being supplied to this method.
* @return a Ruby <code>ActiveRecord::Result</code> instance
* @throws SQLException when a database error occurs
*
*/
@JRubyMethod(required = 1, optional = 2)
public IRubyObject execute_query(final ThreadContext context, final IRubyObject[] args) throws SQLException {
final String query = args[0].convertToString().getUnicodeValue(); // sql
final RubyArray binds;
final int maxRows;
// args: (sql), (sql, max_rows), (sql, binds), (sql, max_rows, binds)
switch (args.length) {
case 2:
if (args[1] instanceof RubyNumeric) { // (sql, max_rows)
maxRows = RubyNumeric.fix2int(args[1]);
binds = null;
} else { // (sql, binds)
maxRows = 0;
binds = (RubyArray) TypeConverter.checkArrayType(args[1]);
}
break;
case 3: // (sql, max_rows, binds)
maxRows = RubyNumeric.fix2int(args[1]);
binds = (RubyArray) TypeConverter.checkArrayType(args[2]);
break;
default: // (sql) 1-arg
maxRows = 0;
binds = null;
break;
}
if (binds != null) { // prepared statement
return executePreparedQuery(context, query, binds, maxRows);
} else {
return executeQuery(context, query, maxRows);
}
}
@JRubyMethod(name = "execute_prepared_query")
public IRubyObject execute_prepared_query(final ThreadContext context,
final IRubyObject sql, final IRubyObject binds) throws SQLException {
final String query = sql.convertToString().getUnicodeValue();
if (binds == null || !(binds instanceof RubyArray)) {
throw context.runtime.newArgumentError("binds exptected to an instance of Array");
}
return executePreparedQuery(context, query, (RubyArray) binds, 0);
}
/**
* NOTE: This methods behavior changed in AR-JDBC 1.3 the old behavior is
* achievable using {@link #executeQueryRaw(ThreadContext, String, int, Block)}.
*
* @param context
* @param query
* @param maxRows
* @return AR (mapped) query result
*
*/
protected IRubyObject executeQuery(final ThreadContext context, final String query, final int maxRows) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
Statement statement = null;
ResultSet resultSet = null;
try {
statement = createStatement(context, connection);
statement.setMaxRows(maxRows); // zero means there is no limit
resultSet = statement.executeQuery(query);
return mapQueryResult(context, connection, resultSet);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(resultSet);
close(statement);
}
}
});
}
@JRubyMethod
public IRubyObject execute_prepared(final ThreadContext context, final IRubyObject sql, final IRubyObject binds) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
PreparedStatement statement = null;
final String query = sql.convertToString().getUnicodeValue();
try {
statement = connection.prepareStatement(query);
setStatementParameters(context, connection, statement, (RubyArray) binds);
boolean hasResultSet = statement.execute();
if (hasResultSet) {
ResultSet resultSet = statement.getResultSet();
ColumnData[] columns = extractColumns(context.runtime, connection, resultSet, false);
return mapToResult(context, context.runtime, connection, resultSet, columns);
} else {
return context.runtime.newEmptyArray();
}
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
}
});
}
protected IRubyObject executePreparedQuery(final ThreadContext context, final String query,
final RubyArray binds, final int maxRows) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
PreparedStatement statement = null; ResultSet resultSet = null;
try {
statement = connection.prepareStatement(query);
statement.setMaxRows(maxRows); // zero means there is no limit
setStatementParameters(context, connection, statement, binds);
resultSet = statement.executeQuery();
return mapQueryResult(context, connection, resultSet);
}
catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
}
finally { close(resultSet); close(statement); }
}
});
}
private IRubyObject mapQueryResult(final ThreadContext context,
final Connection connection, final ResultSet resultSet) throws SQLException {
final Ruby runtime = context.getRuntime();
final ColumnData[] columns = extractColumns(runtime, connection, resultSet, false);
return mapToResult(context, runtime, connection, resultSet, columns);
}
/**
* @deprecated please do not use this method
*/
@Deprecated // only used by Oracle adapter - also it's really a bad idea
@JRubyMethod(name = "execute_id_insert", required = 2)
public IRubyObject execute_id_insert(final ThreadContext context,
final IRubyObject sql, final IRubyObject id) throws SQLException {
final Ruby runtime = context.getRuntime();
callMethod("warn", RubyString.newUnicodeString(runtime, "DEPRECATED: execute_id_insert(sql, id) will be removed"));
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
PreparedStatement statement = null;
final String insertSQL = sql.convertToString().getUnicodeValue();
try {
statement = connection.prepareStatement(insertSQL);
statement.setLong(1, RubyNumeric.fix2long(id));
statement.executeUpdate();
}
catch (final SQLException e) {
debugErrorSQL(context, insertSQL);
throw e;
}
finally { close(statement); }
return id;
}
});
}
@JRubyMethod(name = "supported_data_types")
public IRubyObject supported_data_types(final ThreadContext context) throws SQLException {
final Ruby runtime = context.getRuntime();
final Connection connection = getConnection(context, true);
final ResultSet typeDesc = connection.getMetaData().getTypeInfo();
final IRubyObject types;
try {
types = mapToRawResult(context, runtime, connection, typeDesc, true);
}
finally { close(typeDesc); }
return types;
}
@JRubyMethod(name = "primary_keys", required = 1)
public IRubyObject primary_keys(ThreadContext context, IRubyObject tableName) throws SQLException {
@SuppressWarnings("unchecked")
List<IRubyObject> primaryKeys = (List) primaryKeys(context, tableName.toString());
return context.getRuntime().newArray(primaryKeys);
}
protected static final int PRIMARY_KEYS_COLUMN_NAME = 4;
@Deprecated // NOTE: this should go private
protected List<RubyString> primaryKeys(final ThreadContext context, final String tableName) {
return withConnection(context, new Callable<List<RubyString>>() {
public List<RubyString> call(final Connection connection) throws SQLException {
final String _tableName = caseConvertIdentifierForJdbc(connection, tableName);
final TableName table = extractTableName(connection, null, null, _tableName);
return primaryKeys(context, connection, table);
}
});
}
protected List<RubyString> primaryKeys(final ThreadContext context,
final Connection connection, final TableName table) throws SQLException {
final DatabaseMetaData metaData = connection.getMetaData();
ResultSet resultSet = null;
final List<RubyString> keyNames = new ArrayList<RubyString>();
try {
resultSet = metaData.getPrimaryKeys(table.catalog, table.schema, table.name);
final Ruby runtime = context.getRuntime();
while ( resultSet.next() ) {
String columnName = resultSet.getString(PRIMARY_KEYS_COLUMN_NAME);
columnName = caseConvertIdentifierForRails(connection, columnName);
keyNames.add( RubyString.newUnicodeString(runtime, columnName) );
}
}
finally { close(resultSet); }
return keyNames;
}
@Deprecated //@JRubyMethod(name = "tables")
public IRubyObject tables(ThreadContext context) {
return tables(context, null, null, null, TABLE_TYPE);
}
@Deprecated //@JRubyMethod(name = "tables")
public IRubyObject tables(ThreadContext context, IRubyObject catalog) {
return tables(context, toStringOrNull(catalog), null, null, TABLE_TYPE);
}
@Deprecated //@JRubyMethod(name = "tables")
public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern) {
return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), null, TABLE_TYPE);
}
@Deprecated //@JRubyMethod(name = "tables")
public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern, IRubyObject tablePattern) {
return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), toStringOrNull(tablePattern), TABLE_TYPE);
}
@JRubyMethod(name = "tables", required = 0, optional = 4)
public IRubyObject tables(final ThreadContext context, final IRubyObject[] args) {
switch ( args.length ) {
case 0:
return tables(context, null, null, null, TABLE_TYPE);
case 1: // (catalog)
return tables(context, toStringOrNull(args[0]), null, null, TABLE_TYPE);
case 2: // (catalog, schemaPattern)
return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), null, TABLE_TYPE);
case 3: // (catalog, schemaPattern, tablePattern)
return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), toStringOrNull(args[2]), TABLE_TYPE);
}
return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), toStringOrNull(args[2]), getTypes(args[3]));
}
protected IRubyObject tables(final ThreadContext context,
final String catalog, final String schemaPattern, final String tablePattern, final String[] types) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
return matchTables(context.getRuntime(), connection, catalog, schemaPattern, tablePattern, types, false);
}
});
}
protected String[] getTableTypes() {
return TABLE_TYPES;
}
@JRubyMethod(name = "table_exists?")
public IRubyObject table_exists_p(final ThreadContext context, IRubyObject table) {
if ( table.isNil() ) {
throw context.getRuntime().newArgumentError("nil table name");
}
final String tableName = table.toString();
return tableExists(context, null, tableName);
}
@JRubyMethod(name = "table_exists?")
public IRubyObject table_exists_p(final ThreadContext context, IRubyObject table, IRubyObject schema) {
if ( table.isNil() ) {
throw context.getRuntime().newArgumentError("nil table name");
}
final String tableName = table.toString();
final String defaultSchema = schema.isNil() ? null : schema.toString();
return tableExists(context, defaultSchema, tableName);
}
protected IRubyObject tableExists(final ThreadContext context,
final String defaultSchema, final String tableName) {
final Ruby runtime = context.getRuntime();
return withConnection(context, new Callable<RubyBoolean>() {
public RubyBoolean call(final Connection connection) throws SQLException {
final TableName components = extractTableName(connection, null, defaultSchema, tableName);
return runtime.newBoolean( tableExists(runtime, connection, components) );
}
});
}
@JRubyMethod(name = {"columns", "columns_internal"}, required = 1, optional = 2)
public IRubyObject columns_internal(final ThreadContext context, final IRubyObject[] args)
throws SQLException {
return withConnection(context, new Callable<RubyArray>() {
public RubyArray call(final Connection connection) throws SQLException {
ResultSet columns = null;
try {
final String tableName = args[0].toString();
// optionals (NOTE: catalog argumnet was never used before 1.3.0) :
final String catalog = args.length > 1 ? toStringOrNull(args[1]) : null;
final String defaultSchema = args.length > 2 ? toStringOrNull(args[2]) : null;
final TableName components;
components = extractTableName(connection, catalog, defaultSchema, tableName);
if ( ! tableExists(context.getRuntime(), connection, components) ) {
throw new SQLException("table: " + tableName + " does not exist");
}
final DatabaseMetaData metaData = connection.getMetaData();
columns = metaData.getColumns(components.catalog, components.schema, components.name, null);
return mapColumnsResult(context, metaData, components, columns);
}
finally {
close(columns);
}
}
});
}
@JRubyMethod(name = "indexes")
public IRubyObject indexes(final ThreadContext context, IRubyObject tableName, IRubyObject name) {
return indexes(context, toStringOrNull(tableName), toStringOrNull(name), null);
}
@JRubyMethod(name = "indexes")
public IRubyObject indexes(final ThreadContext context, IRubyObject tableName, IRubyObject name, IRubyObject schemaName) {
return indexes(context, toStringOrNull(tableName), toStringOrNull(name), toStringOrNull(schemaName));
}
// NOTE: metaData.getIndexInfo row mappings :
protected static final int INDEX_INFO_TABLE_NAME = 3;
protected static final int INDEX_INFO_NON_UNIQUE = 4;
protected static final int INDEX_INFO_NAME = 6;
protected static final int INDEX_INFO_COLUMN_NAME = 9;
/**
* Default JDBC introspection for index metadata on the JdbcConnection.
*
* JDBC index metadata is denormalized (multiple rows may be returned for
* one index, one row per column in the index), so a simple block-based
* filter like that used for tables doesn't really work here. Callers
* should filter the return from this method instead.
*/
protected IRubyObject indexes(final ThreadContext context, final String tableName, final String name, final String schemaName) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final Ruby runtime = context.getRuntime();
final RubyClass IndexDefinition = getIndexDefinition(context);
String _tableName = caseConvertIdentifierForJdbc(connection, tableName);
String _schemaName = caseConvertIdentifierForJdbc(connection, schemaName);
final TableName table = extractTableName(connection, null, _schemaName, _tableName);
final List<RubyString> primaryKeys = primaryKeys(context, connection, table);
ResultSet indexInfoSet = null;
final List<IRubyObject> indexes = new ArrayList<IRubyObject>();
try {
final DatabaseMetaData metaData = connection.getMetaData();
indexInfoSet = metaData.getIndexInfo(table.catalog, table.schema, table.name, false, true);
String currentIndex = null;
while ( indexInfoSet.next() ) {
String indexName = indexInfoSet.getString(INDEX_INFO_NAME);
if ( indexName == null ) continue;
indexName = caseConvertIdentifierForRails(metaData, indexName);
final String columnName = indexInfoSet.getString(INDEX_INFO_COLUMN_NAME);
final RubyString rubyColumnName = RubyString.newUnicodeString(
runtime, caseConvertIdentifierForRails(metaData, columnName)
);
if ( primaryKeys.contains(rubyColumnName) ) continue;
// We are working on a new index
if ( ! indexName.equals(currentIndex) ) {
currentIndex = indexName;
String indexTableName = indexInfoSet.getString(INDEX_INFO_TABLE_NAME);
indexTableName = caseConvertIdentifierForRails(metaData, indexTableName);
final boolean nonUnique = indexInfoSet.getBoolean(INDEX_INFO_NON_UNIQUE);
IRubyObject[] args = new IRubyObject[] {
RubyString.newUnicodeString(runtime, indexTableName), // table_name
RubyString.newUnicodeString(runtime, indexName), // index_name
runtime.newBoolean( ! nonUnique ), // unique
runtime.newArray() // [] for column names, we'll add to that in just a bit
// orders, (since AR 3.2) where, type, using (AR 4.0)
};
indexes.add( IndexDefinition.callMethod(context, "new", args) ); // IndexDefinition.new
}
// One or more columns can be associated with an index
IRubyObject lastIndexDef = indexes.isEmpty() ? null : indexes.get(indexes.size() - 1);
if (lastIndexDef != null) {
lastIndexDef.callMethod(context, "columns").callMethod(context, "<<", rubyColumnName);
}
}
return runtime.newArray(indexes);
} finally { close(indexInfoSet); }
}
});
}
protected RubyClass getIndexDefinition(final ThreadContext context) {
final RubyClass adapterClass = getAdapter(context).getMetaClass();
IRubyObject IDef = adapterClass.getConstantAt("IndexDefinition");
return IDef != null ? (RubyClass) IDef : getIndexDefinition(context.runtime);
}
@JRubyMethod
public IRubyObject foreign_keys(final ThreadContext context, IRubyObject table_name) {
return foreignKeys(context, table_name.toString(), null, null);
}
protected IRubyObject foreignKeys(final ThreadContext context, final String tableName, final String schemaName, final String catalog) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final Ruby runtime = context.getRuntime();
final RubyClass FKDefinition = getForeignKeyDefinition(context);
String _tableName = caseConvertIdentifierForJdbc(connection, tableName);
String _schemaName = caseConvertIdentifierForJdbc(connection, schemaName);
final TableName table = extractTableName(connection, catalog, _schemaName, _tableName);
ResultSet fkInfoSet = null;
final List<IRubyObject> fKeys = new ArrayList<IRubyObject>(8);
try {
final DatabaseMetaData metaData = connection.getMetaData();
fkInfoSet = metaData.getImportedKeys(table.catalog, table.schema, table.name);
while ( fkInfoSet.next() ) {
final RubyHash options = RubyHash.newHash(runtime);
String fkName = fkInfoSet.getString("FK_NAME");
if (fkName != null) {
fkName = caseConvertIdentifierForRails(metaData, fkName);
options.put(runtime.newSymbol("name"), fkName);
}
String columnName = fkInfoSet.getString("FKCOLUMN_NAME");
options.put(runtime.newSymbol("column"), caseConvertIdentifierForRails(metaData, columnName));
columnName = fkInfoSet.getString("PKCOLUMN_NAME");
options.put(runtime.newSymbol("primary_key"), caseConvertIdentifierForRails(metaData, columnName));
String fkTableName = fkInfoSet.getString("FKTABLE_NAME");
fkTableName = caseConvertIdentifierForRails(metaData, fkTableName);
String pkTableName = fkInfoSet.getString("PKTABLE_NAME");
pkTableName = caseConvertIdentifierForRails(metaData, pkTableName);
final String onDelete = extractForeignKeyRule( fkInfoSet.getInt("DELETE_RULE") );
if ( onDelete != null ) options.op_aset(context, runtime.newSymbol("on_delete"), runtime.newSymbol(onDelete));
final String onUpdate = extractForeignKeyRule( fkInfoSet.getInt("UPDATE_RULE") );
if ( onUpdate != null ) options.op_aset(context, runtime.newSymbol("on_update"), runtime.newSymbol(onUpdate));
IRubyObject[] args = new IRubyObject[] {
RubyString.newUnicodeString(runtime, fkTableName), // from_table
RubyString.newUnicodeString(runtime, pkTableName), // to_table
options
};
fKeys.add( FKDefinition.callMethod(context, "new", args) ); // ForeignKeyDefinition.new
}
return runtime.newArray(fKeys);
} finally { close(fkInfoSet); }
}
});
}
protected String extractForeignKeyRule(final int rule) {
switch (rule) {
case DatabaseMetaData.importedKeyNoAction : return null ;
case DatabaseMetaData.importedKeyCascade : return "cascade" ;
case DatabaseMetaData.importedKeySetNull : return "nullify" ;
case DatabaseMetaData.importedKeySetDefault: return "default" ;
}
return null;
}
protected RubyClass getForeignKeyDefinition(final ThreadContext context) {
final RubyClass adapterClass = getAdapter(context).getMetaClass();
IRubyObject FKDef = adapterClass.getConstantAt("ForeignKeyDefinition");
return FKDef != null ? (RubyClass) FKDef : getForeignKeyDefinition(context.runtime);
}
@JRubyMethod(name = "supports_foreign_keys?")
public IRubyObject supports_foreign_keys_p(final ThreadContext context) throws SQLException {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final DatabaseMetaData metaData = connection.getMetaData();
return context.getRuntime().newBoolean( metaData.supportsIntegrityEnhancementFacility() );
}
});
}
@JRubyMethod(name = "supports_views?")
public IRubyObject supports_views_p(final ThreadContext context) throws SQLException {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final DatabaseMetaData metaData = connection.getMetaData();
final ResultSet tableTypes = metaData.getTableTypes();
try {
while ( tableTypes.next() ) {
if ( "VIEW".equalsIgnoreCase( tableTypes.getString(1) ) ) {
return context.getRuntime().newBoolean( true );
}
}
}
finally {
close(tableTypes);
}
return context.getRuntime().newBoolean( false );
}
});
}
@JRubyMethod(name = "with_connection_retry_guard", frame = true)
public IRubyObject with_connection_retry_guard(final ThreadContext context, final Block block) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
return block.call(context, new IRubyObject[] { convertJavaToRuby(connection) });
}
});
}
/*
* (binary?, column_name, table_name, id_key, id_value, value)
*/
@Deprecated
@JRubyMethod(name = "write_large_object", required = 6)
public IRubyObject write_large_object(final ThreadContext context, final IRubyObject[] args)
throws SQLException {
final boolean binary = args[0].isTrue();
final String columnName = args[1].toString();
final String tableName = args[2].toString();
final String idKey = args[3].toString();
final IRubyObject idVal = args[4];
final IRubyObject lobValue = args[5];
int count = updateLobValue(context, tableName, columnName, null, idKey, idVal, null, lobValue, binary);
return context.getRuntime().newFixnum(count);
}
@JRubyMethod(name = "update_lob_value", required = 3)
public IRubyObject update_lob_value(final ThreadContext context,
final IRubyObject record, final IRubyObject column, final IRubyObject value)
throws SQLException {
final boolean binary = // column.type == :binary
column.callMethod(context, "type").toString() == (Object) "binary";
final IRubyObject recordClass = record.callMethod(context, "class");
final IRubyObject adapter = recordClass.callMethod(context, "connection");
IRubyObject columnName = column.callMethod(context, "name");
columnName = adapter.callMethod(context, "quote_column_name", columnName);
IRubyObject tableName = recordClass.callMethod(context, "table_name");
tableName = adapter.callMethod(context, "quote_table_name", tableName);
final IRubyObject idKey = recordClass.callMethod(context, "primary_key");
// callMethod(context, "quote", primaryKey);
final IRubyObject idColumn = // record.class.columns_hash['id']
recordClass.callMethod(context, "columns_hash").callMethod(context, "[]", idKey);
final IRubyObject id = record.callMethod(context, "id"); // record.id
final int count = updateLobValue(context,
tableName.toString(), columnName.toString(), column,
idKey.toString(), id, idColumn, value, binary
);
return context.getRuntime().newFixnum(count);
}
private int updateLobValue(final ThreadContext context,
final String tableName, final String columnName, final IRubyObject column,
final String idKey, final IRubyObject idValue, final IRubyObject idColumn,
final IRubyObject value, final boolean binary) {
final String sql = "UPDATE "+ tableName +" SET "+ columnName +" = ? WHERE "+ idKey +" = ?" ;
// TODO: Fix this, the columns don't have the info needed to handle this anymore
// currently commented out so that it will compile
return withConnection(context, new Callable<Integer>() {
public Integer call(final Connection connection) throws SQLException {
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
/*
if ( binary ) { // blob
setBlobParameter(context, connection, statement, 1, value, column, Types.BLOB);
}
else { // clob
setClobParameter(context, connection, statement, 1, value, column, Types.CLOB);
}
setStatementParameter(context, context.getRuntime(), connection, statement, 2, idValue, idColumn);
*/
return statement.executeUpdate();
}
finally { close(statement); }
}
});
}
protected String caseConvertIdentifierForRails(final Connection connection, final String value)
throws SQLException {
if ( value == null ) return null;
return caseConvertIdentifierForRails(connection.getMetaData(), value);
}
/**
* Convert an identifier coming back from the database to a case which Rails is expecting.
*
* Assumption: Rails identifiers will be quoted for mixed or will stay mixed
* as identifier names in Rails itself. Otherwise, they expect identifiers to
* be lower-case. Databases which store identifiers uppercase should be made
* lower-case.
*
* Assumption 2: It is always safe to convert all upper case names since it appears that
* some adapters do not report StoresUpper/Lower/Mixed correctly (am I right postgres/mysql?).
*/
protected static String caseConvertIdentifierForRails(final DatabaseMetaData metaData, final String value)
throws SQLException {
if ( value == null ) return null;
return metaData.storesUpperCaseIdentifiers() ? value.toLowerCase() : value;
}
protected String caseConvertIdentifierForJdbc(final Connection connection, final String value)
throws SQLException {
if ( value == null ) return null;
return caseConvertIdentifierForJdbc(connection.getMetaData(), value);
}
/**
* Convert an identifier destined for a method which cares about the databases internal
* storage case. Methods like DatabaseMetaData.getPrimaryKeys() needs the table name to match
* the internal storage name. Arbitrary queries and the like DO NOT need to do this.
*/
protected static String caseConvertIdentifierForJdbc(final DatabaseMetaData metaData, final String value)
throws SQLException {
if ( value == null ) return null;
if ( metaData.storesUpperCaseIdentifiers() ) {
return value.toUpperCase();
}
else if ( metaData.storesLowerCaseIdentifiers() ) {
return value.toLowerCase();
}
return value;
}
@JRubyMethod(name = "jndi_config?", meta = true)
public static IRubyObject jndi_config_p(final ThreadContext context,
final IRubyObject self, final IRubyObject config) {
// config[:jndi] || config[:data_source]
final Ruby runtime = context.getRuntime();
IRubyObject configValue;
if ( config.getClass() == RubyHash.class ) { // "optimized" version
final RubyHash configHash = ((RubyHash) config);
configValue = configHash.fastARef(runtime.newSymbol("jndi"));
if ( configValue == null ) {
configValue = configHash.fastARef(runtime.newSymbol("data_source"));
}
}
else {
configValue = config.callMethod(context, "[]", runtime.newSymbol("jndi"));
if ( configValue.isNil() ) configValue = null;
if ( configValue == null ) {
configValue = config.callMethod(context, "[]", runtime.newSymbol("data_source"));
}
}
final IRubyObject rubyFalse = runtime.newBoolean( false );
if ( configValue == null || configValue.isNil() || configValue == rubyFalse ) {
return rubyFalse;
}
return context.getRuntime().newBoolean( true );
}
private IRubyObject getConfig(final ThreadContext context) {
return getInstanceVariable("@config"); // this.callMethod(context, "config");
}
protected final IRubyObject getConfigValue(final ThreadContext context, final String key) {
final IRubyObject config = getConfig(context);
final RubySymbol keySym = context.runtime.newSymbol(key);
if ( config instanceof RubyHash ) {
return ((RubyHash) config).op_aref(context, keySym);
}
return config.callMethod(context, "[]", keySym);
}
private static String toStringOrNull(final IRubyObject arg) {
return arg.isNil() ? null : arg.toString();
}
protected final IRubyObject getAdapter(final ThreadContext context) {
return callMethod(context, "adapter");
}
protected final RubyClass getJdbcColumnClass(final ThreadContext context) {
return (RubyClass) getAdapter(context).callMethod(context, "jdbc_column_class");
}
protected JdbcConnectionFactory getConnectionFactory() throws RaiseException {
if ( connectionFactory == null ) {
// NOTE: only for (backwards) compatibility - no likely that anyone
// overriden this - thus can likely be safely deleted (no needed) :
IRubyObject connection_factory = getInstanceVariable("@connection_factory");
if ( connection_factory == null ) {
throw getRuntime().newRuntimeError("@connection_factory not set");
}
connectionFactory = (JdbcConnectionFactory) connection_factory.toJava(JdbcConnectionFactory.class);
}
return connectionFactory;
}
public void setConnectionFactory(JdbcConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
protected Connection newConnection() throws RaiseException, SQLException {
return getConnectionFactory().newConnection();
}
private static String[] getTypes(final IRubyObject typeArg) {
if ( typeArg instanceof RubyArray ) {
IRubyObject[] rubyTypes = ((RubyArray) typeArg).toJavaArray();
final String[] types = new String[rubyTypes.length];
for ( int i = 0; i < types.length; i++ ) {
types[i] = rubyTypes[i].toString();
}
return types;
}
return new String[] { typeArg.toString() }; // expect a RubyString
}
/**
* @deprecated this method is no longer used, instead consider overriding
* {@link #mapToResult(ThreadContext, Ruby, Connection, ResultSet, RubyJdbcConnection.ColumnData[])}
*/
@Deprecated
protected void populateFromResultSet(
final ThreadContext context, final Ruby runtime,
final List<IRubyObject> results, final ResultSet resultSet,
final ColumnData[] columns) throws SQLException {
while ( resultSet.next() ) {
results.add(mapRawRow(context, runtime, columns, resultSet, this));
}
}
/**
* Maps a query result into a <code>ActiveRecord</code> result.
* @param context
* @param runtime
* @param connection
* @param resultSet
* @param columns
* @return since 3.1 expected to return a <code>ActiveRecord::Result</code>
* @throws SQLException
*/
protected IRubyObject mapToResult(final ThreadContext context, final Ruby runtime,
final Connection connection, final ResultSet resultSet,
final ColumnData[] columns) throws SQLException {
final RubyArray resultRows = runtime.newArray();
while (resultSet.next()) {
resultRows.append(mapRow(context, runtime, columns, resultSet, this));
}
return newResult(context, columns, resultRows);
}
@Deprecated
protected IRubyObject jdbcToRuby(final Ruby runtime,
final int column, final int type, final ResultSet resultSet)
throws SQLException {
return jdbcToRuby(runtime.getCurrentContext(), runtime, column, type, resultSet);
}
protected IRubyObject jdbcToRuby(
final ThreadContext context, final Ruby runtime,
final int column, final int type, final ResultSet resultSet)
throws SQLException {
try {
switch (type) {
case Types.BLOB:
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return streamToRuby(context, runtime, resultSet, column);
case Types.CLOB:
case Types.NCLOB: // JDBC 4.0
return readerToRuby(context, runtime, resultSet, column);
case Types.LONGVARCHAR:
case Types.LONGNVARCHAR: // JDBC 4.0
return readerToRuby(context, runtime, resultSet, column);
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return integerToRuby(context, runtime, resultSet, column);
case Types.REAL:
case Types.FLOAT:
case Types.DOUBLE:
return doubleToRuby(context, runtime, resultSet, column);
case Types.BIGINT:
return bigIntegerToRuby(context, runtime, resultSet, column);
case Types.NUMERIC:
case Types.DECIMAL:
return decimalToRuby(context, runtime, resultSet, column);
case Types.DATE:
return dateToRuby(context, runtime, resultSet, column);
case Types.TIME:
return timeToRuby(context, runtime, resultSet, column);
case Types.TIMESTAMP:
return timestampToRuby(context, runtime, resultSet, column);
case Types.BIT:
case Types.BOOLEAN:
return booleanToRuby(context, runtime, resultSet, column);
case Types.SQLXML: // JDBC 4.0
return xmlToRuby(context, runtime, resultSet, column);
case Types.ARRAY: // we handle JDBC Array into (Ruby) []
return arrayToRuby(context, runtime, resultSet, column);
case Types.NULL:
return runtime.getNil();
// NOTE: (JDBC) exotic stuff just cause it's so easy with JRuby :)
case Types.JAVA_OBJECT:
case Types.OTHER:
return objectToRuby(context, runtime, resultSet, column);
// (default) String
case Types.CHAR:
case Types.VARCHAR:
case Types.NCHAR: // JDBC 4.0
case Types.NVARCHAR: // JDBC 4.0
default:
return stringToRuby(context, runtime, resultSet, column);
}
// NOTE: not mapped types :
//case Types.DISTINCT:
//case Types.STRUCT:
//case Types.REF:
//case Types.DATALINK:
}
catch (IOException e) {
throw new SQLException(e.getMessage(), e);
}
}
protected IRubyObject integerToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final long value = resultSet.getLong(column);
if ( value == 0 && resultSet.wasNull() ) return runtime.getNil();
return runtime.newFixnum(value);
}
protected IRubyObject doubleToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final double value = resultSet.getDouble(column);
if ( value == 0 && resultSet.wasNull() ) return runtime.getNil();
return runtime.newFloat(value);
}
protected IRubyObject stringToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException {
final String value = resultSet.getString(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return RubyString.newUnicodeString(runtime, value);
}
protected IRubyObject bigIntegerToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException {
final String value = resultSet.getString(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return RubyBignum.bignorm(runtime, new BigInteger(value));
}
protected IRubyObject decimalToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException {
final String value = resultSet.getString(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return RubyBigDecimal.newInstance(context, runtime.getModule("BigDecimal"), runtime.newString(value));
}
protected static Boolean rawDateTime;
static {
final String dateTimeRaw = System.getProperty("arjdbc.datetime.raw");
if ( dateTimeRaw != null ) {
rawDateTime = Boolean.parseBoolean(dateTimeRaw);
}
// NOTE: we do this since it will have a different value depending on
// AR version - since 4.0 false by default otherwise will be true ...
}
@JRubyMethod(name = "raw_date_time?", meta = true)
public static IRubyObject useRawDateTime(final ThreadContext context, final IRubyObject self) {
if ( rawDateTime == null ) return context.getRuntime().getNil();
return context.getRuntime().newBoolean( rawDateTime.booleanValue() );
}
@JRubyMethod(name = "raw_date_time=", meta = true)
public static IRubyObject setRawDateTime(final IRubyObject self, final IRubyObject value) {
if ( value instanceof RubyBoolean ) {
rawDateTime = ((RubyBoolean) value).isTrue();
}
else {
rawDateTime = value.isNil() ? null : Boolean.TRUE;
}
return value;
}
/**
* @return AR::Type-casted value
* @since 1.3.18
*/
protected static IRubyObject typeCastFromDatabase(final ThreadContext context,
final IRubyObject adapter, final RubySymbol typeName, final RubyString value) {
final IRubyObject type = adapter.callMethod(context, "lookup_cast_type", typeName);
return type.callMethod(context, "deserialize", value);
}
protected IRubyObject dateToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Date value = resultSet.getDate(column);
if ( value == null ) {
if ( resultSet.wasNull() ) return runtime.getNil();
return runtime.newString();
}
final RubyString strValue = RubyString.newUnicodeString(runtime, value.toString());
if ( rawDateTime != null && rawDateTime.booleanValue() ) return strValue;
final IRubyObject adapter = callMethod(context, "adapter"); // self.adapter
if ( adapter.isNil() ) return strValue; // NOTE: we warn on init_connection
// NOTE: this CAN NOT be 100% correct - as :date is just a type guess!
return typeCastFromDatabase(context, adapter, runtime.newSymbol("date"), strValue);
}
protected IRubyObject timeToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Time value = resultSet.getTime(column);
if ( value == null ) {
if ( resultSet.wasNull() ) return runtime.getNil();
return runtime.newString();
}
final RubyString strValue = RubyString.newUnicodeString(runtime, value.toString());
if ( rawDateTime != null && rawDateTime.booleanValue() ) return strValue;
final IRubyObject adapter = callMethod(context, "adapter"); // self.adapter
if ( adapter.isNil() ) return strValue; // NOTE: we warn on init_connection
// NOTE: this CAN NOT be 100% correct - as :time is just a type guess!
return typeCastFromDatabase(context, adapter, runtime.newSymbol("time"), strValue);
}
protected IRubyObject timestampToRuby(final ThreadContext context, // TODO
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Timestamp value = resultSet.getTimestamp(column);
if ( value == null ) {
if ( resultSet.wasNull() ) return runtime.getNil();
return runtime.newString();
}
final RubyString strValue = timestampToRubyString(runtime, value.toString());
if ( rawDateTime != null && rawDateTime.booleanValue() ) return strValue;
final IRubyObject adapter = callMethod(context, "adapter"); // self.adapter
if ( adapter.isNil() ) return strValue; // NOTE: we warn on init_connection
// NOTE: this CAN NOT be 100% correct - as :timestamp is just a type guess!
return typeCastFromDatabase(context, adapter, runtime.newSymbol("timestamp"), strValue);
}
protected static RubyString timestampToRubyString(final Ruby runtime, String value) {
// Timestamp's format: yyyy-mm-dd hh:mm:ss.fffffffff
String suffix; // assumes java.sql.Timestamp internals :
if ( value.endsWith( suffix = " 00:00:00.0" ) ) {
value = value.substring( 0, value.length() - suffix.length() );
}
else if ( value.endsWith( suffix = ".0" ) ) {
value = value.substring( 0, value.length() - suffix.length() );
}
return RubyString.newUnicodeString(runtime, value);
}
protected static Boolean rawBoolean;
static {
final String booleanRaw = System.getProperty("arjdbc.boolean.raw");
if ( booleanRaw != null ) {
rawBoolean = Boolean.parseBoolean(booleanRaw);
}
}
@JRubyMethod(name = "raw_boolean?", meta = true)
public static IRubyObject useRawBoolean(final ThreadContext context, final IRubyObject self) {
if ( rawBoolean == null ) return context.getRuntime().getNil();
return context.getRuntime().newBoolean( rawBoolean.booleanValue() );
}
@JRubyMethod(name = "raw_boolean=", meta = true)
public static IRubyObject setRawBoolean(final IRubyObject self, final IRubyObject value) {
if ( value instanceof RubyBoolean ) {
rawBoolean = ((RubyBoolean) value).isTrue();
}
else {
rawBoolean = value.isNil() ? null : Boolean.TRUE;
}
return value;
}
protected IRubyObject booleanToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
if ( rawBoolean != null && rawBoolean.booleanValue() ) {
final String value = resultSet.getString(column);
if ( resultSet.wasNull() ) return runtime.getNil();
return RubyString.newUnicodeString(runtime, value);
}
final boolean value = resultSet.getBoolean(column);
if ( resultSet.wasNull() ) return runtime.getNil();
return booleanToRuby(runtime, resultSet, value);
}
@Deprecated
protected IRubyObject booleanToRuby(
final Ruby runtime, final ResultSet resultSet, final boolean value)
throws SQLException {
if ( value == false && resultSet.wasNull() ) return runtime.getNil();
return runtime.newBoolean(value);
}
protected static int streamBufferSize = 2048;
protected IRubyObject streamToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException, IOException {
final InputStream stream = resultSet.getBinaryStream(column);
try {
if ( resultSet.wasNull() ) return runtime.getNil();
return streamToRuby(runtime, resultSet, stream);
}
finally { if ( stream != null ) stream.close(); }
}
@Deprecated
protected IRubyObject streamToRuby(
final Ruby runtime, final ResultSet resultSet, final InputStream stream)
throws SQLException, IOException {
if ( stream == null && resultSet.wasNull() ) return runtime.getNil();
final int bufSize = streamBufferSize;
final ByteList string = new ByteList(bufSize);
final byte[] buf = new byte[bufSize];
for (int len = stream.read(buf); len != -1; len = stream.read(buf)) {
string.append(buf, 0, len);
}
return runtime.newString(string);
}
protected IRubyObject readerToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException, IOException {
final Reader reader = resultSet.getCharacterStream(column);
try {
if ( resultSet.wasNull() ) return runtime.getNil();
return readerToRuby(runtime, resultSet, reader);
}
finally { if ( reader != null ) reader.close(); }
}
@Deprecated
protected IRubyObject readerToRuby(
final Ruby runtime, final ResultSet resultSet, final Reader reader)
throws SQLException, IOException {
if ( reader == null && resultSet.wasNull() ) return runtime.getNil();
final int bufSize = streamBufferSize;
final StringBuilder string = new StringBuilder(bufSize);
final char[] buf = new char[bufSize];
for (int len = reader.read(buf); len != -1; len = reader.read(buf)) {
string.append(buf, 0, len);
}
return RubyString.newUnicodeString(runtime, string.toString());
}
protected IRubyObject objectToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Object value = resultSet.getObject(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return JavaUtil.convertJavaToRuby(runtime, value);
}
protected IRubyObject arrayToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Array value = resultSet.getArray(column);
try {
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
final RubyArray array = runtime.newArray();
final ResultSet arrayResult = value.getResultSet(); // 1: index, 2: value
final int baseType = value.getBaseType();
while ( arrayResult.next() ) {
array.append( jdbcToRuby(context, runtime, 2, baseType, arrayResult) );
}
return array;
}
finally { if ( value != null ) value.free(); }
}
protected IRubyObject xmlToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final SQLXML xml = resultSet.getSQLXML(column);
try {
if ( xml == null || resultSet.wasNull() ) return runtime.getNil();
return RubyString.newUnicodeString(runtime, xml.getString());
}
finally { if ( xml != null ) xml.free(); }
}
protected void setStatementParameters(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final RubyArray binds) throws SQLException {
for ( int i = 0; i < binds.getLength(); i++ ) {
setStatementParameter(context, connection, statement, i + 1, binds.eltInternal(i));
}
}
// Set the prepared statement attributes based on the passed in Attribute object
protected void setStatementParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject attribute) throws SQLException {
//debugMessage(context, attribute);
int type = jdbcTypeForAttribute(context, attribute);
IRubyObject value = valueForDatabase(context, attribute);
// All the set methods were calling this first so save a method call in the nil case
if ( value.isNil() ) {
statement.setNull(index, type);
return;
}
switch (type) {
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
setIntegerParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.BIGINT:
setBigIntegerParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.REAL:
case Types.FLOAT:
case Types.DOUBLE:
setDoubleParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.NUMERIC:
case Types.DECIMAL:
setDecimalParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.DATE:
setDateParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.TIME:
setTimeParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.TIMESTAMP:
setTimestampParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.BIT:
case Types.BOOLEAN:
setBooleanParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.SQLXML:
setXmlParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.ARRAY:
setArrayParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.JAVA_OBJECT:
case Types.OTHER:
setObjectParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.BLOB:
setBlobParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.CLOB:
case Types.NCLOB: // JDBC 4.0
setClobParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.CHAR:
case Types.VARCHAR:
case Types.NCHAR: // JDBC 4.0
case Types.NVARCHAR: // JDBC 4.0
default:
setStringParameter(context, connection, statement, index, value, attribute, type);
}
}
protected static final Map<String, Integer> JDBC_TYPE_FOR = new HashMap<String, Integer>(32, 1);
static {
JDBC_TYPE_FOR.put("string", Types.VARCHAR);
JDBC_TYPE_FOR.put("text", Types.CLOB);
JDBC_TYPE_FOR.put("integer", Types.INTEGER);
JDBC_TYPE_FOR.put("float", Types.FLOAT);
JDBC_TYPE_FOR.put("real", Types.REAL);
JDBC_TYPE_FOR.put("decimal", Types.DECIMAL);
JDBC_TYPE_FOR.put("date", Types.DATE);
JDBC_TYPE_FOR.put("time", Types.TIME);
JDBC_TYPE_FOR.put("datetime", Types.TIMESTAMP);
JDBC_TYPE_FOR.put("timestamp", Types.TIMESTAMP);
JDBC_TYPE_FOR.put("boolean", Types.BOOLEAN);
JDBC_TYPE_FOR.put("array", Types.ARRAY);
JDBC_TYPE_FOR.put("xml", Types.SQLXML);
// also mapping standard SQL names :
JDBC_TYPE_FOR.put("bit", Types.BIT);
JDBC_TYPE_FOR.put("tinyint", Types.TINYINT);
JDBC_TYPE_FOR.put("smallint", Types.SMALLINT);
JDBC_TYPE_FOR.put("bigint", Types.BIGINT);
JDBC_TYPE_FOR.put("int", Types.INTEGER);
JDBC_TYPE_FOR.put("double", Types.DOUBLE);
JDBC_TYPE_FOR.put("numeric", Types.NUMERIC);
JDBC_TYPE_FOR.put("char", Types.CHAR);
JDBC_TYPE_FOR.put("varchar", Types.VARCHAR);
JDBC_TYPE_FOR.put("binary", Types.BINARY);
JDBC_TYPE_FOR.put("varbinary", Types.VARBINARY);
//JDBC_TYPE_FOR.put("struct", Types.STRUCT);
JDBC_TYPE_FOR.put("blob", Types.BLOB);
JDBC_TYPE_FOR.put("clob", Types.CLOB);
JDBC_TYPE_FOR.put("nchar", Types.NCHAR);
JDBC_TYPE_FOR.put("nvarchar", Types.NVARCHAR);
JDBC_TYPE_FOR.put("nclob", Types.NCLOB);
}
protected int jdbcTypeForAttribute(final ThreadContext context,
final IRubyObject attribute) throws SQLException {
final String internedType = internedTypeFor(context, attribute);
final Integer sqlType = jdbcTypeFor(internedType);
if ( sqlType != null ) {
return sqlType.intValue();
}
return Types.OTHER; // -1 as well as 0 are used in Types
}
protected Integer jdbcTypeFor(final String type) {
return JDBC_TYPE_FOR.get(type);
}
protected IRubyObject attributeType(final ThreadContext context, final IRubyObject attribute) {
return attribute.callMethod(context, "type");
}
protected IRubyObject attributeSQLType(final ThreadContext context, final IRubyObject attribute) {
return attributeType(context, attribute).callMethod(context, "type");
}
protected String internedTypeFor(final ThreadContext context, final IRubyObject attribute) throws SQLException {
final IRubyObject type = attributeSQLType(context, attribute);
if ( !type.isNil() ) {
return type.asJavaString();
}
final IRubyObject value = attribute.callMethod(context, "value");
if ( value instanceof RubyInteger ) {
return "integer";
}
if ( value instanceof RubyNumeric ) {
return "float";
}
if ( value instanceof RubyTime ) {
return "timestamp";
}
return "string";
}
protected void setIntegerParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value instanceof RubyBignum ) { // e.g. HSQLDB / H2 report JDBC type 4
setBigIntegerParameter(context, connection, statement, index, (RubyBignum) value, attribute, type);
}
else if ( value instanceof RubyFixnum ) {
statement.setLong(index, ((RubyFixnum) value).getLongValue());
}
else if ( value instanceof RubyNumeric ) {
// NOTE: fix2int will call value.convertToInteger for non-numeric
// types which won't work for Strings since it uses `to_int` ...
statement.setInt(index, RubyNumeric.fix2int(value));
}
else {
statement.setLong(index, value.convertToInteger("to_i").getLongValue());
}
}
protected void setBigIntegerParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value instanceof RubyBignum ) {
setLongOrDecimalParameter(statement, index, ((RubyBignum) value).getValue());
}
else if ( value instanceof RubyInteger ) {
statement.setLong(index, ((RubyInteger) value).getLongValue());
}
else {
setLongOrDecimalParameter(statement, index, value.convertToInteger("to_i").getBigIntegerValue());
}
}
private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);
private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE);
protected static void setLongOrDecimalParameter(final PreparedStatement statement,
final int index, final BigInteger value) throws SQLException {
if ( value.compareTo(MAX_LONG) <= 0 // -1 intValue < MAX_VALUE
&& value.compareTo(MIN_LONG) >= 0 ) {
statement.setLong(index, value.longValue());
}
else {
statement.setBigDecimal(index, new BigDecimal(value));
}
}
protected void setDoubleParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value instanceof RubyNumeric ) {
statement.setDouble(index, ((RubyNumeric) value).getDoubleValue());
}
else {
statement.setDouble(index, value.convertToFloat().getDoubleValue());
}
}
protected void setDecimalParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if (value instanceof RubyBigDecimal) {
statement.setBigDecimal(index, ((RubyBigDecimal) value).getValue());
}
else if ( value instanceof RubyInteger ) {
statement.setBigDecimal(index, new BigDecimal(((RubyInteger) value).getBigIntegerValue()));
}
else if ( value instanceof RubyNumeric ) {
statement.setDouble(index, ((RubyNumeric) value).getDoubleValue());
}
else { // e.g. `BigDecimal '42.00000000000000000001'`
statement.setBigDecimal(index,
RubyBigDecimal.newInstance(context, context.runtime.getModule("BigDecimal"), value).getValue());
}
}
protected void setTimestampParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
value = getTimeInDefaultTimeZone(context, value);
if ( value instanceof RubyTime ) {
final RubyTime timeValue = (RubyTime) value;
final DateTime dateTime = timeValue.getDateTime();
final Timestamp timestamp = new Timestamp(dateTime.getMillis());
if ( type != Types.DATE ) { // 1942-11-30T01:02:03.123_456
// getMillis already set nanos to: 123_000_000
final int usec = (int) timeValue.getUSec(); // 456 on JRuby
if ( usec >= 0 ) {
timestamp.setNanos(timestamp.getNanos() + usec * 1000);
}
}
statement.setTimestamp( index, timestamp, getTimeZoneCalendar(dateTime.getZone().getID()) );
}
else if ( value instanceof RubyString ) { // yyyy-[m]m-[d]d hh:mm:ss[.f...]
final Timestamp timestamp = Timestamp.valueOf(value.toString());
statement.setTimestamp(index, timestamp); // assume local time-zone
}
else { // DateTime ( ActiveSupport::TimeWithZone.to_time )
final RubyFloat timeValue = value.convertToFloat(); // to_f
final Timestamp timestamp = convertToTimestamp(timeValue);
statement.setTimestamp( index, timestamp, getTimeZoneCalendar("GMT") );
}
}
protected static Timestamp convertToTimestamp(final RubyFloat value) {
final Timestamp timestamp = new Timestamp(value.getLongValue() * 1000); // millis
// for usec we shall not use: ((long) floatValue * 1000000) % 1000
// if ( usec >= 0 ) timestamp.setNanos( timestamp.getNanos() + usec * 1000 );
// due doubles inaccurate precision it's better to parse to_s :
final ByteList strValue = ((RubyString) value.to_s()).getByteList();
final int dot1 = strValue.lastIndexOf('.') + 1, dot4 = dot1 + 3;
final int len = strValue.getRealSize() - strValue.getBegin();
if ( dot1 > 0 && dot4 < len ) { // skip .123 but handle .1234
final int end = Math.min( len - dot4, 3 );
CharSequence usecSeq = strValue.subSequence(dot4, end);
final int usec = Integer.parseInt( usecSeq.toString() );
if ( usec < 10 ) { // 0.1234 ~> 4
timestamp.setNanos( timestamp.getNanos() + usec * 100 );
}
else if ( usec < 100 ) { // 0.12345 ~> 45
timestamp.setNanos( timestamp.getNanos() + usec * 10 );
}
else { // if ( usec < 1000 ) { // 0.123456 ~> 456
timestamp.setNanos( timestamp.getNanos() + usec );
}
}
return timestamp;
}
protected static IRubyObject getTimeInDefaultTimeZone(final ThreadContext context, IRubyObject value) {
if ( value.respondsTo("to_time") ) {
value = value.callMethod(context, "to_time");
}
final String method = isDefaultTimeZoneUTC(context) ? "getutc" : "getlocal";
if ( value.respondsTo(method) ) {
value = value.callMethod(context, method);
}
return value;
}
protected static boolean isDefaultTimeZoneUTC(final ThreadContext context) {
// :utc
final String tz = ActiveRecord(context).getClass("Base").callMethod(context, "default_timezone").toString();
return "utc".equalsIgnoreCase(tz);
}
private static Calendar getTimeZoneCalendar(final String ID) {
return Calendar.getInstance( TimeZone.getTimeZone(ID) );
}
protected void setTimeParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
value = getTimeInDefaultTimeZone(context, value);
if ( value instanceof RubyTime ) {
final DateTime dateTime = ((RubyTime) value).getDateTime();
final Time time = new Time(dateTime.getMillis());
statement.setTime(index, time, getTimeZoneCalendar(dateTime.getZone().getID()));
}
else if ( value instanceof RubyString ) {
final Time time = Time.valueOf(value.toString());
statement.setTime(index, time); // assume local time-zone
}
else { // DateTime ( ActiveSupport::TimeWithZone.to_time )
final RubyFloat timeValue = value.convertToFloat(); // to_f
final Time time = new Time(timeValue.getLongValue() * 1000); // millis
// java.sql.Time is expected to be only up to second precision
statement.setTime(index, time, getTimeZoneCalendar("GMT"));
}
}
protected void setDateParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( ! "Date".equals(value.getMetaClass().getName()) && value.respondsTo("to_date") ) {
value = value.callMethod(context, "to_date");
}
final Date date = Date.valueOf(value.asString().toString()); // to_s
statement.setDate(index, date);
}
protected void setBooleanParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
statement.setBoolean(index, value.isTrue());
}
protected void setStringParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
statement.setString(index, value.asString().toString());
}
protected void setArrayParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
final String typeName = resolveArrayBaseTypeName(context, attribute);
final IRubyObject valueForDB = value.callMethod(context, "values");
Array array = connection.createArrayOf(typeName, ((RubyArray) valueForDB).toArray());
statement.setArray(index, array);
}
protected String resolveArrayBaseTypeName(final ThreadContext context, final IRubyObject attribute) throws SQLException {
// This shouldn't return nil at this point because we know we have an array typed attribute
final RubySymbol type = (RubySymbol) attributeSQLType(context, attribute);
// For some reason the driver doesn't like "character varying" as a type
if ( type.eql(context.runtime.newSymbol("string")) ){
return "text";
}
final IRubyObject adapter = callMethod("adapter");
final RubyHash nativeTypes = (RubyHash) adapter.callMethod(context, "native_database_types");
final RubyHash typeInfo = (RubyHash) nativeTypes.op_aref(context, type);
return typeInfo.op_aref(context, context.runtime.newSymbol("name")).asString().toString();
}
protected void setXmlParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
SQLXML xml = connection.createSQLXML();
xml.setString(value.asString().toString());
statement.setSQLXML(index, xml);
}
protected void setBlobParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value instanceof RubyIO ) { // IO/File
// JDBC 4.0: statement.setBlob(index, ((RubyIO) value).getInStream());
statement.setBinaryStream(index, ((RubyIO) value).getInStream());
}
else { // should be a RubyString
final ByteList blob = value.asString().getByteList();
statement.setBytes(index, blob.bytes());
// JDBC 4.0 :
//statement.setBlob(index,
// new ByteArrayInputStream(bytes.unsafeBytes(), bytes.getBegin(), bytes.getRealSize())
}
}
protected void setClobParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value.isNil() ) statement.setNull(index, Types.CLOB);
else {
if ( value instanceof RubyIO ) { // IO/File
statement.setClob(index, new InputStreamReader(((RubyIO) value).getInStream()));
}
else { // should be a RubyString
final String clob = value.asString().decodeString();
statement.setCharacterStream(index, new StringReader(clob), clob.length());
// JDBC 4.0 :
//statement.setClob(index, new StringReader(clob));
}
}
}
protected void setObjectParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, Object value,
final IRubyObject attribute, final int type) throws SQLException {
if (value instanceof IRubyObject) {
value = ((IRubyObject) value).toJava(Object.class);
}
statement.setObject(index, value);
}
protected Connection getConnection(ThreadContext context, boolean reportMissingConnection) {
Connection connection = (Connection) dataGetStruct(); // synchronized
if (connection == null && reportMissingConnection) {
throw new RaiseException(getRuntime(), ActiveRecord(context).getClass("ConnectionNotEstablished"),
"no connection available", false);
}
return connection;
}
private IRubyObject setConnection(ThreadContext context, final Connection connection) {
close(getConnection(context, false)); // close previously open connection if there is one
final IRubyObject rubyConnectionObject = connection != null ?
convertJavaToRuby(connection) : context.runtime.getNil();
setInstanceVariable( "@connection", rubyConnectionObject );
dataWrapStruct(connection);
return rubyConnectionObject;
}
protected boolean isConnectionValid(final ThreadContext context, final Connection connection) {
if ( connection == null ) return false;
Statement statement = null;
try {
final RubyString aliveSQL = getAliveSQL(context);
final RubyInteger aliveTimeout = getAliveTimeout(context);
if ( aliveSQL != null && isSelect(aliveSQL) ) {
// expect a SELECT/CALL SQL statement
statement = createStatement(context, connection);
if (aliveTimeout != null) {
statement.setQueryTimeout((int) aliveTimeout.getLongValue()); // 0 - no timeout
}
statement.execute( aliveSQL.toString() );
return true; // connection alive
}
else { // alive_sql nil (or not a statement we can execute)
return connection.isValid(aliveTimeout == null ? 0 : (int) aliveTimeout.getLongValue()); // since JDBC 4.0
// ... isValid(0) (default) means no timeout applied
}
}
catch (Exception e) {
debugMessage(context, "connection considered broken due: " + e.toString());
return false;
}
catch (AbstractMethodError e) { // non-JDBC 4.0 driver
warn( context,
"WARN: driver does not support checking if connection isValid()" +
" please make sure you're using a JDBC 4.0 compilant driver or" +
" set `connection_alive_sql: ...` in your database configuration" );
debugStackTrace(context, e);
throw e;
}
finally { close(statement); }
}
/**
* internal API do not depend on it
*/
protected final RubyString getAliveSQL(final ThreadContext context) {
final IRubyObject alive_sql = getConfigValue(context, "connection_alive_sql");
return alive_sql.isNil() ? null : alive_sql.convertToString();
}
/**
* internal API do not depend on it
*/
protected final RubyInteger getAliveTimeout(final ThreadContext context) {
final IRubyObject timeout = getConfigValue(context, "connection_alive_timeout");
return timeout.isNil() ? null : timeout.convertToInteger("to_i");
}
private boolean tableExists(final Ruby runtime,
final Connection connection, final TableName tableName) throws SQLException {
final IRubyObject matchedTables =
matchTables(runtime, connection, tableName.catalog, tableName.schema, tableName.name, getTableTypes(), true);
// NOTE: allow implementers to ignore checkExistsOnly paramater - empty array means does not exists
return matchedTables != null && ! matchedTables.isNil() &&
( ! (matchedTables instanceof RubyArray) || ! ((RubyArray) matchedTables).isEmpty() );
}
/**
* Match table names for given table name (pattern).
* @param runtime
* @param connection
* @param catalog
* @param schemaPattern
* @param tablePattern
* @param types table types
* @param checkExistsOnly an optimization flag (that might be ignored by sub-classes)
* whether the result really matters if true no need to map table names and a truth-y
* value is sufficient (except for an empty array which is considered that the table
* did not exists).
* @return matched (and Ruby mapped) table names
* @see #mapTables(Ruby, DatabaseMetaData, String, String, String, ResultSet)
* @throws SQLException
*/
protected IRubyObject matchTables(final Ruby runtime,
final Connection connection,
final String catalog, final String schemaPattern,
final String tablePattern, final String[] types,
final boolean checkExistsOnly) throws SQLException {
final String _tablePattern = caseConvertIdentifierForJdbc(connection, tablePattern);
final String _schemaPattern = caseConvertIdentifierForJdbc(connection, schemaPattern);
final DatabaseMetaData metaData = connection.getMetaData();
ResultSet tablesSet = null;
try {
tablesSet = metaData.getTables(catalog, _schemaPattern, _tablePattern, types);
if ( checkExistsOnly ) { // only check if given table exists
return tablesSet.next() ? runtime.getTrue() : null;
}
else {
return mapTables(runtime, metaData, catalog, _schemaPattern, _tablePattern, tablesSet);
}
}
finally { close(tablesSet); }
}
// NOTE java.sql.DatabaseMetaData.getTables :
protected final static int TABLES_TABLE_CAT = 1;
protected final static int TABLES_TABLE_SCHEM = 2;
protected final static int TABLES_TABLE_NAME = 3;
protected final static int TABLES_TABLE_TYPE = 4;
/**
* @param runtime
* @param metaData
* @param catalog
* @param schemaPattern
* @param tablePattern
* @param tablesSet
* @return List<RubyString>
* @throws SQLException
*/
// NOTE: change to accept a connection instead of meta-data
protected RubyArray mapTables(final Ruby runtime, final DatabaseMetaData metaData,
final String catalog, final String schemaPattern, final String tablePattern,
final ResultSet tablesSet) throws SQLException {
final RubyArray tables = runtime.newArray();
while ( tablesSet.next() ) {
String name = tablesSet.getString(TABLES_TABLE_NAME);
name = caseConvertIdentifierForRails(metaData, name);
tables.add(RubyString.newUnicodeString(runtime, name));
}
return tables;
}
protected static final int COLUMN_NAME = 4;
protected static final int DATA_TYPE = 5;
protected static final int TYPE_NAME = 6;
protected static final int COLUMN_SIZE = 7;
protected static final int DECIMAL_DIGITS = 9;
protected static final int COLUMN_DEF = 13;
protected static final int IS_NULLABLE = 18;
/**
* Create a string which represents a SQL type usable by Rails from the
* resultSet column meta-data
* @param resultSet
*/
protected String typeFromResultSet(final ResultSet resultSet) throws SQLException {
final int precision = intFromResultSet(resultSet, COLUMN_SIZE);
final int scale = intFromResultSet(resultSet, DECIMAL_DIGITS);
final String type = resultSet.getString(TYPE_NAME);
return formatTypeWithPrecisionAndScale(type, precision, scale);
}
protected static int intFromResultSet(
final ResultSet resultSet, final int column) throws SQLException {
final int precision = resultSet.getInt(column);
return precision == 0 && resultSet.wasNull() ? -1 : precision;
}
protected static String formatTypeWithPrecisionAndScale(
final String type, final int precision, final int scale) {
if ( precision <= 0 ) return type;
final StringBuilder typeStr = new StringBuilder().append(type);
typeStr.append('(').append(precision); // type += "(" + precision;
if ( scale > 0 ) typeStr.append(',').append(scale); // type += "," + scale;
return typeStr.append(')').toString(); // type += ")";
}
private static IRubyObject defaultValueFromResultSet(final Ruby runtime, final ResultSet resultSet)
throws SQLException {
final String defaultValue = resultSet.getString(COLUMN_DEF);
return defaultValue == null ? runtime.getNil() : RubyString.newUnicodeString(runtime, defaultValue);
}
protected RubyArray mapColumnsResult(final ThreadContext context,
final DatabaseMetaData metaData, final TableName components, final ResultSet results)
throws SQLException {
final RubyClass Column = getJdbcColumnClass(context);
final boolean lookupCastType = Column.isMethodBound("cast_type", false);
// NOTE: primary/primary= methods were removed from Column in AR 4.2
// setPrimary = ! lookupCastType by default ... it's better than checking
// whether primary= is bound since it might be a left over in AR-JDBC ext
return mapColumnsResult(context, metaData, components, results, Column, lookupCastType, ! lookupCastType);
}
protected final RubyArray mapColumnsResult(final ThreadContext context,
final DatabaseMetaData metaData, final TableName components, final ResultSet results,
final RubyClass Column, final boolean lookupCastType, final boolean setPrimary)
throws SQLException {
final Ruby runtime = context.getRuntime();
final Collection<String> primaryKeyNames =
setPrimary ? getPrimaryKeyNames(metaData, components) : null;
final RubyArray columns = runtime.newArray();
final IRubyObject config = getConfig(context);
while ( results.next() ) {
final String colName = results.getString(COLUMN_NAME);
final RubyString railsColumnName = RubyString.newUnicodeString(runtime, caseConvertIdentifierForRails(metaData, colName));
final IRubyObject defaultValue = defaultValueFromResultSet( runtime, results );
final RubyString sqlType = RubyString.newUnicodeString( runtime, typeFromResultSet(results) );
final RubyBoolean nullable = runtime.newBoolean( ! results.getString(IS_NULLABLE).trim().equals("NO") );
final IRubyObject[] args;
if ( lookupCastType ) {
final IRubyObject castType = getAdapter(context).callMethod(context, "lookup_cast_type", sqlType);
args = new IRubyObject[] {config, railsColumnName, defaultValue, castType, sqlType, nullable};
} else {
args = new IRubyObject[] {config, railsColumnName, defaultValue, sqlType, nullable};
}
IRubyObject column = Column.callMethod(context, "new", args);
columns.append(column);
if ( primaryKeyNames != null ) {
final RubyBoolean primary = runtime.newBoolean( primaryKeyNames.contains(colName) );
column.getInstanceVariables().setInstanceVariable("@primary", primary);
}
}
return columns;
}
private static Collection<String> getPrimaryKeyNames(final DatabaseMetaData metaData,
final TableName components) throws SQLException {
ResultSet primaryKeys = null;
try {
primaryKeys = metaData.getPrimaryKeys(components.catalog, components.schema, components.name);
final List<String> primaryKeyNames = new ArrayList<String>(4);
while ( primaryKeys.next() ) {
primaryKeyNames.add( primaryKeys.getString(COLUMN_NAME) );
}
return primaryKeyNames;
}
finally {
close(primaryKeys);
}
}
protected IRubyObject mapGeneratedKeys(
final Ruby runtime, final Connection connection,
final Statement statement) throws SQLException {
return mapGeneratedKeys(runtime, connection, statement, null);
}
protected IRubyObject mapGeneratedKeys(
final Ruby runtime, final Connection connection,
final Statement statement, final Boolean singleResult)
throws SQLException {
if ( supportsGeneratedKeys(connection) ) {
ResultSet genKeys = null;
try {
genKeys = statement.getGeneratedKeys();
// drivers might report a non-result statement without keys
// e.g. on derby with SQL: 'SET ISOLATION = SERIALIZABLE'
if ( genKeys == null ) return runtime.getNil();
return doMapGeneratedKeys(runtime, genKeys, singleResult);
}
catch (SQLFeatureNotSupportedException e) {
return null; // statement.getGeneratedKeys()
}
finally { close(genKeys); }
}
return null; // not supported
}
protected final IRubyObject doMapGeneratedKeys(final Ruby runtime,
final ResultSet genKeys, final Boolean singleResult)
throws SQLException {
IRubyObject firstKey = null;
// no generated keys - e.g. INSERT statement for a table that does
// not have and auto-generated ID column :
boolean next = genKeys.next() && genKeys.getMetaData().getColumnCount() > 0;
// singleResult == null - guess if only single key returned
if ( singleResult == null || singleResult.booleanValue() ) {
if ( next ) {
firstKey = mapGeneratedKey(runtime, genKeys);
if ( singleResult != null || ! genKeys.next() ) {
return firstKey;
}
next = true; // 2nd genKeys.next() returned true
}
else {
/* if ( singleResult != null ) */ return runtime.getNil();
}
}
final RubyArray keys = runtime.newArray();
if ( firstKey != null ) keys.append(firstKey); // singleResult == null
while ( next ) {
keys.append( mapGeneratedKey(runtime, genKeys) );
next = genKeys.next();
}
return keys;
}
protected IRubyObject mapGeneratedKey(final Ruby runtime, final ResultSet genKeys) throws SQLException {
return runtime.newFixnum(genKeys.getLong(1));
}
private Boolean supportsGeneratedKeys;
protected boolean supportsGeneratedKeys(final Connection connection) throws SQLException {
if (supportsGeneratedKeys == null) {
synchronized(this) {
if (supportsGeneratedKeys == null) {
supportsGeneratedKeys = connection.getMetaData().supportsGetGeneratedKeys();
}
}
}
return supportsGeneratedKeys.booleanValue();
}
/**
* Converts a JDBC result set into an array (rows) of hashes (row).
*
* @param downCase should column names only be in lower case?
*/
@SuppressWarnings("unchecked")
private IRubyObject mapToRawResult(final ThreadContext context, final Ruby runtime,
final Connection connection, final ResultSet resultSet,
final boolean downCase) throws SQLException {
final ColumnData[] columns = extractColumns(runtime, connection, resultSet, downCase);
final RubyArray results = runtime.newArray();
// [ { 'col1': 1, 'col2': 2 }, { 'col1': 3, 'col2': 4 } ]
populateFromResultSet(context, runtime, (List<IRubyObject>) results, resultSet, columns);
return results;
}
private IRubyObject yieldResultRows(final ThreadContext context, final Ruby runtime,
final Connection connection, final ResultSet resultSet,
final Block block) throws SQLException {
final ColumnData[] columns = extractColumns(runtime, connection, resultSet, false);
final IRubyObject[] blockArgs = new IRubyObject[columns.length];
while ( resultSet.next() ) {
for ( int i = 0; i < columns.length; i++ ) {
final ColumnData column = columns[i];
blockArgs[i] = jdbcToRuby(context, runtime, column.index, column.type, resultSet);
}
block.call( context, blockArgs );
}
return runtime.getNil(); // yielded result rows
}
/**
* Extract columns from result set.
* @param runtime
* @param connection
* @param resultSet
* @param downCase
* @return columns data
* @throws SQLException
*/
protected ColumnData[] extractColumns(final Ruby runtime,
final Connection connection, final ResultSet resultSet,
final boolean downCase) throws SQLException {
return setupColumns(runtime, connection, resultSet.getMetaData(), downCase);
}
protected <T> T withConnection(final ThreadContext context, final Callable<T> block)
throws RaiseException {
try {
return withConnection(context, true, block);
}
catch (final SQLException e) {
return handleException(context, e); // should never happen
}
}
private <T> T withConnection(final ThreadContext context, final boolean handleException, final Callable<T> block)
throws RaiseException, RuntimeException, SQLException {
Throwable exception = null; int retry = 0; int i = 0;
do {
if ( retry > 0 ) reconnect(context); // we're retrying running block
final Connection connection = getConnection(context, true);
boolean autoCommit = true; // retry in-case getAutoCommit throws
try {
autoCommit = connection.getAutoCommit();
return block.call(connection);
}
catch (final Exception e) { // SQLException or RuntimeException
exception = e;
if ( autoCommit ) { // do not retry if (inside) transactions
if ( i == 0 ) {
IRubyObject retryCount = getConfigValue(context, "retry_count");
if ( ! retryCount.isNil() ) {
retry = (int) retryCount.convertToInteger().getLongValue();
}
}
if ( isConnectionValid(context, connection) ) {
break; // connection not broken yet failed (do not retry)
}
// we'll reconnect and retry calling block again
}
else break;
}
} while ( i++ < retry ); // i == 0, retry == 1 means we should retry once
// (retry) loop ended and we did not return ... exception != null
if ( handleException ) {
return handleException(context, getCause(exception)); // throws
}
else {
if ( exception instanceof SQLException ) {
throw (SQLException) exception;
}
if ( exception instanceof RuntimeException ) {
throw (RuntimeException) exception;
}
// won't happen - our try block only throws SQL or Runtime exceptions
throw new RuntimeException(exception);
}
}
private static Throwable getCause(Throwable exception) {
Throwable cause = exception.getCause();
while (cause != null && cause != exception) {
// SQLException's cause might be DB specific (checked/unchecked) :
if ( exception instanceof SQLException ) break;
exception = cause; cause = exception.getCause();
}
return exception;
}
protected <T> T handleException(final ThreadContext context, Throwable exception)
throws RaiseException {
// NOTE: we shall not wrap unchecked (runtime) exceptions into AR::Error
// if it's really a misbehavior of the driver throwing a RuntimeExcepion
// instead of SQLException than this should be overriden for the adapter
if ( exception instanceof RuntimeException ) {
throw (RuntimeException) exception;
}
debugStackTrace(context, exception);
throw wrapException(context, exception);
}
protected RaiseException wrapException(final ThreadContext context, final Throwable exception) {
final Ruby runtime = context.getRuntime();
if ( exception instanceof SQLException ) {
final String message = SQLException.class == exception.getClass() ?
exception.getMessage() : exception.toString(); // useful to easily see type on Ruby side
final RaiseException error = wrapException(context, getJDBCError(runtime), exception, message);
final int errorCode = ((SQLException) exception).getErrorCode();
final RubyException self = error.getException();
self.getMetaClass().finvoke(context, self, "errno=", runtime.newFixnum(errorCode));
self.getMetaClass().finvoke(context, self, "sql_exception=", JavaEmbedUtils.javaToRuby(runtime, exception));
return error;
}
return wrapException(context, getJDBCError(runtime), exception);
}
protected static RaiseException wrapException(final ThreadContext context,
final RubyClass errorClass, final Throwable exception) {
return wrapException(context, errorClass, exception, exception.toString());
}
protected static RaiseException wrapException(final ThreadContext context,
final RubyClass errorClass, final Throwable exception, final String message) {
final RaiseException error = new RaiseException(context.getRuntime(), errorClass, message, true);
error.initCause(exception);
return error;
}
private IRubyObject convertJavaToRuby(final Object object) {
return JavaUtil.convertJavaToRuby( getRuntime(), object );
}
/**
* Some databases support schemas and others do not.
* For ones which do this method should return true, aiding in decisions regarding schema vs database determination.
*/
protected boolean databaseSupportsSchemas() {
return false;
}
private static final byte[] SELECT = new byte[] { 's','e','l','e','c','t' };
private static final byte[] WITH = new byte[] { 'w','i','t','h' };
private static final byte[] SHOW = new byte[] { 's','h','o','w' };
private static final byte[] CALL = new byte[]{ 'c','a','l','l' };
@JRubyMethod(name = "select?", required = 1, meta = true, frame = false)
public static IRubyObject select_p(final ThreadContext context,
final IRubyObject self, final IRubyObject sql) {
return context.getRuntime().newBoolean( isSelect(sql.convertToString()) );
}
private static boolean isSelect(final RubyString sql) {
final ByteList sqlBytes = sql.getByteList();
return startsWithIgnoreCase(sqlBytes, SELECT) ||
startsWithIgnoreCase(sqlBytes, WITH) ||
startsWithIgnoreCase(sqlBytes, SHOW) ||
startsWithIgnoreCase(sqlBytes, CALL);
}
private static final byte[] INSERT = new byte[] { 'i','n','s','e','r','t' };
@JRubyMethod(name = "insert?", required = 1, meta = true, frame = false)
public static IRubyObject insert_p(final ThreadContext context,
final IRubyObject self, final IRubyObject sql) {
final ByteList sqlBytes = sql.convertToString().getByteList();
return context.getRuntime().newBoolean(startsWithIgnoreCase(sqlBytes, INSERT));
}
protected static boolean startsWithIgnoreCase(final ByteList string, final byte[] start) {
int p = skipWhitespace(string, string.getBegin());
final byte[] stringBytes = string.unsafeBytes();
if ( stringBytes[p] == '(' ) p = skipWhitespace(string, p + 1);
for ( int i = 0; i < string.getRealSize() && i < start.length; i++ ) {
if ( Character.toLowerCase(stringBytes[p + i]) != start[i] ) return false;
}
return true;
}
private static int skipWhitespace(final ByteList string, final int from) {
final int end = string.getBegin() + string.getRealSize();
final byte[] stringBytes = string.unsafeBytes();
for ( int i = from; i < end; i++ ) {
if ( ! Character.isWhitespace( stringBytes[i] ) ) return i;
}
return end;
}
// maps a AR::Result row
protected IRubyObject mapRow(final ThreadContext context, final Ruby runtime,
final ColumnData[] columns, final ResultSet resultSet,
final RubyJdbcConnection connection) throws SQLException {
final RubyArray row = runtime.newArray(columns.length);
for (int i = 0; i < columns.length; i++) {
final ColumnData column = columns[i];
row.append(connection.jdbcToRuby(context, runtime, column.index, column.type, resultSet));
}
return row;
}
IRubyObject mapRawRow(final ThreadContext context, final Ruby runtime,
final ColumnData[] columns, final ResultSet resultSet,
final RubyJdbcConnection connection) throws SQLException {
final RubyHash row = RubyHash.newHash(runtime);
for ( int i = 0; i < columns.length; i++ ) {
final ColumnData column = columns[i];
row.op_aset( context, column.name,
connection.jdbcToRuby(context, runtime, column.index, column.type, resultSet)
);
}
return row;
}
protected IRubyObject newResult(final ThreadContext context, ColumnData[] columns, IRubyObject rows) {
RubyClass result = ActiveRecord(context).getClass("Result");
return Helpers.invoke(context, result, "new", columnsToArray(context, columns), rows);
}
private RubyArray columnsToArray(ThreadContext context, ColumnData[] columns) {
final RubyArray cols = RubyArray.newArray(context.runtime, columns.length);
for ( int i = 0; i < columns.length; i++ ) {
cols.append( columns[i].name );
}
return cols;
}
protected static final class TableName {
public final String catalog, schema, name;
public TableName(String catalog, String schema, String table) {
this.catalog = catalog;
this.schema = schema;
this.name = table;
}
@Override
public String toString() {
return getClass().getName() +
"{catalog=" + catalog + ",schema=" + schema + ",name=" + name + "}";
}
}
protected TableName extractTableName(
final Connection connection, String catalog, String schema,
final String tableName) throws IllegalArgumentException, SQLException {
final String[] nameParts = tableName.split("\\.");
if ( nameParts.length > 3 ) {
throw new IllegalArgumentException("table name: " + tableName + " should not contain more than 2 '.'");
}
String name = tableName;
if ( nameParts.length == 2 ) {
schema = nameParts[0];
name = nameParts[1];
}
else if ( nameParts.length == 3 ) {
catalog = nameParts[0];
schema = nameParts[1];
name = nameParts[2];
}
if ( schema != null ) {
schema = caseConvertIdentifierForJdbc(connection, schema);
}
name = caseConvertIdentifierForJdbc(connection, name);
if ( schema != null && ! databaseSupportsSchemas() ) {
catalog = schema;
}
if ( catalog == null ) catalog = connection.getCatalog();
return new TableName(catalog, schema, name);
}
protected IRubyObject valueForDatabase(final ThreadContext context, final IRubyObject attribute) {
return attribute.callMethod(context, "value_for_database");
}
protected static final class ColumnData {
public final RubyString name;
public final int index;
public final int type;
public ColumnData(RubyString name, int type, int idx) {
this.name = name;
this.type = type;
this.index = idx;
}
@Override
public String toString() {
return "'" + name + "'i" + index + "t" + type + "";
}
}
private ColumnData[] setupColumns(
final Ruby runtime,
final Connection connection,
final ResultSetMetaData resultMetaData,
final boolean downCase) throws SQLException {
final int columnCount = resultMetaData.getColumnCount();
final ColumnData[] columns = new ColumnData[columnCount];
for ( int i = 1; i <= columnCount; i++ ) { // metadata is one-based
String name = resultMetaData.getColumnLabel(i);
if ( downCase ) {
name = name.toLowerCase();
} else {
name = caseConvertIdentifierForRails(connection, name);
}
final RubyString columnName = RubyString.newUnicodeString(runtime, name);
final int columnType = resultMetaData.getColumnType(i);
columns[i - 1] = new ColumnData(columnName, columnType, i);
}
return columns;
}
// JDBC API Helpers :
protected static void close(final Connection connection) {
if ( connection != null ) {
try { connection.close(); }
catch (final Exception e) { /* NOOP */ }
}
}
public static void close(final ResultSet resultSet) {
if (resultSet != null) {
try { resultSet.close(); }
catch (final Exception e) { /* NOOP */ }
}
}
public static void close(final Statement statement) {
if (statement != null) {
try { statement.close(); }
catch (final Exception e) { /* NOOP */ }
}
}
// DEBUG-ing helpers :
private static boolean debug = Boolean.getBoolean("arjdbc.debug");
public static boolean isDebug() { return debug; }
public static void setDebug(boolean debug) {
RubyJdbcConnection.debug = debug;
}
public static void debugMessage(final String msg) {
debugMessage(null, msg);
}
public static void debugMessage(final ThreadContext context, final String msg) {
if ( debug || ( context != null && context.runtime.isDebug() ) ) {
final PrintStream out = context != null ? context.runtime.getOut() : System.out;
out.println(msg);
}
}
public static void debugMessage(final ThreadContext context, final IRubyObject item) {
debugMessage(context, item.callMethod(context, "inspect").asString().toString());
}
protected static void debugErrorSQL(final ThreadContext context, final String sql) {
if ( debug || ( context != null && context.runtime.isDebug() ) ) {
final PrintStream out = context != null ? context.runtime.getOut() : System.out;
out.println("Error SQL: '" + sql + "'");
}
}
// disables full (Java) traces to be printed while DEBUG is on
private static final Boolean debugStackTrace;
static {
String debugTrace = System.getProperty("arjdbc.debug.trace");
debugStackTrace = debugTrace == null ? null : Boolean.parseBoolean(debugTrace);
}
public static void debugStackTrace(final ThreadContext context, final Throwable e) {
if ( debug || ( context != null && context.runtime.isDebug() ) ) {
final PrintStream out = context != null ? context.runtime.getOut() : System.out;
if ( debugStackTrace == null || debugStackTrace.booleanValue() ) {
e.printStackTrace(out);
}
else {
out.println(e);
}
}
}
protected void warn(final ThreadContext context, final String message) {
callMethod(context, "warn", context.getRuntime().newString(message));
}
private static RubyArray createCallerBacktrace(final ThreadContext context) {
final Ruby runtime = context.getRuntime();
runtime.incrementCallerCount();
Method gatherCallerBacktrace; RubyStackTraceElement[] trace;
try {
gatherCallerBacktrace = context.getClass().getMethod("gatherCallerBacktrace");
trace = (RubyStackTraceElement[]) gatherCallerBacktrace.invoke(context); // 1.6.8
}
catch (NoSuchMethodException ignore) {
try {
gatherCallerBacktrace = context.getClass().getMethod("gatherCallerBacktrace", Integer.TYPE);
trace = (RubyStackTraceElement[]) gatherCallerBacktrace.invoke(context, 0); // 1.7.4
}
catch (NoSuchMethodException e) { throw new RuntimeException(e); }
catch (IllegalAccessException e) { throw new RuntimeException(e); }
catch (InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); }
}
catch (IllegalAccessException e) { throw new RuntimeException(e); }
catch (InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); }
// RubyStackTraceElement[] trace = context.gatherCallerBacktrace(level);
final RubyArray backtrace = runtime.newArray(trace.length);
for (int i = 0; i < trace.length; i++) {
RubyStackTraceElement element = trace[i];
backtrace.append( RubyString.newString(runtime,
element.getFileName() + ":" + element.getLineNumber() + ":in `" + element.getMethodName() + "'"
) );
}
return backtrace;
}
}
|
package net.bettyluke.util;
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
public class XML10FilterReader extends FilterReader {
/**
* Creates filter reader which skips invalid xml characters.
*
* @param in
* original reader
*/
public XML10FilterReader(Reader in) {
super(in);
}
/**
* Every overload of {@link Reader#read()} method delegates to this one so it is
* enough to override only this one. <br />
* To skip invalid characters this method shifts only valid chars to left and returns
* decreased value of the original read method. So after last valid character there
* will be some unused chars in the buffer.
*
* @return Number of read valid characters or <code>-1</code> if end of the underling
* reader was reached.
*/
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int read = super.read(cbuf, off, len);
/*
* If read chars are -1 then we have reach the end of the reader.
*/
if (read == -1) {
return -1;
}
/*
* pos will show the index where chars should be moved if there are gaps from
* invalid characters.
*/
int pos = off - 1;
for (int readPos = off; readPos < off + read; readPos++) {
if (isValidXmlChar(cbuf[readPos])) {
pos++;
} else {
continue;
}
/*
* If there is gap(s) move current char to its position.
*/
if (pos < readPos) {
cbuf[pos] = cbuf[readPos];
}
}
/*
* Number of read valid characters.
*/
return pos - off + 1;
}
private boolean isValidXmlChar(int c) {
return c >= 0x0001 && c <= 0xD7FF ||
c >= 0xE000 && c <= 0xFFFD ||
c >= 0x10000 && c <= 0x10FFFF;
}
}
|
package com.akiban.server.test.mt.mtatomics;
import com.akiban.ais.model.Index;
import com.akiban.ais.model.TableName;
import com.akiban.ais.model.UserTable;
import com.akiban.server.api.dml.scan.CursorId;
import com.akiban.server.api.dml.scan.NewRow;
import com.akiban.server.api.dml.scan.ScanAllRequest;
import com.akiban.server.api.dml.scan.ScanFlag;
import com.akiban.server.api.dml.scan.ScanLimit;
import com.akiban.server.error.InvalidOperationException;
import com.akiban.server.error.OldAISException;
import com.akiban.server.service.ServiceManagerImpl;
import com.akiban.server.test.mt.mtutil.TimePoints;
import com.akiban.server.test.mt.mtutil.TimePointsComparison;
import com.akiban.server.test.mt.mtutil.TimedCallable;
import com.akiban.server.test.mt.mtutil.TimedExceptionCatcher;
import com.akiban.server.test.mt.mtutil.Timing;
import com.akiban.server.test.mt.mtutil.TimedResult;
import com.akiban.server.service.dxl.ConcurrencyAtomicsDXLService;
import com.akiban.server.service.session.Session;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public final class ConcurrentDDLAtomicsMT extends ConcurrentAtomicsBase {
@Test
public void dropTableWhileScanningPK() throws Exception {
final int tableId = tableWithTwoRows();
dropTableWhileScanning(
tableId,
"PRIMARY",
createNewRow(tableId, 1L, "the snowman"),
createNewRow(tableId, 2L, "mr melty")
);
}
@Test
public void dropTableWhileScanningOnIndex() throws Exception {
final int tableId = tableWithTwoRows();
dropTableWhileScanning(
tableId,
"name",
createNewRow(tableId, 2L, "mr melty"),
createNewRow(tableId, 1L, "the snowman")
);
}
private void dropTableWhileScanning(int tableId, String indexName, NewRow... expectedScanRows) throws Exception {
final int SCAN_WAIT = 5000;
int indexId = ddl().getUserTable(session(), new TableName(SCHEMA, TABLE)).getIndex(indexName).getIndexId();
TimedCallable<List<NewRow>> scanCallable
= new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.topOfLoopDelayer(0, SCAN_WAIT, "SCAN: PAUSE").get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
TableName table = new TableName(SCHEMA, TABLE);
Timing.sleep(2000);
timePoints.mark("TABLE: DROP>");
ddl().dropTable(session, table);
timePoints.mark("TABLE: <DROP");
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"(SCAN: PAUSE)>",
"TABLE: DROP>",
"<(SCAN: PAUSE)",
"SCAN: FINISH",
"TABLE: <DROP"
);
List<NewRow> rowsScanned = scanResult.getItem();
assertEquals("rows scanned size", expectedScanRows.length, rowsScanned.size());
assertEquals("rows", Arrays.asList(expectedScanRows), rowsScanned);
}
@Test
public void rowConvertedAfterTableDrop() throws Exception {
final String index = "PRIMARY";
final int tableId = tableWithTwoRows();
final int indexId = ddl().getUserTable(session(), new TableName(SCHEMA, TABLE)).getIndex(index).getIndexId();
DelayScanCallableBuilder callableBuilder = new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.markFinish(false)
.beforeConversionDelayer(new DelayerFactory() {
@Override
public Delayer delayer(TimePoints timePoints) {
return new Delayer(timePoints, 0, 5000)
.markBefore(1, "SCAN: PAUSE")
.markAfter(1, "SCAN: CONVERTED");
}
});
TimedCallable<List<NewRow>> scanCallable = callableBuilder.get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
TableName table = new TableName(SCHEMA, TABLE);
Timing.sleep(2000);
timePoints.mark("TABLE: DROP>");
ddl().dropTable(session, table);
timePoints.mark("TABLE: <DROP");
return null;
}
};
// Has to happen before the table is dropped!
List<NewRow> rowsExpected = Arrays.asList(
createNewRow(tableId, 1L, "the snowman"),
createNewRow(tableId, 2L, "mr melty")
);
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"SCAN: PAUSE",
"TABLE: DROP>",
"SCAN: CONVERTED",
"TABLE: <DROP"
);
List<NewRow> rowsScanned = scanResult.getItem();
assertEquals("rows scanned (in order)", rowsExpected, rowsScanned);
}
@Test
public void scanPKWhileDropping() throws Exception {
scanWhileDropping("PRIMARY");
}
@Test
public void scanIndexWhileDropping() throws Exception {
scanWhileDropping("name");
}
@Test
public void dropShiftsIndexIdWhileScanning() throws Exception {
final int tableId = createTable(SCHEMA, TABLE, "id int not null primary key", "name varchar(32)", "age varchar(2)",
"UNIQUE(name)", "UNIQUE(age)");
writeRows(
createNewRow(tableId, 2, "alpha", 3),
createNewRow(tableId, 1, "bravo", 2),
createNewRow(tableId, 3, "charlie", 1)
// the above are listed in order of index #1 (the name index)
// after that index is dropped, index #1 is age, and that will come in this order:
// (3, charlie 1)
// (1, bravo, 2)
// (2, alpha, 3)
// We'll get to the 2nd index (bravo) when we drop the index, and we want to make sure we don't
// continue scanning with alpha (which would thus badly order name)
);
final TableName tableName = new TableName(SCHEMA, TABLE);
Index nameIndex = ddl().getUserTable(session(), tableName).getIndex("name");
Index ageIndex = ddl().getUserTable(session(), tableName).getIndex("age");
final int nameIndexId = nameIndex.getIndexId();
assertTrue("age index's ID relative to name's", ageIndex.getIndexId() != nameIndexId);
TimedCallable<List<NewRow>> scanCallable
= new DelayScanCallableBuilder(aisGeneration(), tableId, nameIndexId)
.topOfLoopDelayer(2, 5000, "SCAN: PAUSE").get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
Timing.sleep(2500);
timePoints.mark("DROP: IN");
ddl().dropTableIndexes(session, tableName, Collections.singleton("name"));
timePoints.mark("DROP: OUT");
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"(SCAN: PAUSE)>",
"DROP: IN",
"<(SCAN: PAUSE)",
"SCAN: FINISH",
"DROP: OUT"
);
newRowsOrdered(scanResult.getItem(), 1);
}
/**
* Smoke test of concurrent DDL causing failures. One thread will drop a table; the other one will try to create
* another table while that drop is still going on.
* @throws Exception if something went wrong :)
*/
@Test
public void createTableWhileDroppingAnother() throws Exception {
largeEnoughTable(5000);
final String uniqueTableName = TABLE + "thesnowman";
TimedCallable<Void> dropTable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
timePoints.mark("DROP>");
ddl().dropTable(session, new TableName(SCHEMA, TABLE));
timePoints.mark("DROP<");
return null;
}
};
TimedCallable<Void> createTable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
Timing.sleep(2000);
timePoints.mark("ADD>");
try {
createTable(SCHEMA, uniqueTableName, "id int not null primary key");
timePoints.mark("ADD SUCCEEDED");
} catch (IllegalStateException e) {
timePoints.mark("ADD FAILED");
}
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<Void>> dropFuture = executor.submit(dropTable);
Future<TimedResult<Void>> createFuture = executor.submit(createTable);
TimedResult<Void> dropResult = dropFuture.get();
TimedResult<Void> createResult = createFuture.get();
new TimePointsComparison(dropResult, createResult).verify(
"DROP>",
"ADD>",
"ADD FAILED",
"DROP<"
);
Set<TableName> userTableNames = new HashSet<TableName>();
for (UserTable userTable : ddl().getAIS(session()).getUserTables().values()) {
if (!"akiban_information_schema".equals(userTable.getName().getSchemaName())) {
userTableNames.add(userTable.getName());
}
}
assertEquals(
"user tables at end",
Collections.singleton(new TableName(SCHEMA, TABLE+"parent")),
userTableNames
);
}
private void newRowsOrdered(List<NewRow> rows, final int fieldIndex) {
assertTrue("not enough rows: " + rows, rows.size() > 1);
List<NewRow> ordered = new ArrayList<NewRow>(rows);
Collections.sort(ordered, new Comparator<NewRow>() {
@Override @SuppressWarnings("unchecked")
public int compare(NewRow o1, NewRow o2) {
Object o1Field = o1.getFields().get(fieldIndex);
Object o2Field = o2.getFields().get(fieldIndex);
if (o1Field == null) {
return o2Field == null ? 0 : -1;
}
if (o2Field == null) {
return 1;
}
Comparable o1Comp = (Comparable)o1Field;
Comparable o2Comp = (Comparable)o2Field;
return o1Comp.compareTo(o2Comp);
}
});
}
private void scanWhileDropping(String indexName) throws InvalidOperationException, InterruptedException, ExecutionException {
final int tableId = largeEnoughTable(5000);
final TableName tableName = new TableName(SCHEMA, TABLE);
final int indexId = ddl().getUserTable(session(), tableName).getIndex(indexName).getIndexId();
DelayScanCallableBuilder callableBuilder = new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.topOfLoopDelayer(1, 100, "SCAN: FIRST")
.initialDelay(2500)
.markFinish(false)
.markOpenCursor(true);
DelayableScanCallable scanCallable = callableBuilder.get();
TimedCallable<Void> dropCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(final TimePoints timePoints, Session session) throws Exception {
ConcurrencyAtomicsDXLService.hookNextDropTable(
session,
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: IN");
}
},
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: OUT");
Timing.sleep(50);
}
}
);
ddl().dropTable(session, tableName); // will take ~5 seconds
assertFalse(
"drop table hook still installed",
ConcurrencyAtomicsDXLService.isDropTableHookInstalled(session)
);
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> updateFuture = executor.submit(dropCallable);
try {
scanFuture.get();
fail("expected an exception!");
} catch (ExecutionException e) {
if (!OldAISException.class.equals(e.getCause().getClass())) {
throw new RuntimeException("Expected a OldAISException!", e.getCause());
}
}
TimedResult<Void> updateResult = updateFuture.get();
new TimePointsComparison(updateResult, TimedResult.ofNull(scanCallable.getTimePoints())).verify(
"DROP: IN",
"(SCAN: OPEN CURSOR)>",
"DROP: OUT",
"SCAN: exception OldAISException"
);
assertTrue("rows weren't empty!", scanCallable.getRows().isEmpty());
}
/**
* Creates a table with enough rows that it takes a while to drop it
* @param msForDropping how long (at least) it should take to drop this table
* @return the table's id
* @throws InvalidOperationException if ever encountered
*/
private int largeEnoughTable(long msForDropping) throws InvalidOperationException {
int rowCount;
long dropTime;
float factor = 1.5f; // after we write N rows, we'll write an additional (factor-1)*N rows as buffer
int parentId = createTable(SCHEMA, TABLE+"parent", "id int not null primary key");
writeRows(
createNewRow(parentId, 1)
);
final String[] childTableDDL = {"id int not null primary key", "pid int", "name varchar(32)", "UNIQUE(name)",
"GROUPING FOREIGN KEY (pid) REFERENCES " +TABLE+"parent(id)"};
do {
int tableId = createTable(SCHEMA, TABLE, childTableDDL);
rowCount = 1;
final long writeStart = System.currentTimeMillis();
while (System.currentTimeMillis() - writeStart < msForDropping) {
writeRows(
createNewRow(tableId, rowCount, Integer.toString(rowCount))
);
++rowCount;
}
for(int i = rowCount; i < (int) factor * rowCount ; ++i) {
writeRows(
createNewRow(tableId, i, Integer.toString(i))
);
}
final long dropStart = System.currentTimeMillis();
ddl().dropTable(session(), new TableName(SCHEMA, TABLE));
dropTime = System.currentTimeMillis() - dropStart;
factor += 0.2;
} while(dropTime < msForDropping);
int tableId = createTable(SCHEMA, TABLE, childTableDDL);
for(int i = 1; i < rowCount ; ++i) {
writeRows(
createNewRow(tableId, i, Integer.toString(i))
);
}
return tableId;
}
@Test
public void dropIndexWhileScanning() throws Exception {
final int tableId = tableWithTwoRows();
final int SCAN_WAIT = 5000;
int indexId = ddl().getUserTable(session(), new TableName(SCHEMA, TABLE)).getIndex("name").getIndexId();
TimedCallable<List<NewRow>> scanCallable
= new DelayScanCallableBuilder(aisGeneration(), tableId, indexId)
.topOfLoopDelayer(0, SCAN_WAIT, "SCAN: PAUSE").get();
TimedCallable<Void> dropIndexCallable = new TimedCallable<Void>() {
@Override
protected Void doCall(TimePoints timePoints, Session session) throws Exception {
TableName table = new TableName(SCHEMA, TABLE);
Timing.sleep(2000);
timePoints.mark("INDEX: DROP>");
ddl().dropTableIndexes(ServiceManagerImpl.newSession(), table, Collections.singleton("name"));
timePoints.mark("INDEX: <DROP");
return null;
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<List<NewRow>>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Void>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<List<NewRow>> scanResult = scanFuture.get();
TimedResult<Void> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: START",
"(SCAN: PAUSE)>",
"INDEX: DROP>",
"<(SCAN: PAUSE)",
"SCAN: FINISH",
"INDEX: <DROP"
);
List<NewRow> rowsScanned = scanResult.getItem();
List<NewRow> rowsExpected = Arrays.asList(
createNewRow(tableId, 2L, "mr melty"),
createNewRow(tableId, 1L, "the snowman")
);
assertEquals("rows scanned (in order)", rowsExpected, rowsScanned);
}
@Test
public void scanWhileDroppingIndex() throws Throwable {
final long SCAN_PAUSE_LENGTH = 2500;
final long DROP_START_LENGTH = 1000;
final long DROP_PAUSE_LENGTH = 2500;
final int NUMBER_OF_ROWS = 100;
final int initialTableId = createTable(SCHEMA, TABLE, "id int not null primary key", "age int");
createIndex(SCHEMA, TABLE, "age", "age");
final TableName tableName = new TableName(SCHEMA, TABLE);
for(int i=0; i < NUMBER_OF_ROWS; ++i) {
writeRows(createNewRow(initialTableId, i, i + 1));
}
final Index index = ddl().getUserTable(session(), tableName).getIndex("age");
final Collection<String> indexNameCollection = Collections.singleton(index.getIndexName().getName());
final int tableId = ddl().getTableId(session(), tableName);
TimedCallable<Throwable> dropIndexCallable = new TimedExceptionCatcher() {
@Override
protected void doOrThrow(final TimePoints timePoints, Session session) throws Exception {
Timing.sleep(DROP_START_LENGTH);
timePoints.mark("DROP: PREPARING");
ConcurrencyAtomicsDXLService.hookNextDropIndex(session,
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: IN");
Timing.sleep(DROP_PAUSE_LENGTH);
}
},
new Runnable() {
@Override
public void run() {
timePoints.mark("DROP: OUT");
Timing.sleep(DROP_PAUSE_LENGTH);
}
}
);
ddl().dropTableIndexes(session, tableName, indexNameCollection);
assertFalse("drop hook not removed!", ConcurrencyAtomicsDXLService.isDropIndexHookInstalled(session));
}
};
final int localAISGeneration = aisGeneration();
TimedCallable<Throwable> scanCallable = new TimedExceptionCatcher() {
@Override
protected void doOrThrow(TimePoints timePoints, Session session) throws Exception {
timePoints.mark("SCAN: PREPARING");
ScanAllRequest request = new ScanAllRequest(
tableId,
new HashSet<Integer>(Arrays.asList(0, 1)),
index.getIndexId(),
EnumSet.of(ScanFlag.START_AT_BEGINNING, ScanFlag.END_AT_END),
ScanLimit.NONE
);
timePoints.mark("(SCAN: PAUSE)>");
Timing.sleep(SCAN_PAUSE_LENGTH);
timePoints.mark("<(SCAN: PAUSE)");
try {
CursorId cursorId = dml().openCursor(session, localAISGeneration, request);
timePoints.mark("SCAN: cursorID opened");
dml().closeCursor(session, cursorId);
} catch (OldAISException e) {
timePoints.mark("SCAN: OldAISException");
}
}
@Override
protected void handleCaught(TimePoints timePoints, Session session, Throwable t) {
timePoints.mark("SCAN: Unexpected exception " + t.getClass().getSimpleName());
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<TimedResult<Throwable>> scanFuture = executor.submit(scanCallable);
Future<TimedResult<Throwable>> dropIndexFuture = executor.submit(dropIndexCallable);
TimedResult<Throwable> scanResult = scanFuture.get();
TimedResult<Throwable> dropIndexResult = dropIndexFuture.get();
new TimePointsComparison(scanResult, dropIndexResult).verify(
"SCAN: PREPARING",
"(SCAN: PAUSE)>",
"DROP: PREPARING",
"DROP: IN",
"<(SCAN: PAUSE)",
"DROP: OUT",
"SCAN: OldAISException"
);
TimedExceptionCatcher.throwIfThrown(scanResult);
TimedExceptionCatcher.throwIfThrown(dropIndexResult);
}
}
|
package arjdbc.jdbc;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigInteger;
import java.sql.Array;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyInteger;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
import org.jruby.RubyTime;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.javasupport.JavaUtil;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
/**
* Part of our ActiveRecord::ConnectionAdapters::Connection impl.
*/
public class RubyJdbcConnection extends RubyObject {
private static final String[] TABLE_TYPE = new String[] { "TABLE" };
private static final String[] TABLE_TYPES = new String[] { "TABLE", "VIEW", "SYNONYM" };
protected RubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
}
private static ObjectAllocator JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyJdbcConnection(runtime, klass);
}
};
public static RubyClass createJdbcConnectionClass(final Ruby runtime) {
RubyClass jdbcConnection = getConnectionAdapters(runtime).
defineClassUnder("JdbcConnection", runtime.getObject(), JDBCCONNECTION_ALLOCATOR);
jdbcConnection.defineAnnotatedMethods(RubyJdbcConnection.class);
return jdbcConnection;
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters</code>
*/
protected static RubyModule getConnectionAdapters(final Ruby runtime) {
return (RubyModule) runtime.getModule("ActiveRecord").getConstant("ConnectionAdapters");
}
/**
* @param runtime
* @return <code>ActiveRecord::Result</code>
*/
static RubyClass getResult(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("Result");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters::IndexDefinition</code>
*/
protected static RubyClass getIndexDefinition(final Ruby runtime) {
return getConnectionAdapters(runtime).getClass("IndexDefinition");
}
/**
* @param runtime
* @return <code>ActiveRecord::JDBCError</code>
*/
protected static RubyClass getJDBCError(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("JDBCError");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionNotEstablished</code>
*/
protected static RubyClass getConnectionNotEstablished(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("ConnectionNotEstablished");
}
/**
* NOTE: Only available since AR-4.0
* @param runtime
* @return <code>ActiveRecord::TransactionIsolationError</code>
*/
protected static RubyClass getTransactionIsolationError(final Ruby runtime) {
return (RubyClass) runtime.getModule("ActiveRecord").getConstant("TransactionIsolationError");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters::JdbcTypeConverter</code>
*/
private static RubyClass getJdbcTypeConverter(final Ruby runtime) {
return getConnectionAdapters(runtime).getClass("JdbcTypeConverter");
}
/*
def transaction_isolation_levels
{
read_uncommitted: "READ UNCOMMITTED",
read_committed: "READ COMMITTED",
repeatable_read: "REPEATABLE READ",
serializable: "SERIALIZABLE"
}
end
*/
public static int mapTransactionIsolationLevel(IRubyObject isolation) {
if ( ! ( isolation instanceof RubySymbol ) ) {
isolation = isolation.convertToString().callMethod("intern");
}
final Object isolationString = isolation.toString(); // RubySymbol.toString
if ( isolationString == "read_uncommitted" ) return Connection.TRANSACTION_READ_UNCOMMITTED;
if ( isolationString == "read_committed" ) return Connection.TRANSACTION_READ_COMMITTED;
if ( isolationString == "repeatable_read" ) return Connection.TRANSACTION_REPEATABLE_READ;
if ( isolationString == "serializable" ) return Connection.TRANSACTION_SERIALIZABLE;
throw new IllegalArgumentException(
"unexpected isolation level: " + isolation + " (" + isolationString + ")"
);
}
@JRubyMethod(name = "supports_transaction_isolation?", optional = 1)
public IRubyObject supports_transaction_isolation_p(final ThreadContext context,
final IRubyObject[] args) throws SQLException {
final IRubyObject isolation = args.length > 0 ? args[0] : null;
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final DatabaseMetaData metaData = connection.getMetaData();
final boolean supported;
if ( isolation != null && ! isolation.isNil() ) {
final int level = mapTransactionIsolationLevel(isolation);
supported = metaData.supportsTransactionIsolationLevel(level);
}
else {
final int level = metaData.getDefaultTransactionIsolation();
supported = level > Connection.TRANSACTION_NONE;
}
return context.getRuntime().newBoolean(supported);
}
});
}
@JRubyMethod(name = "begin", optional = 1) // optional isolation argument for AR-4.0
public IRubyObject begin(final ThreadContext context, final IRubyObject[] args) {
final IRubyObject isolation = args.length > 0 ? args[0] : null;
try { // handleException == false so we can handle setTXIsolation
return withConnection(context, false, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
connection.setAutoCommit(false);
if ( isolation != null && ! isolation.isNil() ) {
final int level = mapTransactionIsolationLevel(isolation);
try {
connection.setTransactionIsolation(level);
}
catch (SQLException e) {
RubyClass txError = getTransactionIsolationError(context.getRuntime());
if ( txError != null ) throw wrapException(context, txError, e);
throw e; // let it roll - will be wrapped into a JDBCError (non 4.0)
}
}
return context.getRuntime().getNil();
}
});
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "commit")
public IRubyObject commit(final ThreadContext context) {
final Connection connection = getConnection(true);
try {
if ( ! connection.getAutoCommit() ) {
try {
connection.commit();
return context.getRuntime().newBoolean(true);
}
finally {
connection.setAutoCommit(true);
}
}
return context.getRuntime().getNil();
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "rollback")
public IRubyObject rollback(final ThreadContext context) {
final Connection connection = getConnection(true);
try {
if ( ! connection.getAutoCommit() ) {
try {
connection.rollback();
return context.getRuntime().newBoolean(true);
} finally {
connection.setAutoCommit(true);
}
}
return context.getRuntime().getNil();
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "connection")
public IRubyObject connection(final ThreadContext context) {
if ( getConnection(false) == null ) {
synchronized (this) {
if ( getConnection(false) == null ) {
reconnect(context);
}
}
}
return getInstanceVariable("@connection");
}
@JRubyMethod(name = "disconnect!")
public IRubyObject disconnect(final ThreadContext context) {
// TODO: only here to try resolving multi-thread issues :
if ( Boolean.getBoolean("arjdbc.disconnect.debug") ) {
final Ruby runtime = context.getRuntime();
List backtrace = (List) context.createCallerBacktrace(runtime, 0);
runtime.getOut().println(this + " connection.disconnect! occured: ");
for ( Object element : backtrace ) {
runtime.getOut().println(element);
}
runtime.getOut().flush();
}
return setConnection(null);
}
@JRubyMethod(name = "reconnect!")
public IRubyObject reconnect(final ThreadContext context) {
try {
return setConnection( getConnectionFactory().newConnection() );
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "database_name")
public IRubyObject database_name(ThreadContext context) throws SQLException {
Connection connection = getConnection(true);
String name = connection.getCatalog();
if (null == name) {
name = connection.getMetaData().getUserName();
if (null == name) name = "db1";
}
return context.getRuntime().newString(name);
}
@JRubyMethod(name = "execute", required = 1)
public IRubyObject execute(final ThreadContext context, final IRubyObject sql) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
Statement statement = null;
final String query = sql.convertToString().getUnicodeValue();
try {
statement = connection.createStatement();
if ( doExecute(statement, query) ) {
return unmarshalResults(context, connection.getMetaData(), statement, false);
} else {
return unmarshalKeysOrUpdateCount(context, connection, statement);
}
}
catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
}
finally { close(statement); }
}
});
}
/**
* Execute a query using the given statement.
* @param statement
* @param query
* @return true if the first result is a <code>ResultSet</code>;
* false if it is an update count or there are no results
* @throws SQLException
*/
protected boolean doExecute(final Statement statement, final String query) throws SQLException {
return genericExecute(statement, query);
}
/**
* @deprecated renamed to {@link #doExecute(Statement, String)}
*/
@Deprecated
protected boolean genericExecute(final Statement statement, final String query) throws SQLException {
return statement.execute(query);
}
protected IRubyObject unmarshalKeysOrUpdateCount(final ThreadContext context,
final Connection connection, final Statement statement) throws SQLException {
final Ruby runtime = context.getRuntime();
final IRubyObject key;
if ( connection.getMetaData().supportsGetGeneratedKeys() ) {
key = unmarshalIdResult(runtime, statement);
}
else {
key = runtime.getNil();
}
return key.isNil() ? runtime.newFixnum( statement.getUpdateCount() ) : key;
}
@JRubyMethod(name = "execute_id_insert", required = 2)
public IRubyObject execute_id_insert(final ThreadContext context,
final IRubyObject sql, final IRubyObject id) throws SQLException {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
PreparedStatement statement = null;
final String insertSQL = sql.convertToString().getUnicodeValue();
try {
statement = connection.prepareStatement(insertSQL);
statement.setLong(1, RubyNumeric.fix2long(id));
statement.executeUpdate();
}
catch (final SQLException e) {
debugErrorSQL(context, insertSQL);
throw e;
}
finally { close(statement); }
return id;
}
});
}
@JRubyMethod(name = "execute_insert", required = 1)
public IRubyObject execute_insert(final ThreadContext context, final IRubyObject sql)
throws SQLException {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
Statement statement = null;
final String insertSQL = sql.convertToString().getUnicodeValue();
try {
statement = connection.createStatement();
statement.executeUpdate(insertSQL, Statement.RETURN_GENERATED_KEYS);
return unmarshal_id_result(context.getRuntime(), statement.getGeneratedKeys());
}
catch (final SQLException e) {
debugErrorSQL(context, insertSQL);
throw e;
}
finally { close(statement); }
}
});
}
@JRubyMethod(name = "execute_query", required = 1)
public IRubyObject execute_query(final ThreadContext context, IRubyObject sql)
throws SQLException {
final String query = sql.convertToString().getUnicodeValue();
return executeQuery(context, query, 0);
}
@JRubyMethod(name = "execute_query", required = 2)
public IRubyObject execute_query(final ThreadContext context,
final IRubyObject sql, final IRubyObject maxRows) throws SQLException {
final String query = sql.convertToString().getUnicodeValue();
return executeQuery(context, query, RubyNumeric.fix2int(maxRows));
}
protected IRubyObject executeQuery(final ThreadContext context, final String query, final int maxRows) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final Ruby runtime = context.getRuntime();
Statement statement = null; ResultSet resultSet = null;
try {
final DatabaseMetaData metaData = connection.getMetaData();
statement = connection.createStatement();
statement.setMaxRows(maxRows); // zero means there is no limit
resultSet = statement.executeQuery(query);
return unmarshalResult(context, runtime, metaData, resultSet, false);
}
catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
}
finally { close(statement); }
}
});
}
@JRubyMethod(name = {"execute_update", "execute_delete"}, required = 1)
public IRubyObject execute_update(final ThreadContext context, final IRubyObject sql)
throws SQLException {
return withConnection(context, new Callable<RubyInteger>() {
public RubyInteger call(final Connection connection) throws SQLException {
Statement statement = null;
final String updateSQL = sql.convertToString().getUnicodeValue();
try {
statement = connection.createStatement();
return context.getRuntime().newFixnum(statement.executeUpdate(updateSQL));
}
catch (final SQLException e) {
debugErrorSQL(context, updateSQL);
throw e;
}
finally { close(statement); }
}
});
}
@JRubyMethod(name = "native_database_types", frame = false)
public IRubyObject native_database_types() {
return getInstanceVariable("@native_database_types");
}
@JRubyMethod(name = "primary_keys", required = 1)
public IRubyObject primary_keys(ThreadContext context, IRubyObject tableName) throws SQLException {
@SuppressWarnings("unchecked")
List<IRubyObject> primaryKeys = (List) primaryKeys(context, tableName.toString());
return context.getRuntime().newArray(primaryKeys);
}
private static final int PRIMARY_KEYS_COLUMN_NAME = 4;
protected List<RubyString> primaryKeys(final ThreadContext context, final String tableName) {
return withConnection(context, new Callable<List<RubyString>>() {
public List<RubyString> call(final Connection connection) throws SQLException {
final Ruby runtime = context.getRuntime();
final DatabaseMetaData metaData = connection.getMetaData();
final String _tableName = caseConvertIdentifierForJdbc(metaData, tableName);
ResultSet resultSet = null;
final List<RubyString> keyNames = new ArrayList<RubyString>();
try {
TableName components = extractTableName(connection, null, _tableName);
resultSet = metaData.getPrimaryKeys(components.catalog, components.schema, components.name);
while (resultSet.next()) {
String columnName = resultSet.getString(PRIMARY_KEYS_COLUMN_NAME);
columnName = caseConvertIdentifierForRails(metaData, columnName);
keyNames.add( RubyString.newUnicodeString(runtime, columnName) );
}
}
finally { close(resultSet); }
return keyNames;
}
});
}
@JRubyMethod(name = "set_native_database_types")
public IRubyObject set_native_database_types(final ThreadContext context) throws SQLException {
final Ruby runtime = context.getRuntime();
final DatabaseMetaData metaData = getConnection(true).getMetaData();
final IRubyObject types; final ResultSet typeDesc = metaData.getTypeInfo();
try {
types = unmarshalResult(context, runtime, metaData, typeDesc, true);
}
finally { close(typeDesc); }
final IRubyObject typeConverter = getJdbcTypeConverter(runtime).callMethod("new", types);
setInstanceVariable("@native_types", typeConverter.callMethod(context, "choose_best_types"));
return runtime.getNil();
}
@JRubyMethod(name = "tables")
public IRubyObject tables(ThreadContext context) {
return tables(context, null, null, null, TABLE_TYPE);
}
@JRubyMethod(name = "tables")
public IRubyObject tables(ThreadContext context, IRubyObject catalog) {
return tables(context, toStringOrNull(catalog), null, null, TABLE_TYPE);
}
@JRubyMethod(name = "tables")
public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern) {
return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), null, TABLE_TYPE);
}
@JRubyMethod(name = "tables")
public IRubyObject tables(ThreadContext context, IRubyObject catalog, IRubyObject schemaPattern, IRubyObject tablePattern) {
return tables(context, toStringOrNull(catalog), toStringOrNull(schemaPattern), toStringOrNull(tablePattern), TABLE_TYPE);
}
@JRubyMethod(name = "tables", required = 4, rest = true)
public IRubyObject tables(ThreadContext context, IRubyObject[] args) {
return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), toStringOrNull(args[2]), getTypes(args[3]));
}
protected IRubyObject tables(final ThreadContext context,
final String catalog, final String schemaPattern, final String tablePattern, final String[] types) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
return matchTables(context.getRuntime(), connection, catalog, schemaPattern, tablePattern, types, false);
}
});
}
protected String[] getTableTypes() {
return TABLE_TYPES;
}
@JRubyMethod(name = "table_exists?", required = 1, optional = 1)
public IRubyObject table_exists_p(final ThreadContext context, final IRubyObject[] args) {
IRubyObject name = args[0], schema_name = args.length > 1 ? args[1] : null;
if ( ! ( name instanceof RubyString ) ) {
name = name.callMethod(context, "to_s");
}
final String tableName = ((RubyString) name).getUnicodeValue();
final String tableSchema = schema_name == null ? null : schema_name.convertToString().getUnicodeValue();
final Ruby runtime = context.getRuntime();
return withConnection(context, new Callable<RubyBoolean>() {
public RubyBoolean call(final Connection connection) throws SQLException {
final TableName components = extractTableName(connection, tableSchema, tableName);
return runtime.newBoolean( tableExists(runtime, connection, components) );
}
});
}
@JRubyMethod(name = {"columns", "columns_internal"}, required = 1, optional = 2)
public IRubyObject columns_internal(final ThreadContext context, final IRubyObject[] args)
throws SQLException {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
ResultSet columns = null, primaryKeys = null;
try {
final String tableName = args[0].convertToString().getUnicodeValue();
// optionals (NOTE: catalog argumnet was never used before 1.3.0) :
final String catalog = args.length > 1 ? toStringOrNull(args[1]) : null;
final String defaultSchema = args.length > 2 ? toStringOrNull(args[2]) : null;
final TableName components;
if ( catalog == null ) { // backwards-compatibility with < 1.3.0
components = extractTableName(connection, defaultSchema, tableName);
}
else {
components = extractTableName(connection, catalog, defaultSchema, tableName);
}
if ( ! tableExists(context.getRuntime(), connection, components) ) {
throw new SQLException("table: " + tableName + " does not exist");
}
final DatabaseMetaData metaData = connection.getMetaData();
columns = metaData.getColumns(components.catalog, components.schema, components.name, null);
primaryKeys = metaData.getPrimaryKeys(components.catalog, components.schema, components.name);
return unmarshalColumns(context, metaData, columns, primaryKeys);
}
finally {
close(columns);
close(primaryKeys);
}
}
});
}
@JRubyMethod(name = "indexes")
public IRubyObject indexes(ThreadContext context, IRubyObject tableName, IRubyObject name, IRubyObject schemaName) {
return indexes(context, toStringOrNull(tableName), toStringOrNull(name), toStringOrNull(schemaName));
}
// NOTE: metaData.getIndexInfo row mappings :
private static final int INDEX_INFO_TABLE_NAME = 3;
private static final int INDEX_INFO_NON_UNIQUE = 4;
private static final int INDEX_INFO_NAME = 6;
private static final int INDEX_INFO_COLUMN_NAME = 9;
/**
* Default JDBC introspection for index metadata on the JdbcConnection.
*
* JDBC index metadata is denormalized (multiple rows may be returned for
* one index, one row per column in the index), so a simple block-based
* filter like that used for tables doesn't really work here. Callers
* should filter the return from this method instead.
*/
protected IRubyObject indexes(final ThreadContext context, final String tableName, final String name, final String schemaName) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final Ruby runtime = context.getRuntime();
final RubyClass indexDefinition = getIndexDefinition(runtime);
final DatabaseMetaData metaData = connection.getMetaData();
String _tableName = caseConvertIdentifierForJdbc(metaData, tableName);
String _schemaName = caseConvertIdentifierForJdbc(metaData, schemaName);
final List<RubyString> primaryKeys = primaryKeys(context, _tableName);
ResultSet indexInfoSet = null;
final List<IRubyObject> indexes = new ArrayList<IRubyObject>();
try {
indexInfoSet = metaData.getIndexInfo(null, _schemaName, _tableName, false, true);
String currentIndex = null;
while ( indexInfoSet.next() ) {
String indexName = indexInfoSet.getString(INDEX_INFO_NAME);
if ( indexName == null ) continue;
indexName = caseConvertIdentifierForRails(metaData, indexName);
final String columnName = indexInfoSet.getString(INDEX_INFO_COLUMN_NAME);
final RubyString rubyColumnName = RubyString.newUnicodeString(
runtime, caseConvertIdentifierForRails(metaData, columnName)
);
if ( primaryKeys.contains(rubyColumnName) ) continue;
// We are working on a new index
if ( ! indexName.equals(currentIndex) ) {
currentIndex = indexName;
String indexTableName = indexInfoSet.getString(INDEX_INFO_TABLE_NAME);
indexTableName = caseConvertIdentifierForRails(metaData, indexTableName);
final boolean nonUnique = indexInfoSet.getBoolean(INDEX_INFO_NON_UNIQUE);
IRubyObject[] args = new IRubyObject[] {
RubyString.newUnicodeString(runtime, indexTableName), // table_name
RubyString.newUnicodeString(runtime, indexName), // index_name
runtime.newBoolean( ! nonUnique ), // unique
runtime.newArray() // [] for column names, we'll add to that in just a bit
// orders, (since AR 3.2) where, type, using (AR 4.0)
};
indexes.add( indexDefinition.callMethod(context, "new", args) ); // IndexDefinition.new
}
// One or more columns can be associated with an index
IRubyObject lastIndexDef = indexes.isEmpty() ? null : indexes.get(indexes.size() - 1);
if (lastIndexDef != null) {
lastIndexDef.callMethod(context, "columns").callMethod(context, "<<", rubyColumnName);
}
}
return runtime.newArray(indexes);
} finally { close(indexInfoSet); }
}
});
}
// NOTE: this seems to be not used ... at all ?!
/*
* sql, values, types, name = nil, pk = nil, id_value = nil, sequence_name = nil
*/
@Deprecated
@JRubyMethod(name = "insert_bind", required = 3, rest = true)
public IRubyObject insert_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException {
final Ruby runtime = context.getRuntime();
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final String sql = args[0].convertToString().toString();
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
setValues(context, args[1], args[2], statement);
statement.executeUpdate();
return unmarshalIdResult(runtime, statement);
}
finally { close(statement); }
}
});
}
// NOTE: this seems to be not used ... at all ?!
/*
* sql, values, types, name = nil
*/
@Deprecated
@JRubyMethod(name = "update_bind", required = 3, rest = true)
public IRubyObject update_bind(final ThreadContext context, final IRubyObject[] args) throws SQLException {
final Ruby runtime = context.getRuntime();
Arity.checkArgumentCount(runtime, args, 3, 4);
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final String sql = args[0].convertToString().toString();
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
setValues(context, args[1], args[2], statement);
statement.executeUpdate();
}
finally { close(statement); }
return runtime.getNil();
}
});
}
@JRubyMethod(name = "with_connection_retry_guard", frame = true)
public IRubyObject with_connection_retry_guard(final ThreadContext context, final Block block) {
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
return block.call(context, new IRubyObject[] { convertJavaToRuby(connection) });
}
});
}
/*
* (is binary?, colname, tablename, primary_key, id, lob_value)
*/
@JRubyMethod(name = "write_large_object", required = 6)
public IRubyObject write_large_object(final ThreadContext context, final IRubyObject[] args)
throws SQLException {
final boolean isBinary = args[0].isTrue();
final RubyString columnName = args[1].convertToString();
final RubyString tableName = args[2].convertToString();
final RubyString idKey = args[3].convertToString();
final RubyString idVal = args[4].convertToString();
final IRubyObject lobValue = args[5];
final Ruby runtime = context.getRuntime();
return withConnection(context, new Callable<IRubyObject>() {
public IRubyObject call(final Connection connection) throws SQLException {
final String sql = "UPDATE "+ tableName +
" SET "+ columnName +" = ? WHERE "+ idKey +" = "+ idVal;
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
if ( isBinary ) { // binary
final ByteList blob = lobValue.convertToString().getByteList();
final int realSize = blob.getRealSize();
statement.setBinaryStream(1,
new ByteArrayInputStream(blob.unsafeBytes(), blob.getBegin(), realSize), realSize
);
} else { // clob
String clob = lobValue.convertToString().getUnicodeValue();
statement.setCharacterStream(1, new StringReader(clob), clob.length());
}
statement.executeUpdate();
}
finally { close(statement); }
return runtime.getNil();
}
});
}
/**
* Convert an identifier coming back from the database to a case which Rails is expecting.
*
* Assumption: Rails identifiers will be quoted for mixed or will stay mixed
* as identifier names in Rails itself. Otherwise, they expect identifiers to
* be lower-case. Databases which store identifiers uppercase should be made
* lower-case.
*
* Assumption 2: It is always safe to convert all upper case names since it appears that
* some adapters do not report StoresUpper/Lower/Mixed correctly (am I right postgres/mysql?).
*/
protected static String caseConvertIdentifierForRails(final DatabaseMetaData metaData, final String value)
throws SQLException {
if ( value == null ) return null;
return metaData.storesUpperCaseIdentifiers() ? value.toLowerCase() : value;
}
/**
* Convert an identifier destined for a method which cares about the databases internal
* storage case. Methods like DatabaseMetaData.getPrimaryKeys() needs the table name to match
* the internal storage name. Arbtrary queries and the like DO NOT need to do this.
*/
protected String caseConvertIdentifierForJdbc(final DatabaseMetaData metaData, final String value)
throws SQLException {
if ( value == null ) return null;
if ( metaData.storesUpperCaseIdentifiers() ) {
return value.toUpperCase();
}
else if ( metaData.storesLowerCaseIdentifiers() ) {
return value.toLowerCase();
}
return value;
}
protected IRubyObject getConfigValue(final ThreadContext context, final String key) {
final IRubyObject config = getInstanceVariable("@config");
return config.callMethod(context, "[]", context.getRuntime().newSymbol(key));
}
/**
* @deprecated renamed to {@link #getConfigValue(ThreadContext, String)}
*/
@Deprecated
protected IRubyObject config_value(ThreadContext context, String key) {
return getConfigValue(context, key);
}
private static String toStringOrNull(IRubyObject arg) {
return arg.isNil() ? null : arg.toString();
}
protected IRubyObject getAdapter(ThreadContext context) {
return callMethod(context, "adapter");
}
protected IRubyObject getJdbcColumnClass(ThreadContext context) {
return getAdapter(context).callMethod(context, "jdbc_column_class");
}
protected JdbcConnectionFactory getConnectionFactory() throws RaiseException {
IRubyObject connection_factory = getInstanceVariable("@connection_factory");
if (connection_factory == null) {
throw getRuntime().newRuntimeError("@connection_factory not set");
}
JdbcConnectionFactory connectionFactory;
try {
connectionFactory = (JdbcConnectionFactory)
connection_factory.toJava(JdbcConnectionFactory.class);
}
catch (Exception e) { // TODO debug this !
connectionFactory = null;
}
if (connectionFactory == null) {
throw getRuntime().newRuntimeError("@connection_factory not set properly");
}
return connectionFactory;
}
private static String[] getTypes(final IRubyObject typeArg) {
if ( typeArg instanceof RubyArray ) {
IRubyObject[] rubyTypes = ((RubyArray) typeArg).toJavaArray();
final String[] types = new String[rubyTypes.length];
for ( int i = 0; i < types.length; i++ ) {
types[i] = rubyTypes[i].toString();
}
return types;
}
return new String[] { typeArg.toString() }; // expect a RubyString
}
private static int jdbcTypeFor(final ThreadContext context, IRubyObject type)
throws SQLException {
if ( ! ( type instanceof RubySymbol ) ) {
if ( type instanceof RubyString ) { // to_sym
if ( context.getRuntime().is1_9() ) {
type = ( (RubyString) type ).intern19();
}
else {
type = ( (RubyString) type ).intern();
}
}
else {
throw new IllegalArgumentException(
"expected a Ruby string/symbol but got: " + type + " (" + type.getMetaClass().getName() + ")"
);
}
}
final String internedValue = type.asJavaString();
if ( internedValue == (Object) "string" ) return Types.VARCHAR;
else if ( internedValue == (Object) "text" ) return Types.CLOB;
else if ( internedValue == (Object) "integer" ) return Types.INTEGER;
else if ( internedValue == (Object) "decimal" ) return Types.DECIMAL;
else if ( internedValue == (Object) "float" ) return Types.FLOAT;
else if ( internedValue == (Object) "datetime") return Types.TIMESTAMP;
else if ( internedValue == (Object) "timestamp" ) return Types.TIMESTAMP;
else if ( internedValue == (Object) "time" ) return Types.TIME;
else if ( internedValue == (Object) "date" ) return Types.DATE;
else if ( internedValue == (Object) "binary" ) return Types.BLOB;
else if ( internedValue == (Object) "boolean" ) return Types.BOOLEAN;
else if ( internedValue == (Object) "xml" ) return Types.SQLXML;
else if ( internedValue == (Object) "array" ) return Types.ARRAY;
else return -1;
}
protected void populateFromResultSet(
final ThreadContext context, final Ruby runtime,
final List<IRubyObject> results, final ResultSet resultSet,
final ColumnData[] columns) throws SQLException {
final int columnCount = columns.length;
while ( resultSet.next() ) {
RubyHash row = RubyHash.newHash(runtime);
for ( int i = 0; i < columnCount; i++ ) {
final ColumnData column = columns[i];
row.op_aset(context, column.name, jdbcToRuby(runtime, column.index, column.type, resultSet));
}
results.add(row);
}
}
protected IRubyObject jdbcToRuby(final Ruby runtime, final int column,
final int type, final ResultSet resultSet) throws SQLException {
try {
switch (type) {
case Types.BLOB:
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return streamToRuby(runtime, resultSet, column);
case Types.CLOB:
case Types.NCLOB: // JDBC 4.0
return readerToRuby(runtime, resultSet, column);
case Types.LONGVARCHAR:
case Types.LONGNVARCHAR: // JDBC 4.0
if ( runtime.is1_9() ) {
return readerToRuby(runtime, resultSet, column);
}
else {
return streamToRuby(runtime, resultSet, column);
}
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return integerToRuby(runtime, resultSet, column);
case Types.REAL:
case Types.FLOAT:
case Types.DOUBLE:
return doubleToRuby(runtime, resultSet, column);
case Types.BIGINT:
return bigIntegerToRuby(runtime, resultSet, column);
case Types.NUMERIC:
case Types.DECIMAL:
return decimalToRuby(runtime, resultSet, column);
case Types.DATE:
return dateToRuby(runtime, resultSet, column);
case Types.TIME:
return timeToRuby(runtime, resultSet, column);
case Types.TIMESTAMP:
return timestampToRuby(runtime, resultSet, column);
case Types.BIT:
case Types.BOOLEAN:
return booleanToRuby(runtime, resultSet, column);
case Types.SQLXML: // JDBC 4.0
return xmlToRuby(runtime, resultSet, column);
case Types.NULL:
return runtime.getNil();
// NOTE: (JDBC) exotic stuff just cause it's so easy with JRuby :)
case Types.JAVA_OBJECT:
case Types.OTHER:
return objectToRuby(runtime, resultSet, column);
case Types.ARRAY: // we handle JDBC Array into (Ruby) []
return arrayToRuby(runtime, resultSet, column);
// (default) String
case Types.CHAR:
case Types.VARCHAR:
case Types.NCHAR: // JDBC 4.0
case Types.NVARCHAR: // JDBC 4.0
default:
return stringToRuby(runtime, resultSet, column);
}
// NOTE: not mapped types :
//case Types.DISTINCT:
//case Types.STRUCT:
//case Types.REF:
//case Types.DATALINK:
}
catch (IOException e) {
throw new SQLException(e.getMessage(), e);
}
}
protected IRubyObject integerToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final long value = resultSet.getLong(column);
if ( value == 0 && resultSet.wasNull() ) return runtime.getNil();
return integerToRuby(runtime, resultSet, value);
}
@Deprecated
protected IRubyObject integerToRuby(
final Ruby runtime, final ResultSet resultSet, final long longValue)
throws SQLException {
if ( longValue == 0 && resultSet.wasNull() ) return runtime.getNil();
return runtime.newFixnum(longValue);
}
protected IRubyObject doubleToRuby(Ruby runtime, ResultSet resultSet, final int column)
throws SQLException {
final double value = resultSet.getDouble(column);
if ( value == 0 && resultSet.wasNull() ) return runtime.getNil();
return doubleToRuby(runtime, resultSet, value);
}
@Deprecated
protected IRubyObject doubleToRuby(Ruby runtime, ResultSet resultSet, double doubleValue)
throws SQLException {
if ( doubleValue == 0 && resultSet.wasNull() ) return runtime.getNil();
return runtime.newFloat(doubleValue);
}
protected IRubyObject stringToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final String value = resultSet.getString(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return stringToRuby(runtime, resultSet, value);
}
@Deprecated
protected IRubyObject stringToRuby(
final Ruby runtime, final ResultSet resultSet, final String string)
throws SQLException {
if ( string == null && resultSet.wasNull() ) return runtime.getNil();
return RubyString.newUnicodeString(runtime, string);
}
protected IRubyObject bigIntegerToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final String value = resultSet.getString(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return bigIntegerToRuby(runtime, resultSet, value);
}
@Deprecated
protected IRubyObject bigIntegerToRuby(
final Ruby runtime, final ResultSet resultSet, final String intValue)
throws SQLException {
if ( intValue == null && resultSet.wasNull() ) return runtime.getNil();
return RubyBignum.bignorm(runtime, new BigInteger(intValue));
}
protected IRubyObject decimalToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final String value = resultSet.getString(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
// NOTE: JRuby 1.6 -> 1.7 API change : moved org.jruby.RubyBigDecimal
return runtime.getKernel().callMethod("BigDecimal", runtime.newString(value));
}
private static boolean parseDateTime = false; // TODO
protected IRubyObject dateToRuby( // TODO
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Date value = resultSet.getDate(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return RubyString.newUnicodeString(runtime, value.toString());
}
protected IRubyObject timeToRuby( // TODO
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Time value = resultSet.getTime(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return RubyString.newUnicodeString(runtime, value.toString());
}
protected IRubyObject timestampToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Timestamp value = resultSet.getTimestamp(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return timestampToRuby(runtime, resultSet, value);
}
@Deprecated
protected IRubyObject timestampToRuby(
final Ruby runtime, final ResultSet resultSet, final Timestamp value)
throws SQLException {
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
String format = value.toString(); // yyyy-mm-dd hh:mm:ss.fffffffff
if ( format.endsWith(" 00:00:00.0") ) {
format = format.substring(0, format.length() - (" 00:00:00.0".length()));
}
if ( format.endsWith(".0") ) {
format = format.substring(0, format.length() - (".0".length()));
}
return RubyString.newUnicodeString(runtime, format);
}
protected IRubyObject booleanToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final boolean value = resultSet.getBoolean(column);
if ( resultSet.wasNull() ) return runtime.getNil();
return booleanToRuby(runtime, resultSet, value);
}
@Deprecated
protected IRubyObject booleanToRuby(
final Ruby runtime, final ResultSet resultSet, final boolean value)
throws SQLException {
if ( value == false && resultSet.wasNull() ) return runtime.getNil();
return runtime.newBoolean(value);
}
protected static int streamBufferSize = 2048;
protected IRubyObject streamToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException, IOException {
final InputStream stream = resultSet.getBinaryStream(column);
try {
if ( resultSet.wasNull() ) return runtime.getNil();
return streamToRuby(runtime, resultSet, stream);
}
finally { if ( stream != null ) stream.close(); }
}
@Deprecated
protected IRubyObject streamToRuby(
final Ruby runtime, final ResultSet resultSet, final InputStream stream)
throws SQLException, IOException {
if ( stream == null && resultSet.wasNull() ) return runtime.getNil();
final int bufSize = streamBufferSize;
final ByteList string = new ByteList(bufSize);
final byte[] buf = new byte[bufSize];
for (int len = stream.read(buf); len != -1; len = stream.read(buf)) {
string.append(buf, 0, len);
}
return runtime.newString(string);
}
protected IRubyObject readerToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException, IOException {
final Reader reader = resultSet.getCharacterStream(column);
try {
if ( resultSet.wasNull() ) return runtime.getNil();
return readerToRuby(runtime, resultSet, reader);
}
finally { if ( reader != null ) reader.close(); }
}
@Deprecated
protected IRubyObject readerToRuby(
final Ruby runtime, final ResultSet resultSet, final Reader reader)
throws SQLException, IOException {
if ( reader == null && resultSet.wasNull() ) return runtime.getNil();
final int bufSize = streamBufferSize;
final StringBuilder string = new StringBuilder(bufSize);
final char[] buf = new char[bufSize];
for (int len = reader.read(buf); len != -1; len = reader.read(buf)) {
string.append(buf, 0, len);
}
return RubyString.newUnicodeString(runtime, string.toString());
}
protected IRubyObject objectToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Object value = resultSet.getObject(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
return JavaUtil.convertJavaToRuby(runtime, value);
}
protected IRubyObject arrayToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Array value = resultSet.getArray(column);
try {
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
final RubyArray array = runtime.newArray();
final ResultSet arrayResult = value.getResultSet(); // 1: index, 2: value
final int baseType = value.getBaseType();
while ( arrayResult.next() ) {
IRubyObject element = jdbcToRuby(runtime, 2, baseType, arrayResult);
array.append(element);
}
return array;
}
finally { value.free(); }
}
protected IRubyObject xmlToRuby(
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final SQLXML xml = resultSet.getSQLXML(column);
try {
return RubyString.newUnicodeString(runtime, xml.getString());
}
finally { xml.free(); }
}
protected final Connection getConnection() {
return getConnection(false);
}
protected Connection getConnection(boolean error) {
final Connection connection = (Connection) dataGetStruct();
if ( connection == null && error ) {
final RubyClass errorClass = getConnectionNotEstablished( getRuntime() );
throw new RaiseException(getRuntime(), errorClass, "no connection available", false);
}
return connection;
}
private synchronized RubyJdbcConnection setConnection(final Connection connection) {
close( getConnection(false) ); // close previously open connection if there is one
final IRubyObject rubyConnectionObject =
connection != null ? convertJavaToRuby(connection) : getRuntime().getNil();
setInstanceVariable( "@connection", rubyConnectionObject );
dataWrapStruct(connection);
return this;
}
private boolean isConnectionBroken(final ThreadContext context, final Connection connection) {
Statement statement = null;
try {
final RubyString aliveSQL = getConfigValue(context, "connection_alive_sql").convertToString();
if ( isSelect(aliveSQL) ) { // expect a SELECT/CALL SQL statement
statement = connection.createStatement();
statement.execute( aliveSQL.toString() );
return false; // connection ain't broken
}
else { // alive_sql nil (or not a statement we can execute)
return ! connection.isClosed(); // if closed than broken
}
}
catch (Exception e) { // TODO log this
return true;
}
finally { close(statement); }
}
private final static DateFormat FORMAT = new SimpleDateFormat("%y-%M-%d %H:%m:%s");
private static void setValue(final ThreadContext context,
final IRubyObject value, final IRubyObject type,
final PreparedStatement statement, final int index) throws SQLException {
final int jdbcType = jdbcTypeFor(context, type);
if ( value.isNil() ) {
statement.setNull(index, jdbcType);
return;
}
switch (jdbcType) {
case Types.VARCHAR:
case Types.CLOB:
statement.setString(index, RubyString.objAsString(context, value).toString());
break;
case Types.INTEGER:
statement.setLong(index, RubyNumeric.fix2long(value));
break;
case Types.FLOAT:
statement.setDouble(index, ((RubyNumeric) value).getDoubleValue());
break;
case Types.TIMESTAMP:
case Types.TIME:
case Types.DATE:
if ( ! ( value instanceof RubyTime ) ) {
final String stringValue = RubyString.objAsString(context, value).toString();
try {
Timestamp timestamp = new Timestamp( FORMAT.parse( stringValue ).getTime() );
statement.setTimestamp( index, timestamp, Calendar.getInstance() );
}
catch (Exception e) {
statement.setString( index, stringValue );
}
} else {
final RubyTime timeValue = (RubyTime) value;
final java.util.Date dateValue = timeValue.getJavaDate();
long millis = dateValue.getTime();
Timestamp timestamp = new Timestamp(millis);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateValue);
if ( jdbcType != Types.DATE ) {
int micros = (int) timeValue.microseconds();
timestamp.setNanos( micros * 1000 ); // time.nsec ~ time.usec * 1000
}
statement.setTimestamp( index, timestamp, calendar );
}
break;
case Types.BOOLEAN:
statement.setBoolean(index, value.isTrue());
break;
default: throw new RuntimeException("type " + jdbcType + " not supported in _bind (yet)");
}
}
private static void setValues(final ThreadContext context,
final IRubyObject valuesArg, final IRubyObject typesArg,
final PreparedStatement statement) throws SQLException {
final RubyArray values = (RubyArray) valuesArg;
final RubyArray types = (RubyArray) typesArg;
for( int i = 0, j = values.getLength(); i < j; i++ ) {
setValue(context, values.eltInternal(i), types.eltInternal(i), statement, i + 1);
}
}
private boolean tableExists(final Ruby runtime,
final Connection connection, final TableName tableName) throws SQLException {
final IRubyObject matchedTables =
matchTables(runtime, connection, tableName.catalog, tableName.schema, tableName.name, getTableTypes(), true);
// NOTE: allow implementers to ignore checkExistsOnly paramater - empty array means does not exists
return matchedTables != null && ! matchedTables.isNil() &&
( ! (matchedTables instanceof RubyArray) || ! ((RubyArray) matchedTables).isEmpty() );
}
/**
* Match table names for given table name (pattern).
* @param runtime
* @param connection
* @param catalog
* @param schemaPattern
* @param tablePattern
* @param types table types
* @param checkExistsOnly an optimization flag (that might be ignored by sub-classes)
* whether the result really matters if true no need to map table names and a truth-y
* value is sufficient (except for an empty array which is considered that the table
* did not exists).
* @return matched (and Ruby mapped) table names
* @see #mapTables(Ruby, DatabaseMetaData, String, String, String, ResultSet)
* @throws SQLException
*/
protected IRubyObject matchTables(final Ruby runtime,
final Connection connection,
final String catalog, final String schemaPattern,
final String tablePattern, final String[] types,
final boolean checkExistsOnly) throws SQLException {
final DatabaseMetaData metaData = connection.getMetaData();
final String _tablePattern = caseConvertIdentifierForJdbc(metaData, tablePattern);
final String _schemaPattern = caseConvertIdentifierForJdbc(metaData, schemaPattern);
ResultSet tablesSet = null;
try {
tablesSet = metaData.getTables(catalog, _schemaPattern, _tablePattern, types);
if ( checkExistsOnly ) { // only check if given table exists
return tablesSet.next() ? runtime.getTrue() : null;
}
else {
return mapTables(runtime, metaData, catalog, _schemaPattern, _tablePattern, tablesSet);
}
}
finally { close(tablesSet); }
}
// NOTE java.sql.DatabaseMetaData.getTables :
protected final static int TABLES_TABLE_CAT = 1;
protected final static int TABLES_TABLE_SCHEM = 2;
protected final static int TABLES_TABLE_NAME = 3;
protected final static int TABLES_TABLE_TYPE = 4;
/**
* @param runtime
* @param metaData
* @param catalog
* @param schemaPattern
* @param tablePattern
* @param tablesSet
* @return List<RubyString>
* @throws SQLException
*/
protected RubyArray mapTables(final Ruby runtime, final DatabaseMetaData metaData,
final String catalog, final String schemaPattern, final String tablePattern,
final ResultSet tablesSet) throws SQLException {
final RubyArray tables = runtime.newArray();
while ( tablesSet.next() ) {
String name = tablesSet.getString(TABLES_TABLE_NAME);
name = caseConvertIdentifierForRails(metaData, name);
tables.add(RubyString.newUnicodeString(runtime, name));
}
return tables;
}
/**
* NOTE: since 1.3.0 only present for binary compatibility (with extensions).
*
* @depreacated no longer used - replaced with
* {@link #matchTables(Ruby, Connection, String, String, String, String[], boolean)}
* please update your sub-class esp. if you're overriding this method !
*/
@Deprecated
protected SQLBlock tableLookupBlock(final Ruby runtime,
final String catalog, final String schemaPattern,
final String tablePattern, final String[] types) {
return new SQLBlock() {
public IRubyObject call(final Connection connection) throws SQLException {
return matchTables(runtime, connection, catalog, schemaPattern, tablePattern, types, false);
}
};
}
protected static final int COLUMN_NAME = 4;
protected static final int DATA_TYPE = 5;
protected static final int TYPE_NAME = 6;
protected static final int COLUMN_SIZE = 7;
protected static final int DECIMAL_DIGITS = 9;
protected static final int COLUMN_DEF = 13;
protected static final int IS_NULLABLE = 18;
protected int intFromResultSet(ResultSet resultSet, int column) throws SQLException {
int precision = resultSet.getInt(column);
return precision == 0 && resultSet.wasNull() ? -1 : precision;
}
/**
* Create a string which represents a sql type usable by Rails from the resultSet column
* metadata object.
*/
protected String typeFromResultSet(final ResultSet resultSet) throws SQLException {
final int precision = intFromResultSet(resultSet, COLUMN_SIZE);
final int scale = intFromResultSet(resultSet, DECIMAL_DIGITS);
final String type = resultSet.getString(TYPE_NAME);
return formatTypeWithPrecisionAndScale(type, precision, scale);
}
protected static String formatTypeWithPrecisionAndScale(final String type, final int precision, final int scale) {
if ( precision <= 0 ) return type;
final StringBuilder typeStr = new StringBuilder().append(type);
typeStr.append('(').append(precision); // type += "(" + precision;
if ( scale > 0 ) typeStr.append(',').append(scale); // type += "," + scale;
return typeStr.append(')').toString(); // type += ")";
}
private IRubyObject defaultValueFromResultSet(Ruby runtime, ResultSet resultSet)
throws SQLException {
String defaultValue = resultSet.getString(COLUMN_DEF);
return defaultValue == null ? runtime.getNil() : RubyString.newUnicodeString(runtime, defaultValue);
}
private IRubyObject unmarshalColumns(final ThreadContext context, final DatabaseMetaData metaData,
final ResultSet results, final ResultSet primaryKeys) throws SQLException {
final Ruby runtime = context.getRuntime();
// RubyHash types = (RubyHash) native_database_types();
final IRubyObject jdbcColumn = getJdbcColumnClass(context);
final List<String> primarykeyNames = new ArrayList<String>();
while ( primaryKeys.next() ) {
primarykeyNames.add( primaryKeys.getString(COLUMN_NAME) );
}
final List<IRubyObject> columns = new ArrayList<IRubyObject>();
while ( results.next() ) {
final String colName = results.getString(COLUMN_NAME);
IRubyObject column = jdbcColumn.callMethod(context, "new",
new IRubyObject[] {
getInstanceVariable("@config"),
RubyString.newUnicodeString( runtime, caseConvertIdentifierForRails(metaData, colName) ),
defaultValueFromResultSet( runtime, results ),
RubyString.newUnicodeString( runtime, typeFromResultSet(results) ),
runtime.newBoolean( ! results.getString(IS_NULLABLE).trim().equals("NO") )
});
columns.add(column);
if ( primarykeyNames.contains(colName) ) {
column.callMethod(context, "primary=", runtime.getTrue());
}
}
return runtime.newArray(columns);
}
protected static IRubyObject unmarshalIdResult(
final Ruby runtime, final Statement statement) throws SQLException {
final ResultSet genKeys = statement.getGeneratedKeys();
try {
if (genKeys.next() && genKeys.getMetaData().getColumnCount() > 0) {
return runtime.newFixnum( genKeys.getLong(1) );
}
return runtime.getNil();
}
finally { close(genKeys); }
}
/**
* @deprecated confusing as it closes the result set it receives use
* @see #unmarshalIdResult(Ruby, Statement)
*/
@Deprecated
public static IRubyObject unmarshal_id_result(
final Ruby runtime, final ResultSet genKeys) throws SQLException {
try {
if (genKeys.next() && genKeys.getMetaData().getColumnCount() > 0) {
return runtime.newFixnum( genKeys.getLong(1) );
}
return runtime.getNil();
}
finally { close(genKeys); }
}
protected IRubyObject unmarshalResults(final ThreadContext context,
final DatabaseMetaData metaData, final Statement statement,
final boolean downCase) throws SQLException {
final Ruby runtime = context.getRuntime();
IRubyObject result;
ResultSet resultSet = statement.getResultSet();
try {
result = unmarshalResult(context, runtime, metaData, resultSet, downCase);
}
finally { close(resultSet); }
if ( ! statement.getMoreResults() ) return result;
final List<IRubyObject> results = new ArrayList<IRubyObject>();
results.add(result);
do {
resultSet = statement.getResultSet();
try {
result = unmarshalResult(context, runtime, metaData, resultSet, downCase);
}
finally { close(resultSet); }
results.add(result);
}
while ( statement.getMoreResults() );
return runtime.newArray(results);
}
/**
* @deprecated no longer used but kept for API compatibility
* NOTE: this method no longer closes the passed result set !
*/
@Deprecated
protected IRubyObject unmarshalResult(final ThreadContext context,
final DatabaseMetaData metaData, final ResultSet resultSet,
final boolean downCase) throws SQLException {
return unmarshalResult(context, context.getRuntime(), metaData, resultSet, downCase);
}
/**
* Converts a jdbc resultset into an array (rows) of hashes (row) that AR expects.
*
* @param downCase should column names only be in lower case?
*/
@SuppressWarnings("unchecked")
private IRubyObject unmarshalResult(final ThreadContext context, final Ruby runtime,
final DatabaseMetaData metaData, final ResultSet resultSet,
final boolean downCase) throws SQLException {
final RubyArray results = runtime.newArray();
// [ { 'col1': 1, 'col2': 2 }, { 'col1': 3, 'col2': 4 } ]
ColumnData[] columns = setupColumns(runtime, metaData, resultSet.getMetaData(), downCase);
populateFromResultSet(context, runtime, (List<IRubyObject>) results, resultSet, columns);
return results;
}
/**
* @deprecated renamed and parameterized to {@link #withConnection(ThreadContext, SQLBlock)}
*/
@Deprecated
@SuppressWarnings("unchecked")
protected Object withConnectionAndRetry(final ThreadContext context, final SQLBlock block)
throws RaiseException {
return withConnection(context, block);
}
protected <T> T withConnection(final ThreadContext context, final Callable<T> block)
throws RaiseException {
try {
return withConnection(context, true, block);
}
catch (final SQLException e) {
return handleException(context, e); // should never happen
}
}
private <T> T withConnection(final ThreadContext context, final boolean handleException, final Callable<T> block)
throws RaiseException, RuntimeException, SQLException {
Throwable exception = null; int tries = 1; int i = 0;
while ( i++ < tries ) {
final Connection connection = getConnection(true);
boolean autoCommit = true; // retry in-case getAutoCommit throws
try {
autoCommit = connection.getAutoCommit();
return block.call(connection);
}
catch (final Exception e) { // SQLException or RuntimeException
exception = e;
if ( autoCommit ) { // do not retry if (inside) transactions
if ( i == 1 ) {
IRubyObject retryCount = getConfigValue(context, "retry_count");
tries = (int) retryCount.convertToInteger().getLongValue();
if ( tries <= 0 ) tries = 1;
}
if ( isConnectionBroken(context, connection) ) {
reconnect(context); continue; // retry connection (block) again
}
break; // connection not broken yet failed
}
}
}
// (retry) loop ended and we did not return ... exception != null
if ( handleException ) {
return handleException(context, getCause(exception)); // throws
}
else {
if ( exception instanceof SQLException ) {
throw (SQLException) exception;
}
if ( exception instanceof RuntimeException ) {
throw (RuntimeException) exception;
}
// won't happen - our try block only throws SQL or Runtime exceptions
throw new RuntimeException(exception);
}
}
private static Throwable getCause(Throwable exception) {
Throwable cause = exception.getCause();
while (cause != null && cause != exception) {
// SQLException's cause might be DB specific (checked/unchecked) :
if ( exception instanceof SQLException ) break;
exception = cause; cause = exception.getCause();
}
return exception;
}
protected <T> T handleException(final ThreadContext context, Throwable exception)
throws RaiseException {
// NOTE: we shall not wrap unchecked (runtime) exceptions into AR::Error
// if it's really a misbehavior of the driver throwing a RuntimeExcepion
// instead of SQLException than this should be overriden for the adapter
if ( exception instanceof RuntimeException ) {
throw (RuntimeException) exception;
}
debugStackTrace(context, exception);
throw wrapException(context, exception);
}
/**
* @deprecated use {@link #wrapException(ThreadContext, Throwable)} instead
* for overriding how exceptions are handled use {@link #handleException(ThreadContext, Throwable)}
*/
@Deprecated
protected RuntimeException wrap(final ThreadContext context, final Throwable exception) {
return wrapException(context, exception);
}
protected RaiseException wrapException(final ThreadContext context, final Throwable exception) {
final Ruby runtime = context.getRuntime();
if ( exception instanceof SQLException ) {
final String message = SQLException.class == exception.getClass() ?
exception.getMessage() : exception.toString(); // useful to easily see type on Ruby side
final RaiseException error = wrapException(context, getJDBCError(runtime), exception, message);
final int errorCode = ((SQLException) exception).getErrorCode();
RuntimeHelpers.invoke( context, error.getException(),
"errno=", runtime.newFixnum(errorCode) );
RuntimeHelpers.invoke( context, error.getException(),
"sql_exception=", JavaEmbedUtils.javaToRuby(runtime, exception) );
return error;
}
return wrapException(context, getJDBCError(runtime), exception);
}
protected static RaiseException wrapException(final ThreadContext context,
final RubyClass errorClass, final Throwable exception) {
return wrapException(context, errorClass, exception, exception.toString());
}
protected static RaiseException wrapException(final ThreadContext context,
final RubyClass errorClass, final Throwable exception, final String message) {
final RaiseException error = new RaiseException(context.getRuntime(), errorClass, message, true);
error.initCause(exception);
return error;
}
private IRubyObject convertJavaToRuby(final Connection connection) {
return JavaUtil.convertJavaToRuby( getRuntime(), connection );
}
/**
* Some databases support schemas and others do not.
* For ones which do this method should return true, aiding in decisions regarding schema vs database determination.
*/
protected boolean databaseSupportsSchemas() {
return false;
}
private static final byte[] SELECT = new byte[] { 's','e','l','e','c','t' };
private static final byte[] WITH = new byte[] { 'w','i','t','h' };
private static final byte[] SHOW = new byte[] { 's','h','o','w' };
private static final byte[] CALL = new byte[]{ 'c','a','l','l' };
@JRubyMethod(name = "select?", required = 1, meta = true, frame = false)
public static IRubyObject select_p(final ThreadContext context,
final IRubyObject self, final IRubyObject sql) {
return context.getRuntime().newBoolean( isSelect(sql.convertToString()) );
}
private static boolean isSelect(final RubyString sql) {
final ByteList sqlBytes = sql.getByteList();
return startsWithIgnoreCase(sqlBytes, SELECT) ||
startsWithIgnoreCase(sqlBytes, WITH) ||
startsWithIgnoreCase(sqlBytes, SHOW) ||
startsWithIgnoreCase(sqlBytes, CALL);
}
private static final byte[] INSERT = new byte[] { 'i','n','s','e','r','t' };
@JRubyMethod(name = "insert?", required = 1, meta = true, frame = false)
public static IRubyObject insert_p(final ThreadContext context,
final IRubyObject self, final IRubyObject sql) {
final ByteList sqlBytes = sql.convertToString().getByteList();
return context.getRuntime().newBoolean(startsWithIgnoreCase(sqlBytes, INSERT));
}
protected static boolean startsWithIgnoreCase(final ByteList string, final byte[] start) {
int p = skipWhitespace(string, string.getBegin());
final byte[] stringBytes = string.unsafeBytes();
if ( stringBytes[p] == '(' ) p = skipWhitespace(string, p + 1);
for ( int i = 0; i < string.getRealSize() && i < start.length; i++ ) {
if ( Character.toLowerCase(stringBytes[p + i]) != start[i] ) return false;
}
return true;
}
private static int skipWhitespace(final ByteList string, final int from) {
final int end = string.getBegin() + string.getRealSize();
final byte[] stringBytes = string.unsafeBytes();
for ( int i = from; i < end; i++ ) {
if ( ! Character.isWhitespace( stringBytes[i] ) ) return i;
}
return end;
}
protected static final class TableName {
public final String catalog, schema, name;
public TableName(String catalog, String schema, String table) {
this.catalog = catalog;
this.schema = schema;
this.name = table;
}
}
protected TableName extractTableName(
final Connection connection, String catalog, String schema,
final String tableName) throws IllegalArgumentException, SQLException {
final String[] nameParts = tableName.split("\\.");
if ( nameParts.length > 3 ) {
throw new IllegalArgumentException("table name: " + tableName + " should not contain more than 2 '.'");
}
String name = tableName;
if ( nameParts.length == 2 ) {
schema = nameParts[0];
name = nameParts[1];
}
else if ( nameParts.length == 3 ) {
catalog = nameParts[0];
schema = nameParts[1];
name = nameParts[2];
}
final DatabaseMetaData metaData = connection.getMetaData();
if (schema != null) {
schema = caseConvertIdentifierForJdbc(metaData, schema);
}
name = caseConvertIdentifierForJdbc(metaData, name);
if (schema != null && ! databaseSupportsSchemas()) {
catalog = schema;
}
if (catalog == null) catalog = connection.getCatalog();
return new TableName(catalog, schema, name);
}
/**
* @deprecated use {@link #extractTableName(Connection, String, String, String)}
*/
@Deprecated
protected TableName extractTableName(
final Connection connection, final String schema,
final String tableName) throws IllegalArgumentException, SQLException {
return extractTableName(connection, null, schema, tableName);
}
protected static final class ColumnData {
public final RubyString name;
public final int index;
public final int type;
public ColumnData(RubyString name, int type, int idx) {
this.name = name;
this.type = type;
this.index = idx;
}
}
private static ColumnData[] setupColumns(
final Ruby runtime,
final DatabaseMetaData metaData,
final ResultSetMetaData resultMetaData,
final boolean downCase) throws SQLException {
final int columnCount = resultMetaData.getColumnCount();
final ColumnData[] columns = new ColumnData[columnCount];
for ( int i = 1; i <= columnCount; i++ ) { // metadata is one-based
final String name;
if (downCase) {
name = resultMetaData.getColumnLabel(i).toLowerCase();
} else {
name = caseConvertIdentifierForRails(metaData, resultMetaData.getColumnLabel(i));
}
final int columnType = resultMetaData.getColumnType(i);
final RubyString columnName = RubyString.newUnicodeString(runtime, name);
columns[i - 1] = new ColumnData(columnName, columnType, i);
}
return columns;
}
// JDBC API Helpers :
protected static void close(final Connection connection) {
if ( connection != null ) {
try { connection.close(); }
catch (final Exception e) { /* NOOP */ }
}
}
public static void close(final ResultSet resultSet) {
if (resultSet != null) {
try { resultSet.close(); }
catch (final Exception e) { /* NOOP */ }
}
}
public static void close(final Statement statement) {
if (statement != null) {
try { statement.close(); }
catch (final Exception e) { /* NOOP */ }
}
}
// DEBUG-ing helpers :
private static boolean debug = Boolean.getBoolean("arjdbc.debug");
public static boolean isDebug() { return debug; }
public static void setDebug(boolean debug) {
RubyJdbcConnection.debug = debug;
}
public static void debugMessage(final ThreadContext context, final String msg) {
if ( debug || context.runtime.isDebug() ) {
context.runtime.getOut().println(msg);
}
}
protected static void debugErrorSQL(final ThreadContext context, final String sql) {
if ( debug || context.runtime.isDebug() ) {
context.runtime.getOut().println("Error SQL: " + sql);
}
}
public static void debugStackTrace(final ThreadContext context, final Throwable e) {
if ( debug || context.runtime.isDebug() ) {
e.printStackTrace(context.runtime.getOut());
}
}
}
|
package javaUtilities;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.Condition;
import javaUtilities.UpgradableLock.Mode;
import org.junit.*;
import org.junit.rules.Timeout;
public class UpgradableLockTest {
private static int MAX_TEST_LENGTH_MILLIS = 5000;
private static long MAX_WAIT_FOR_LOCK_MILLIS = 10;
private UpgradableLock myLock;
@Rule
public Timeout myTimeout = new Timeout(MAX_TEST_LENGTH_MILLIS);
@Before
public void setup() {
myLock = new UpgradableLock();
Thread.interrupted();
}
@Test
public void testWriteLock() throws Throwable {
myLock.lock(Mode.WRITE);
myLock.lock(Mode.READ);
assertTrue(hasWriter());
myLock.unlock();
assertTrue(hasWriter());
myLock.unlock();
assertTrue(isUnlocked());
}
@Test
public void testUpgrading() throws Throwable {
myLock.lock(Mode.UPGRADABLE);
assertTrue(hasUpgradable());
myLock.lock(Mode.READ);
assertTrue(hasUpgradable());
myLock.upgrade();
assertTrue(hasWriter());
myLock.downgrade();
assertTrue(hasUpgradable());
myLock.lock(Mode.WRITE);
assertTrue(hasWriter());
myLock.unlock();
assertTrue(hasUpgradable());
myLock.unlock();
assertTrue(hasUpgradable());
myLock.unlock();
assertTrue(isUnlocked());
}
@Test
public void testReadLock() throws Throwable {
myLock.lock(Mode.READ);
assertTrue(hasReaders());
myLock.lock(Mode.READ);
assertTrue(hasReaders());
myLock.unlock();
assertTrue(hasReaders());
myLock.unlock();
assertTrue(isUnlocked());
}
@Test
public void clearUpgradesAfterFullUnlock() throws Throwable {
myLock.lock(Mode.UPGRADABLE);
myLock.upgrade();
assertTrue(hasWriter());
myLock.unlock();
assertTrue(isUnlocked());
myLock.lock(Mode.UPGRADABLE);
assertTrue(hasUpgradable());
}
@Test
public void keepUpgradesAfterReleasingWriteLock() throws Throwable {
myLock.lock(Mode.UPGRADABLE);
myLock.lock(Mode.WRITE);
myLock.upgrade();
assertTrue(hasWriter());
myLock.unlock();
assertTrue(hasWriter());
myLock.downgrade();
assertTrue(hasUpgradable());
}
@Test
public void testTimeout() throws InterruptedException {
lockPermanently(Mode.WRITE);
for (Mode mMode : Mode.values()) {
boolean mSuccess = myLock.tryLock(mMode, 100, TimeUnit.MICROSECONDS);
assertFalse(mSuccess);
}
}
@Test
public void testNegativeTimeout() throws InterruptedException {
lockPermanently(Mode.UPGRADABLE);
boolean mSuccess = myLock.tryLock(Mode.UPGRADABLE, -3L, TimeUnit.MICROSECONDS);
assertFalse(mSuccess);
}
@Test
public void testTryLockWhenAvailable() throws Throwable {
for (Mode mMode : Mode.values()) {
assertTrue(myLock.tryLock(mMode));
myLock.unlock();
assertTrue(isUnlocked());
}
}
@Test
public void testTryLockWhenNotAvailable() throws InterruptedException {
lockPermanently(Mode.WRITE);
for (Mode mMode : Mode.values()) {
assertFalse(myLock.tryLock(mMode));
}
}
@Test
public void testInterruption() throws InterruptedException {
final AtomicBoolean mInterrupted = new AtomicBoolean();
Thread mThread = new Thread() {
@Override
public void run() {
try {
myLock.lockInterruptibly(Mode.UPGRADABLE);
} catch (InterruptedException e) {
mInterrupted.set(true);
}
}
};
lockPermanently(Mode.WRITE);
mThread.start();
Thread.sleep(MAX_WAIT_FOR_LOCK_MILLIS);
mThread.interrupt();
mThread.join();
assertTrue(mInterrupted.get());
}
@Test
public void retainInterruptedStatusWithTryLock() throws InterruptedException {
Thread mCurrent = Thread.currentThread();
mCurrent.interrupt();
assertTrue(myLock.tryLock(Mode.WRITE));
myLock.unlock();
assertTrue(Thread.interrupted());
lockPermanently(Mode.READ);
mCurrent.interrupt();
assertFalse(myLock.tryLock(Mode.WRITE));
assertTrue(Thread.interrupted());
}
/*
* Several threads with read locks and one thread with an upgradable lock
* wait on a barrier.
*/
@Test
public void allowConcurrentReadAndUpgradableAccess() throws Throwable {
int mNThreads = 4;
final CyclicBarrier mBarrier = new CyclicBarrier(mNThreads);
final AtomicReference<Throwable> mError = new AtomicReference<Throwable>();
ExecutorService mPool = Executors.newCachedThreadPool();
for (int i = 0; i < mNThreads - 1; i++) {
mPool.execute(newBarrierTask(mBarrier, Mode.READ, mError));
}
mPool.execute(newBarrierTask(mBarrier, Mode.UPGRADABLE, mError));
mPool.shutdown();
assertTrue(mPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS));
assertEquals(null, mError.get());
assertTrue(isUnlocked());
}
private Runnable newBarrierTask(
final CyclicBarrier aBarrier,
final Mode aMode,
final AtomicReference<Throwable> aError) {
return new Runnable() {
@Override
public void run() {
myLock.lock(aMode);
try {
aBarrier.await();
} catch (Exception e) {
aError.set(e);
} finally {
myLock.unlock();
}
}
};
}
/*
* Threads 0 - n wait on a condition for a counter to reach their index
* numbers. Then they increment the counter and notify the other threads. The
* counter starts at zero to allow the first thread to proceed without
* waiting.
*/
@Test
public void testCondition() throws InterruptedException {
final Condition mIncremented = myLock.newCondition();
final AtomicInteger mCounter = new AtomicInteger();
ExecutorService mPool = Executors.newCachedThreadPool();
int mNThreads = 10;
for (int i = 0; i < mNThreads; i++) {
mPool.execute(newWaitTask(i, mCounter, mIncremented));
}
mPool.shutdown();
mPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
assertEquals(mNThreads, mCounter.get());
}
private Runnable newWaitTask(
final int aExpectedCount,
final AtomicInteger aCounter,
final Condition aIncremented) {
return new Runnable() {
@Override
public void run() {
myLock.lock(Mode.WRITE);
try {
while (aCounter.get() != aExpectedCount) {
aIncremented.await();
}
aCounter.incrementAndGet();
aIncremented.signalAll();
} catch (InterruptedException e) {
// return
} finally {
myLock.unlock();
}
}
};
}
@Test
public void serializeWithWriter() throws Throwable {
lockPermanently(Mode.WRITE);
byte[] mSerializedLock = serialize(myLock);
assertTrue(hasWriter());
myLock = (UpgradableLock) deserialize(mSerializedLock);
assertTrue(isUnlocked());
}
@Test
public void serializeWithReaders() throws Throwable {
Mode[] mModes = {Mode.READ, Mode.UPGRADABLE};
for (Mode mMode : mModes) {
lockPermanently(mMode);
byte[] mSerializedLock = serialize(myLock);
assertFalse(canLock(Mode.WRITE));
myLock = (UpgradableLock) deserialize(mSerializedLock);
assertTrue(isUnlocked());
}
}
private static byte[] serialize(Serializable aValue) throws IOException {
ByteArrayOutputStream mOS = new ByteArrayOutputStream();
ObjectOutputStream mOOS = new ObjectOutputStream(mOS);
mOOS.writeObject(aValue);
return mOS.toByteArray();
}
private static Serializable deserialize(byte[] aSerialized) throws IOException, ClassNotFoundException {
InputStream mIS = new ByteArrayInputStream(aSerialized);
ObjectInputStream mOIS = new ObjectInputStream(mIS);
return (Serializable) mOIS.readObject();
}
@Test(expected=IllegalMonitorStateException.class)
public void preventWaitingWithoutWriteLock() throws InterruptedException {
myLock.lock(Mode.READ);
Condition mCondition = myLock.newCondition();
mCondition.await();
}
@Test(expected=IllegalMonitorStateException.class)
public void preventSignallingWithoutWriteLock() {
myLock.lock(Mode.UPGRADABLE);
Condition mCondition = myLock.newCondition();
mCondition.signal();
}
/*
* One thread tries to acquire the write lock multiple times while several
* threads use a counter to try to trade off acquiring the read lock.
*/
@Test
public void preventWriterStarvation() throws Throwable {
Mode[] mModes = {Mode.WRITE, Mode.UPGRADABLE};
for (Mode mMode : mModes) {
final AtomicInteger mCounter = new AtomicInteger();
ExecutorService mPool = Executors.newCachedThreadPool();
for (int i = 0; i < 3; i++) {
mPool.execute(new Runnable() {
@Override
public void run() {
try {
while (true) {
myLock.lockInterruptibly(Mode.READ);
try {
int mStartCount = mCounter.incrementAndGet();
long mEndTime = System.nanoTime() + 5000 * 1000;
while (mCounter.get() == mStartCount && System.nanoTime() < mEndTime) {
Thread.sleep(0, 1000);
}
} finally {
myLock.unlock();
}
}
} catch (InterruptedException e) {
// return
}
}
});
}
for (int i = 0; i < 5; i++) {
Thread.sleep(MAX_WAIT_FOR_LOCK_MILLIS);
myLock.lock(mMode);
myLock.upgrade();
myLock.unlock();
}
mPool.shutdownNow();
mPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
assertTrue(isUnlocked());
}
}
@Test
public void releaseWriteWithWaitingThreads() throws Throwable {
Mode[] mModes = {Mode.UPGRADABLE, Mode.WRITE};
for (Mode mMode : mModes) {
Thread mThread = new Thread() {
@Override
public void run() {
myLock.lock(Mode.READ);
myLock.unlock();
}
};
myLock.lock(mMode);
myLock.upgrade();
mThread.start();
Thread.sleep(MAX_WAIT_FOR_LOCK_MILLIS);
myLock.downgrade();
if (mMode == Mode.WRITE) myLock.unlock();
mThread.join();
if (mMode == Mode.UPGRADABLE) myLock.unlock();
assertTrue(isUnlocked());
}
}
@Test
public void releaseReadWithWaitingThreads() throws Throwable {
Mode[] mUnlockModes = {Mode.UPGRADABLE, Mode.READ};
Mode[] mLockModes = {Mode.UPGRADABLE, Mode.WRITE};
for (Mode mUnlockMode : mUnlockModes) {
for (final Mode mLockMode : mLockModes) {
Thread mThread = new Thread() {
@Override
public void run() {
myLock.lock(mLockMode);
myLock.upgrade();
myLock.unlock();
}
};
myLock.lock(mUnlockMode);
mThread.start();
Thread.sleep(MAX_WAIT_FOR_LOCK_MILLIS);
myLock.unlock();
mThread.join();
assertTrue(isUnlocked());
}
}
}
@Test(expected=IllegalMonitorStateException.class)
public void preventLockingWriteAfterRead() throws Throwable {
myLock.lock(Mode.READ);
try {
myLock.lock(Mode.WRITE);
} finally {
assertTrue(hasReaders());
myLock.unlock();
assertTrue(isUnlocked());
}
}
@Test(expected=IllegalMonitorStateException.class)
public void preventUpgradeFromRead() {
myLock.lock(Mode.READ);
myLock.upgrade();
}
@Test(expected=IllegalMonitorStateException.class)
public void preventDowngradeWithoutUpgrade() throws Throwable {
myLock.lock(Mode.UPGRADABLE);
try {
myLock.downgrade();
} finally {
myLock.unlock();
assertTrue(isUnlocked());
}
}
@Test(expected=IllegalMonitorStateException.class)
public void preventUnlockWithoutLock() throws Throwable {
try {
myLock.unlock();
} finally {
assertTrue(isUnlocked());
}
}
@Test(expected=NullPointerException.class)
public void disallowNullLockModeWithLock() {
myLock.lock(null);
}
@Test(expected=NullPointerException.class)
public void disallowNullLockModeWithTryLock() {
myLock.tryLock(null);
}
@Test(expected=NullPointerException.class)
public void disallowNullTimeUnitWithLock() throws InterruptedException {
myLock.tryLock(Mode.READ, 10, null);
}
@Test(expected=NullPointerException.class)
public void disallowNullTimeUnitWithUpgrade() throws InterruptedException {
myLock.lock(Mode.UPGRADABLE);
myLock.tryUpgrade(-10, null);
}
private void lockPermanently(final Mode aMode) throws InterruptedException {
final AtomicBoolean mSuccess = new AtomicBoolean();
Thread mThread = new Thread() {
@Override
public void run() {
mSuccess.set(myLock.tryLock(aMode));
}
};
mThread.start();
mThread.join();
assertTrue(mSuccess.get());
}
private boolean isUnlocked() throws Throwable {
return canLock(Mode.WRITE);
}
private boolean hasReaders() throws Throwable {
return !canLock(Mode.WRITE) && canLock(Mode.UPGRADABLE);
}
private boolean hasUpgradable() throws Throwable {
return !canLock(Mode.UPGRADABLE) && canLock(Mode.READ);
}
private boolean hasWriter() throws Throwable {
return !canLock(Mode.READ);
}
private boolean canLock(final Mode aMode) throws Throwable {
RunnableFuture<Boolean> mFuture = new FutureTask<>(new Callable<Boolean>() {
@Override
public Boolean call() {
boolean mSuccess = myLock.tryLock(aMode);
if (mSuccess) myLock.unlock();
return mSuccess;
}
});
new Thread(mFuture).start();
try {
return mFuture.get();
} catch (ExecutionException e) {
throw e.getCause();
}
}
}
|
package com.microsoft.sqlserver.jdbc.unit.statement;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import com.microsoft.sqlserver.jdbc.SQLServerConnection;
import com.microsoft.sqlserver.testframework.AbstractTest;
import com.microsoft.sqlserver.testframework.DBConnection;
@RunWith(JUnitPlatform.class)
public class RegressionTest extends AbstractTest {
private static String tableName = "[ServerCursorPStmt]";
private static String procName = "[ServerCursorProc]";
/**
* Tests select into stored proc
*
* @throws SQLException
*/
@Test
public void testServerCursorPStmt() throws SQLException {
SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString);
Statement stmt = con.createStatement();
PreparedStatement pstmt = null;
ResultSet rs = null;
// expected values
int numRowsInResult = 1;
String col3Value = "India";
String col3Lookup = "IN";
stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key, col2 varchar(3), col3 varchar(128))");
stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (1, 'CAN', 'Canada')");
stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (2, 'USA', 'United States of America')");
stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (3, 'JPN', 'Japan')");
stmt.executeUpdate("INSERT INTO " + tableName + " VALUES (4, '" + col3Lookup + "', '" + col3Value + "')");
// create stored proc
String storedProcString;
if (DBConnection.isSqlAzure(con)) {
// On SQL Azure, 'SELECT INTO' is not supported. So do not use it.
storedProcString = "CREATE PROCEDURE " + procName + " @param varchar(3) AS SELECT col3 FROM " + tableName + " WHERE col2 = @param";
}
else {
// On SQL Server
storedProcString = "CREATE PROCEDURE " + procName + " @param varchar(3) AS SELECT col3 INTO #TMPTABLE FROM " + tableName
+ " WHERE col2 = @param SELECT col3 FROM #TMPTABLE";
}
stmt.executeUpdate(storedProcString);
// execute stored proc via pstmt
pstmt = con.prepareStatement("EXEC " + procName + " ?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
pstmt.setString(1, col3Lookup);
// should return 1 row
rs = pstmt.executeQuery();
rs.last();
assertEquals(rs.getRow(), numRowsInResult, "getRow mismatch");
rs.beforeFirst();
while (rs.next()) {
assertEquals(rs.getString(1), col3Value, "Value mismatch");
}
if (null != stmt)
stmt.close();
if (null != con)
con.close();
}
@AfterAll
public static void terminate() throws SQLException {
SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString);
Statement stmt = con.createStatement();
stmt.executeUpdate("IF EXISTS (select * from sysobjects where id = object_id(N'" + tableName + "') and OBJECTPROPERTY(id, N'IsTable') = 1)"
+ " DROP TABLE " + tableName);
stmt.executeUpdate("IF EXISTS (select * from sysobjects where id = object_id(N'" + procName + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)"
+ " DROP PROCEDURE " + procName);
}
}
|
package com.windh.util.neo;
import java.lang.reflect.Constructor;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Transaction;
import org.neo4j.impl.core.NodeManager;
import org.neo4j.impl.core.NotFoundException;
public abstract class NodeWrapper
{
private Node node;
protected NodeWrapper( Node node )
{
this.node = node;
}
public Node getUnderlyingNode()
{
return node;
}
public static <T extends NodeWrapper> T newInstance(
Class<T> instanceClass, long nodeId ) throws NotFoundException
{
Transaction tx = Transaction.begin();
try
{
Node node = NodeManager.getManager().getNodeById( ( int ) nodeId );
return newInstance( instanceClass, node );
}
finally
{
tx.finish();
}
}
public static <T extends NodeWrapper> T newInstance(
Class<T> instanceClass, Node node )
{
try
{
Constructor<T> constructor =
instanceClass.getConstructor( Node.class );
T result = constructor.newInstance( node );
return result;
}
catch ( RuntimeException e )
{
throw e;
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
@Override
public boolean equals( Object o )
{
if ( o == null || !getClass().equals( o.getClass() ) )
{
return false;
}
return getUnderlyingNode().equals(
( ( NodeWrapper ) o ).getUnderlyingNode() );
}
@Override
public int hashCode()
{
return getUnderlyingNode().hashCode();
}
}
|
package org.apache.xmlrpc;
import java.net.*;
import java.io.*;
import java.util.*;
import org.xml.sax.*;
/**
* A multithreaded, reusable XML-RPC client object. Use this if you need a full-grown
* HTTP client (e.g. for Proxy and Cookies support). If you don't need that, <code>XmlRpcClientLite</code>
* may work better for you.
*
* @author <a href="mailto:hannes@apache.org">Hannes Wallnoefer</a>
*/
public class XmlRpcClient
implements XmlRpcHandler
{
URL url;
String auth;
int maxThreads = 100;
// pool of worker instances
Stack pool = new Stack ();
int workers = 0;
int asyncWorkers = 0;
// a queue of calls to be handled asynchronously
CallData first, last;
/**
* Construct a XML-RPC client with this URL.
*/
public XmlRpcClient (URL url)
{
this.url = url;
}
/**
* Construct a XML-RPC client for the URL represented by this String.
*/
public XmlRpcClient (String url) throws MalformedURLException
{
this.url = new URL (url);
}
/**
* Construct a XML-RPC client for the specified hostname and port.
*/
public XmlRpcClient (String hostname,
int port) throws MalformedURLException
{
this.url = new URL ("http://"+hostname + ":"+port + "/RPC2");
}
/**
* Return the URL for this XML-RPC client.
*/
public URL getURL ()
{
return url;
}
public void setBasicAuthentication (String user, String password)
{
if (user == null || password == null)
auth = null;
else
{
char[] basicAuth =
Base64.encode ((user + ":"+password).getBytes());
auth = new String (basicAuth).trim();
}
}
/**
* Generate an XML-RPC request and send it to the server. Parse the result and
* return the corresponding Java object.
*
* @exception XmlRpcException: If the remote host returned a fault message.
* @exception IOException: If the call could not be made because of lower level problems.
*/
public Object execute (String method,
Vector params) throws XmlRpcException, IOException
{
Worker worker = getWorker (false);
try
{
Object retval = worker.execute (method, params);
return retval;
}
finally { releaseWorker (worker, false);
}
}
/**
* Generate an XML-RPC request and send it to the server in a new thread.
* This method returns immediately.
* If the callback parameter is not null, it will be called later to handle the result or error when the call is finished.
*
*/
public void executeAsync (String method, Vector params,
AsyncCallback callback)
{
// if at least 4 threads are running, don't create any new ones,
// just enqueue the request.
if (asyncWorkers >= 4)
{
enqueue (method, params, callback);
return;
}
Worker worker = null;
try
{
worker = getWorker (true);
worker.start (method, params, callback);
}
catch (IOException iox)
{
// make a queued worker that doesn't run immediately
enqueue (method, params, callback);
}
}
synchronized Worker getWorker (boolean async)
throws IOException
{
try
{
Worker w = (Worker) pool.pop ();
if (async)
asyncWorkers += 1;
else
workers += 1;
return w;
}
catch (EmptyStackException x)
{
if (workers < maxThreads)
{
if (async)
asyncWorkers += 1;
else
workers += 1;
return new Worker ();
}
throw new IOException ("XML-RPC System overload");
}
}
/**
* Release possibly big per-call object references to allow them to be garbage collected
*/
synchronized void releaseWorker (Worker w, boolean async)
{
w.result = null;
w.call = null;
if (pool.size() < 20 && !w.fault)
pool.push (w);
if (async)
asyncWorkers -= 1;
else
workers -= 1;
}
synchronized void enqueue (String method, Vector params,
AsyncCallback callback)
{
CallData call = new CallData (method, params, callback);
if (last == null)
first = last = call;
else
{
last.next = call;
last = call;
}
}
synchronized CallData dequeue ()
{
if (first == null)
return null;
CallData call = first;
if (first == last)
first = last = null;
else
first = first.next;
return call;
}
class Worker extends XmlRpc implements Runnable
{
boolean fault;
Object result = null;
StringBuffer strbuf;
CallData call;
public Worker ()
{
super ();
}
public void start (String method, Vector params,
AsyncCallback callback)
{
this.call = new CallData (method, params, callback);
Thread t = new Thread (this);
t.start ();
}
public void run ()
{
while (call != null)
{
executeAsync (call.method, call.params, call.callback);
call = dequeue ();
}
releaseWorker (this, true);
}
/**
* Execute an XML-RPC call and handle asyncronous callback.
*/
void executeAsync (String method, Vector params, AsyncCallback callback)
{
Object res = null;
try
{
res = execute (method, params);
// notify callback object
if (callback != null)
callback.handleResult (res, url, method);
}
catch (Exception x)
{
if (callback != null)
try
{
callback.handleError (x, url, method);
}
catch (Exception ignore)
{}
}
}
/**
* Execute an XML-RPC call.
*/
Object execute (String method,
Vector params) throws XmlRpcException, IOException
{
fault = false;
long now = System.currentTimeMillis ();
try
{
ByteArrayOutputStream bout = new ByteArrayOutputStream ();
if (strbuf == null)
strbuf = new StringBuffer ();
else
strbuf.setLength (0);
XmlWriter writer = new XmlWriter (strbuf);
writeRequest (writer, method, params);
byte[] request = writer.getBytes();
URLConnection con = url.openConnection ();
con.setDoInput (true);
con.setDoOutput (true);
con.setUseCaches (false);
con.setAllowUserInteraction(false);
con.setRequestProperty ("Content-Length",
Integer.toString (request.length));
con.setRequestProperty ("Content-Type", "text/xml");
if (auth != null)
con.setRequestProperty ("Authorization", "Basic "+auth);
// con.connect ();
OutputStream out = con.getOutputStream ();
out.write (request);
out.flush ();
InputStream in = con.getInputStream ();
parse (in);
}
catch (Exception x)
{
x.printStackTrace ();
throw new IOException (x.getMessage ());
}
if (fault)
{ // generate an XmlRpcException
XmlRpcException exception = null;
try
{
Hashtable f = (Hashtable) result;
String faultString = (String) f.get ("faultString");
int faultCode = Integer.parseInt (
f.get ("faultCode").toString ());
exception = new XmlRpcException (faultCode,
faultString.trim ());
}
catch (Exception x)
{
throw new XmlRpcException (0, "Invalid fault response");
}
throw exception;
}
if (debug)
System.err.println ("Spent "+
(System.currentTimeMillis () - now) + " in request");
return result;
}
/**
* Called when the return value has been parsed.
*/
void objectParsed (Object what)
{
result = what;
}
/**
* Generate an XML-RPC request from a method name and a parameter vector.
*/
void writeRequest (XmlWriter writer, String method,
Vector params) throws IOException, XmlRpcException
{
writer.startElement ("methodCall");
writer.startElement ("methodName");
writer.write (method);
writer.endElement ("methodName");
writer.startElement ("params");
int l = params.size ();
for (int i = 0; i < l; i++)
{
writer.startElement ("param");
writeObject (params.elementAt (i), writer);
writer.endElement ("param");
}
writer.endElement ("params");
writer.endElement ("methodCall");
}
/**
* Overrides method in XmlRpc to handle fault repsonses.
*/
public void startElement (String name,
AttributeList atts) throws SAXException
{
if ("fault".equals (name))
fault = true;
else
super.startElement (name, atts);
}
} // end of inner class Worker
class CallData
{
String method;
Vector params;
AsyncCallback callback;
CallData next;
/**
* Make a call to be queued and then executed by the next free async thread
*/
public CallData (String method, Vector params,
AsyncCallback callback)
{
this.method = method;
this.params = params;
this.callback = callback;
this.next = null;
}
}
/**
* Just for testing.
*/
public static void main (String args[]) throws Exception
{
// XmlRpc.setDebug (true);
// XmlRpc.setKeepAlive (true);
try
{
String url = args[0];
String method = args[1];
Vector v = new Vector ();
for (int i = 2; i < args.length; i++)
try
{
v.addElement (
new Integer (Integer.parseInt (args[i])));
}
catch (NumberFormatException nfx)
{
v.addElement (args[i]);
}
XmlRpcClient client = new XmlRpcClientLite (url);
try
{
System.err.println (client.execute (method, v));
}
catch (Exception ex)
{
System.err.println ("Error: "+ex.getMessage());
}
}
catch (Exception x)
{
System.err.println (x);
System.err.println ("Usage: java org.apache.xmlrpc.XmlRpcClient <url> <method> <arg> ....");
System.err.println ("Arguments are sent as integers or strings.");
}
}
}
|
package org.orbeon.oxf.util;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.log4j.Logger;
import org.orbeon.oxf.cache.Cache;
import org.orbeon.oxf.cache.InternalCacheKey;
import org.orbeon.oxf.cache.ObjectCache;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.xml.NamespaceMapping;
import org.orbeon.oxf.xml.XPathCacheStaticContext;
import org.orbeon.oxf.xml.dom4j.ExtendedLocationData;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.orbeon.saxon.Configuration;
import org.orbeon.saxon.expr.Expression;
import org.orbeon.saxon.expr.ExpressionTool;
import org.orbeon.saxon.expr.ExpressionVisitor;
import org.orbeon.saxon.functions.FunctionLibrary;
import org.orbeon.saxon.functions.FunctionLibraryList;
import org.orbeon.saxon.instruct.SlotManager;
import org.orbeon.saxon.om.Item;
import org.orbeon.saxon.om.NamePool;
import org.orbeon.saxon.om.ValueRepresentation;
import org.orbeon.saxon.style.AttributeValueTemplate;
import org.orbeon.saxon.sxpath.IndependentContext;
import org.orbeon.saxon.sxpath.XPathEvaluator;
import org.orbeon.saxon.sxpath.XPathExpression;
import org.orbeon.saxon.sxpath.XPathVariable;
import org.orbeon.saxon.trans.XPathException;
import org.orbeon.saxon.type.Type;
import org.orbeon.saxon.value.SequenceExtent;
import java.util.*;
/**
* Use the object cache to cache XPath expressions, which are costly to parse.
*
* It is mandatory to call returnToPool() on the returned PooledXPathExpression after use. It is
* good to do this within a finally() block enclosing the use of the expression.
*/
public class XPathCache {
private static NamePool NAME_POOL = new NamePool();
private static Configuration CONFIGURATION = new Configuration() {
@Override
public void setAllowExternalFunctions(boolean allowExternalFunctions) {
throw new IllegalStateException("Global XPath configuration is be read-only");
}
@Override
public void setConfigurationProperty(String name, Object value) {
throw new IllegalStateException("Global XPath configuration is be read-only");
}
};
static {
CONFIGURATION.setNamePool(NAME_POOL);
}
public static final String XPATH_CACHE_NAME = "cache.xpath";
private static final int XPATH_CACHE_DEFAULT_SIZE = 200;
public static final String XPATH_CACHE_CONFIGURATION_PROPERTY = "orbeon.cache.xpath.configuration";
private static final Logger logger = LoggerFactory.createLogger(XPathCache.class);
public static class XPathContext {
public final NamespaceMapping namespaceMapping;
public final Map<String, ValueRepresentation> variableToValueMap;
public final FunctionLibrary functionLibrary;
public final FunctionContext functionContext;
public final String baseURI;
public final LocationData locationData;
public XPathContext(NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
this.namespaceMapping = namespaceMapping;
this.variableToValueMap = variableToValueMap;
this.functionLibrary = functionLibrary;
this.functionContext = functionContext;
this.baseURI = baseURI;
this.locationData = locationData;
}
}
public static Configuration getGlobalConfiguration() {
return CONFIGURATION;
}
private static Configuration getConfiguration(PropertyContext propertyContext) {
// TEMP: XPath configuration from PropertyContext so we don't have to change all calls to XPath expressions
return (Configuration) propertyContext.getAttribute(XPATH_CACHE_CONFIGURATION_PROPERTY);
}
/**
* Evaluate an XPath expression on the document.
*/
public static List evaluate(PropertyContext propertyContext, Item contextItem, String xpathString,
NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
return evaluate(propertyContext, Collections.singletonList(contextItem), 1, xpathString, namespaceMapping,
variableToValueMap, functionLibrary, functionContext, baseURI, locationData);
}
/**
* Evaluate an XPath expression on the document.
*/
public static List evaluate(PropertyContext propertyContext, List<Item> contextItems, int contextPosition, String xpathString,
NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
final PooledXPathExpression xpathExpression = XPathCache.getXPathExpression(propertyContext,
getConfiguration(propertyContext), contextItems, contextPosition,
xpathString, namespaceMapping, variableToValueMap, functionLibrary, baseURI, false, locationData);
try {
return xpathExpression.evaluateKeepNodeInfo(functionContext);
} catch (Exception e) {
throw handleXPathException(e, xpathString, "evaluating XPath expression", locationData);
} finally {
if (xpathExpression != null)
xpathExpression.returnToPool();
}
}
/**
* Evaluate an XPath expression on the document and keep Item objects in the result.
*/
public static List<Item> evaluateKeepItems(PropertyContext propertyContext, List<Item> contextItems, int contextPosition,
String xpathString, NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
final PooledXPathExpression xpathExpression = XPathCache.getXPathExpression(propertyContext,
getConfiguration(propertyContext), contextItems, contextPosition,
xpathString, namespaceMapping, variableToValueMap, functionLibrary, baseURI, false, locationData);
try {
return xpathExpression.evaluateKeepItems(functionContext);
} catch (Exception e) {
throw handleXPathException(e, xpathString, "evaluating XPath expression", locationData);
} finally {
if (xpathExpression != null)
xpathExpression.returnToPool();
}
}
/**
* Evaluate the expression as a variable value usable by Saxon in further XPath expressions.
*/
public static SequenceExtent evaluateAsExtent(PropertyContext propertyContext, List<Item> contextItems, int contextPosition,
String xpathString, NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
final PooledXPathExpression xpathExpression = XPathCache.getXPathExpression(propertyContext,
getConfiguration(propertyContext), contextItems, contextPosition,
xpathString, namespaceMapping, variableToValueMap, functionLibrary, baseURI, false, locationData);
try {
return xpathExpression.evaluateAsExtent(functionContext);
} catch (Exception e) {
throw handleXPathException(e, xpathString, "evaluating XPath expression", locationData);
} finally {
if (xpathExpression != null)
xpathExpression.returnToPool();
}
}
/**
* Evaluate an XPath expression on the document.
*/
public static Object evaluateSingle(PropertyContext propertyContext, XPathCache.XPathContext xpathContext, Item contextItem, String xpathString) {
return evaluateSingle(propertyContext, Collections.singletonList(contextItem), 1, xpathString,
xpathContext.namespaceMapping, xpathContext.variableToValueMap, xpathContext.functionLibrary,
xpathContext.functionContext, xpathContext.baseURI, xpathContext.locationData);
}
/**
* Evaluate an XPath expression on the document.
*/
public static Object evaluateSingle(PropertyContext propertyContext, Item contextItem, String xpathString,
NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
return evaluateSingle(propertyContext, Collections.singletonList(contextItem), 1, xpathString, namespaceMapping,
variableToValueMap, functionLibrary, functionContext, baseURI, locationData);
}
/**
* Evaluate an XPath expression on the document.
*/
public static Object evaluateSingle(PropertyContext propertyContext, List<Item> contextItems, int contextPosition, String xpathString,
NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
final PooledXPathExpression xpathExpression = XPathCache.getXPathExpression(propertyContext,
getConfiguration(propertyContext), contextItems, contextPosition,
xpathString, namespaceMapping, variableToValueMap, functionLibrary, baseURI, false, locationData);
try {
return xpathExpression.evaluateSingleKeepNodeInfo(functionContext);
} catch (XPathException e) {
throw handleXPathException(e, xpathString, "evaluating XPath expression", locationData);
} finally {
if (xpathExpression != null)
xpathExpression.returnToPool();
}
}
/**
* Evaluate an XPath expression on the document as an attribute value template, and return its string value.
*/
public static String evaluateAsAvt(PropertyContext propertyContext, XPathCache.XPathContext xpathContext, Item contextItem, String xpathString) {
return evaluateAsAvt(propertyContext, Collections.singletonList(contextItem), 1, xpathString, xpathContext.namespaceMapping,
xpathContext.variableToValueMap, xpathContext.functionLibrary, xpathContext.functionContext, xpathContext.baseURI, xpathContext.locationData);
}
/**
* Evaluate an XPath expression on the document as an attribute value template, and return its string value.
*/
public static String evaluateAsAvt(PropertyContext propertyContext, Item contextItem, String xpathString, NamespaceMapping namespaceMapping,
Map<String, ValueRepresentation> variableToValueMap, FunctionLibrary functionLibrary,
FunctionContext functionContext, String baseURI, LocationData locationData) {
return evaluateAsAvt(propertyContext, Collections.singletonList(contextItem), 1, xpathString, namespaceMapping,
variableToValueMap, functionLibrary, functionContext, baseURI, locationData);
}
/**
* Evaluate an XPath expression on the document as an attribute value template, and return its string value.
*/
public static String evaluateAsAvt(PropertyContext propertyContext, List<Item> contextItems, int contextPosition, String xpathString,
NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
final PooledXPathExpression xpathExpression = XPathCache.getXPathExpression(propertyContext,
getConfiguration(propertyContext), contextItems, contextPosition, xpathString,
namespaceMapping, variableToValueMap, functionLibrary, baseURI, true, locationData);
try {
final Object result = xpathExpression.evaluateSingleKeepNodeInfo(functionContext);
return (result != null) ? result.toString() : null;
} catch (XPathException e) {
throw handleXPathException(e, xpathString, "evaluating XPath expression", locationData);
} finally {
if (xpathExpression != null) xpathExpression.returnToPool();
}
}
/**
* Evaluate an XPath expression and return its string value.
*/
public static String evaluateAsString(PropertyContext propertyContext, Item contextItem, String xpathString,
NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
return evaluateAsString(propertyContext, Collections.singletonList(contextItem), 1, xpathString, namespaceMapping,
variableToValueMap, functionLibrary, functionContext, baseURI, locationData);
}
/**
* Evaluate an XPath expression and return its string value.
*/
public static String evaluateAsString(PropertyContext propertyContext, List<Item> contextItems, int contextPosition,
String xpathString, NamespaceMapping namespaceMapping, Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary, FunctionContext functionContext, String baseURI, LocationData locationData) {
final PooledXPathExpression xpathExpression = XPathCache.getXPathExpression(propertyContext,
getConfiguration(propertyContext), contextItems, contextPosition, "xs:string((" + xpathString + ")[1])",
namespaceMapping, variableToValueMap, functionLibrary, baseURI, false, locationData);
try {
final Object result = xpathExpression.evaluateSingleKeepNodeInfo(functionContext);
return (result != null) ? result.toString() : null;
} catch (XPathException e) {
throw handleXPathException(e, xpathString, "evaluating XPath expression", locationData);
} finally {
if (xpathExpression != null) xpathExpression.returnToPool();
}
}
// NOTE: called from DelegationProcessor and ConcreteForEachProcessor
public static PooledXPathExpression getXPathExpression(PropertyContext propertyContext, Configuration configuration,
Item contextItem,
String xpathString,
LocationData locationData) {
return getXPathExpression(propertyContext, configuration, contextItem, xpathString, null, null, null, null, locationData);
}
public static PooledXPathExpression getXPathExpression(PropertyContext propertyContext, Configuration configuration,
Item contextItem,
String xpathString,
NamespaceMapping namespaceMapping,
LocationData locationData) {
return getXPathExpression(propertyContext, configuration, contextItem, xpathString, namespaceMapping, null, null, null, locationData);
}
public static PooledXPathExpression getXPathExpression(PropertyContext propertyContext, Configuration configuration,
Item contextItem,
String xpathString,
NamespaceMapping namespaceMapping,
Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary,
String baseURI,
LocationData locationData) {
final List<Item> contextItems = Collections.singletonList(contextItem);
return getXPathExpression(propertyContext, configuration, contextItems, 1, xpathString, namespaceMapping, variableToValueMap,
functionLibrary, baseURI, false, locationData);
}
/**
* Just attempt to compile an XPath expression. An exception is thrown if the expression is not statically correct.
* Any variable used by the expression is assumed to be in scope. The expression is not added to the cache.
*
* @param xpathString XPath string
* @param namespaceMapping namespace mapping
* @param functionLibrary function library
* @throws Exception if the expression is not correct
*/
public static void checkXPathExpression(Configuration configuration, String xpathString, NamespaceMapping namespaceMapping,
FunctionLibrary functionLibrary) throws Exception {
new XPathCachePoolableObjectFactory(null, configuration, xpathString, namespaceMapping, null, functionLibrary, null, false, true, null).makeObject();
}
public static Expression createExpression(Configuration configuration, String xpathString, NamespaceMapping namespaceMapping, FunctionLibrary functionLibrary) {
try {
return ((PooledXPathExpression) new XPathCachePoolableObjectFactory(null, configuration, xpathString, namespaceMapping,
null, functionLibrary, null, false, true, null).makeObject()).getExpression();
} catch (Exception e) {
throw new OXFException(e);
}
}
private static PooledXPathExpression getXPathExpression(PropertyContext propertyContext, Configuration configuration,
List<Item> contextItems, int contextPosition,
String xpathString,
NamespaceMapping namespaceMapping,
Map<String, ValueRepresentation> variableToValueMap,
FunctionLibrary functionLibrary,
String baseURI,
boolean isAvt,
LocationData locationData) {
try {
// Find pool from cache
final Long validity = (long) 0;
final Cache cache = ObjectCache.instance(XPATH_CACHE_NAME, XPATH_CACHE_DEFAULT_SIZE);
final StringBuilder cacheKeyString = new StringBuilder(xpathString);
if (functionLibrary != null) {// This is ok
cacheKeyString.append('|');
cacheKeyString.append(Integer.toString(functionLibrary.hashCode()));
}
// NOTE: Mike Kay confirms on 2007-07-04 that compilation depends on the namespace context, so we need
// to use it as part of the cache key.
if (namespaceMapping != null) {
// NOTE: Hash is mandatory in NamespaceMapping
cacheKeyString.append('|');
cacheKeyString.append(namespaceMapping.hash);
}
if (variableToValueMap != null && variableToValueMap.size() > 0) {
// There are some variables in scope. They must be part of the key
// TODO: Put this in static state as this can be determined statically once and for all
for (final String variableName: variableToValueMap.keySet()) {
cacheKeyString.append('|');
cacheKeyString.append(variableName);
}
}
// Add this to the key as evaluating "name" as XPath or as AVT is very different!
cacheKeyString.append('|');
cacheKeyString.append(Boolean.toString(isAvt));
// TODO: Add baseURI to cache key (currently, baseURI is pretty much unused)
// NOTE: Copy HashSet, as the one returned by the map keeps a pointer to the Map! This can cause the XPath
// cache to keep a reference to variable values, which in turn can keep a reference all the way to e.g. an
// XFormsContainingDocument.
final Set<String> variableNames = (variableToValueMap != null) ? new LinkedHashSet<String>(variableToValueMap.keySet()) : null;
final PooledXPathExpression pooledXPathExpression;
{
// Get or create pool
final InternalCacheKey cacheKey = new InternalCacheKey("XPath Expression2", cacheKeyString.toString());
ObjectPool pool = (ObjectPool) cache.findValid(propertyContext, cacheKey, validity);
if (pool == null) {
pool = createXPathPool(configuration, xpathString, namespaceMapping, variableNames, functionLibrary, baseURI, isAvt, locationData);
cache.add(propertyContext, cacheKey, validity, pool);
}
// Get object from pool
final Object o = pool.borrowObject();
pooledXPathExpression = (PooledXPathExpression) o;
}
// Set context items and position
pooledXPathExpression.setContextItems(contextItems, contextPosition);
// Set variables
pooledXPathExpression.setVariables(variableToValueMap);
return pooledXPathExpression;
} catch (Exception e) {
throw handleXPathException(e, xpathString, "preparing XPath expression", locationData);
}
}
private static ValidationException handleXPathException(Exception e, String xpathString, String description, LocationData locationData) {
final ValidationException validationException = ValidationException.wrapException(e, new ExtendedLocationData(locationData, description,
"expression", xpathString));
// Details of ExtendedLocationData passed are discarded by the constructor for ExtendedLocationData above,
// so we need to explicitly add them.
if (locationData instanceof ExtendedLocationData)
validationException.addLocationData(locationData);
return validationException;
}
private static ObjectPool createXPathPool(Configuration xpathConfiguration,
String xpathString,
NamespaceMapping namespaceMapping,
Set<String> variableNames,
FunctionLibrary functionLibrary,
String baseURI,
boolean isAvt,
LocationData locationData) {
try {
// TODO: pool should have at least one hard reference
final SoftReferenceObjectPool pool = new SoftReferenceObjectPool();
pool.setFactory(new XPathCachePoolableObjectFactory(pool, xpathConfiguration, xpathString,
namespaceMapping, variableNames, functionLibrary, baseURI, isAvt, false, locationData));
return pool;
} catch (Exception e) {
throw new OXFException(e);
}
}
private static class XPathCachePoolableObjectFactory implements PoolableObjectFactory {
private final ObjectPool pool;
private Configuration xpathConfiguration;
private final String xpathString;
private final NamespaceMapping namespaceMapping;
private final Set<String> variableNames;
// NOTE: storing the FunctionLibrary in cache is ok if it doesn't hold dynamic references (case of global XFormsFunctionLibrary)
private final FunctionLibrary functionLibrary;
private final String baseURI;
private final boolean isAvt;
private final boolean allowAllVariables;
private final LocationData locationData;
public XPathCachePoolableObjectFactory(ObjectPool pool,
Configuration xpathConfiguration,
String xpathString,
NamespaceMapping namespaceMapping,
Set<String> variableNames,
FunctionLibrary functionLibrary,
String baseURI,
boolean isAvt,
boolean allowAllVariables,
LocationData locationData) {
this.pool = pool;
this.xpathConfiguration = (xpathConfiguration != null) ? xpathConfiguration : XPathCache.getGlobalConfiguration();
this.xpathString = xpathString;
this.namespaceMapping = namespaceMapping;
this.variableNames = variableNames;
this.functionLibrary = functionLibrary;
this.baseURI = baseURI;
this.isAvt = isAvt;
this.allowAllVariables = allowAllVariables;
this.locationData = locationData;
}
public void activateObject(Object o) throws Exception {
}
public void destroyObject(Object o) throws Exception {
if (o instanceof PooledXPathExpression) {
PooledXPathExpression xp = (PooledXPathExpression) o;
xp.destroy();
} else
throw new OXFException(o.toString() + " is not a PooledXPathExpression");
}
/**
* Create and compile an XPath expression object.
*/
public Object makeObject() throws Exception {
if (logger.isDebugEnabled())
logger.debug("makeObject(" + xpathString + ")");
// Create context
final IndependentContext independentContext = new XPathCacheStaticContext(xpathConfiguration, allowAllVariables);
// Set the base URI if specified
if (baseURI != null)
independentContext.setBaseURI(baseURI);
// Declare namespaces
if (namespaceMapping != null) {
for (final Map.Entry<String, String> entry : namespaceMapping.mapping.entrySet()) {
independentContext.declareNamespace(entry.getKey(), entry.getValue());
}
}
// Declare variables (we don't use the values here, just the names)
final Map<String, XPathVariable> variables = new HashMap<String, XPathVariable>();
if (variableNames != null) {
for (final String name : variableNames) {
final XPathVariable variable = independentContext.declareVariable("", name);
variables.put(name, variable);
}
}
// Add function library
if (functionLibrary != null) {
((FunctionLibraryList) independentContext.getFunctionLibrary()).libraryList.add(0, functionLibrary);
}
return createPoolableXPathExpression(pool, independentContext, xpathString, variables, isAvt);
}
public void passivateObject(Object o) throws Exception {
}
public boolean validateObject(Object o) {
return true;
}
}
public static PooledXPathExpression createPoolableXPathExpression(ObjectPool pool, IndependentContext independentContext,
String xpathString, Map<String, XPathVariable> variables, boolean isAvt) {
// Create and compile the expression
try {
final XPathExpression expression;
if (isAvt) {
// AVT
final Expression tempExpression = AttributeValueTemplate.make(xpathString, -1, independentContext);
expression = prepareExpression(independentContext, tempExpression);
} else {
// Regular expression
final XPathEvaluator evaluator = new XPathEvaluator();
evaluator.setStaticContext(independentContext);
expression = evaluator.createExpression(xpathString);
}
return new PooledXPathExpression(expression, pool, variables);
} catch (Throwable t) {
throw new OXFException(t);
}
}
// Ideally: add this to Saxon XPathEvaluator
public static XPathExpression prepareExpression(IndependentContext independentContext, Expression expression) throws XPathException {
// Based on XPathEvaluator.createExpression()
expression.setContainer(independentContext);
ExpressionVisitor visitor = ExpressionVisitor.make(independentContext);
visitor.setExecutable(independentContext.getExecutable());
expression = visitor.typeCheck(expression, Type.ITEM_TYPE);
expression = visitor.optimize(expression, Type.ITEM_TYPE);
final SlotManager map = independentContext.getStackFrameMap();
final int numberOfExternalVariables = map.getNumberOfVariables();
ExpressionTool.allocateSlots(expression, numberOfExternalVariables, map);
// Set an evaluator as later it might be requested
final XPathEvaluator evaluator = new XPathEvaluator();
evaluator.setStaticContext(independentContext);
return new CustomXPathExpression(evaluator, expression, map, numberOfExternalVariables);
}
private static class CustomXPathExpression extends XPathExpression {
// private SlotManager slotManager;
protected CustomXPathExpression(XPathEvaluator evaluator, Expression exp, SlotManager map, int numberOfExternalVariables) {
super(evaluator, exp);
setStackFrameMap(map, numberOfExternalVariables);
// this.slotManager = map;
}
// Ideally: put this here instead of modifying Saxon, but then we need our own XPathEvaluator as well to return CustomXPathExpression
// public XPathDynamicContext createDynamicContext(XPathContextMajor context, Item contextItem) {
// // Set context item
// final UnfailingIterator contextIterator = SingletonIterator.makeIterator(contextItem);
// contextIterator.next();
// context.setCurrentIterator(contextIterator);
// context.openStackFrame(slotManager);
// return new XPathDynamicContext(context, slotManager);
}
/**
* Marker interface for XPath function context.
*/
public interface FunctionContext {}
}
|
package org.mitallast.queue.action.queue.enqueue;
import org.junit.Test;
import org.mitallast.queue.common.BaseQueueTest;
import org.mitallast.queue.queue.QueueMessage;
public class EnQueueActionTest extends BaseQueueTest {
@Test
public void testSingleThread() throws Exception {
createQueue();
// warm up
send(max());
long start = System.currentTimeMillis();
send(max());
long end = System.currentTimeMillis();
printQps("send", max(), start, end);
}
@Test
public void testMultiThread() throws Exception {
createQueue();
// warm up
send(max());
long start = System.currentTimeMillis();
executeConcurrent(() -> send(max()));
long end = System.currentTimeMillis();
printQps("send", total(), start, end);
}
private void send(int max) throws Exception {
for (int i = 0; i < max; i++) {
QueueMessage message = createMessage();
EnQueueRequest request = new EnQueueRequest(queueName(), message);
EnQueueResponse response = client().queue().enqueueRequest(request).get();
assert response.getUUID().equals(message.getUuid());
}
}
}
|
package orbitSimulator;
import java.awt.Font;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Array;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import java.awt.Color;
public class EllipticalOrbitInputs extends JPanel implements ActionListener {
// input text fields - NB need to add each new tf to getUserInputs() and a private parameter below
private JTextField tfArgOfPeri;
private JTextField tfPeriapsis;
private JTextField tfApoapsis;
private JTextField tfSemimajorAxis;
private JTextField tfEccentricity;
private JTextField tfPeriod;
private JTextField tfRAAN;
private double ArgOfPeri;
private double Periapsis;
private double Apoapsis;
private double SemimajorAxis;
private double Eccentricity;
private double OrbitalPeriod;
private double RAAN;
private double Period;
private boolean ArgOfPeriAdded;
private boolean PeriapsisAdded;
private boolean ApoapsisAdded;
private boolean SemimajorAxisAdded;
private boolean EccentricityAdded;
private boolean OrbitalPeriodAdded;
private boolean RAANAdded;
private boolean PeriodAdded;
private JButton btnCalculateEllipticalOrbit;
private MainFrameListenerElliptical newGraphicsListener;
private JTextField tfSME;
private JTextField tfVelocity;
private JTextField tfInclination;
private DocumentListener tfListener;
EllipticalOrbitInputs()
{
setLayout(new MigLayout("", "[22.00][18.00][29.00][83.00][59.00][73.00][81.00]", "[][][][12.00][][14.00][][center][][][][]"));
JLabel lblEllipticalOrbitInputs = new JLabel("Elliptical Orbit Inputs");
lblEllipticalOrbitInputs.setFont(new Font("Lucida Grande", Font.BOLD, 13));
add(lblEllipticalOrbitInputs, "cell 0 0 4 1");
JLabel lblArgumentOfPeriapsis = new JLabel("Arg of Periapsis");
lblArgumentOfPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblArgumentOfPeriapsis, "cell 1 1 2 1");
tfArgOfPeri = new JTextField();
tfArgOfPeri.setBackground(Color.WHITE);
tfArgOfPeri.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfArgOfPeri, "cell 3 1,growx");
tfArgOfPeri.setColumns(10);
JLabel lblRadius = new JLabel("Radius");
lblRadius.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblRadius, "cell 1 2 2 1");
JLabel lblPeriapsis = new JLabel("Periapsis");
lblPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblPeriapsis, "cell 2 3,alignx left");
tfPeriapsis = new JTextField();
tfPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfPeriapsis, "cell 3 3,growx");
tfPeriapsis.setColumns(10);
JLabel lblApoapsis = new JLabel("Apoapsis");
lblApoapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblApoapsis, "cell 4 3,alignx left");
tfApoapsis = new JTextField();
tfApoapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfApoapsis, "cell 5 3,growx");
tfApoapsis.setColumns(10);
JLabel lblSemimajorAxis = new JLabel("Semimajor Axis");
lblSemimajorAxis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblSemimajorAxis, "cell 1 4 2 1");
tfSemimajorAxis = new JTextField();
tfSemimajorAxis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfSemimajorAxis, "cell 3 4,growx");
tfSemimajorAxis.setColumns(10);
JLabel lblEccentricity = new JLabel("Eccentricity");
lblEccentricity.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblEccentricity, "cell 1 5 2 1");
tfEccentricity = new JTextField();
tfEccentricity.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfEccentricity, "cell 3 5,growx");
tfEccentricity.setColumns(10);
JLabel lblInclination = new JLabel("Inclination");
lblInclination.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblInclination, "cell 1 6 2 1,alignx left");
tfInclination = new JTextField();
tfInclination.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfInclination, "cell 3 6,growx,aligny top");
tfInclination.setColumns(10);
JLabel lblVelecity = new JLabel("Velocity @");
lblVelecity.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblVelecity, "cell 1 7 2 1,alignx left");
JComboBox comboBox = new JComboBox();
comboBox.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(comboBox, "cell 3 7,growx");
tfVelocity = new JTextField();
tfVelocity.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfVelocity, "cell 4 7 2 1,growx");
tfVelocity.setColumns(10);
JLabel lblSME = new JLabel("SME");
lblSME.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblSME, "cell 1 8 2 1");
tfSME = new JTextField();
tfSME.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfSME, "cell 3 8,growx");
tfSME.setColumns(10);
JLabel lblRaan = new JLabel("RAAN");
lblRaan.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblRaan, "cell 1 9 2 1");
tfRAAN = new JTextField();
tfRAAN.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfRAAN, "cell 3 9,growx");
tfRAAN.setColumns(10);
JLabel lblOrbitalPeriod = new JLabel("Orbital Period");
lblOrbitalPeriod.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblOrbitalPeriod, "cell 1 10 2 1,alignx left");
tfPeriod = new JTextField();
tfPeriod.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfPeriod, "cell 3 10,growx,aligny top");
tfPeriod.setColumns(10);
btnCalculateEllipticalOrbit = new JButton("Calculate Orbit");
btnCalculateEllipticalOrbit.addActionListener(this);
add(btnCalculateEllipticalOrbit, "cell 4 11 3 1");
// Listen for changes to textFields
tfArgOfPeri.getDocument().putProperty("owner", tfArgOfPeri);
tfArgOfPeri.setName("argofperi");
tfPeriapsis.getDocument().putProperty("owner", tfPeriapsis);
tfPeriapsis.setName("periapsis");
tfApoapsis.getDocument().putProperty("owner", tfApoapsis);
tfApoapsis.setName("apoapsis");
tfSemimajorAxis.getDocument().putProperty("owner", tfSemimajorAxis);
tfSemimajorAxis.setName("SemimajorAxis");
tfEccentricity.getDocument().putProperty("owner", tfEccentricity);
tfEccentricity.setName("Eccentricity");
tfInclination.getDocument().putProperty("owner", tfInclination);
tfInclination.setName("Inclination");
tfVelocity.getDocument().putProperty("owner", tfVelocity);
tfVelocity.setName("Velocity");
tfSME.getDocument().putProperty("owner", tfSME);
tfSME.setName("sme");
tfPeriod.getDocument().putProperty("owner", tfPeriod);
tfPeriod.setName("Period");
tfRAAN.getDocument().putProperty("owner", tfRAAN);
tfRAAN.setName("RAAN");
DocumentListener docListener = new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
doStuff(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
doStuff(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
doStuff(e);
}
private void doStuff(DocumentEvent e) {
Object owner = e.getDocument().getProperty("owner");
String tfName = ((JTextField) owner).getName();
System.out.println("the textfield that changed is: " + tfName);
// enableDetachButton(getRootPane());
// changeColor((JTextField) owner);
}
};
tfArgOfPeri.getDocument().addDocumentListener(docListener);
tfPeriapsis.getDocument().addDocumentListener(docListener);
tfApoapsis.getDocument().addDocumentListener(docListener);
tfSemimajorAxis.getDocument().addDocumentListener(docListener);
tfEccentricity.getDocument().addDocumentListener(docListener);
tfInclination.getDocument().addDocumentListener(docListener);
tfVelocity.getDocument().addDocumentListener(docListener);
tfSME.getDocument().addDocumentListener(docListener);
tfPeriod.getDocument().addDocumentListener(docListener);
tfRAAN.getDocument().addDocumentListener(docListener);
/*tfArgOfPeri.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfPeriapsis.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfApoapsis.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfSemimajorAxis.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfEccentricity.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfInclination.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfVelocity.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfSME.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfPeriod.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfRAAN.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});*/
} // END CONSTRUCTOR
// listener model view controller architecture
public void setNewGraphics(MainFrameListenerElliptical listener)
{
System.out.println("setNewGraphics()");
this.newGraphicsListener = listener;
}
/*@Override - I'm not sure why this isnt required as it is in CircularOrbitInputs using the same architecture.
The only possibility I can think of is that circularPanel has a button which may mean that it needs
overriding.*/
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("in actionPerformed(ActionEvent e)");
//getOrbitRenderScale();
calculateEllipticalOrbit();
newGraphicsListener.setNewGraphics();
}
private void getOrbitRenderScale() {
// TODO Auto-generated method stub
}
private void calculateEllipticalOrbit() {
System.out.println("in calculateEllipticalOrbit()");
// get all the inputs and set them to private parameters
getUserInputs();
// calculations (multiple methods)
// write calculated values to relevant text fields
}
private void getUserInputs() {
if (isNumeric(tfArgOfPeri.getText()) == true) {
ArgOfPeri = Double.parseDouble(tfArgOfPeri.getText());
ArgOfPeriAdded = true;
}
else {
ArgOfPeriAdded = false;
}
//System.out.println("ArgOfPeri = " + ArgOfPeri);
if (isNumeric(tfPeriapsis.getText()) == true) {
Periapsis = Double.parseDouble(tfPeriapsis.getText());
PeriapsisAdded = true;
}
else {
PeriapsisAdded = false;
}
//System.out.println("Periapsis = " + Periapsis);
if (isNumeric(tfApoapsis.getText()) == true) {
Apoapsis = Double.parseDouble(tfApoapsis.getText());
ApoapsisAdded = true;
}
else {
ApoapsisAdded = false;
}
//System.out.println("Apoapsis = " + Apoapsis);
if (isNumeric(tfSemimajorAxis.getText()) == true) {
SemimajorAxis = Double.parseDouble(tfSemimajorAxis.getText());
SemimajorAxisAdded = true;
}
else {
SemimajorAxisAdded = false;
}
//System.out.println("SemimajorAxis = " + SemimajorAxis);
if (isNumeric(tfEccentricity.getText()) == true) {
Eccentricity = Double.parseDouble(tfEccentricity.getText());
EccentricityAdded = true;
}
else {
EccentricityAdded = false;
}
//System.out.println("Eccentricity = " + Eccentricity);
if (isNumeric(tfPeriod.getText()) == true) {
OrbitalPeriod = Double.parseDouble(tfPeriod.getText());
OrbitalPeriodAdded = true;
}
else {
OrbitalPeriodAdded = false;
}
//System.out.println("OrbitalPeriod = " + OrbitalPeriod);
if (isNumeric(tfRAAN.getText()) == true) {
RAAN = Double.parseDouble(tfRAAN.getText());
RAANAdded = true;
}
else {
RAANAdded = false;
}
//System.out.println("RANN = " + RAAN);
if (isNumeric(tfPeriod.getText()) == true) {
Period = Double.parseDouble(tfPeriod.getText());
PeriodAdded = true;
}
else {
PeriodAdded = false;
}
//System.out.println("Period = " + Period);
}
public static void resetEllipticalPanel() {
// TODO Auto-generated method stub
}
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
|
package org.appwork.controlling;
import java.util.ArrayList;
import org.appwork.utils.logging.Log;
public class StateMachine {
private State initState;
private State currentState;
private StateEventsender eventSender;
private State finalState;
private ArrayList<State> path;
private StateMachineInterface owner;
private Object lock = new Object();
/**
* @param interfac
* TODO
* @param initState2
* @param stoppedState
*/
public StateMachine(StateMachineInterface interfac, State startState, State endState) {
owner = interfac;
initState = startState;
currentState = startState;
finalState = endState;
this.eventSender = new StateEventsender();
this.path = new ArrayList<State>();
path.add(initState);
}
/**
* @return the owner
*/
public StateMachineInterface getOwner() {
return owner;
}
/**
* validates a statechain and checks if all states can be reached, and if
* all chans result in one common finalstate
*
* @param initState2
* @throws StateConflictException
*/
public static void validateStateChain(State initState) {
if (initState.getParents().size() > 0) throw new StateConflictException("initState must not have a parent");
checkState(initState);
}
/**
* @param s
* @return
* @throws StateConflictException
*/
private static State checkState(State state) {
State finalState = null;
for (State s : state.getChildren()) {
State ret = checkState(s);
if (finalState == null) finalState = ret;
if (finalState != ret) throw new StateConflictException("States do not all result in one common final state");
}
if (finalState == null) { throw new StateConflictException(state + " is a blind state (has no children)"); }
return finalState;
}
/**
* @param addLinkState
*/
public synchronized void setStatus(State newState) {
if (currentState == newState) return;
if (!currentState.getChildren().contains(newState)) { throw new StateConflictException("Cannot change state from " + currentState + " to " + newState); }
this.forceState(newState);
}
public void fireUpdate(State currentState) {
if (currentState != null) {
if (this.currentState != currentState) throw new StateConflictException("Cannot update state " + currentState + " because current state is " + this.currentState);
}
StateEvent event = new StateEvent(this, StateEvent.UPDATED, currentState, currentState);
eventSender.fireEvent(event);
}
/**
* @param canceledState
* @param progressUpdate
* @return
*/
public boolean isState(State... states) {
// TODO Auto-generated method stub
for (State s : states) {
if (s == currentState) return true;
}
return false;
}
/**
* @param remoteUpload
*/
public void addListener(StateEventListener listener) {
eventSender.addListener(listener);
}
/**
* @param transferController
*/
public void removeListener(StateEventListener listener) {
eventSender.removeListener(listener);
}
public void reset() {
StateEvent event;
synchronized (lock) {
if (currentState == initState) return;
if (finalState != currentState) throw new StateConflictException("Cannot reset from state " + currentState);
event = new StateEvent(this, StateEvent.CHANGED, currentState, initState);
this.currentState = this.initState;
path.clear();
path.add(initState);
}
eventSender.fireEvent(event);
}
/**
* @return
*/
public boolean isFinal() {
// TODO Auto-generated method stub
return finalState == currentState;
}
/**
* @param parseInt
*/
public void forceState(int id) {
State newState;
synchronized (lock) {
newState = getStateById(this.initState, id, null);
if (newState == null) throw new StateConflictException("No State with ID " + id);
}
forceState(newState);
}
/**
* @param newState
*/
public void forceState(State newState) {
StateEvent event;
synchronized (lock) {
if (currentState == newState) return;
event = new StateEvent(this, StateEvent.CHANGED, currentState, newState);
path.add(newState);
Log.L.finest(owner + " State changed " + currentState + " -> " + newState);
currentState = newState;
}
eventSender.fireEvent(event);
}
/**
* @param id
* @return
*/
private State getStateById(State startState, int id, ArrayList<State> foundStates) {
if (foundStates == null) foundStates = new ArrayList<State>();
if (foundStates.contains(startState)) return null;
foundStates.add(startState);
State ret = null;
for (State s : startState.getChildren()) {
if (s.getID() == id) return s;
ret = getStateById(s, id, foundStates);
if (ret != null) return ret;
}
return null;
}
/**
* @param statusErrorUploadUnknown
* @param statusErrorFilesizeToBig
* @param statusErrorDownloadUnknown
* @param statusFinished
* @return
*/
public boolean hasPassed(State... states) {
for (State s : states) {
if (path.contains(s)) return true;
}
return false;
}
/**
* returns if the statemachine is in startstate currently
*
* @return
*/
public boolean isStartState() {
// TODO Auto-generated method stub
return currentState == this.initState;
}
/**
* @return
*/
public State getState() {
// TODO Auto-generated method stub
return currentState;
}
}
|
package org.biojava.spice.Panel;
// Swing dependencies
import javax.swing.JTable;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.table.TableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TableModelListener ;
import javax.swing.event.TableModelEvent ;
import javax.swing.DefaultCellEditor;
import javax.swing.ListSelectionModel ;
import javax.swing.JButton;
import javax.swing.Box;
import java.awt.event.ActionEvent ;
import java.awt.event.ActionListener ;
// AWT
import java.awt.Color;
import java.awt.Frame;
import java.awt.Dialog;
import java.awt.Component;
import java.awt.BorderLayout;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.BorderLayout ;
// Logging
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
// Collections
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
// Resources
// disabled by Andreas Prlic
//import org.geotools.resources.XArray;
//import org.geotools.resources.gui.Resources;
//import org.geotools.resources.gui.ResourceKeys;
//import org.geotools.resources.SwingUtilities;
/**
* THis class is taken from the LGPL package Geotools.
*
* A panel displaying logging messages. The windows displaying Geotools's logging messages
* can be constructed with the following code:
*
* <blockquote><pre>
* new LoggingPanel("org.biojava.spice").{@link #show(Component) show}(null);
* </pre></blockquote>
*
* This panel is initially set to listen to messages of level {@link Level#CONFIG} or higher.
* This level can be changed with <code>{@link #getHandler}.setLevel(aLevel)</code>.
*
* @version $Id: LoggingPanel.java,v 1.10 2003/06/03 18:09:26 desruisseaux Exp $
* @author Martin Desruisseaux
*/
public class LoggingPanel extends JPanel {
JScrollPane scroll ;
/**
* Enumeration class for columns to be shown in a {@link LoggingPanel}.
* Valid columns include {@link #LOGGER LOGGER}, {@link #CLASS CLASS},
* {@link #METHOD METHOD}, {@link #TIME_OF_DAY TIME_OF_DAY}, {@link #LEVEL LEVEL}
* and {@link #MESSAGE MESSAGE}.
*
* @task TODO: Use the enum keyword once J2SE 1.5 will be available.
*/
public static final class Column {
final int index;
Column(final int index) {
this.index = index;
}
}
/*
* NOTE: Values for the following contants MUST match
* index in the LoggingTableModel.COLUMN_NAMES array.
*/
/** Constant for {@link #setColumnVisible}. */ public static final Column LOGGER = new Column(0);
/** Constant for {@link #setColumnVisible}. */ public static final Column CLASS = new Column(1);
/** Constant for {@link #setColumnVisible}. */ public static final Column METHOD = new Column(2);
/** Constant for {@link #setColumnVisible}. */ public static final Column TIME_OF_DAY = new Column(3);
/** Constant for {@link #setColumnVisible}. */ public static final Column LEVEL = new Column(4);
/** Constant for {@link #setColumnVisible}. */ public static final Column MESSAGE = new Column(5);
/**
* The background color for the columns prior to the logging message.
*/
private static final Color INFO_BACKGROUND = new Color(240,240,240);
/**
* The model for this component.
*/
private final LoggingTableModel model = new LoggingTableModel();
/**
* The table for displaying logging messages.
*/
private final JTable table = new JTable(model);
/**
* The levels for colors enumerated in <code>levelColors</code>. This array
* <strong>must</strong> be in increasing order. Logging messages of level
* <code>levelValues[i]</code> or higher will be displayed with foreground
* color <code>levelColors[i*2]</code> and background color <code>levelColors[i*2+1]</code>.
*
* @see Level#intValue
* @see #getForeground(LogRecord)
* @see #getBackground(LogRecord)
*/
private int[] levelValues = new int[0];
/**
* Pairs of foreground and background colors to use for displaying logging messages.
* Logging messages of level <code>levelValues[i]</code> or higher will be displayed
* with foreground color <code>levelColors[i*2]</code> and background color
* <code>levelColors[i*2+1]</code>.
*
* @see #getForeground(LogRecord)
* @see #getBackground(LogRecord)
*/
private final List levelColors = new ArrayList();
/**
* The logger specified at construction time, or <code>null</code> if none.
*/
private Logger logger;
/**
* Constructs a new logging panel. This panel is not registered to any logger.
* Registration can be done with the following code:
*
* <blockquote><pre>
* logger.{@link Logger#addHandler addHandler}({@link #getHandler});
* </pre></blockquote>
*/
public LoggingPanel() {
super(new BorderLayout());
table.setShowGrid(false);
// by AP
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setCellSelectionEnabled(true);
table.setGridColor(Color.LIGHT_GRAY);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setDefaultRenderer(Object.class, new CellRenderer());
if (true) {
int width = 300;
final TableColumnModel columns = table.getColumnModel();
for (int i=model.getColumnCount(); --i>=0;) {
columns.getColumn(i).setPreferredWidth(width);
width = 80;
}
}
scroll = new JScrollPane(table);
// added a new record, scroll to end
model.addTableModelListener(new TableModelListener(){
public void tableChanged(TableModelEvent e){
if ( e.getType() == TableModelEvent.INSERT ) {
scroll.getVerticalScrollBar().setValue(scroll.getVerticalScrollBar().getMaximum());
}
}
});
Box vBox = Box.createVerticalBox();
vBox.add(scroll);
// modifications by AP 20050305
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener(){
// button is pressed
public void actionPerformed(ActionEvent e) {
LoggingTableModel ltm = (LoggingTableModel) table.getModel();
ltm.clearRecords();
table.repaint();
}
});
//Box hBox = Box.createHorizontalBox();
//hBox.add(clearButton,BorderLayout.WEST);
//vBox.add(Box.createGlue());
//vBox.add(clearButton);
/*JButton close = new JButton("Close");
close.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
/hm do not know about frame here :-/
dispose();
}
});
*/
Box hBoxb = Box.createHorizontalBox();
hBoxb.add(Box.createGlue());
hBoxb.add(clearButton,BorderLayout.EAST);
//hBoxb.add(close,BorderLayout.EAST);
vBox.add(hBoxb);
add(vBox);
setLevelColor(Level.ALL, Color.GRAY, null);
setLevelColor(Level.CONFIG, null, null);
setLevelColor(Level.WARNING, Color.RED, null);
setLevelColor(Level.SEVERE, Color.WHITE, Color.RED);
}
/**
* Constructs a new logging panel and register it to the specified logger.
*
* @param logger The logger to listen to, or <code>null</code> for the root logger.
*/
public LoggingPanel(Logger logger) {
this();
if (logger == null) {
logger = Logger.getLogger("");
}
logger.addHandler(getHandler());
this.logger = logger;
}
/**
* Construct a logging panel and register it to the specified logger.
*
* @param logger The logger name to listen to, or <code>null</code> for the root logger.
*/
public LoggingPanel(final String logger) {
this(Logger.getLogger(logger!=null ? logger : ""));
}
/**
* Returns the logging handler.
*/
public Handler getHandler() {
return model;
}
/**
* Returns <code>true</code> if the given column is visible.
*
* @param column The column to show or hide. May be one of {@link #LOGGER}, {@link #CLASS},
* {@link #METHOD}, {@link #TIME_OF_DAY}, {@link #LEVEL} or {@link #MESSAGE}.
*/
public boolean isColumnVisible(final Column column) {
return model.isColumnVisible(column.index);
}
/**
* Show or hide the given column.
*
* @param column The column to show or hide. May be one of {@link #LOGGER}, {@link #CLASS},
* {@link #METHOD}, {@link #TIME_OF_DAY}, {@link #LEVEL} or {@link #MESSAGE}.
* @param visible The visible state for the specified column.
*/
public void setColumnVisible(final Column column, final boolean visible) {
model.setColumnVisible(column.index, visible);
}
/**
* Returns the capacity. This is the maximum number of {@link LogRecord}s the handler
* can memorize. If more messages are logged, then the earliest messages will be discarted.
*/
public int getCapacity() {
return model.getCapacity();
}
/**
* Set the capacity. This is the maximum number of {@link LogRecord}s the handler can
* memorize. If more messages are logged, then the earliest messages will be discarted.
*/
public void setCapacity(final int capacity) {
model.setCapacity(capacity);
}
/**
* Returns the foreground color for the specified log record. This method is invoked at
* rendering time for every cell in the table's "message" column. The default implementation
* returns a color based on the record's level, using colors set with {@link #setLevelColor}.
*
* @param record The record to get the foreground color.
* @return The foreground color for the specified record,
* or <code>null</code> for the default color.
*/
public Color getForeground(final LogRecord record) {
return getColor(record, 0);
}
/**
* Returns the background color for the specified log record. This method is invoked at
* rendering time for every cell in the table's "message" column. The default implementation
* returns a color based on the record's level, using colors set with {@link #setLevelColor}.
*
* @param record The record to get the background color.
* @return The background color for the specified record,
* or <code>null</code> for the default color.
*/
public Color getBackground(final LogRecord record) {
return getColor(record, 1);
}
/**
* Returns the foreground or background color for the specified record.
*
* @param record The record to get the color.
* @param offset 0 for the foreground color, or 1 for the background color.
* @return The color for the specified record, or <code>null</code> for the default color.
*/
private Color getColor(final LogRecord record, final int offset) {
int i = Arrays.binarySearch(levelValues, record.getLevel().intValue());
if (i < 0) {
i = ~i - 1; // "~" is the tild symbol, not minus.
if (i < 0) {
return null;
}
}
return (Color) levelColors.get(i*2 + offset);
}
// by AP
// replacement for XArray lib from geotools
private int[] insertArray( int[] array, int index, int length) {
if (length == 0) {
return array;
}
int arrayLength = array.length ;
int[] newArray = new int[arrayLength + length ];
System.arraycopy(array, 0, newArray, 0, index );
System.arraycopy(array, index, newArray, index+length, arrayLength-index);
return (int[]) newArray;
}
/**
* Set the foreground and background colors for messages of the specified level.
* The specified colors will apply on any messages of level <code>level</code> or
* greater, up to the next level set with an other call to <code>setLevelColor(...)</code>.
*
* @param level The minimal level to set color for.
* @param foreground The foreground color, or <code>null</code> for the default color.
* @param background The background color, or <code>null</code> for the default color.
*/
public void setLevelColor(final Level level, final Color foreground, final Color background) {
final int value = level.intValue();
int i = Arrays.binarySearch(levelValues, value);
if (i >= 0) {
i *= 2;
levelColors.set(i+0, foreground);
levelColors.set(i+1, background);
} else {
i = ~i;
// by AP
levelValues = insertArray(levelValues, i, 1);
levelValues[i] = value;
i *= 2;
levelColors.add(i+0, foreground);
levelColors.add(i+1, background);
}
// by AP
//assert XArray.isSorted(levelValues);
assert levelValues.length*2 == levelColors.size();
}
/**
* Layout this component. This method give all the remaining space, if any,
* to the last table's column. This column is usually the one with logging
* messages.
*/
public void doLayout() {
final TableColumnModel model = table.getColumnModel();
final int messageColumn = model.getColumnCount()-1;
Component parent = table.getParent();
int delta = parent.getWidth();
if ((parent=parent.getParent()) instanceof JScrollPane) {
delta -= ((JScrollPane) parent).getVerticalScrollBar().getPreferredSize().width;
}
for (int i=0; i<messageColumn; i++) {
delta -= model.getColumn(i).getWidth();
}
final TableColumn column = model.getColumn(messageColumn);
if (delta > Math.max(column.getWidth(), column.getPreferredWidth())) {
column.setPreferredWidth(delta);
}
super.doLayout();
}
/**
* Convenience method showing this logging panel into a frame.
* Different kinds of frame can be constructed according <code>owner</code> class:
*
* <ul>
* <li>If <code>owner</code> or one of its parent is a {@link JDesktopPane},
* then <code>panel</code> is added into a {@link JInternalFrame}.</li>
* <li>If <code>owner</code> or one of its parent is a {@link Frame} or a {@link Dialog},
* then <code>panel</code> is added into a {@link JDialog}.</li>
* <li>Otherwise, <code>panel</code> is added into a {@link JFrame}.</li>
* </ul>
*
* @param owner The owner, or <code>null</code> to show
* this logging panel in a top-level window.
* @return The frame. May be a {@link JInternalFrame},
* a {@link JDialog} or a {@link JFrame}.
*/
public Component show(final Component owner) {
int frameWidth = 750 ;
int frameHeight = 300 ;
// Get the size of the default screen
java.awt.Dimension dim = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
//System.out.println("LoggingPanel show!!!!!!!");
JFrame frame = new JFrame();
frame.setLocation((dim.width - frameWidth),(dim.height - frameHeight));
frame.setTitle("SPICE - log");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosed(WindowEvent event) {
dispose();
}
});
frame.getContentPane().add(this);
frame.pack();
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
doLayout();
frame.show();
return frame;
}
/**
* Free any resources used by this <code>LoggingPanel</code>. If a {@link Logger} was
* specified at construction time, then this method unregister the <code>LoggingPanel</code>'s
* handler from the specified logger. Next, {@link Handler#close} is invoked.
* <br><br>
* This method is invoked automatically when the user close the windows created
* with {@link #show(Component)}. If this <code>LoggingPanel</code> is displayed
* by some other ways (for example if it has been added into a {@link JPanel}),
* then this <code>dispose()</code> should be invoked explicitely when the container
* is being discarted.
*/
public void dispose() {
final Handler handler = getHandler();
while (logger != null) {
logger.removeHandler(handler);
logger = logger.getParent();
}
handler.close();
}
/**
* Display cell contents. This class is used for changing
* the cell's color according the log record level.
*/
private final class CellRenderer extends DefaultTableCellRenderer
implements TableColumnModelListener
{
/**
* Default color for the foreground.
*/
private Color foreground;
/**
* Default color for the background.
*/
private Color background;
/**
* The index of messages column.
*/
private int messageColumn;
/**
* The last row for which the side has been computed.
*/
private int lastRow;
/**
* Construct a new cell renderer.
*/
public CellRenderer() {
foreground = super.getForeground();
background = super.getBackground();
table.getColumnModel().addColumnModelListener(this);
}
/**
* Set the foreground color.
*/
public void setForeground(final Color foreground) {
super.setForeground(this.foreground=foreground);
}
/**
* Set the background colior
*/
public void setBackground(final Color background) {
super.setBackground(this.background=background);
}
/**
* Returns the component to use for painting the cell.
*/
public Component getTableCellRendererComponent(final JTable table,
final Object value,
final boolean isSelected,
final boolean hasFocus,
final int rowIndex,
final int columnIndex)
{
//System.out.println("LoggingPanel getTableCellrendererComponent");
Color foreground = this.foreground;
Color background = this.background;
final boolean isMessage = (columnIndex == messageColumn);
if (!isMessage) {
background = INFO_BACKGROUND;
}
if (rowIndex >= 0) {
final TableModel candidate = table.getModel();
if (candidate instanceof LoggingTableModel) {
final LoggingTableModel model = (LoggingTableModel) candidate;
final LogRecord record = model.getLogRecord(rowIndex);
Color color;
color=LoggingPanel.this.getForeground(record); if (color!=null) foreground=color;
color=LoggingPanel.this.getBackground(record); if (color!=null) background=color;
}
}
super.setBackground(background);
super.setForeground(foreground);
final Component component = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, rowIndex, columnIndex);
/*
* If a new record is being painted and this new record is wider
* than previous ones, then make the message column width larger.
*/
if (isMessage) {
if (rowIndex > lastRow) {
final int width = component.getPreferredSize().width + 15;
final TableColumn column = table.getColumnModel().getColumn(columnIndex);
if (width > column.getPreferredWidth()) {
column.setPreferredWidth(width);
}
if (rowIndex == lastRow+1) {
lastRow = rowIndex;
}
}
}
return component;
}
/**
* Invoked when the message column may have moved. This method update the
* {@link #messageColumn} field, so that the message column will continue
* to be paint with special colors.
*/
private final void update() {
messageColumn = table.convertColumnIndexToView(model.getColumnCount()-1);
}
public void columnAdded (TableColumnModelEvent e) {update();}
public void columnMarginChanged (ChangeEvent e) {update();}
public void columnMoved (TableColumnModelEvent e) {update();}
public void columnRemoved (TableColumnModelEvent e) {update();}
public void columnSelectionChanged(ListSelectionEvent e) {update();}
}
}
|
package org.ensembl.healthcheck;
import java.util.logging.Logger;
/**
* Typesafe "enum" to store information about the type of a database. Declared final since it only
* has private constructors.
*/
public final class DatabaseType {
/** A core database */
public static final DatabaseType CORE = new DatabaseType("core");
/** An EST database */
public static final DatabaseType EST = new DatabaseType("est");
/** An ESTgene database */
public static final DatabaseType ESTGENE = new DatabaseType("estgene");
/** A Vega database */
public static final DatabaseType VEGA = new DatabaseType("vega");
/** A Compara database */
public static final DatabaseType COMPARA = new DatabaseType("compara");
/** A Mart database */
public static final DatabaseType MART = new DatabaseType("mart");
/** A variation database */
public static final DatabaseType VARIATION = new DatabaseType("variation");
/** A disease database */
public static final DatabaseType DISEASE = new DatabaseType("disease");
/** A haplotype database */
public static final DatabaseType HAPLOTYPE = new DatabaseType("haplotype");
/** A lite database */
public static final DatabaseType LITE = new DatabaseType("lite");
/** A GO database */
public static final DatabaseType GO = new DatabaseType("go");
/** An expression database */
public static final DatabaseType EXPRESSION = new DatabaseType("expression");
/** An xref database */
public static final DatabaseType XREF = new DatabaseType("xref");
/** An cDNA database */
public static final DatabaseType CDNA = new DatabaseType("cdna");
/** A database whos type has not been determined */
public static final DatabaseType UNKNOWN = new DatabaseType("unknown");
private final String name;
private DatabaseType(final String name) {
this.name = name;
}
/**
* @return a String representation of this DatabaseType object.
*/
public String toString() {
return this.name;
}
/**
* Resolve an alias to a DatabaseType object.
*
* @param alias The alias (e.g. core).
* @return The DatabaseType object corresponding to alias, or DatabaseType.UNKNOWN if it cannot
* be resolved.
*/
public static DatabaseType resolveAlias(final String alias) {
String lcAlias = alias.toLowerCase();
// needs to be before core and est since names
// are of the form homo_sapiens_core_expression_est_24_34e
if (in(lcAlias, "expression")) {
return EXPRESSION;
}
if (in(lcAlias, "core")) {
return CORE;
}
if (in(lcAlias, "est")) {
return EST;
}
if (in(lcAlias, "estgene")) {
return ESTGENE;
}
if (in(lcAlias, "compara")) {
return COMPARA;
}
if (in(lcAlias, "mart")) {
return MART;
}
if (in(lcAlias, "vega")) {
return VEGA;
}
if (in(lcAlias, "variation")) {
return VARIATION;
}
if (in(lcAlias, "disease")) {
return DISEASE;
}
if (in(lcAlias, "haplotype")) {
return HAPLOTYPE;
}
if (in(lcAlias, "lite")) {
return LITE;
}
if (in(lcAlias, "go")) {
return GO;
}
if (in(lcAlias, "expression")) {
return EXPRESSION;
}
if (in(lcAlias, "xref")) {
return XREF;
}
if (in(lcAlias, "cdna")) {
return CDNA;
}
// default case
return UNKNOWN;
} // resolveAlias
/**
* Return true if alias appears somewhere in comma-separated list.
*/
private static boolean in(final String alias, final String list) {
return (list.indexOf(alias) > -1);
}
/**
* Check if a DatabaseType is generic (core, est, estgene, vega).
* @return true if t is core, est, estgene or vega.
*/
public boolean isGeneric() {
if (name.equals("core") || name.equals("est") || name.equals("estgene") || name.equals("vega") || name.equals("cdna")) {
return true;
}
return false;
}
} // DatabaseType
|
package org.ensembl.healthcheck;
import java.util.*;
import java.util.logging.*;
import org.ensembl.healthcheck.testcase.*;
/**
* Subclass of TestRunner that lists all tests.
*/
public class ListAllTests extends TestRunner {
String groupToList = "";
boolean showGroups = false;
boolean showDesc = false;
/**
* Command-line run method.
* @param args The command-line arguments.
*/
public static void main(String[] args) {
ListAllTests lat = new ListAllTests();
logger.setLevel(Level.OFF);
lat.parseCommandLine(args);
lat.readPropertiesFile();
lat.listAllTests();
} // main
private void parseCommandLine(String[] args) {
for (int i=0; i < args.length; i++) {
if (args[i].equals("-h")) {
printUsage();
System.exit(0);
}
if (args[i].equals("-g")) {
showGroups = true;
} else if (args[i].equals("-d")){
showDesc = true;
} else {
groupToList = args[i];
}
}
if (groupToList.equals("")){
groupToList = "all";
}
} // parseCommandLine
private void printUsage() {
System.out.println("\nUsage: ListTests group1 ...\n");
System.out.println("Options:");
System.out.println(" -h This message.");
System.out.println(" -g Show groups associated with each test.");
System.out.println(" -d Show test description.");
System.out.println(" group1 List tests that are members of group1.");
System.out.println("");
System.out.println("If no groups are specified, the group 'all', which contains all tests, is listed.");
} // printUsage
private void listAllTests() {
System.out.println("Tests in group " + groupToList + ":");
List tests = findAllTests();
Iterator it = tests.iterator();
while (it.hasNext()) {
EnsTestCase test = (EnsTestCase)it.next();
if (test.inGroup(groupToList)) {
StringBuffer testline = new StringBuffer(test.getShortTestName());
if (test.canRepair()) {
testline.append(" [ can repair] ");
}
if (showGroups){
testline.append( " (" );
List groups = test.getGroups();
java.util.Iterator gIt = groups.iterator();
while (gIt.hasNext()) {
String groupname = (String)gIt.next();
if (!groupname.equals(test.getShortTestName())){
testline.append(groupname);
testline.append(",");
}
}
if (testline.charAt(testline.length()-1) == ','){
testline.deleteCharAt(testline.length()-1);
}
testline.append( ")" );
}
if (showDesc){
testline.append("\n" + test.getDescription() + "\n");
}
System.out.println(testline.toString());
}
}
} // listAllTests
} // ListAllTests
|
package org.ensembl.healthcheck.util;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
import org.ensembl.healthcheck.DatabaseRegistry;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseServer;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.TestRunner;
import org.ensembl.healthcheck.configuration.ConfigureHost;
import org.ensembl.healthcheck.testcase.EnsTestCase;
/**
* Various database utilities.
*/
public final class DBUtils {
private static Logger logger = Logger.getLogger("HealthCheckLogger");
private static List<DatabaseServer> mainDatabaseServers;
private static List<DatabaseServer> secondaryDatabaseServers;
private static DatabaseRegistry mainDatabaseRegistry;
private static DatabaseRegistry secondaryDatabaseRegistry;
private static ConfigureHost hostConfiguration;
private static boolean useDefaultsFromFile = true;
/**
* <p>
* Initialises all attributes of DBUtils.
* </p>
*
* <p>
* This can be necessary in the GUI, if the user wants to change the
* database server. In that case the user calls
* </p>
*
* <code>
* DBUtils.initialise();
* DBUtils.setHostConfiguration(newHostConfiguration);
* </code>
*
* <p>
* then things like
* </p>
*
* <code>
* DatabaseRegistry databaseRegistry = new DatabaseRegistry(regexps, null, null, false);
* <code>
*
* <p>
* will work as expected.
* </p>
*
*/
public static void initialise() {
mainDatabaseServers = null;
secondaryDatabaseServers = null;
mainDatabaseRegistry = null;
secondaryDatabaseRegistry = null;
hostConfiguration = null;
useDefaultsFromFile = true;
}
public static void initialise(boolean useDefaultsFromFile) {
initialise();
DBUtils.useDefaultsFromFile = useDefaultsFromFile;
}
public static ConfigureHost getHostConfiguration() {
return hostConfiguration;
}
public static void setHostConfiguration(ConfigureHost hostConfiguration) {
DBUtils.hostConfiguration = hostConfiguration;
}
// hide constructor to stop instantiation
private DBUtils() {
}
/**
* Helper to avoid having to keep constructing tedious URLs - mysql only
*
* @param driverClassName
* @param host
* @param port
* @param user
* @param password
* @param database
* @return
* @throws SQLException
*/
public static Connection openConnection(String driverClassName,
String host, String port, String user, String password,
String database) throws SQLException {
return ConnectionPool.getConnection(driverClassName, "jdbc:mysql:
+ host + ":" + port + "/" + database, user, password);
}
/**
* Open a connection to the database.
*
* @param driverClassName
* The class name of the driver to load.
* @param databaseURL
* The URL of the database to connect to.
* @param user
* The username to connect with.
* @param password
* Password for user.
* @return A connection to the database, or null.
* @throws SQLException
*/
public static Connection openConnection(String driverClassName,
String databaseURL, String user, String password)
throws SQLException {
return ConnectionPool.getConnection(driverClassName, databaseURL, user,
password);
} // openConnection
/**
* Get a list of the database names for a particular connection.
*
* @param con
* The connection to query.
* @return An array of Strings containing the database names.
*/
public static String[] listDatabases(Connection con) {
List<String> dbs = getSqlTemplate(con).queryForDefaultObjectList(
"SHOW DATABASES", String.class);
return dbs.toArray(new String[] {});
} // listDatabases
/**
* Get a list of the database names that match a certain pattern for a
* particular connection.
*
* @param conn
* The connection to query.
* @param regex
* A regular expression to match. If null, match all.
* @return An array of Strings containing the database names.
*/
public static String[] listDatabases(Connection con, String regex) {
ArrayList<String> dbMatches = new ArrayList<String>();
String[] allDBNames = listDatabases(con);
for (String name : allDBNames) {
if (regex == null) {
dbMatches.add(name);
} else if (name.matches(regex)) {
dbMatches.add(name);
}
}
String[] ret = new String[dbMatches.size()];
return (String[]) dbMatches.toArray(ret);
} // listDatabases
/**
* Compare a list of ResultSets to see if there are any differences. Note
* that if the ResultSets are large and/or there are many of them, this may
* take a long time!
*
* @return The number of differences.
* @param testCase
* The test case that is calling the comparison. Used for
* ReportManager.
* @param resultSetGroup
* The list of ResultSets to compare
*/
public static boolean compareResultSetGroup(List<ResultSet> resultSetGroup,
EnsTestCase testCase, boolean comparingSchema) {
boolean same = true;
// avoid comparing the same two ResultSets more than once
// i.e. only need the upper-right triangle of the comparison matrix
int size = resultSetGroup.size();
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
ResultSet rsi = resultSetGroup.get(i);
ResultSet rsj = resultSetGroup.get(j);
same &= compareResultSets(rsi, rsj, testCase, "", true, true,
"", comparingSchema);
}
}
return same;
} // compareResultSetGroup
/**
* Compare two ResultSets.
*
* @return True if all the following are true:
* <ol>
* <li>rs1 and rs2 have the same number of columns</li>
* <li>The name and type of each column in rs1 is equivalent to the
* corresponding column in rs2.</li>
* <li>All the rows in rs1 have the same type and value as the
* corresponding rows in rs2.</li>
* </ol>
* @param testCase
* The test case calling the comparison; used in ReportManager.
* @param text
* Additional text to put in any error reports.
* @param rs1
* The first ResultSet to compare.
* @param rs2
* The second ResultSet to compare.
* @param reportErrors
* If true, error details are stored in ReportManager as they are
* found.
* @param singleTableName
* If comparing 2 result sets from a single table (or from a
* DESCRIBE table) this should be the name of the table, to be
* output in any error text. Otherwise "".
*/
public static boolean compareResultSets(ResultSet rs1, ResultSet rs2,
EnsTestCase testCase, String text, boolean reportErrors,
boolean warnNull, String singleTableName, boolean comparingSchema) {
return compareResultSets(rs1, rs2, testCase, text, reportErrors,
warnNull, singleTableName, null, comparingSchema);
}
/**
* Check that a particular SQL statement has the same result when executed
* on more than one database.
*
* @return True if all matched databases provide the same result, false
* otherwise.
* @param sql
* The SQL query to execute.
* @param regexp
* A regexp matching the database names to check.
*/
public static boolean checkSameSQLResult(EnsTestCase test, String sql,
String regexp, boolean comparingSchema) {
ArrayList<ResultSet> resultSetGroup = new ArrayList<ResultSet>();
ArrayList<Statement> statements = new ArrayList<Statement>();
try {
DatabaseRegistry mainDatabaseRegistry = DBUtils
.getMainDatabaseRegistry();
for (DatabaseRegistryEntry dbre : mainDatabaseRegistry
.getMatching(regexp)) {
Connection con = dbre.getConnection();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if (rs != null) {
resultSetGroup.add(rs);
}
logger.fine("Added ResultSet for "
+ DBUtils.getShortDatabaseName(con) + ": " + sql);
// note that the Statement can't be closed here as we use
// the
// ResultSet elsewhere so store a reference to it for
// closing
// later
statements.add(stmt);
} catch (Exception e) {
throw new SqlUncheckedException(
"Could not check same SQL results", e);
} finally {
closeQuietly(rs);
closeQuietly(stmt);
}
}
logger.finest("Number of ResultSets to compare: "
+ resultSetGroup.size());
return DBUtils.compareResultSetGroup(resultSetGroup, test,
comparingSchema);
} finally {
for (ResultSet rs : resultSetGroup) {
closeQuietly(rs);
}
for (Statement s : statements) {
closeQuietly(s);
}
}
} // checkSameSQLResult
/**
* Check that a particular SQL statement has the same result when executed
* on more than one database.
*
* @return True if all matched databases provide the same result, false
* otherwise.
* @param sql
* The SQL query to execute.
* @param databases
* The DatabaseRegistryEntries on which to execute sql.
*/
public static boolean checkSameSQLResult(EnsTestCase test, String sql,
DatabaseRegistryEntry[] databases, boolean comparingSchema) {
List<ResultSet> resultSetGroup = new ArrayList<ResultSet>();
List<Statement> statements = new ArrayList<Statement>();
try {
for (int i = 0; i < databases.length; i++) {
Connection con = databases[i].getConnection();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if (rs != null) {
resultSetGroup.add(rs);
}
logger.fine("Added ResultSet for "
+ DBUtils.getShortDatabaseName(con) + ": " + sql);
statements.add(stmt);
} catch (Exception e) {
DBUtils.closeQuietly(rs);
DBUtils.closeQuietly(stmt);
throw new SqlUncheckedException(
"Could not check same SQL results", e);
}
}
logger.finest("Number of ResultSets to compare: "
+ resultSetGroup.size());
return DBUtils.compareResultSetGroup(resultSetGroup, test,
comparingSchema);
} catch (Exception e) {
throw new SqlUncheckedException("Could not check same SQL results",
e);
} finally {
for (ResultSet rs : resultSetGroup) {
DBUtils.closeQuietly(rs);
}
for (Statement s : statements) {
DBUtils.closeQuietly(s);
}
}
} // checkSameSQLResult
public static boolean compareResultSets(ResultSet rs1, ResultSet rs2,
EnsTestCase testCase, String text, boolean reportErrors,
boolean warnNull, String singleTableName, int[] columns,
boolean comparingSchema) {
// quick tests first
// Check for object equality
if (rs1.equals(rs2)) {
return true;
}
try {
// get some information about the ResultSets
String name1 = getShortDatabaseName(rs1.getStatement()
.getConnection());
String name2 = getShortDatabaseName(rs2.getStatement()
.getConnection());
// Check for same column count, names and types
ResultSetMetaData rsmd1 = rs1.getMetaData();
ResultSetMetaData rsmd2 = rs2.getMetaData();
if (rsmd1.getColumnCount() != rsmd2.getColumnCount()
&& columns == null) {
if (reportErrors) {
ReportManager.problem(
testCase,
name1,
"Column counts differ " + singleTableName + " "
+ name1 + ": " + rsmd1.getColumnCount()
+ " " + name2 + ": "
+ rsmd2.getColumnCount());
}
return false; // Deliberate early return for performance
// reasons
}
if (columns == null) {
columns = new int[rsmd1.getColumnCount()];
for (int i = 0; i < columns.length; i++) {
columns[i] = i + 1;
}
}
for (int j = 0; j < columns.length; j++) {
int i = columns[j];
// note columns indexed from l
if (!((rsmd1.getColumnName(i)).equals(rsmd2.getColumnName(i)))) {
if (reportErrors) {
ReportManager.problem(testCase, name1,
"Column names differ for " + singleTableName
+ " column " + i + " - " + name1 + ": "
+ rsmd1.getColumnName(i) + " " + name2
+ ": " + rsmd2.getColumnName(i));
}
// Deliberate early return for performance reasons
return false;
}
if (rsmd1.getColumnType(i) != rsmd2.getColumnType(i)) {
if (reportErrors) {
ReportManager.problem(testCase, name1,
"Column types differ for " + singleTableName
+ " column " + i + " - " + name1 + ": "
+ rsmd1.getColumnType(i) + " " + name2
+ ": " + rsmd2.getColumnType(i));
}
return false; // Deliberate early return for performance
// reasons
}
} // for column
// make sure both cursors are at the start of the ResultSet
// (default is before the start)
rs1.beforeFirst();
rs2.beforeFirst();
// if quick checks didn't cause return, try comparing row-wise
int row = 1;
while (rs1.next()) {
if (rs2.next()) {
for (int j = 0; j < columns.length; j++) {
int i = columns[j];
// note columns indexed from 1
if (!compareColumns(rs1, rs2, i, warnNull)) {
String str = name1
+ " and "
+ name2
+ text
+ " "
+ singleTableName
+ " differ at row "
+ row
+ " column "
+ i
+ " ("
+ rsmd1.getColumnName(i)
+ ")"
+ " Values: "
+ Utils.truncate(rs1.getString(i), 250,
true)
+ ", "
+ Utils.truncate(rs2.getString(i), 250,
true);
if (reportErrors) {
ReportManager.problem(testCase, name1, str);
}
return false;
}
}
row++;
} else {
// rs1 has more rows than rs2
if (reportErrors) {
ReportManager.problem(testCase, name1, singleTableName
+ " has more rows in " + name1 + " than in "
+ name2);
}
return false;
}
} // while rs1
// if both ResultSets are the same, then we should be at the end of
// both, i.e. .next() should return false
String extra = comparingSchema ? ". This means that there are missing columns in the table, rectify!"
: "";
if (rs1.next()) {
if (reportErrors) {
ReportManager.problem(testCase, name1, name1 + " "
+ singleTableName
+ " has additional rows that are not in " + name2
+ extra);
}
return false;
} else if (rs2.next()) {
if (reportErrors) {
ReportManager.problem(testCase, name2, name2 + " "
+ singleTableName
+ " has additional rows that are not in " + name1
+ extra);
}
return false;
}
} catch (SQLException se) {
throw new SqlUncheckedException(
"Could not compare two result sets", se);
}
return true;
} // compareResultSets
/**
* Compare a particular column in two ResultSets.
*
* @param rs1
* The first ResultSet to compare.
* @param rs2
* The second ResultSet to compare.
* @param i
* The index of the column to compare.
* @return True if the type and value of the columns match.
*/
public static boolean compareColumns(ResultSet rs1, ResultSet rs2, int i,
boolean warnNull) {
try {
ResultSetMetaData rsmd = rs1.getMetaData();
Connection con1 = rs1.getStatement().getConnection();
Connection con2 = rs2.getStatement().getConnection();
if (rs1.getObject(i) == null) {
if (warnNull) {
logger.fine("Column " + rsmd.getColumnName(i)
+ " is null in table " + rsmd.getTableName(i)
+ " in " + DBUtils.getShortDatabaseName(con1));
}
return (rs2.getObject(i) == null); // true if both are null
}
if (rs2.getObject(i) == null) {
if (warnNull) {
logger.fine("Column " + rsmd.getColumnName(i)
+ " is null in table " + rsmd.getTableName(i)
+ " in " + DBUtils.getShortDatabaseName(con2));
}
return (rs1.getObject(i) == null); // true if both are null
}
// Note deliberate early returns for performance reasons
switch (rsmd.getColumnType(i)) {
case Types.INTEGER:
return rs1.getInt(i) == rs2.getInt(i);
case Types.SMALLINT:
return rs1.getInt(i) == rs2.getInt(i);
case Types.TINYINT:
return rs1.getInt(i) == rs2.getInt(i);
case Types.VARCHAR:
String s1 = rs1.getString(i);
String s2 = rs2.getString(i);
// ignore "AUTO_INCREMENT=" part in final part of table
// definition
s1 = s1.replaceAll("AUTO_INCREMENT=[0-9]+ ", "");
s2 = s2.replaceAll("AUTO_INCREMENT=[0-9]+ ", "");
return s1.equals(s2);
case Types.FLOAT:
return rs1.getFloat(i) == rs2.getFloat(i);
case Types.DOUBLE:
return rs1.getDouble(i) == rs2.getDouble(i);
case Types.TIMESTAMP:
return rs1.getTimestamp(i).equals(rs2.getTimestamp(i));
default:
// treat everything else as a String (should deal with ENUM and
// TEXT)
if (rs1.getString(i) == null || rs2.getString(i) == null) {
return true;
} else {
return rs1.getString(i).equals(rs2.getString(i));
}
} // switch
} catch (SQLException se) {
throw new SqlUncheckedException(
"Could not compare two columns sets", se);
}
} // compareColumns
/**
* Print a ResultSet to standard out. Optionally limit the number of rows.
*
* @param maxRows
* The maximum number of rows to print. -1 to print all rows.
* @param rs
* The ResultSet to print.
*/
public static void printResultSet(ResultSet rs, int maxRows) {
int row = 0;
try {
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rs.getString(i) + "\t");
}
System.out.println("");
if (maxRows != -1 && ++row >= maxRows) {
break;
}
}
} catch (SQLException se) {
throw new SqlUncheckedException("Could not print result set", se);
}
} // printResultSet
/**
* Gets the database name, without the jdbc:// prefix.
*
* @param con
* The Connection to query.
* @return The name of the database (everything after the last / in the JDBC
* URL).
*/
public static String getShortDatabaseName(Connection con) {
String url = null;
try {
url = con.getMetaData().getURL();
} catch (SQLException se) {
throw new SqlUncheckedException("Could not get database name", se);
}
String name = url.substring(url.lastIndexOf('/') + 1);
return name;
} // getShortDatabaseName
/**
* Scans through a result set's metadata in an attempt to find a column
*
* @param rs
* The ResultSet to scan
* @param column
* The column to find
* @return Boolean indicating if there was a column with said name
* @throws SQLException
* Thrown in the event of an error whilst processing
*/
public static boolean resultSetContainsColumn(ResultSet rs, String column)
throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
int total = meta.getColumnCount();
for (int i = 1; i <= total; i++) {
if (meta.getColumnName(i).equals(column)) {
return true;
}
}
return false;
} // resultSetContainsColumn
/**
* Generate a name for a temporary database. Should be fairly unique; name
* is _temp_{user}_{time} where user is current user and time is current
* time in ms.
*
* @return The temporary name. Will not have any spaces.
*/
public static String generateTempDatabaseName() {
StringBuffer buf = new StringBuffer("_temp_");
buf.append(System.getProperty("user.name"));
buf.append("_" + System.currentTimeMillis());
String str = buf.toString();
str = str.replace(' ', '_'); // filter any spaces
logger.fine("Generated temporary database name: " + str);
return str;
}
/**
* Get a list of all the table names.
*
* @param con
* The database connection to use.
* @return An array of Strings representing the names of the base tables.
*/
public static String[] getTableNames(Connection con) {
List<String> result = getSqlTemplate(con)
.queryForDefaultObjectList(
"SELECT TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'",
String.class);
return result.toArray(new String[] {});
}
/**
* Get a list of the table names that match a particular SQL pattern.
*
* @param con
* The database connection to use.
* @param pattern
* The SQL pattern to match the table names against.
* @return An array of Strings representing the names of the tables.
*/
public static String[] getTableNames(Connection con, String pattern) {
List<String> result = getSqlTemplate(con).queryForDefaultObjectList(
"SHOW TABLES LIKE '" + pattern + "'", String.class);
return result.toArray(new String[] {});
}
/**
* List the columns in a particular table.
*
* @param table
* The name of the table to list.
* @param con
* The connection to use.
* @return A List of Strings representing the column names.
*/
public static List<String> getColumnsInTable(Connection con, String table) {
return getSqlTemplate(con).queryForDefaultObjectList(
"DESCRIBE " + table, String.class);
}
/**
* List the column information in a table - names, types, defaults etc.
*
* @param table
* The name of the table to list.
* @param con
* The connection to use.
* @param typeFilter
* If not null, only return columns whose types start with this
* string (case insensitive).
* @return A List of 6-element String[] arrays representing: 0: Column name
* 1: Type 2: Null? 3: Key 4: Default 5: Extra
*/
public static List<String[]> getTableInfo(Connection con, String table,
String typeFilter) {
List<String[]> results = getSqlTemplate(con).queryForList(
"DESCRIBE " + table, new RowMapper<String[]>() {
@Override
public String[] mapRow(ResultSet rs, int position)
throws SQLException {
String[] info = new String[6];
for (int i = 0; i < 6; i++) {
info[i] = rs.getString(i + 1);
}
return info;
}
});
if (typeFilter != null) {
typeFilter = typeFilter.toLowerCase();
for (Iterator<String[]> i = results.iterator(); i.hasNext();) {
String[] info = i.next();
if (!info[1].toLowerCase().startsWith(typeFilter)) {
i.remove();
}
}
}
return results;
}
/**
* Requests all known views in the current schema from the MySQL information
* schema
*
* @param con
* The connection to use
* @return All known views in the given schema
*/
public static List<String> getViews(Connection con) {
String sql = "SELECT TABLE_NAME from information_schema.TABLES where TABLE_SCHEMA = DATABASE() AND TABLE_TYPE =?";
SqlTemplate t = new ConnectionBasedSqlTemplateImpl(con);
return t.queryForDefaultObjectList(sql, String.class, "VIEW");
}
/**
* Execute SQL and writes results to ReportManager.info().
*
* @param testCase
* testCase which created the sql statement
* @param con
* connection to execute sql on.
* @param sql
* sql statement to execute.
*/
public static void printRows(EnsTestCase testCase, Connection con,
String sql) {
ResultSet rs = null;
try {
rs = con.createStatement().executeQuery(sql);
if (rs.next()) {
int nCols = rs.getMetaData().getColumnCount();
StringBuffer line = new StringBuffer();
do {
line.delete(0, line.length());
for (int i = 1; i <= nCols; ++i) {
line.append(rs.getString(i));
if (i < nCols) {
line.append("\t");
}
}
ReportManager.info(testCase, con, line.toString());
} while (rs.next());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeQuietly(rs);
}
}
/**
* Get the meta_value for a named key in the meta table.
*/
public static String getMetaValue(Connection con, String key) {
List<String> results = getSqlTemplate(con).queryForDefaultObjectList(
"SELECT meta_value FROM meta WHERE meta_key='" + key + "'",
String.class);
return CollectionUtils.getFirstElement(results, StringUtils.EMPTY);
}
/**
* <p>
* Depends on system properties being set by a call like
* </p>
*
* <pre>
* Utils.readPropertiesFileIntoSystem(getPropertiesFile(), false);
* </pre>
*
* <p>
* New code should use the method getMainDatabaseServersConf which gets
* configuration information from a configuration object. If all goes well,
* this method will eventually become deprecated.
* </p>
*
*/
public static List<DatabaseServer> getMainDatabaseServers() {
if (DBUtils.hostConfiguration == null) {
if (useDefaultsFromFile) {
return getMainDatabaseServersProperties();
} else {
// If nothing was preconfigured and defaults should not be
// used, return empty list.
return new ArrayList<DatabaseServer>();
}
} else {
return getMainDatabaseServersConf();
}
}
public static List<DatabaseServer> getMainDatabaseServersProperties() {
// EG replace literal reference to file with variable
Utils.readPropertiesFileIntoSystem(TestRunner.getPropertiesFile(),
false);
if (mainDatabaseServers == null) {
mainDatabaseServers = new ArrayList<DatabaseServer>();
checkAndAddDatabaseServer(mainDatabaseServers, "host", "port",
"user", "password", "driver");
checkAndAddDatabaseServer(mainDatabaseServers, "host1", "port1",
"user1", "password1", "driver1");
checkAndAddDatabaseServer(mainDatabaseServers, "host2", "port2",
"user2", "password2", "driver2");
}
logger.fine("Number of main database servers found: "
+ mainDatabaseServers.size());
return mainDatabaseServers;
}
public static List<DatabaseServer> getMainDatabaseServersConf() {
if (DBUtils.hostConfiguration == null) {
throw new NullPointerException(
"hostConfiguration is null, so was probably never set!");
}
if (mainDatabaseServers == null) {
mainDatabaseServers = new ArrayList<DatabaseServer>();
boolean primaryHostConfigured = DBUtils.hostConfiguration.isHost()
&& DBUtils.hostConfiguration.isPort()
&& DBUtils.hostConfiguration.isUser()
&& DBUtils.hostConfiguration.isPassword()
&& DBUtils.hostConfiguration.isDriver();
if (primaryHostConfigured) {
checkAndAddDatabaseServerConf(mainDatabaseServers,
DBUtils.hostConfiguration.getHost(),
DBUtils.hostConfiguration.getPort(),
DBUtils.hostConfiguration.getUser(),
DBUtils.hostConfiguration.getPassword(),
DBUtils.hostConfiguration.getDriver());
}
}
return mainDatabaseServers;
}
/**
*
* <p>
* Check for the existence of a particular database server. Assumes
* properties file has already been read in. If it exists, add it to the
* list.
* </p>
*
* <p>
* Gets called by getMainDatabaseServers() and should not be used any
* further, because it uses system properties.
* </p>
*
*/
private static void checkAndAddDatabaseServer(List<DatabaseServer> servers,
String hostProp, String portProp, String userProp,
String passwordProp, String driverProp) {
if (System.getProperty(hostProp) != null
&& System.getProperty(portProp) != null
&& System.getProperty(userProp) != null) {
DatabaseServer server = new DatabaseServer(
System.getProperty(hostProp), System.getProperty(portProp),
System.getProperty(userProp),
System.getProperty(passwordProp),
System.getProperty(driverProp));
servers.add(server);
logger.fine("Added server: " + server.toString());
}
}
public static List<DatabaseServer> getSecondaryDatabaseServers() {
if (DBUtils.hostConfiguration == null) {
return getSecondaryDatabaseServersProperties();
} else {
return getSecondaryDatabaseServersConf();
}
}
/**
* Look for secondary database servers.
*/
public static List<DatabaseServer> getSecondaryDatabaseServersProperties() {
Utils.readPropertiesFileIntoSystem(TestRunner.getPropertiesFile(),
false);
if (secondaryDatabaseServers == null) {
secondaryDatabaseServers = new ArrayList<DatabaseServer>();
checkAndAddDatabaseServer(secondaryDatabaseServers,
"secondary.host", "secondary.port", "secondary.user",
"secondary.password", "secondary.driver");
checkAndAddDatabaseServer(secondaryDatabaseServers,
"secondary.host1", "secondary.port1", "secondary.user1",
"secondary.password1", "secondary.driver1");
checkAndAddDatabaseServer(secondaryDatabaseServers,
"secondary.host2", "secondary.port2", "secondary.user2",
"secondary.password2", "secondary.driver2");
}
logger.fine("Number of secondary database servers found: "
+ secondaryDatabaseServers.size());
return secondaryDatabaseServers;
}
/**
*
* Look for secondary database servers.
*
*/
public static List<DatabaseServer> getSecondaryDatabaseServersConf() {
if (secondaryDatabaseServers == null) {
secondaryDatabaseServers = new ArrayList<DatabaseServer>();
boolean secondaryHostConfigured = DBUtils.hostConfiguration
.isSecondaryHost()
&& DBUtils.hostConfiguration.isSecondaryPort()
&& DBUtils.hostConfiguration.isSecondaryUser()
&& DBUtils.hostConfiguration.isSecondaryPassword()
&& DBUtils.hostConfiguration.isSecondaryDriver();
if (secondaryHostConfigured) {
logger.config("Adding database "
+ DBUtils.hostConfiguration.getSecondaryHost());
checkAndAddDatabaseServerConf(secondaryDatabaseServers,
DBUtils.hostConfiguration.getSecondaryHost(),
DBUtils.hostConfiguration.getSecondaryPort(),
DBUtils.hostConfiguration.getSecondaryUser(),
DBUtils.hostConfiguration.getSecondaryPassword(),
DBUtils.hostConfiguration.getSecondaryDriver());
} else {
logger.config("No secondary database configured.");
}
}
logger.fine("Number of secondary database servers found: "
+ secondaryDatabaseServers.size());
return secondaryDatabaseServers;
}
/**
*
* <p>
* Adds a DatabaseServer object to the List<DatabaseServer> passed as the
* first argument.
* </p>
*
* @param servers
* @param host
* @param port
* @param user
* @param password
* @param driver
*
*/
private static void checkAndAddDatabaseServerConf(
List<DatabaseServer> servers, String host, String port,
String user, String password, String driver) {
DatabaseServer server = new DatabaseServer(host, port, user, password,
driver);
if (server.isConnectedSuccessfully()) {
servers.add(server);
logger.fine("Added server: " + server.toString());
} else {
logger.fine("Couldn't connect to server: " + server.toString());
}
}
public static DatabaseRegistry getSecondaryDatabaseRegistry() {
if (secondaryDatabaseRegistry == null) {
secondaryDatabaseRegistry = new DatabaseRegistry(null, null, null,
true);
}
return secondaryDatabaseRegistry;
}
public static void setMainDatabaseRegistry(DatabaseRegistry dbr) {
mainDatabaseRegistry = dbr;
}
public static DatabaseRegistry getMainDatabaseRegistry() {
if (mainDatabaseRegistry == null) {
mainDatabaseRegistry = new DatabaseRegistry(null, null, null, false);
}
return mainDatabaseRegistry;
}
public static void setSecondaryDatabaseRegistry(DatabaseRegistry dbr) {
secondaryDatabaseRegistry = dbr;
}
public static boolean tableExists(Connection con, String table) {
boolean result = false;
ResultSet rs = null;
try {
DatabaseMetaData dbm = con.getMetaData();
rs = dbm.getTables(null, null, table, null);
if (rs.next()) {
result = true;
}
} catch (SQLException e) {
throw new SqlUncheckedException("Could not check for table "
+ table, e);
} finally {
closeQuietly(rs);
}
return result;
}
public static boolean columnExists(Connection con, String table,
String column) {
boolean result = false;
ResultSet rs = null;
try {
DatabaseMetaData dbm = con.getMetaData();
rs = dbm.getColumns(null, null, table, column);
if (rs.next()) {
result = true;
}
} catch (SQLException e) {
throw new SqlUncheckedException("Could not check for table "
+ table, e);
} finally {
closeQuietly(rs);
}
return result;
}
public static void closeQuietly(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// ignore
}
}
}
public static void closeQuietly(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
// ignore
}
}
}
public static void closeQuietly(Connection c) {
if (c != null) {
try {
c.close();
} catch (SQLException e) {
// ignore
}
}
}
/**
* Produce an instance of {@link SqlTemplate} from a
* {@link DatabaseRegistryEntry}.
*/
public static SqlTemplate getSqlTemplate(DatabaseRegistryEntry dbre) {
return new ConnectionBasedSqlTemplateImpl(dbre);
}
/**
* Produce an instance of {@link SqlTemplate} from a {@link Connection}.
*/
public static SqlTemplate getSqlTemplate(Connection conn) {
return new ConnectionBasedSqlTemplateImpl(conn);
}
/**
* Count the number of rows in a table.
*
* @param con
* The database connection to use. Should have been opened
* already.
* @param table
* The name of the table to analyse.
* @return The number of rows in the table.
*/
public static int countRowsInTable(Connection con, String table) {
if (con == null) {
logger.severe("countRowsInTable: Database connection is null");
}
return getRowCount(con, "SELECT COUNT(*) FROM " + table);
} // countRowsInTable
/**
* Use SELECT COUNT(*) to get a row count.
*/
public static int getRowCountFast(Connection con, String sql) {
return getSqlTemplate(con).queryForDefaultObject(sql, Integer.class);
} // getRowCountFast
/**
* Use a row-by-row approach to counting the rows in a table.
*/
public static int getRowCountSlow(Connection con, String sql) {
int result = -1;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if (rs != null) {
if (rs.last()) {
result = rs.getRow();
} else {
result = 0; // probably signifies an empty ResultSet
}
}
rs.close();
stmt.close();
} catch (Exception e) {
throw new SqlUncheckedException("Could not retrieve row count", e);
} finally {
closeQuietly(rs);
closeQuietly(stmt);
}
return result;
} // getRowCountSlow
/**
* Count the rows in a particular table or query.
*
* @param con
* A connection to the database. Should already be open.
* @param sql
* The SQL to execute. Note that if possible this should begin
* with <code>SELECT COUNT FROM</code> since this is much quicker
* to execute. If a standard SELECT statement is used, a
* row-by-row count will be performed, which may be slow if the
* table is large.
* @return The number of matching rows, or -1 if the query did not execute
* for some reason.
*/
public static int getRowCount(Connection con, String sql) {
if (con == null) {
logger.severe("getRowCount: Database connection is null");
}
int result = -1;
// if the query starts with SELECT COUNT and does not include a GROUP
// BY clause
// we can execute it and just take the first result, which is the count
if (sql.toLowerCase().indexOf("select count") >= 0
&& sql.toLowerCase().indexOf("group by") < 0) {
result = getRowCountFast(con, sql);
} else if (sql.toLowerCase().indexOf("select count") < 0) {
// otherwise, do it row-by-row
logger.fine("getRowCount() executing SQL which does not appear to begin with SELECT COUNT - performing row-by-row count, which may take a long time if the table is large.");
result = getRowCountSlow(con, sql);
}
return result;
} // getRowCount
/**
* Execute a SQL statement and return the value of one column of one row.
* Only the FIRST row matched is returned.
*
* @param con
* The Connection to use.
* @param sql
* The SQL to check; should return ONE value.
* @return The value returned by the SQL.
*/
public static String getRowColumnValue(Connection con, String sql) {
return CollectionUtils.getFirstElement(getSqlTemplate(con)
.queryForDefaultObjectList(sql, String.class),
StringUtils.EMPTY);
} // DBUtils.getRowColumnValue
/**
* Execute a SQL statement and return the value of the columns of one row.
* Only the FIRST row matched is returned.
*
* @param con
* The Connection to use.
* @param sql
* The SQL to check; can return several values.
* @return The value(s) returned by the SQL in an array of Strings.
*/
public static String[] getRowValues(Connection con, String sql) {
List<String[]> v = getRowValuesList(con, sql);
if(v.isEmpty()) {
throw new SqlUncheckedException("The query '"+sql+"' returned no rows. Cannot return anything");
}
return v.get(0);
} // getRowValues
/**
* Returns a List of String arrays for working with multiple values
*
* @param con Connection to use
* @param sql SQL to run; can return several values
* @return Returns a list of values
*/
public static List<String[]> getRowValuesList(Connection con, String sql) {
return getSqlTemplate(con).queryForList(sql, new RowMapper<String[]>() {
@Override
public String[] mapRow(ResultSet resultSet, int position)
throws SQLException {
int length = resultSet.getMetaData().getColumnCount();
String[] values = new String[length];
for (int sqlIndex = 1, arrayIndex = 0; sqlIndex <= length; sqlIndex++, arrayIndex++) {
values[arrayIndex] = resultSet.getString(sqlIndex);
}
return values;
}
});
}
/**
* Execute a SQL statement and return the values of one column of the
* result.
*
* @param con
* The Connection to use.
* @param sql
* The SQL to check; should return ONE column.
* @return The value(s) making up the column, in the order that they were
* read.
*/
public static String[] getColumnValues(Connection con, String sql) {
return getColumnValuesList(con, sql).toArray(new String[] {});
} // getColumnValues
/**
* Execute a SQL statement and return the values of one column of the
* result.
*
* @param con
* The Connection to use.
* @param sql
* The SQL to check; should return ONE column.
* @return The value(s) making up the column, in the order that they were
* read.
*/
public static List<String> getColumnValuesList(Connection con, String sql) {
return getSqlTemplate(con).queryForDefaultObjectList(sql, String.class);
} // getColumnValues
/**
* Check for the presence of a particular String in a table column.
*
* @param con
* The database connection to use.
* @param table
* The name of the table to examine.
* @param column
* The name of the column to look in.
* @param str
* The string to search for; can use database wildcards (%, _)
* Note that if you want to search for one of these special
* characters, it must be backslash-escaped.
* @return The number of times the string is matched.
*/
public static int findStringInColumn(Connection con, String table,
String column, String str) {
if (con == null) {
logger.severe("findStringInColumn: Database connection is null");
}
String sql = "SELECT COUNT(*) FROM " + table + " WHERE " + column
+ " LIKE \"" + str + "\"";
logger.fine(sql);
return getRowCount(con, sql);
} // findStringInColumn
/**
* Check that all entries in column match a particular pattern.
*
* @param con
* The database connection to use.
* @param table
* The name of the table to examine.
* @param column
* The name of the column to look in.
* @param pattern
* The SQL pattern (can contain _,%) to look for.
* @return The number of columns that <em>DO NOT</em> match the pattern.
*/
public static int checkColumnPattern(Connection con, String table,
String column, String pattern) {
// @todo - what about NULLs?
// cheat by looking for any rows that DO NOT match the pattern
String sql = "SELECT COUNT(*) FROM " + table + " WHERE " + column
+ " NOT LIKE \"" + pattern + "\"";
logger.fine(sql);
return getRowCount(con, sql);
} // checkColumnPattern
/**
* Check that all entries in column match a particular value.
*
* @param con
* The database connection to use.
* @param table
* The name of the table to examine.
* @param column
* The name of the column to look in.
* @param value
* The string to look for (not a pattern).
* @return The number of columns that <em>DO NOT</em> match value.
*/
public static int checkColumnValue(Connection con, String table,
String column, String value) {
// @todo - what about NULLs?
// cheat by looking for any rows that DO NOT match the pattern
String sql = "SELECT COUNT(*) FROM " + table + " WHERE " + column
+ " != '" + value + "'";
logger.fine(sql);
return getRowCount(con, sql);
} // checkColumnPattern
/**
* Check if there are any blank entires in a column that is not supposed to
* be null.
*
* @param con
* The database connection to use.
* @param table
* The table to use.
* @param column
* The column to examine.
* @return An list of the row indices of any blank entries. Will be
* zero-length if there are none.
*/
public static List<String> checkBlankNonNull(Connection con, String table,
String column) {
if (con == null) {
logger.severe("checkBlankNonNull (column): Database connection is null");
return null;
}
List<String> blanks = new ArrayList<String>();
Statement stmt = null;
ResultSet rs = null;
try {
String sql = "SELECT " + column + " FROM " + table;
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
String columnValue = rs.getString(1);
// should it be non-null?
if (rsmd.isNullable(1) == ResultSetMetaData.columnNoNulls) {
if (StringUtils.isEmpty(columnValue)) {
blanks.add(Integer.toString(rs.getRow()));
}
}
}
rs.close();
stmt.close();
} catch (Exception e) {
throw new SqlUncheckedException("Could not check blanks or nulls",
e);
} finally {
closeQuietly(rs);
closeQuietly(stmt);
}
return blanks;
} // checkBlankNonNull
/**
* Check all columns of a table for blank entires in columns that are marked
* as being NOT NULL.
*
* @param con
* The database connection to use.
* @param table
* The table to use.
* @return The total number of blank null enums.
*/
public static int checkBlankNonNull(Connection con, String table) {
if (con == null) {
logger.severe("checkBlankNonNull (table): Database connection is null");
return 0;
}
int blanks = 0;
String sql = "SELECT * FROM " + table;
ResultSet rs = null;
Statement stmt = null;
try {
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnValue = rs.getString(i);
String columnName = rsmd.getColumnName(i);
// should it be non-null?
if (rsmd.isNullable(i) == ResultSetMetaData.columnNoNulls) {
if (columnValue == null || columnValue.equals("")) {
blanks++;
logger.warning("Found blank non-null value in column "
+ columnName + " in " + table);
}
}
} // for column
}
} catch (Exception e) {
throw new SqlUncheckedException(
"Could not check for blank non-nulls", e);
} finally {
closeQuietly(rs);
closeQuietly(stmt);
}
return blanks;
} // checkBlankNonNull
/**
* Check if a particular table exists in a database.
*
* @param con
* The database connection to check.
* @param table
* The table to check for.
* @return true if the table exists in the database.
*/
public static boolean checkTableExists(Connection con, String table) {
String tables = DBUtils.getRowColumnValue(con, "SHOW TABLES LIKE '"
+ table + "'");
boolean result = false;
if (tables != null && tables.length() != 0) {
result = true;
}
return result;
} // checkTableExists
/**
* @param con
* @param tableName
* @return
*/
public static long getChecksum(Connection con, String tableName) {
String sql = "CHECKSUM TABLE "+tableName;
RowMapper<Long> mapper = new DefaultObjectRowMapper<Long>(Long.class, 2);
return getSqlTemplate(con).queryForObject(sql, mapper);
}
} // DBUtils
|
package org.exist.xquery.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import org.exist.xmldb.XPathQueryServiceImpl;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XMLResource;
import org.xmldb.api.modules.XPathQueryService;
public class XPathQueryTest extends TestCase {
private final static String URI = "xmldb:exist:
private final static String nested =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<test><c></c><b><c><b></b></c></b><b></b><c></c></test>";
private final static String numbers =
"<test>"
+ "<item id='1'><price>5.6</price><stock>22</stock></item>"
+ "<item id='2'><price>7.4</price><stock>43</stock></item>"
+ "<item id='3'><price>18.4</price><stock>5</stock></item>"
+ "<item id='4'><price>65.54</price><stock>16</stock></item>"
+ "</test>";
private final static String namespaces =
"<test xmlns='http:
+ "<section>"
+ "<title>Test Document</title>"
+ "<c:comment xmlns:c='http:
+ "</section>"
+ "</test>";
private final static String strings =
"<test>"
+ "<string>Hello World!</string>"
+ "<string value='Hello World!'/>"
+ "<string>Hello</string>"
+ "</test>";
private final static String nested2 =
"<RootElement>" +
"<ChildA>" +
"<ChildB id=\"2\"/>" +
"</ChildA>" +
"</RootElement>";
private Collection testCollection;
public XPathQueryTest(String name) {
super(name);
}
protected void setUp() {
try {
// initialize driver
Class cl = Class.forName("org.exist.xmldb.DatabaseImpl");
Database database = (Database) cl.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
Collection root =
DatabaseManager.getCollection(
URI,
"admin",
null);
CollectionManagementService service =
(CollectionManagementService) root.getService(
"CollectionManagementService",
"1.0");
testCollection = service.createCollection("test");
assertNotNull(testCollection);
// XMLResource doc =
// (XMLResource) root.createResource("r_and_j.xml", "XMLResource");
// doc.setContent(new File("samples/shakespeare/r_and_j.xml"));
// root.storeResource(doc);
} catch (ClassNotFoundException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (XMLDBException e) {
e.printStackTrace();
}
}
public void testStarAxis() {
ResourceSet result;
try {
XPathQueryService service =
storeXMLStringAndGetQueryService("numbers.xml", numbers);
result = service.queryResource(
"numbers.xml", "/*/item" );
System.out.println("testStarAxis 1: ========" ); printResult(result);
assertEquals( "XPath: /*/item", 4, result.getSize() );
result = service.queryResource(
assertEquals( "XPath: /*/*", 12, result.getSize() );
queryResource(service, "nested2.xml", "/RootElement/descendant::*[self::ChildB]/parent::RootElement", 0);
queryResource(service, "nested2.xml", "/RootElement/descendant::*[self::ChildA]/parent::RootElement", 1);
} catch (XMLDBException e) {
fail(e.getMessage());
}
}
public void testNumbers() {
try {
XPathQueryService service =
storeXMLStringAndGetQueryService("numbers.xml", numbers);
ResourceSet result = queryResource(service, "numbers.xml", "sum(/test/item/price)", 1);
assertEquals( "96.94", result.getResource(0).getContent() );
result = queryResource(service, "numbers.xml", "round(sum(/test/item/price))", 1);
assertEquals( "97.0", result.getResource(0).getContent() );
result = queryResource(service, "numbers.xml", "floor(sum(/test/item/stock))", 1);
assertEquals( "86.0", result.getResource(0).getContent());
queryResource(service, "numbers.xml", "/test/item[round(price + 3) > 60]", 1);
result = queryResource(service, "numbers.xml", "min( 123456789123456789123456789, " +
"123456789123456789123456789123456789123456789 )", 1);
assertEquals("minimum of big integers",
"123456789123456789123456789",
result.getResource(0).getContent() );
} catch (XMLDBException e) {
fail(e.getMessage());
}
}
public void testStrings() {
try {
XPathQueryService service =
storeXMLStringAndGetQueryService("strings.xml", strings);
ResourceSet result = queryResource(service, "strings.xml", "substring(/test/string[1], 1, 5)", 1);
assertEquals( "Hello", result.getResource(0).getContent() );
queryResource(service, "strings.xml", "/test/string[starts-with(string(.), 'Hello')]", 2);
result = queryResource(service, "strings.xml", "count(/test/item/price)", 1,
"Query should return an empty set (wrong document)");
assertEquals("0", result.getResource(0).getContent());
} catch (XMLDBException e) {
System.out.println("testStrings(): XMLDBException: "+e);
fail(e.getMessage());
}
}
public void testBoolean() {
try {
System.out.println("Testing effective boolean value of expressions ...");
XPathQueryService service =
storeXMLStringAndGetQueryService("numbers.xml", numbers);
ResourceSet result = queryResource(service, "numbers.xml", "boolean(1.0)", 1);
assertEquals("boolean value of 1.0 should be true", "true", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(0.0)", 1);
assertEquals("boolean value of 0.0 should be false", "false", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(xs:double(0.0))", 1);
assertEquals("boolean value of double 0.0 should be false", "false", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(xs:double(1.0))", 1);
assertEquals("boolean value of double 1.0 should be true", "true", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(xs:float(1.0))", 1);
assertEquals("boolean value of float 1.0 should be true", "true", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(xs:float(0.0))", 1);
assertEquals("boolean value of float 0.0 should be false", "false", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(xs:integer(0))", 1);
assertEquals("boolean value of integer 0 should be false", "false", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(xs:integer(1))", 1);
assertEquals("boolean value of integer 1 should be true", "true", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "'true' cast as xs:boolean", 1);
assertEquals("boolean value of 'true' cast to xs:boolean should be true",
"true", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "'false' cast as xs:boolean", 1);
assertEquals("boolean value of 'false' cast to xs:boolean should be false",
"false", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean('Hello')", 1);
assertEquals("boolean value of string 'Hello' should be true", "true", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean('')", 1);
assertEquals("boolean value of empty string should be false", "false", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(())", 1);
assertEquals("boolean value of empty sequence should be false", "false", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(('Hello'))", 1);
assertEquals("boolean value of sequence with non-empty string should be true",
"true", result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean((0.0, 0.0))", 1);
assertEquals("boolean value of sequence with two elements should be true", "true",
result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(//item[@id = '1']/price)", 1);
assertEquals("boolean value of 5.6 should be true", "true",
result.getResource(0).getContent());
result = queryResource(service, "numbers.xml", "boolean(current-time())", 1);
assertEquals("boolean value of current-time() should be true", "true",
result.getResource(0).getContent());
} catch (XMLDBException e) {
System.out.println("testBoolean(): XMLDBException: "+e);
fail(e.getMessage());
}
}
public void testNot() {
try {
XPathQueryService service =
storeXMLStringAndGetQueryService("strings.xml", strings);
queryResource(service, "strings.xml", "/test/string[not(@value)]", 2);
ResourceSet result = queryResource(service, "strings.xml", "not(/test/abcd)", 1);
Resource r = result.getResource(0);
assertEquals("true", r.getContent().toString());
result = queryResource(service, "strings.xml", "not(/test)", 1);
r = result.getResource(0);
assertEquals("false", r.getContent().toString());
result = queryResource(service, "strings.xml", "/test/string[not(@id)]", 3);
r = result.getResource(0);
assertEquals("<string>Hello World!</string>", r.getContent().toString());
// test with non-existing items
queryResource( service, "strings.xml", "document()/blah[not(blah)]", 0);
/**
* @param service
* @throws XMLDBException
*/
private ResourceSet queryResource(XPathQueryService service, String resource, String query,
int expected, String message) throws XMLDBException {
ResourceSet result = service.queryResource(resource, query);
if(message == null)
assertEquals(expected, result.getSize());
else
assertEquals(message, expected, result.getSize());
return result;
}
/**
* @return
* @throws XMLDBException
*/
private XPathQueryService storeXMLStringAndGetQueryService(String documentName,
String content) throws XMLDBException {
XMLResource doc =
(XMLResource) testCollection.createResource(
documentName, "XMLResource" );
doc.setContent(content);
testCollection.storeResource(doc);
XPathQueryService service =
(XPathQueryService) testCollection.getService(
"XPathQueryService",
"1.0");
return service;
}
public void testNamespaces() {
try {
XPathQueryService service =
storeXMLStringAndGetQueryService("namespaces.xml", namespaces);
service.setNamespace("t", "http:
ResourceSet result =
service.queryResource("namespaces.xml", "//t:section");
assertEquals(1, result.getSize());
result =
service.queryResource("namespaces.xml", "/t:test//c:comment");
assertEquals(1, result.getSize());
result = service.queryResource("namespaces.xml", "
assertEquals(1, result.getSize());
/**
* @param result
* @throws XMLDBException
*/
private void printResult(ResourceSet result) throws XMLDBException {
for (ResourceIterator i = result.getIterator();
i.hasMoreResources();
) {
Resource r = i.nextResource();
System.out.println(r.getContent());
}
}
public void testMembersAsResource() {
try {
// XPathQueryService service =
// (XPathQueryService) testCollection.getService(
// "XPathQueryService",
// ResourceSet result = service.query("//SPEECH[LINE &= 'marriage']");
XPathQueryService service =
storeXMLStringAndGetQueryService("numbers.xml", numbers);
ResourceSet result = service.query("//item/price");
Resource r = result.getMembersAsResource();
String content = (String)r.getContent();
System.out.println(content);
Pattern p = Pattern.compile( ".*(<price>.*){4}", Pattern.DOTALL);
Matcher m = p.matcher(content);
assertTrue( "get whole document numbers.xml", m.matches() );
} catch (XMLDBException e) {
fail(e.getMessage());
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(XPathQueryTest.class);
}
}
|
// $Id: ConfiguratorFactory.java,v 1.8 2004/07/30 04:43:52 jiwils Exp $
package org.jgroups.conf;
import org.w3c.dom.Element;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.ChannelException;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
/**
* The ConfigurationFactory is a factory that returns a protocol stack configurator.
* The protocol stack configurator is an object that read a stack configuration and
* parses it so that the ProtocolStack can create a stack.
* <BR>
* Currently the factory returns one of the following objects:<BR>
* 1. XmlConfigurator - parses XML files that are according to the jgroups-protocol.dtd<BR>
* 2. PlainConfigurator - uses the old style strings UDP:FRAG: etc etc<BR>
*
* @author Filip Hanik (<a href="mailto:filip@filip.net">filip@filip.net)
* @version 1.0
*/
public class ConfiguratorFactory {
public static final String JAXP_MISSING_ERROR_MSG=
"JAXP Error: the required XML parsing classes are not available; " +
"make sure that JAXP compatible libraries are in the classpath.";
static final String FORCE_CONFIGURATION="force.properties";
static Log log=LogFactory.getLog(ConfiguratorFactory.class);
static final String propertiesOverride;
// Check for the presence of the system property "force.properties", and
// act appropriately if it is set. We only need to do this once since the
// system properties are highly unlikely to change.
static {
Properties properties = System.getProperties();
propertiesOverride = properties.getProperty(FORCE_CONFIGURATION);
if (propertiesOverride != null && log.isInfoEnabled()) {
log.info("using properties override: " + propertiesOverride);
}
}
protected ConfiguratorFactory() {
}
/**
* Returns a protocol stack configurator based on the XML configuration
* provided at the specified URL.
*
* @param url a URL pointing to a JGroups XML configuration.
*
* @return a <code>ProtocolStackConfigurator</code> containing the stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration of
* the protocol stack.
*/
public static ProtocolStackConfigurator getStackConfigurator(File file)
throws ChannelException {
ProtocolStackConfigurator returnValue;
if (propertiesOverride != null) {
returnValue = getStackConfigurator(propertiesOverride);
}
else {
checkForNullConfiguration(file);
checkJAXPAvailability();
try {
returnValue=
XmlConfigurator.getInstance(new FileInputStream(file));
}
catch (IOException ioe) {
throw createChannelConfigurationException(ioe);
}
}
return returnValue;
}
/**
* Returns a protocol stack configurator based on the XML configuration
* provided at the specified URL.
*
* @param url a URL pointing to a JGroups XML configuration.
*
* @return a <code>ProtocolStackConfigurator</code> containing the stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration of
* the protocol stack.
*/
public static ProtocolStackConfigurator getStackConfigurator(URL url)
throws ChannelException {
ProtocolStackConfigurator returnValue;
if (propertiesOverride != null) {
returnValue = getStackConfigurator(propertiesOverride);
}
else {
checkForNullConfiguration(url);
checkJAXPAvailability();
try {
returnValue=XmlConfigurator.getInstance(url);
}
catch (IOException ioe) {
throw createChannelConfigurationException(ioe);
}
}
return returnValue;
}
/**
* Returns a protocol stack configurator based on the XML configuration
* provided by the specified XML element.
*
* @param element a XML element containing a JGroups XML configuration.
*
* @return a <code>ProtocolStackConfigurator</code> containing the stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration of
* the protocol stack.
*/
public static ProtocolStackConfigurator getStackConfigurator(Element element)
throws ChannelException {
ProtocolStackConfigurator returnValue;
if (propertiesOverride != null) {
returnValue = getStackConfigurator(propertiesOverride);
}
else {
checkForNullConfiguration(element);
// Since Element is a part of the JAXP specification and because an
// Element instance already exists, there is no need to check for
// JAXP availability.
// checkJAXPAvailability();
try {
returnValue=XmlConfigurator.getInstance(element);
}
catch (IOException ioe) {
throw createChannelConfigurationException(ioe);
}
}
return returnValue;
}
/**
* Returns a protocol stack configurator based on the provided properties
* string.
*
* @param properties an old style property string, a string representing a
* system resource containing a JGroups XML configuration,
* a string representing a URL pointing to a JGroups XML
* XML configuration, or a string representing a file name
* that contains a JGroups XML configuration.
*/
public static ProtocolStackConfigurator getStackConfigurator(String properties)
throws ChannelException {
if (propertiesOverride != null && propertiesOverride != properties) {
properties = propertiesOverride;
}
checkForNullConfiguration(properties);
ProtocolStackConfigurator returnValue;
// Attempt to treat the properties string as a pointer to an XML
// configuration.
XmlConfigurator configurator = null;
try {
configurator=getXmlConfigurator(properties);
}
catch (IOException ioe) {
throw createChannelConfigurationException(ioe);
}
// Did the properties string point to a JGroups XML configuration?
if (configurator != null) {
returnValue=configurator;
}
else {
// Attempt to process the properties string as the old style
// property string.
returnValue=new PlainConfigurator(properties);
}
return returnValue;
}
public static ProtocolStackConfigurator getStackConfigurator(Object properties) throws IOException {
InputStream input=null;
if (propertiesOverride != null) {
properties = propertiesOverride;
}
if(properties instanceof URL) {
try {
input=((URL)properties).openStream();
}
catch(Throwable t) {
}
}
// if it is a string, then it could be a plain string or a url
if(input == null && properties instanceof String) {
try {
input=new URL((String)properties).openStream();
}
catch(Exception ignore) {
// if we get here this means we don't have a URL
}
// another try - maybe it is a resource, e.g. default.xml
if(input == null && ((String)properties).endsWith("xml")) {
try {
ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
input=classLoader.getResourceAsStream((String)properties);
}
catch(Throwable ignore) {
}
}
// try a regular file name
// This code was moved from the parent block (below) because of the
// possibility of causing a ClassCastException.
if(input == null) {
try {
input=new FileInputStream((String)properties);
}
catch(Throwable t) {
}
}
}
// try a regular file
if(input == null && properties instanceof File) {
try {
input=new FileInputStream((File)properties);
}
catch(Throwable t) {
}
}
if(input == null)
log.info("properties are neither a URL nor a file");
else {
return XmlConfigurator.getInstance(input);
}
if(properties instanceof Element) {
return XmlConfigurator.getInstance((Element)properties);
}
return new PlainConfigurator((String)properties);
}
/**
* Returns a JGroups XML configuration InputStream based on the provided
* properties string.
*
* @param properties a string representing a system resource containing a
* JGroups XML configuration, a string representing a URL
* pointing to a JGroups ML configuration, or a string
* representing a file name that contains a JGroups XML
* configuration.
*
* @throws IOException if the provided properties string appears to be a
* valid URL but is unreachable.
*/
static InputStream getConfigStream(String properties) throws IOException {
InputStream configStream = null;
// Check to see if the properties string is a URL.
try {
configStream=new URL(properties).openStream();
}
catch (MalformedURLException mre) {
// the properties string is not a URL
}
// Commented so the caller is notified of this condition, but left in
// the code for documentation purposes.
// catch (IOException ioe) {
// the specified URL string was not reachable
// Check to see if the properties string is the name of a resource,
// e.g. default.xml.
if(configStream == null && properties.endsWith("xml")) {
ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
configStream=classLoader.getResourceAsStream(properties);
}
// Check to see if the properties string is the name of a file.
if (configStream == null) {
try {
configStream=new FileInputStream((String)properties);
}
catch(FileNotFoundException fnfe) {
// the properties string is likely not a file
}
}
return configStream;
}
/**
* Returns an XmlConfigurator based on the provided properties string (if
* possible).
*
* @param properties a string representing a system resource containing a
* JGroups XML configuration, a string representing a URL
* pointing to a JGroups ML configuration, or a string
* representing a file name that contains a JGroups XML
* configuration.
*
* @return an XmlConfigurator instance based on the provided properties
* string; <code>null</code> if the provided properties string does
* not point to an XML configuration.
*
* @throws IOException if the provided properties string appears to be a
* valid URL but is unreachable, or if the JGroups XML
* configuration pointed to by the URL can not be
* parsed.
*/
static XmlConfigurator getXmlConfigurator(String properties) throws IOException {
XmlConfigurator returnValue=null;
InputStream configStream=getConfigStream(properties);
if (configStream != null) {
checkJAXPAvailability();
returnValue=XmlConfigurator.getInstance(configStream);
}
return returnValue;
}
/**
* Creates a <code>ChannelException</code> instance based upon a
* configuration problem.
*
* @param cause the exceptional configuration condition to be used as the
* created <code>ChannelException</code>'s cause.
*/
static ChannelException createChannelConfigurationException(Throwable cause) {
return new ChannelException("unable to load the protocol stack", cause);
}
/**
* Check to see if the specified configuration properties are
* <code>null</null> which is not allowed.
*
* @param properties the specified protocol stack configuration.
*
* @throws NullPointerException if the specified configuration properties
* are <code>null</code>.
*/
static void checkForNullConfiguration(Object properties) {
if (properties == null) {
final String msg =
"the specifed protocol stack configuration was null.";
throw new NullPointerException(msg);
}
}
/**
* Checks the availability of the JAXP classes on the classpath.
*
* @throws NoClassDefFoundError if the required JAXP classes are not
* availabile on the classpath.
*/
static void checkJAXPAvailability() {
try {
// TODO: Do some real class checking here instead of forcing the
// load of a JGroups class that happens (by default) to do it
// for us.
XmlConfigurator.class.getName();
}
catch (NoClassDefFoundError error) {
throw new NoClassDefFoundError(JAXP_MISSING_ERROR_MSG);
}
}
}
|
// $Id: STATE_TRANSFER.java,v 1.19 2006/03/17 08:33:38 belaban Exp $
package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.View;
import org.jgroups.blocks.GroupRequest;
import org.jgroups.blocks.RequestCorrelator;
import org.jgroups.blocks.RequestHandler;
import org.jgroups.stack.Protocol;
import org.jgroups.stack.StateTransferInfo;
import org.jgroups.util.Rsp;
import org.jgroups.util.RspList;
import org.jgroups.util.Util;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Properties;
import java.util.Vector;
class StateTransferRequest implements Serializable {
static final int MAKE_COPY=1; // arg = originator of request
static final int RETURN_STATE=2; // arg = orginator of request
int type=0;
final Object arg;
private static final long serialVersionUID = -7734608266762273116L;
StateTransferRequest(int type, Object arg) {
this.type=type;
this.arg=arg;
}
public int getType() {
return type;
}
public Object getArg() {
return arg;
}
public String toString() {
return "[StateTransferRequest: type=" + type2Str(type) + ", arg=" + arg + ']';
}
static String type2Str(int t) {
switch(t) {
case MAKE_COPY:
return "MAKE_COPY";
case RETURN_STATE:
return "RETURN_STATE";
default:
return "<unknown>";
}
}
}
/**
* State transfer layer. Upon receiving a GET_STATE event from JChannel, a MAKE_COPY message is
* sent to all members. When the originator receives MAKE_COPY, it queues all messages to the
* channel.
* When another member receives the message, it asks the JChannel to provide it with a copy of
* the current state (GetStateEvent is received by application, returnState() sends state down the
* stack). Then the current layer sends a unicast RETURN_STATE message to the coordinator, which
* returns the cached copy.
* When the state is received by the originator, the GET_STATE sender is unblocked with a
* GET_STATE_OK event up the stack (unless it already timed out).<p>
* Requires QUEUE layer on top.
*
* @author Bela Ban
*/
public class STATE_TRANSFER extends Protocol implements RequestHandler {
Address local_addr=null;
final Vector members=new Vector(11);
final Message m=null;
boolean is_server=false;
byte[] cached_state=null;
final Object state_xfer_mutex=new Object(); // get state from appl (via channel).
long timeout_get_appl_state=5000;
long timeout_return_state=5000;
RequestCorrelator corr=null;
final Vector observers=new Vector(5);
final HashMap map=new HashMap(7);
/**
* All protocol names have to be unique !
*/
public String getName() {
return "STATE_TRANSFER";
}
public void init() throws Exception {
map.put("state_transfer", Boolean.TRUE);
map.put("protocol_class", getClass().getName());
}
public void start() throws Exception {
corr=new RequestCorrelator(getName(), this, this);
passUp(new Event(Event.CONFIG, map));
}
public void stop() {
if(corr != null) {
corr.stop();
corr=null;
}
}
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
// Milliseconds to wait for application to provide requested state, events are
// STATE_TRANSFER up and STATE_TRANSFER_OK down
str=props.getProperty("timeout_get_appl_state");
if(str != null) {
timeout_get_appl_state=Long.parseLong(str);
props.remove("timeout_get_appl_state");
}
// Milliseconds to wait for 1 or all members to return its/their state. 0 means wait
// forever. States are retrieved using GroupRequest/RequestCorrelator
str=props.getProperty("timeout_return_state");
if(str != null) {
timeout_return_state=Long.parseLong(str);
props.remove("timeout_return_state");
}
if(props.size() > 0) {
log.error("STATE_TRANSFER.setProperties(): the following properties are not recognized: " + props);
return false;
}
return true;
}
public Vector requiredUpServices() {
Vector ret=new Vector(2);
ret.addElement(new Integer(Event.START_QUEUEING));
ret.addElement(new Integer(Event.STOP_QUEUEING));
return ret;
}
public void up(Event evt) {
switch(evt.getType()) {
case Event.BECOME_SERVER:
is_server=true;
break;
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
break;
case Event.TMP_VIEW:
case Event.VIEW_CHANGE:
Vector new_members=((View)evt.getArg()).getMembers();
synchronized(members) {
members.removeAllElements();
if(new_members != null && new_members.size() > 0)
for(int k=0; k < new_members.size(); k++)
members.addElement(new_members.elementAt(k));
}
break;
}
if(corr != null)
corr.receive(evt); // will consume or pass up, depending on header
else
passUp(evt);
}
public void down(Event evt) {
Object coord, state;
Vector event_list;
StateTransferInfo info;
switch(evt.getType()) {
case Event.TMP_VIEW:
case Event.VIEW_CHANGE:
Vector new_members=((View)evt.getArg()).getMembers();
synchronized(members) {
members.removeAllElements();
if(new_members != null && new_members.size() > 0)
for(int k=0; k < new_members.size(); k++)
members.addElement(new_members.elementAt(k));
}
break;
case Event.GET_STATE: // generated by JChannel.getState()
info=(StateTransferInfo)evt.getArg();
coord=determineCoordinator();
if(coord == null || coord.equals(local_addr)) {
event_list=new Vector(1);
event_list.addElement(new Event(Event.GET_STATE_OK, new StateTransferInfo()));
passUp(new Event(Event.STOP_QUEUEING, event_list));
return; // don't pass down any further !
}
sendMakeCopyMessage(); // multicast MAKE_COPY to all members (including me)
state=getStateFromSingle(info.target);
/* Pass up the state to the application layer (insert into JChannel's event queue */
event_list=new Vector(1);
event_list.addElement(new Event(Event.GET_STATE_OK, new StateTransferInfo(null, info.state_id, 0L, (byte[])state)));
/* Now stop queueing */
passUp(new Event(Event.STOP_QUEUEING, event_list));
return; // don't pass down any further !
case Event.GET_APPLSTATE_OK:
synchronized(state_xfer_mutex) {
cached_state=(byte[])evt.getArg();
state_xfer_mutex.notifyAll();
}
return; // don't pass down any further !
}
passDown(evt); // pass on to the layer below us
}
public Object handle(Message msg) {
StateTransferRequest req;
try {
req=(StateTransferRequest)msg.getObject();
switch(req.getType()) {
case StateTransferRequest.MAKE_COPY:
makeCopy(req.getArg());
return null;
case StateTransferRequest.RETURN_STATE:
if(is_server)
return cached_state;
else {
if(warn) log.warn("RETURN_STATE: returning null" +
"as I'm not yet an operational state server !");
return null;
}
default:
if(log.isErrorEnabled()) log.error("type " + req.getType() +
"is unknown in StateTransferRequest !");
return null;
}
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception is " + e);
return null;
}
}
byte[] getStateFromSingle(Address target) {
Vector dests=new Vector(11);
Message msg;
StateTransferRequest r=new StateTransferRequest(StateTransferRequest.RETURN_STATE, local_addr);
RspList rsp_list;
Rsp rsp;
Address dest;
GroupRequest req;
int num_tries=0;
try {
msg=new Message(null, null, Util.objectToByteBuffer(r));
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception=" + e);
return null;
}
while(members.size() > 1 && num_tries++ < 3) { // excluding myself
dest=target != null? target : determineCoordinator();
if(dest == null)
return null;
msg.setDest(dest);
dests.removeAllElements();
dests.addElement(dest);
req=new GroupRequest(msg, corr, dests, GroupRequest.GET_FIRST, timeout_return_state, 0);
req.execute();
rsp_list=req.getResults();
for(int i=0; i < rsp_list.size(); i++) { // get the first non-suspected result
rsp=(Rsp)rsp_list.elementAt(i);
if(rsp.wasReceived())
return (byte[])rsp.getValue();
}
Util.sleep(1000);
}
return null;
}
Vector getStateFromMany(Vector targets) {
Vector dests=new Vector(11);
Message msg;
StateTransferRequest r=new StateTransferRequest(StateTransferRequest.RETURN_STATE, local_addr);
RspList rsp_list;
GroupRequest req;
int i;
if(targets != null) {
for(i=0; i < targets.size(); i++)
if(!local_addr.equals(targets.elementAt(i)))
dests.addElement(targets.elementAt(i));
}
else {
for(i=0; i < members.size(); i++)
if(!local_addr.equals(members.elementAt(i)))
dests.addElement(members.elementAt(i));
}
if(dests.size() == 0)
return null;
msg=new Message();
try {
msg.setBuffer(Util.objectToByteBuffer(r));
}
catch(Exception e) {
}
req=new GroupRequest(msg, corr, dests, GroupRequest.GET_ALL, timeout_return_state, 0);
req.execute();
rsp_list=req.getResults();
return rsp_list.getResults();
}
void sendMakeCopyMessage() {
GroupRequest req;
Message msg=new Message();
StateTransferRequest r=new StateTransferRequest(StateTransferRequest.MAKE_COPY, local_addr);
Vector dests=new Vector(11);
for(int i=0; i < members.size(); i++)
dests.addElement(members.elementAt(i));
if(dests.size() == 0)
return;
try {
msg.setBuffer(Util.objectToByteBuffer(r));
}
catch(Exception e) {
}
req=new GroupRequest(msg, corr, dests, GroupRequest.GET_ALL, timeout_return_state, 0);
req.execute();
}
/**
* Return the first element of members which is not me. Otherwise return null.
*/
Address determineCoordinator() {
Address ret=null;
if(members != null && members.size() > 1) {
for(int i=0; i < members.size(); i++)
if(!local_addr.equals(members.elementAt(i)))
return (Address)members.elementAt(i);
}
return ret;
}
/**
* If server, ask application to send us a copy of its state (STATE_TRANSFER up,
* STATE_TRANSFER down). If client, start queueing events. Queuing will be stopped when
* state has been retrieved (or not) from single or all member(s).
*/
void makeCopy(Object sender) {
if(sender.equals(local_addr)) { // was sent by us, has to start queueing
passUp(new Event(Event.START_QUEUEING));
}
else { // only retrieve state from appl when not in client state anymore
if(is_server) { // get state from application and store it locally
synchronized(state_xfer_mutex) {
cached_state=null;
StateTransferInfo info=new StateTransferInfo(local_addr);
passUp(new Event(Event.GET_APPLSTATE, info));
if(cached_state == null) {
try {
state_xfer_mutex.wait(timeout_get_appl_state); // wait for STATE_TRANSFER_OK
}
catch(Exception e) {
}
}
}
}
}
}
}
|
// $Id: JoinRsp.java,v 1.8 2005/12/08 13:13:07 belaban Exp $
package org.jgroups.protocols.pbcast;
import org.jgroups.View;
import org.jgroups.Global;
import org.jgroups.util.Streamable;
import org.jgroups.util.Util;
import java.io.Serializable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.DataInputStream;
public class JoinRsp implements Serializable, Streamable {
View view=null;
Digest digest=null;
private static final long serialVersionUID = 2949193438640587597L;
public JoinRsp() {
}
public JoinRsp(View v, Digest d) {
view=v;
digest=d;
}
View getView() {
return view;
}
Digest getDigest() {
return digest;
}
public void writeTo(DataOutputStream out) throws IOException {
Util.writeStreamable(view, out);
Util.writeStreamable(digest, out);
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
view=(View)Util.readStreamable(View.class, in);
digest=(Digest)Util.readStreamable(Digest.class, in);
}
public int serializedSize() {
int retval=Global.BYTE_SIZE * 2; // presence for view and digest
if(view != null)
retval+=view.serializedSize();
if(digest != null)
retval+=digest.serializedSize();
return retval;
}
public String toString() {
StringBuffer sb=new StringBuffer();
sb.append("view: ");
if(view == null)
sb.append("<null>");
else
sb.append(view);
sb.append(", digest: ");
if(digest == null)
sb.append("<null>");
else
sb.append(digest);
return sb.toString();
}
}
|
/*
* $Id: NewContentCrawler.java,v 1.39 2004-09-27 23:46:45 dcfok Exp $
*/
package org.lockss.crawler;
import java.util.*;
import org.lockss.util.*;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.plugin.*;
import org.lockss.state.*;
public class NewContentCrawler extends FollowLinkCrawler {
private static Logger logger = Logger.getLogger("NewContentCrawler");
public NewContentCrawler(ArchivalUnit au, CrawlSpec spec, AuState aus) {
super(au, spec, aus);
crawlStatus = new Crawler.Status(au, spec.getStartingUrls(), getType());
}
public int getType() {
return Crawler.NEW_CONTENT;
}
/**
* Keeps crawling from the baseUrl til it hits the refetchDepth
* to extract url for newly added pages since last crawl.
*
* @return a set of urls that contains updated content.
*/
protected Set getLinks(){
Set extractedUrls = new HashSet();
int refetchDepth0 = spec.getRefetchDepth();
String key = StringUtil.replaceString(PARAM_REFETCH_DEPTH,
"<auid>", au.getAuId());
int refetchDepth = Configuration.getIntParam(key, refetchDepth0);
if (refetchDepth != refetchDepth0) {
logger.info("Crawl spec refetch depth (" + refetchDepth0 +
") overridden by parameter (" + refetchDepth + ")");
}
//maxDepth should be greater than refetchDepth
if (refetchDepth > maxDepth){ //it should not happen
logger.error("Max. depth is set smaller than refetchDepth." +
" Abort Crawl of " + au);
crawlStatus.setCrawlError("Max. Crawl depth too small");
abortCrawl();
//return null;
}
Iterator it = spec.getStartingUrls().iterator(); //getStartingUrls();
for (int ix=0; ix<refetchDepth; ix++) {
//don't use clear() or it will empty the iterator
extractedUrls = new HashSet();
while (it.hasNext() && !crawlAborted) {
String url = (String)it.next();
//catch and warn if there's a url in the start urls
//that we shouldn't cache
logger.debug3("Trying to process " +url);
// check crawl window during crawl
if (!withinCrawlWindow()) {
crawlStatus.setCrawlError(Crawler.STATUS_WINDOW_CLOSED);
abortCrawl();
//return null;
}
if (parsedPages.contains(url)) {
continue;
}
if (spec.isIncluded(url)) {
if (!fetchAndParse(url, extractedUrls, parsedPages,
cus, true, true)) {
if (crawlStatus.getCrawlError() == null) {
crawlStatus.setCrawlError(Crawler.STATUS_ERROR);
}
}
} else if (ix == 0) {
logger.warning("Called with a starting url we aren't suppose to "+
"cache: "+url);
}
} // end while loop
it = extractedUrls.iterator();
} // end for loop
lvlCnt = refetchDepth;
return extractedUrls;
} // end of getLink()
}
|
package org.nutz.json.entity;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
import org.nutz.json.JsonField;
import org.nutz.json.JsonIgnore;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.Strings;
import org.nutz.lang.eject.EjectByGetter;
import org.nutz.lang.eject.Ejecting;
import org.nutz.lang.inject.InjectBySetter;
import org.nutz.lang.inject.Injecting;
import org.nutz.lang.reflect.ReflectTool;
public class JsonEntityField {
private String name;
private boolean ignore;
private Type genericType;
private Injecting injecting;
private Ejecting ejecting;
private boolean forceString;
private double ignoreNullDouble = -0.94518;
private int ignoreNullInt = -94518;
private boolean isInt;
private boolean isDouble;
private boolean hasJsonIgnore;
private Format dataFormat;
private Mirror<?> mirror;
private Class<?> declaringClass;
public boolean isForceString() {
return forceString;
}
public void setForceString(boolean forceString) {
this.forceString = forceString;
}
public boolean isIgnore() {
return ignore;
}
public void setIgnore(boolean ignore) {
this.ignore = ignore;
}
/**
* , set
*/
public static JsonEntityField eval(Mirror<?> mirror, String name, Method getter, Method setter) {
JsonEntityField jef = new JsonEntityField();
jef.declaringClass = mirror.getType();
jef.setGenericType(getter.getGenericReturnType());
jef.name = name;
jef.ejecting = new EjectByGetter(getter);
jef.injecting = new InjectBySetter(setter);
jef.mirror = Mirror.me(getter.getReturnType());
return jef;
}
public static JsonEntityField eval(Mirror<?> mirror, String name, Type type, Ejecting ejecting, Injecting injecting) {
JsonEntityField jef = new JsonEntityField();
jef.genericType = mirror.getType();
jef.setGenericType(type);
jef.name = name;
jef.ejecting = ejecting;
jef.injecting = injecting;
jef.mirror = Mirror.me(type);
return jef;
}
@SuppressWarnings({"deprecation", "rawtypes"})
public static JsonEntityField eval(Mirror<?> mirror, Field fld) {
if (fld == null) {
return null;
}
// XXX _! by wendal
// if (fld.getName().startsWith("_") || fld.getName().startsWith("$"))
if (fld.getName().startsWith("$")
&& fld.getAnnotation(JsonField.class) == null)
return null;
JsonField jf = fld.getAnnotation(JsonField.class);
JsonEntityField jef = new JsonEntityField();
jef.declaringClass = mirror.getType();
jef.setGenericType(Lang.getFieldType(mirror, fld));
jef.name = Strings.sBlank(null == jf ? null : jf.value(), fld.getName());
jef.ejecting = mirror.getEjecting(fld.getName());
jef.injecting = mirror.getInjecting(fld.getName());
jef.mirror = Mirror.me(fld.getType());
// ignore
if (Modifier.isTransient(fld.getModifiers())
|| (null != jf && jf.ignore())) {
jef.setIgnore(true);
}
if (null != jf) {
jef.setForceString(jf.forceString());
String dataFormat = jf.dataFormat();
if(Strings.isBlank(dataFormat)){
dataFormat = jf.dateFormat();
}
if(!Strings.isBlank(dataFormat)){
Mirror jfmirror = Mirror.me(jef.genericType);
if(jfmirror.isNumber()){
jef.dataFormat = new DecimalFormat(dataFormat);
}else if(jfmirror.isDateTimeLike()){
DateFormat df = null;
if (Strings.isBlank(jf.locale())) {
df = new SimpleDateFormat(dataFormat);
}
else {
df = new SimpleDateFormat(dataFormat, Locale.forLanguageTag(jf.locale()));
}
if (!Strings.isBlank(jf.timeZone())) {
df.setTimeZone(TimeZone.getTimeZone(jf.timeZone()));
}
jef.dataFormat = df;
}
}
}
JsonIgnore jsonIgnore = fld.getAnnotation(JsonIgnore.class);
if (jsonIgnore != null) {
Mirror<?> fldMirror = Mirror.me(fld.getType());
jef.isInt = fldMirror.isInt();
jef.isDouble = fldMirror.isDouble() || fldMirror.isFloat();
jef.hasJsonIgnore = true;
if (jef.isDouble)
jef.ignoreNullDouble = jsonIgnore.null_double();
if (jef.isInt)
jef.ignoreNullInt = jsonIgnore.null_int();
}
return jef;
}
private JsonEntityField() {}
public String getName() {
return name;
}
public Type getGenericType() {
return genericType;
}
public void setValue(Object obj, Object value) {
if (injecting != null)
injecting.inject(obj, value);
}
public Object getValue(Object obj) {
if (ejecting == null)
return null;
Object val = ejecting.eject(obj);
if (val == null)
return null;
if (hasJsonIgnore) {
if (isInt && ((Number)val).intValue() == ignoreNullInt)
return null;
if (isDouble && ((Number)val).doubleValue() == ignoreNullDouble)
return null;
}
return val;
}
public Format getDataFormat() {
return dataFormat == null ? null : (Format)dataFormat.clone();
}
public boolean hasDataFormat() {
return dataFormat != null;
}
public Mirror<?> getMirror() {
return mirror;
}
public void setGenericType(Type genericType) {
this.genericType = ReflectTool.getInheritGenericType(declaringClass, genericType);;
}
public void setInjecting(Injecting injecting) {
this.injecting = injecting;
}
public void setEjecting(Ejecting ejecting) {
this.ejecting = ejecting;
}
public Ejecting getEjecting() {
return ejecting;
}
public Injecting getInjecting() {
return injecting;
}
}
|
package battlecode.world;
import static battlecode.common.GameConstants.*;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import battlecode.common.Chassis;
import battlecode.common.ComponentClass;
import battlecode.common.ComponentType;
import battlecode.common.Direction;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.Message;
import battlecode.common.Robot;
import battlecode.common.Team;
import battlecode.engine.GenericRobot;
import battlecode.engine.signal.Signal;
import battlecode.server.Config;
import battlecode.world.signal.DeathSignal;
import battlecode.world.signal.TurnOffSignal;
public class InternalRobot extends InternalObject implements Robot, GenericRobot {
/**
* Robots that are inside a transport are considered to be at this
* location, so that no one but the dropship will be able to sense them.
*/
public static final MapLocation VERY_FAR_AWAY = new MapLocation(-1000, -1000);
private volatile double myEnergonLevel;
protected volatile Direction myDirection;
private volatile boolean energonChanged = true;
protected volatile long controlBits;
// is this used ever?
protected volatile boolean hasBeenAttacked = false;
private static boolean upkeepEnabled = Config.getGlobalConfig().getBoolean("bc.engine.upkeep-enabled");
/** first index is robot type, second is direction, third is x or y */
private static final Map<ComponentType, int[][][]> offsets = GameMap.computeVisibleOffsets();
/** number of bytecodes used in the most recent round */
private volatile int bytecodesUsed = 0;
private List<Message> incomingMessageQueue;
protected GameMap.MapMemory mapMemory;
private InternalRobotBuffs buffs = new InternalRobotBuffs(this);
public final Chassis chassis;
private List<BaseComponent> newComponents;
private volatile boolean on;
private volatile boolean hasBeenOff;
private volatile int cores;
private volatile int platings;
private volatile int regens;
private volatile int weight;
private volatile int invulnerableRounds;
private volatile InternalRobot transporter;
private Set<InternalRobot> passengers;
private RobotControllerImpl rc;
private volatile Bug buggedBy;
private volatile int dummyRounds = GameConstants.DUMMY_LIFETIME;
static class ComponentList {
ArrayList<BaseComponent> all;
EnumMap<ComponentClass, ArrayList<BaseComponent>> byClass;
public ComponentList() {
all = new ArrayList<BaseComponent>();
byClass = new EnumMap<ComponentClass, ArrayList<BaseComponent>>(ComponentClass.class);
for (ComponentClass c : ComponentClass.values())
byClass.put(c, new ArrayList<BaseComponent>());
}
public void add(BaseComponent t) {
all.add(t);
byClass.get(t.type().componentClass).add(t);
}
public ArrayList<BaseComponent> get(ComponentClass cls) {
return byClass.get(cls);
}
public ArrayList<BaseComponent> values() {
return all;
}
public boolean hasComponent(ComponentType type) {
for (BaseComponent bc : all) {
if (bc.type == type) {
return true;
}
}
return false;
}
}
private ComponentList components = new ComponentList();
public InternalRobotBuffs getBuffs() {
return buffs;
}
public RobotControllerImpl getRC() {
return rc;
}
public void setRC(RobotControllerImpl rc) {
this.rc = rc;
}
@SuppressWarnings("unchecked")
public InternalRobot(GameWorld gw, Chassis chassis, MapLocation loc, Team t,
boolean spawnedRobot) {
super(gw, loc, chassis.level, t);
myDirection = Direction.values()[gw.getRandGen().nextInt(8)];
this.chassis = chassis;
myEnergonLevel = getMaxEnergon();
incomingMessageQueue = new LinkedList<Message>();
mapMemory = new GameMap.MapMemory(gw.getGameMap());
saveMapMemory(null, loc, false);
controlBits = 0;
newComponents = new ArrayList<BaseComponent>();
switch (chassis) {
case DUMMY:
case DEBRIS:
on = false;
default:
on = true;
}
}
public boolean inTransport() {
return transporter != null;
}
@Override
public InternalRobot container() {
return transporter;
}
public boolean isOn() {
return on;
}
public void setPower(boolean b) {
if (b && !on) {
hasBeenOff = true;
for (BaseComponent c : components.values()) {
c.activate(POWER_WAKE_DELAY);
}
}
on = b;
}
public void setBugged(Bug b) {
if (buggedBy != null) {
buggedBy.removeBug();
}
buggedBy = b;
}
public boolean queryHasBeenOff() {
boolean tmp = hasBeenOff;
hasBeenOff = false;
return tmp;
}
public boolean hasRoomFor(ComponentType c) {
if (c == ComponentType.IRON) {
for (BaseComponent bc : components.get(ComponentClass.ARMOR)) {
if (bc.type == ComponentType.IRON) {
return false;
}
}
}
return c.weight + weight <= chassis.weight;
}
public void equip(ComponentType type) {
BaseComponent controller;
switch (type) {
case SHIELD:
case HARDENED:
case REGEN:
case PLASMA:
case PLATING:
case PROCESSOR:
controller = new BaseComponent(type, this);
break;
case SMG:
case BLASTER:
case RAILGUN:
case HAMMER:
case MEDIC:
case BEAM:
controller = new Weapon(type, this);
break;
case SATELLITE:
case TELESCOPE:
case SIGHT:
case RADAR:
case BUILDING_SENSOR:
controller = new Sensor(type, this);
break;
case BUG:
controller = new Bug(type, this);
break;
case ANTENNA:
case DISH:
case NETWORK:
controller = new Radio(type, this);
break;
case RECYCLER:
controller = new Miner(this);
break;
case CONSTRUCTOR:
case FACTORY:
case ARMORY:
case DUMMY:
controller = new Builder(type, this);
break;
case SMALL_MOTOR:
case MEDIUM_MOTOR:
case LARGE_MOTOR:
case FLYING_MOTOR:
case BUILDING_MOTOR:
controller = new Motor(type, this);
break;
case JUMP:
controller = new JumpCore(type, this);
break;
case DROPSHIP:
controller = new Dropship(this);
break;
case IRON:
controller = new IronComponent(type, this);
break;
default:
throw new RuntimeException("component " + type + " is not supported yet");
}
components.add(controller);
newComponents.add(controller);
if (myGameWorld.getCurrentRound() >= 0) {
controller.activate(EQUIP_WAKE_DELAY);
}
weight += type.weight;
switch (type) {
case PLATING:
platings++;
changeEnergonLevel(GameConstants.PLATING_HP_BONUS);
break;
case PROCESSOR:
cores++;
break;
case REGEN:
regens++;
break;
case DROPSHIP:
passengers = new HashSet<InternalRobot>();
break;
}
}
public void addAction(Signal s) {
myGameWorld.visitSignal(s);
}
public Chassis getChassis() {
return chassis;
}
/*
public InternalComponent [] getComponents() {
return Iterables.toArray(Iterables.transform(components.values(),Util.controllerToComponent),InternalComponent.class);
}
*/
public ComponentType[] getComponentTypes() {
return Iterables.toArray(Iterables.transform(components.values(), Util.typeOfComponent), ComponentType.class);
}
public BaseComponent[] getComponentControllers() {
return components.values().toArray(new BaseComponent[0]);
}
public BaseComponent[] getNewComponentControllers() {
BaseComponent[] controllers = newComponents.toArray(new BaseComponent[0]);
newComponents.clear();
return controllers;
}
public BaseComponent[] getComponentControllers(ComponentClass cl) {
return components.get(cl).toArray(new BaseComponent[0]);
}
public BaseComponent[] getComponentControllers(final ComponentType t) {
Predicate<BaseComponent> p = new Predicate<BaseComponent>() {
public boolean apply(BaseComponent c) {
return c.type() == t;
}
};
Iterable<BaseComponent> filtered = Iterables.filter(components.get(t.componentClass), p);
return Iterables.toArray(filtered, BaseComponent.class);
}
@Override
public void processBeginningOfRound() {
super.processBeginningOfRound();
buffs.processBeginningOfRound();
}
public void processBeginningOfTurn() {
rc.processBeginningOfTurn();
for (BaseComponent c : components.values()) {
c.processBeginningOfTurn();
}
if (invulnerableRounds > 0) {
invulnerableRounds
}
if (on && !myGameWorld.spendResources(getTeam(), chassis.upkeep)) {
myGameWorld.visitSignal(new TurnOffSignal(this, false));
}
if (isOn())
changeEnergonLevel(regens * REGEN_AMOUNT);
}
@Override
public void processEndOfTurn() {
super.processEndOfTurn();
for (BaseComponent c : components.values()) {
c.processEndOfTurn();
}
}
@Override
public void processEndOfRound() {
super.processEndOfRound();
buffs.processEndOfRound();
if (chassis == Chassis.DUMMY) {
dummyRounds
if (dummyRounds <= 0)
suicide();
}
if (myEnergonLevel <= 0) {
suicide();
}
}
public double getEnergonLevel() {
return myEnergonLevel;
}
public Direction getDirection() {
return myDirection;
}
public void activateShield() {
invulnerableRounds = IRON_EFFECT_ROUNDS;
}
public void takeDamage(double baseAmount) {
if (baseAmount < 0) {
changeEnergonLevel(-baseAmount);
return;
}
if (!isOn()) {
changeEnergonLevelFromAttack(-baseAmount);
return;
}
if (invulnerableRounds > 0) {
return;
}
boolean haveHardened = false;
double minDamage = Math.min(SHIELD_MIN_DAMAGE, baseAmount);
for (BaseComponent c : components.get(ComponentClass.ARMOR)) {
switch (c.type()) {
case SHIELD:
baseAmount -= SHIELD_DAMAGE_REDUCTION;
break;
case HARDENED:
haveHardened = true;
break;
case PLASMA:
if (!c.isActive()) {
c.activate();
return;
}
break;
}
}
if (haveHardened && baseAmount > HARDENED_MAX_DAMAGE) {
changeEnergonLevelFromAttack(-HARDENED_MAX_DAMAGE);
} else {
changeEnergonLevelFromAttack(-Math.max(minDamage, baseAmount));
}
}
public void changeEnergonLevelFromAttack(double amount) {
hasBeenAttacked = true;
changeEnergonLevel(amount * (buffs.getDamageReceivedMultiplier() + 1));
}
public void changeEnergonLevel(double amount) {
myEnergonLevel += amount;
if (myEnergonLevel > getMaxEnergon()) {
myEnergonLevel = getMaxEnergon();
}
energonChanged = true;
if (myEnergonLevel <= 0) {
suicide();
}
}
public boolean clearEnergonChanged() {
if (energonChanged) {
energonChanged = false;
return true;
} else {
return false;
}
}
public InternalRobot[] robotsOnBoard() {
return passengers.toArray(new InternalRobot[0]);
}
public int spaceAvailable() {
int space = TRANSPORT_CAPACITY;
for (InternalRobot r : passengers) {
space -= r.getChassis().weight;
}
return space;
}
public double getMaxEnergon() {
return chassis.maxHp + platings * PLATING_HP_BONUS;
}
public void setDirection(Direction dir) {
myDirection = dir;
}
public void suicide() {
(new DeathSignal(this)).accept(myGameWorld);
}
public void enqueueIncomingMessage(Message msg) {
incomingMessageQueue.add(msg);
}
public Message dequeueIncomingMessage() {
if (incomingMessageQueue.size() > 0) {
return incomingMessageQueue.remove(0);
} else {
return null;
}
// ~ return incomingMessageQueue.poll();
}
public Message[] dequeueIncomingMessages() {
Message[] result = incomingMessageQueue.toArray(new Message[incomingMessageQueue.size()]);
incomingMessageQueue.clear();
return result;
}
public GameMap.MapMemory getMapMemory() {
return mapMemory;
}
public void saveMapMemory(MapLocation oldLoc, MapLocation newLoc,
boolean fringeOnly) {
for (BaseComponent c : components.get(ComponentClass.SENSOR)) {
saveMapMemory(newLoc, c.type());
}
}
public void saveMapMemory(MapLocation newLoc, ComponentType t) {
if (t != ComponentType.BUG) {
int[][] myOffsets = offsets.get(t)[myDirection.ordinal()];
mapMemory.rememberLocations(newLoc, myOffsets[0], myOffsets[1]);
}
}
public void addPassenger(InternalRobot passenger) {
passengers.add(passenger);
}
public boolean hasPassenger(InternalRobot passenger) {
return passengers.contains(passenger);
}
public void removePassenger(InternalRobot passenger) {
passengers.remove(passenger);
}
public void loadOnto(InternalRobot transporter) {
this.transporter = transporter;
myGameWorld.notifyMovingObject(this, myLocation, null);
myLocation = VERY_FAR_AWAY;
}
public void unloadTo(MapLocation loc) {
myLocation = loc;
transporter = null;
myGameWorld.notifyMovingObject(this, null, myLocation);
}
public void setControlBits(long l) {
controlBits = l;
}
public long getControlBits() {
return controlBits;
}
public void setBytecodesUsed(int numBytecodes) {
bytecodesUsed = numBytecodes;
}
public int getBytecodesUsed() {
return bytecodesUsed;
}
public int getBytecodeLimit() {
if ((!on) || inTransport()) {
return 0;
}
return BYTECODE_LIMIT_BASE + BYTECODE_LIMIT_ADDON * cores;
}
public boolean hasBeenAttacked() {
return hasBeenAttacked;
}
public boolean hasComponentType(ComponentType type) {
return components.hasComponent(type);
}
@Override
public String toString() {
return String.format("%s:%s#%d", getTeam(), chassis, getID());
}
public void freeMemory() {
incomingMessageQueue = null;
mapMemory = null;
buffs = null;
components = null;
newComponents = null;
passengers = null;
}
}
|
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
package org.sosy_lab.java_smt.test;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.Truth.assert_;
import static com.google.common.truth.TruthJUnit.assume;
import static org.sosy_lab.java_smt.api.FormulaType.IntegerType;
import static org.sosy_lab.java_smt.test.ProverEnvironmentSubject.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.java_smt.SolverContextFactory.Solvers;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BasicProverEnvironment;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.FormulaType.BitvectorType;
import org.sosy_lab.java_smt.api.FunctionDeclaration;
import org.sosy_lab.java_smt.api.Model;
import org.sosy_lab.java_smt.api.Model.ValueAssignment;
import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula;
import org.sosy_lab.java_smt.api.NumeralFormula.RationalFormula;
import org.sosy_lab.java_smt.api.ProverEnvironment;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import org.sosy_lab.java_smt.api.SolverException;
/** Test that values from models are appropriately parsed. */
@RunWith(Parameterized.class)
public class ModelTest extends SolverBasedTest0 {
private static final ArrayFormulaType<IntegerFormula, IntegerFormula> ARRAY_TYPE_INT_INT =
FormulaType.getArrayType(IntegerType, IntegerType);
private static final ImmutableList<Solvers> SOLVERS_WITH_PARTIAL_MODEL =
ImmutableList.of(Solvers.Z3, Solvers.PRINCESS);
@Parameters(name = "{0}")
public static Object[] getAllSolvers() {
return Solvers.values();
}
@Parameter public Solvers solver;
@Override
protected Solvers solverToUse() {
return solver;
}
@Before
public void setup() {
requireModel();
}
@Test
public void testEmpty() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m).isEmpty();
}
assertThat(prover.getModelAssignments()).isEmpty();
}
}
@Test
public void testOnlyTrue() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeTrue());
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m).isEmpty();
}
assertThat(prover.getModelAssignments()).isEmpty();
}
}
@Test
public void testGetSmallIntegers() throws SolverException, InterruptedException {
requireIntegers();
testModelGetters(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(10)),
imgr.makeVariable("x"),
BigInteger.valueOf(10),
"x");
}
@Test
public void testGetNegativeIntegers() throws SolverException, InterruptedException {
requireIntegers();
testModelGetters(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(-10)),
imgr.makeVariable("x"),
BigInteger.valueOf(-10),
"x");
}
@Test
public void testGetLargeIntegers() throws SolverException, InterruptedException {
requireIntegers();
BigInteger large = new BigInteger("1000000000000000000000000000000000000000");
testModelGetters(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(large)),
imgr.makeVariable("x"),
large,
"x");
}
@Test
public void testGetSmallIntegralRationals() throws SolverException, InterruptedException {
requireIntegers();
requireRationals();
testModelGetters(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(1)),
rmgr.makeVariable("x"),
Rational.ONE,
"x");
}
@Test
public void testGetLargeIntegralRationals() throws SolverException, InterruptedException {
requireIntegers();
requireRationals();
BigInteger large = new BigInteger("1000000000000000000000000000000000000000");
testModelGetters(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(large)),
rmgr.makeVariable("x"),
Rational.ofBigInteger(large),
"x");
}
@Test
public void testGetRationals() throws SolverException, InterruptedException {
requireIntegers();
requireRationals();
testModelGetters(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(Rational.ofString("1/3"))),
rmgr.makeVariable("x"),
Rational.ofString("1/3"),
"x");
}
@Test
public void testGetBooleans() throws SolverException, InterruptedException {
for (String name : new String[] {"x", "x-x", "x::x", "x@x"}) {
testModelGetters(bmgr.makeVariable(name), bmgr.makeBoolean(true), true, name);
}
}
@Test
public void testGetUFs() throws SolverException, InterruptedException {
// Boolector does not support integers
if (imgr != null) {
IntegerFormula x =
fmgr.declareAndCallUF("UF", IntegerType, ImmutableList.of(imgr.makeVariable("arg")));
testModelGetters(imgr.equal(x, imgr.makeNumber(1)), x, BigInteger.ONE, "UF");
} else {
BitvectorFormula x =
fmgr.declareAndCallUF(
"UF ",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "arg")));
testModelGetters(bvmgr.equal(x, bvmgr.makeBitvector(8, 1)), x, BigInteger.ONE, "UF ");
}
}
@Test
public void testGetUFwithMoreParams() throws Exception {
// Boolector does not support integers
if (imgr != null) {
IntegerFormula x =
fmgr.declareAndCallUF(
"UF",
IntegerType,
ImmutableList.of(imgr.makeVariable("arg1"), imgr.makeVariable("arg2")));
testModelGetters(imgr.equal(x, imgr.makeNumber(1)), x, BigInteger.ONE, "UF");
} else {
BitvectorFormula x =
fmgr.declareAndCallUF(
"UF",
FormulaType.getBitvectorTypeWithSize(8),
ImmutableList.of(bvmgr.makeVariable(8, "arg1"), bvmgr.makeVariable(8, "arg2")));
testModelGetters(bvmgr.equal(x, bvmgr.makeBitvector(8, 1)), x, BigInteger.ONE, "UF");
}
}
@Test
public void testGetMultipleUFsWithInts() throws Exception {
requireIntegers();
IntegerFormula arg1 = imgr.makeVariable("arg1");
IntegerFormula arg2 = imgr.makeVariable("arg2");
FunctionDeclaration<IntegerFormula> declaration =
fmgr.declareUF("UF", IntegerType, IntegerType);
IntegerFormula app1 = fmgr.callUF(declaration, arg1);
IntegerFormula app2 = fmgr.callUF(declaration, arg2);
IntegerFormula one = imgr.makeNumber(1);
IntegerFormula two = imgr.makeNumber(2);
IntegerFormula three = imgr.makeNumber(3);
IntegerFormula four = imgr.makeNumber(4);
ImmutableList<ValueAssignment> expectedModel =
ImmutableList.of(
new ValueAssignment(
arg1,
three,
imgr.equal(arg1, three),
"arg1",
BigInteger.valueOf(3),
ImmutableList.of()),
new ValueAssignment(
arg2,
four,
imgr.equal(arg2, four),
"arg2",
BigInteger.valueOf(4),
ImmutableList.of()),
new ValueAssignment(
fmgr.callUF(declaration, three),
one,
imgr.equal(fmgr.callUF(declaration, three), one),
"UF",
BigInteger.valueOf(1),
ImmutableList.of(BigInteger.valueOf(3))),
new ValueAssignment(
fmgr.callUF(declaration, four),
imgr.makeNumber(2),
imgr.equal(fmgr.callUF(declaration, four), two),
"UF",
BigInteger.valueOf(2),
ImmutableList.of(BigInteger.valueOf(4))));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(
bmgr.and(imgr.equal(app1, imgr.makeNumber(1)), imgr.equal(app2, imgr.makeNumber(2))));
prover.push(imgr.equal(arg1, imgr.makeNumber(3)));
prover.push(imgr.equal(arg2, imgr.makeNumber(4)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(app1)).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(app2)).isEqualTo(BigInteger.valueOf(2));
assertThat(m).containsExactlyElementsIn(expectedModel);
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(expectedModel);
}
}
@Test
public void testGetMultipleUFsWithBvs() throws Exception {
requireBitvectors();
BitvectorFormula arg1 = bvmgr.makeVariable(8, "arg1");
BitvectorFormula arg2 = bvmgr.makeVariable(8, "arg2");
FunctionDeclaration<BitvectorFormula> declaration =
fmgr.declareUF(
"UF", FormulaType.getBitvectorTypeWithSize(8), FormulaType.getBitvectorTypeWithSize(8));
BitvectorFormula app1 = fmgr.callUF(declaration, arg1);
BitvectorFormula app2 = fmgr.callUF(declaration, arg2);
BitvectorFormula one = bvmgr.makeBitvector(8, 1);
BitvectorFormula two = bvmgr.makeBitvector(8, 2);
BitvectorFormula three = bvmgr.makeBitvector(8, 3);
BitvectorFormula four = bvmgr.makeBitvector(8, 4);
ImmutableList<ValueAssignment> expectedModel =
ImmutableList.of(
new ValueAssignment(
arg1,
three,
bvmgr.equal(arg1, three),
"arg1",
BigInteger.valueOf(3),
ImmutableList.of()),
new ValueAssignment(
arg2,
four,
bvmgr.equal(arg2, four),
"arg2",
BigInteger.valueOf(4),
ImmutableList.of()),
new ValueAssignment(
fmgr.callUF(declaration, three),
one,
bvmgr.equal(fmgr.callUF(declaration, three), one),
"UF",
BigInteger.valueOf(1),
ImmutableList.of(BigInteger.valueOf(3))),
new ValueAssignment(
fmgr.callUF(declaration, four),
bvmgr.makeBitvector(8, 2),
bvmgr.equal(fmgr.callUF(declaration, four), two),
"UF",
BigInteger.valueOf(2),
ImmutableList.of(BigInteger.valueOf(4))));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(
bmgr.and(
bvmgr.equal(app1, bvmgr.makeBitvector(8, 1)),
bvmgr.equal(app2, bvmgr.makeBitvector(8, 2))));
prover.push(bvmgr.equal(arg1, bvmgr.makeBitvector(8, 3)));
prover.push(bvmgr.equal(arg2, bvmgr.makeBitvector(8, 4)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(app1)).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(app2)).isEqualTo(BigInteger.valueOf(2));
assertThat(m).containsExactlyElementsIn(expectedModel);
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(expectedModel);
}
}
@Test
public void testGetMultipleUFsWithBvsWithMultipleArguments() throws Exception {
requireBitvectors();
BitvectorFormula arg1 = bvmgr.makeVariable(8, "arg1");
BitvectorFormula arg2 = bvmgr.makeVariable(8, "arg2");
BitvectorFormula arg3 = bvmgr.makeVariable(8, "arg3");
BitvectorFormula arg4 = bvmgr.makeVariable(8, "arg4");
FunctionDeclaration<BitvectorFormula> declaration =
fmgr.declareUF(
"UF",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8));
BitvectorFormula app1 = fmgr.callUF(declaration, arg1, arg2);
BitvectorFormula app2 = fmgr.callUF(declaration, arg3, arg4);
BitvectorFormula one = bvmgr.makeBitvector(8, 1);
BitvectorFormula two = bvmgr.makeBitvector(8, 2);
BitvectorFormula three = bvmgr.makeBitvector(8, 3);
BitvectorFormula four = bvmgr.makeBitvector(8, 4);
BitvectorFormula five = bvmgr.makeBitvector(8, 5);
BitvectorFormula six = bvmgr.makeBitvector(8, 6);
ImmutableList<ValueAssignment> expectedModel =
ImmutableList.of(
new ValueAssignment(
arg1,
three,
bvmgr.equal(arg1, three),
"arg1",
BigInteger.valueOf(3),
ImmutableList.of()),
new ValueAssignment(
arg2,
four,
bvmgr.equal(arg2, four),
"arg2",
BigInteger.valueOf(4),
ImmutableList.of()),
new ValueAssignment(
arg3,
five,
bvmgr.equal(arg3, five),
"arg3",
BigInteger.valueOf(5),
ImmutableList.of()),
new ValueAssignment(
arg4,
six,
bvmgr.equal(arg4, six),
"arg4",
BigInteger.valueOf(6),
ImmutableList.of()),
new ValueAssignment(
fmgr.callUF(declaration, three, four),
one,
bvmgr.equal(fmgr.callUF(declaration, three, four), one),
"UF",
BigInteger.valueOf(1),
ImmutableList.of(BigInteger.valueOf(3), BigInteger.valueOf(4))),
new ValueAssignment(
fmgr.callUF(declaration, five, six),
bvmgr.makeBitvector(8, 2),
bvmgr.equal(fmgr.callUF(declaration, five, six), two),
"UF",
BigInteger.valueOf(2),
ImmutableList.of(BigInteger.valueOf(5), BigInteger.valueOf(6))));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(
bmgr.and(
bvmgr.equal(app1, bvmgr.makeBitvector(8, 1)),
bvmgr.equal(app2, bvmgr.makeBitvector(8, 2))));
prover.push(bvmgr.equal(arg1, bvmgr.makeBitvector(8, 3)));
prover.push(bvmgr.equal(arg2, bvmgr.makeBitvector(8, 4)));
prover.push(bvmgr.equal(arg3, bvmgr.makeBitvector(8, 5)));
prover.push(bvmgr.equal(arg4, bvmgr.makeBitvector(8, 6)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(app1)).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(app2)).isEqualTo(BigInteger.valueOf(2));
assertThat(m).containsExactlyElementsIn(expectedModel);
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(expectedModel);
}
}
// var = 1 & Exists boundVar . (boundVar = 0 & var = f(boundVar))
@Test
public void testQuantifiedUF() throws SolverException, InterruptedException {
requireQuantifiers();
requireIntegers();
// create query: "(var == 1) && exists bound : (bound == 0 && var == func(bound))"
// then check that the model contains an evaluation "func(0) := 1"
IntegerFormula var = imgr.makeVariable("var");
BooleanFormula varIsOne = imgr.equal(var, imgr.makeNumber(1));
IntegerFormula boundVar = imgr.makeVariable("boundVar");
BooleanFormula boundVarIsZero = imgr.equal(boundVar, imgr.makeNumber(0));
String func = "func";
IntegerFormula funcAtZero = fmgr.declareAndCallUF(func, IntegerType, imgr.makeNumber(0));
IntegerFormula funcAtBoundVar = fmgr.declareAndCallUF(func, IntegerType, boundVar);
BooleanFormula body = bmgr.and(boundVarIsZero, imgr.equal(var, funcAtBoundVar));
BooleanFormula f = bmgr.and(varIsOne, qmgr.exists(ImmutableList.of(boundVar), body));
IntegerFormula one = imgr.makeNumber(1);
ValueAssignment expectedValueAssignment =
new ValueAssignment(
funcAtZero,
one,
imgr.equal(funcAtZero, one),
func,
BigInteger.ONE,
ImmutableList.of(BigInteger.ZERO));
// CVC4 does not give back bound variable values. Not even in UFs.
if (solverToUse() == Solvers.CVC4) {
expectedValueAssignment =
new ValueAssignment(
funcAtBoundVar,
one,
imgr.equal(funcAtBoundVar, one),
func,
BigInteger.ONE,
ImmutableList.of("boundVar"));
}
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m).contains(expectedValueAssignment);
}
}
}
// var = 1 & boundVar = 1 & Exists boundVar . (boundVar = 0 & var = f(boundVar))
@Test
public void testQuantifiedUF2() throws SolverException, InterruptedException {
requireQuantifiers();
requireIntegers();
IntegerFormula var = imgr.makeVariable("var");
BooleanFormula varIsOne = imgr.equal(var, imgr.makeNumber(1));
IntegerFormula boundVar = imgr.makeVariable("boundVar");
BooleanFormula boundVarIsZero = imgr.equal(boundVar, imgr.makeNumber(0));
BooleanFormula boundVarIsOne = imgr.equal(boundVar, imgr.makeNumber(1));
String func = "func";
IntegerFormula funcAtZero = fmgr.declareAndCallUF(func, IntegerType, imgr.makeNumber(0));
IntegerFormula funcAtBoundVar = fmgr.declareAndCallUF(func, IntegerType, boundVar);
BooleanFormula body = bmgr.and(boundVarIsZero, imgr.equal(var, funcAtBoundVar));
BooleanFormula f =
bmgr.and(varIsOne, boundVarIsOne, qmgr.exists(ImmutableList.of(boundVar), body));
IntegerFormula one = imgr.makeNumber(1);
ValueAssignment expectedValueAssignment =
new ValueAssignment(
funcAtZero,
one,
imgr.equal(funcAtZero, one),
func,
BigInteger.ONE,
ImmutableList.of(BigInteger.ZERO));
// CVC4 does not give back bound variable values. Not even in UFs.
if (solverToUse() == Solvers.CVC4) {
expectedValueAssignment =
new ValueAssignment(
funcAtBoundVar,
one,
imgr.equal(funcAtBoundVar, one),
func,
BigInteger.ONE,
ImmutableList.of("boundVar"));
}
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m).contains(expectedValueAssignment);
}
}
}
@Test
public void testGetBitvectors() throws SolverException, InterruptedException {
requireBitvectors();
if (solver == Solvers.BOOLECTOR) {
// Boolector uses bitvecs length 1 as bools
testModelGetters(
bvmgr.equal(bvmgr.makeVariable(2, "x"), bvmgr.makeBitvector(2, BigInteger.ONE)),
bvmgr.makeVariable(2, "x"),
BigInteger.ONE,
"x");
} else {
testModelGetters(
bvmgr.equal(bvmgr.makeVariable(1, "x"), bvmgr.makeBitvector(1, BigInteger.ONE)),
bvmgr.makeVariable(1, "x"),
BigInteger.ONE,
"x");
}
}
@Test
public void testGetModelAssignments() throws SolverException, InterruptedException {
if (imgr != null) {
testModelIterator(
bmgr.and(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(1)),
imgr.equal(imgr.makeVariable("x"), imgr.makeVariable("y"))));
} else {
testModelIterator(
bmgr.and(
bvmgr.equal(bvmgr.makeVariable(8, "x"), bvmgr.makeBitvector(8, 1)),
bvmgr.equal(bvmgr.makeVariable(8, "x"), bvmgr.makeVariable(8, "y"))));
}
}
@Test
public void testEmptyStackModel() throws SolverException, InterruptedException {
if (imgr != null) {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(imgr.makeNumber(123))).isEqualTo(BigInteger.valueOf(123));
assertThat(m.evaluate(bmgr.makeBoolean(true))).isTrue();
assertThat(m.evaluate(bmgr.makeBoolean(false))).isFalse();
if (SOLVERS_WITH_PARTIAL_MODEL.contains(solver)) {
// partial model should not return an evaluation
assertThat(m.evaluate(imgr.makeVariable("y"))).isNull();
} else {
assertThat(m.evaluate(imgr.makeVariable("y"))).isNotNull();
}
}
}
} else {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(bvmgr.makeBitvector(8, 123))).isEqualTo(BigInteger.valueOf(123));
assertThat(m.evaluate(bmgr.makeBoolean(true))).isTrue();
assertThat(m.evaluate(bmgr.makeBoolean(false))).isFalse();
if (SOLVERS_WITH_PARTIAL_MODEL.contains(solver)) {
// partial model should not return an evaluation
assertThat(m.evaluate(bvmgr.makeVariable(8, "y"))).isNull();
} else {
assertThat(m.evaluate(bvmgr.makeVariable(8, "y"))).isNotNull();
}
}
}
}
}
@Test
public void testNonExistantSymbol() throws SolverException, InterruptedException {
if (imgr != null) {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeBoolean(true));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
if (SOLVERS_WITH_PARTIAL_MODEL.contains(solver)) {
// partial model should not return an evaluation
assertThat(m.evaluate(imgr.makeVariable("y"))).isNull();
} else {
assertThat(m.evaluate(imgr.makeVariable("y"))).isNotNull();
}
}
}
} else {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeBoolean(true));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
if (SOLVERS_WITH_PARTIAL_MODEL.contains(solver)) {
// partial model should not return an evaluation
assertThat(m.evaluate(bvmgr.makeVariable(8, "y"))).isNull();
} else {
assertThat(m.evaluate(bvmgr.makeVariable(8, "y"))).isNotNull();
}
}
}
}
}
@Test
public void testPartialModels() throws SolverException, InterruptedException {
assume()
.withMessage("As of now, only Z3 and Princess support partial models")
.that(solver)
.isIn(SOLVERS_WITH_PARTIAL_MODEL);
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
IntegerFormula x = imgr.makeVariable("x");
prover.push(imgr.equal(x, x));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(x)).isEqualTo(null);
assertThat(m).isEmpty();
}
}
}
@Test
public void testPartialModels2() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
if (imgr != null) {
IntegerFormula x = imgr.makeVariable("x");
prover.push(imgr.greaterThan(x, imgr.makeNumber(0)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(x)).isEqualTo(BigInteger.ONE);
// it works now, but maybe the model "x=1" for the constraint "x>0" is not valid for new
// solvers.
}
} else {
BitvectorFormula x = bvmgr.makeVariable(8, "x");
prover.push(bvmgr.greaterThan(x, bvmgr.makeBitvector(8, 0), true));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
if (solver != Solvers.BOOLECTOR) {
assertThat(m.evaluate(x)).isEqualTo(BigInteger.ONE);
} else {
assertThat(m.evaluate(x)).isEqualTo(BigInteger.valueOf(64));
}
// it works now, but maybe the model "x=1" for the constraint "x>0" is not valid for new
// solvers.
// Can confirm ;D Boolector likes to take the "max" values for bitvectors instead of the
// min; as a result it returns 64
}
}
}
}
@Test
public void testPartialModelsUF() throws SolverException, InterruptedException {
assume()
.withMessage("As of now, only Z3 supports partial model evaluation")
.that(solver)
.isIn(ImmutableList.of(Solvers.Z3));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
IntegerFormula x = imgr.makeVariable("x");
IntegerFormula f = fmgr.declareAndCallUF("f", IntegerType, x);
prover.push(imgr.equal(x, imgr.makeNumber(1)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(f)).isEqualTo(null);
}
}
}
@Test
public void testEvaluatingConstants() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeVariable("b"));
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
if (imgr != null) {
assertThat(m.evaluate(imgr.makeNumber(0))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(imgr.makeNumber(1))).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(imgr.makeNumber(100))).isEqualTo(BigInteger.valueOf(100));
assertThat(m.evaluate(bmgr.makeBoolean(true))).isTrue();
assertThat(m.evaluate(bmgr.makeBoolean(false))).isFalse();
}
if (bvmgr != null) {
if (solver == Solvers.BOOLECTOR) {
for (int i : new int[] {2, 4, 8, 32, 64, 1000}) {
assertThat(m.evaluate(bvmgr.makeBitvector(i, 0))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.makeBitvector(i, 1))).isEqualTo(BigInteger.ONE);
}
} else {
for (int i : new int[] {1, 2, 4, 8, 32, 64, 1000}) {
assertThat(m.evaluate(bvmgr.makeBitvector(i, 0))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.makeBitvector(i, 1))).isEqualTo(BigInteger.ONE);
}
}
}
}
}
}
@Test
public void testEvaluatingConstantsWithOperation() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.makeVariable("b"));
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
if (imgr != null) {
assertThat(m.evaluate(imgr.add(imgr.makeNumber(45), imgr.makeNumber(55))))
.isEqualTo(BigInteger.valueOf(100));
assertThat(m.evaluate(imgr.subtract(imgr.makeNumber(123), imgr.makeNumber(23))))
.isEqualTo(BigInteger.valueOf(100));
assertThat(m.evaluate(bmgr.and(bmgr.makeBoolean(true), bmgr.makeBoolean(true)))).isTrue();
}
if (bvmgr != null) {
if (solver == Solvers.BOOLECTOR) {
for (int i : new int[] {2, 4, 8, 32, 64, 1000}) {
BitvectorFormula zero = bvmgr.makeBitvector(i, 0);
BitvectorFormula one = bvmgr.makeBitvector(i, 1);
assertThat(m.evaluate(bvmgr.add(zero, zero))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.add(zero, one))).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(bvmgr.subtract(one, one))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.subtract(one, zero))).isEqualTo(BigInteger.ONE);
}
} else {
for (int i : new int[] {1, 2, 4, 8, 32, 64, 1000}) {
BitvectorFormula zero = bvmgr.makeBitvector(i, 0);
BitvectorFormula one = bvmgr.makeBitvector(i, 1);
assertThat(m.evaluate(bvmgr.add(zero, zero))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.add(zero, one))).isEqualTo(BigInteger.ONE);
assertThat(m.evaluate(bvmgr.subtract(one, one))).isEqualTo(BigInteger.ZERO);
assertThat(m.evaluate(bvmgr.subtract(one, zero))).isEqualTo(BigInteger.ONE);
}
}
}
}
}
}
@Test
public void testNonVariableValues() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array", IntegerType, IntegerType);
IntegerFormula selected = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected, imgr.makeNumber(0));
// Note that store is not an assignment that works beyond the section where you put it!
IntegerFormula select1Store7in1 =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(7)), imgr.makeNumber(1));
BooleanFormula selectStoreEq1 = imgr.equal(select1Store7in1, imgr.makeNumber(1));
IntegerFormula select1Store7in1store7in2 =
amgr.select(
amgr.store(
amgr.store(array1, imgr.makeNumber(2), imgr.makeNumber(7)),
imgr.makeNumber(1),
imgr.makeNumber(7)),
imgr.makeNumber(1));
IntegerFormula select1Store1in1 =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(1)), imgr.makeNumber(1));
IntegerFormula arithIs7 =
imgr.add(imgr.add(imgr.makeNumber(5), select1Store1in1), select1Store1in1);
// (arr[1] = 7)[1] = 1 -> ...
// false -> doesn't matter
BooleanFormula assert1 = bmgr.implication(selectStoreEq1, selectEq0);
// (arr[1] = 7)[1] != 1 -> ((arr[2] = 7)[1] = 7)[1] = 7 is true
BooleanFormula assert2 =
bmgr.implication(bmgr.not(selectStoreEq1), imgr.equal(select1Store7in1store7in2, arithIs7));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
// make the right part of the impl in assert1 fail such that the left is negated
prover.push(bmgr.not(selectEq0));
prover.push(assert1);
prover.push(assert2);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(select1Store7in1)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(select1Store7in1store7in2)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(selected)).isNotEqualTo(BigInteger.valueOf(0));
assertThat(m.evaluate(arithIs7)).isEqualTo(BigInteger.valueOf(7));
}
}
}
@Test
public void testNonVariableValues2() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array", IntegerType, IntegerType);
IntegerFormula selected = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected, imgr.makeNumber(0));
// Note that store is not an assignment that works beyond the section where you put it!
IntegerFormula select1Store7in1 =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(7)), imgr.makeNumber(1));
BooleanFormula selectStoreEq1 = imgr.equal(select1Store7in1, imgr.makeNumber(1));
IntegerFormula select1Store7in1store3in1 =
amgr.select(
amgr.store(
amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(3)),
imgr.makeNumber(1),
imgr.makeNumber(7)),
imgr.makeNumber(1));
IntegerFormula select1Store1in1 =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(1)), imgr.makeNumber(1));
IntegerFormula arithIs7 =
imgr.add(imgr.add(imgr.makeNumber(5), select1Store1in1), select1Store1in1);
// (arr[1] = 7)[1] = 1 -> ...
// false -> doesn't matter
BooleanFormula assert1 = bmgr.implication(selectStoreEq1, selectEq0);
// (arr[1] = 7)[1] != 1 -> ((arr[1] = 3)[1] = 7)[1] = 7 is true
BooleanFormula assert2 =
bmgr.implication(bmgr.not(selectStoreEq1), imgr.equal(select1Store7in1store3in1, arithIs7));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
// make the right part of the impl in assert1 fail such that the left is negated
prover.push(bmgr.not(selectEq0));
prover.push(assert1);
prover.push(assert2);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(select1Store7in1)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(select1Store7in1store3in1)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(selected)).isNotEqualTo(BigInteger.valueOf(0));
assertThat(m.evaluate(arithIs7)).isEqualTo(BigInteger.valueOf(7));
}
}
}
@Test
public void testGetIntArrays() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array =
amgr.makeArray("array", IntegerType, IntegerType);
ArrayFormula<IntegerFormula, IntegerFormula> updated =
amgr.store(array, imgr.makeNumber(1), imgr.makeNumber(1));
IntegerFormula selected = amgr.select(updated, imgr.makeNumber(1));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(imgr.equal(selected, imgr.makeNumber(1)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(selected)).isEqualTo(BigInteger.ONE);
// check that model evaluation applies formula simplification or constant propagation.
ArrayFormula<IntegerFormula, IntegerFormula> stored = array;
for (int i = 0; i < 10; i++) {
stored = amgr.store(stored, imgr.makeNumber(i), imgr.makeNumber(i));
// zero is the inner element of array
assertThat(m.evaluate(amgr.select(stored, imgr.makeNumber(0))))
.isEqualTo(BigInteger.ZERO);
// i is the outer element of array
assertThat(m.evaluate(amgr.select(stored, imgr.makeNumber(i))))
.isEqualTo(BigInteger.valueOf(i));
}
}
}
}
@Test
public void testGetArrays2() throws SolverException, InterruptedException {
requireParser();
requireArrays();
requireBitvectors();
ArrayFormula<BitvectorFormula, BitvectorFormula> array =
amgr.makeArray(
"array",
FormulaType.getBitvectorTypeWithSize(8),
FormulaType.getBitvectorTypeWithSize(8));
ArrayFormula<BitvectorFormula, BitvectorFormula> updated =
amgr.store(array, bvmgr.makeBitvector(8, 1), bvmgr.makeBitvector(8, 1));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(
bvmgr.equal(amgr.select(updated, bvmgr.makeBitvector(8, 1)), bvmgr.makeBitvector(8, 1)));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(amgr.select(updated, bvmgr.makeBitvector(8, 1))))
.isEqualTo(BigInteger.ONE);
}
}
}
@Test
public void testGetArrays6() throws SolverException, InterruptedException {
requireArrays();
requireParser();
BooleanFormula f =
mgr.parse(
"(declare-fun |pi@2| () Int)\n"
+ "(declare-fun *unsigned_int@1 () (Array Int Int))\n"
+ "(declare-fun |z2@2| () Int)\n"
+ "(declare-fun |z1@2| () Int)\n"
+ "(declare-fun |t@2| () Int)\n"
+ "(declare-fun |__ADDRESS_OF_t| () Int)\n"
+ "(declare-fun *char@1 () (Array Int Int))\n"
+ "(assert"
+ " (and (= |t@2| 50)"
+ " (not (<= |__ADDRESS_OF_t| 0))"
+ " (= |z1@2| |__ADDRESS_OF_t|)"
+ " (= (select *char@1 |__ADDRESS_OF_t|) |t@2|)"
+ " (= |z2@2| |z1@2|)"
+ " (= |pi@2| |z2@2|)"
+ " (not (= (select *unsigned_int@1 |pi@2|) 50))))");
testModelIterator(f);
}
@Test
public void testGetArrays3() throws SolverException, InterruptedException {
requireParser();
requireArrays();
assume()
.withMessage("As of now, only Princess does not support multi-dimensional arrays")
.that(solver)
.isNotSameInstanceAs(Solvers.PRINCESS);
// create formula for "arr[5][3][1]==x && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arr () (Array Int (Array Int (Array Int Int))))\n"
+ "(assert (and"
+ " (= (select (select (select arr 5) 3) 1) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
ArrayFormulaType<
IntegerFormula,
ArrayFormula<IntegerFormula, ArrayFormula<IntegerFormula, IntegerFormula>>>
arrType =
FormulaType.getArrayType(
IntegerType, FormulaType.getArrayType(IntegerType, ARRAY_TYPE_INT_INT));
testModelGetters(
f,
amgr.select(
amgr.select(
amgr.select(amgr.makeArray("arr", arrType), imgr.makeNumber(5)),
imgr.makeNumber(3)),
imgr.makeNumber(1)),
BigInteger.valueOf(123),
"arr",
true);
}
@Test
public void testGetArrays4() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5]==x && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arr () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select arr 5) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arr", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arr",
true);
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("CheckReturnValue")
public void testGetArrays4invalid() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5]==x && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arr () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select arr 5) x)"
+ " (= x 123)"
+ "))");
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
m.evaluate(amgr.makeArray("arr", ARRAY_TYPE_INT_INT));
}
}
}
@Test
public void testGetArrays5() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5:6]==[x,x] && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arr () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arr 6 x) 5) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arr", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arr",
true);
}
@Test
public void testGetArrays5b() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5]==x && arr[6]==x && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select arrgh 5) x)"
+ " (= (select arrgh 6) x)"
+ " (= x 123)"
+ " (= (select (store ahoi 66 x) 55) x)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true);
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(6)),
BigInteger.valueOf(123),
"arrgh",
true);
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(55)),
BigInteger.valueOf(123),
"ahoi",
true);
// The value for 'ahoi[66]' is not determined by the constraints from above,
// because we only 'store' it in (a copy of) the array, but never read it.
// Thus, the following test case depends on the solver and would be potentially wrong:
// testModelGetters(
// amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(66)),
// BigInteger.valueOf(123),
// "ahoi",
// true);
}
@Test
public void testGetArrays5c() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5:6]==[x,x] && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arrgh 6 x) 5) x)"
+ " (= (select (store ahoi 6 x) 5) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true);
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"ahoi",
true);
}
@Test
public void testGetArrays5d() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arr[5:6]==[x,x] && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arrgh 6 x) 5) x)"
+ " (= (select (store ahoi 6 x) 7) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true);
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(7)),
BigInteger.valueOf(123),
"ahoi",
true);
}
@Test
public void testGetArrays5e() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arrgh[5:6]==[x,x] && ahoi[5,7] == [x,x] && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arrgh 6 x) 5) x)"
+ " (= (select (store ahoi 7 x) 5) x)"
+ " (= x 123)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true);
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"ahoi",
true);
}
@Test
public void testGetArrays5f() throws SolverException, InterruptedException {
requireParser();
requireArrays();
// create formula for "arrgh[5:6]==[x,x] && ahoi[5,6] == [x,y] && y = 125 && x==123"
BooleanFormula f =
mgr.parse(
"(declare-fun x () Int)\n"
+ "(declare-fun y () Int)\n"
+ "(declare-fun arrgh () (Array Int Int))\n"
+ "(declare-fun ahoi () (Array Int Int))\n"
+ "(assert (and"
+ " (= (select (store arrgh 6 x) 5) x)"
+ " (= (select (store ahoi 6 y) 5) x)"
+ " (= x 123)"
+ " (= y 125)"
+ "))");
testModelIterator(f);
testModelGetters(f, imgr.makeVariable("x"), BigInteger.valueOf(123), "x");
testModelGetters(
f,
amgr.select(amgr.makeArray("arrgh", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"arrgh",
true);
testModelGetters(
f,
amgr.select(amgr.makeArray("ahoi", ARRAY_TYPE_INT_INT), imgr.makeNumber(5)),
BigInteger.valueOf(123),
"ahoi",
true);
}
@Test
public void testGetArrays7() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array", IntegerType, IntegerType);
IntegerFormula selected = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected, imgr.makeNumber(0));
// Note that store is not an assignment! This is just so that the implication fails and arr[1] =
BooleanFormula selectStore =
imgr.equal(
amgr.select(
amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(7)), imgr.makeNumber(1)),
imgr.makeNumber(0));
BooleanFormula assert1 = bmgr.implication(bmgr.not(selectEq0), selectStore);
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(assert1);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(selected)).isEqualTo(BigInteger.ZERO);
}
}
}
@Test
public void testGetArrays8() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array", IntegerType, IntegerType);
IntegerFormula selected = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected, imgr.makeNumber(0));
IntegerFormula selectStore =
amgr.select(amgr.store(array1, imgr.makeNumber(1), imgr.makeNumber(7)), imgr.makeNumber(1));
// Note that store is not an assignment! This is just used to make the implication fail and
// arr[1] =
BooleanFormula selectStoreEq0 = imgr.equal(selectStore, imgr.makeNumber(0));
IntegerFormula arithEq7 =
imgr.subtract(
imgr.multiply(imgr.add(imgr.makeNumber(1), imgr.makeNumber(2)), imgr.makeNumber(3)),
imgr.makeNumber(2));
BooleanFormula selectStoreEq7 = imgr.equal(selectStore, arithEq7);
// arr[1] = 0 -> (arr[1] = 7)[1] = 0
// if the left is true, the right has to be, but its false => left false => overall TRUE
BooleanFormula assert1 = bmgr.implication(selectEq0, selectStoreEq0);
// arr[1] != 0 -> (arr[1] = 7)[1] = 7
// left has to be true because of assert1 -> right has to be true as well
BooleanFormula assert2 = bmgr.implication(bmgr.not(selectEq0), selectStoreEq7);
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.and(assert1, assert2));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(m.evaluate(selectStore)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(arithEq7)).isEqualTo(BigInteger.valueOf(7));
assertThat(m.evaluate(selected)).isNotEqualTo(BigInteger.valueOf(0));
}
}
}
@Test
public void testGetArrays9() throws SolverException, InterruptedException {
requireArrays();
requireIntegers();
ArrayFormula<IntegerFormula, IntegerFormula> array1 =
amgr.makeArray("array1", IntegerType, IntegerType);
ArrayFormula<IntegerFormula, IntegerFormula> array2 =
amgr.makeArray("array2", IntegerType, IntegerType);
IntegerFormula selected1 = amgr.select(array1, imgr.makeNumber(1));
BooleanFormula selectEq0 = imgr.equal(selected1, imgr.makeNumber(0));
BooleanFormula selectGT0 = imgr.greaterThan(selected1, imgr.makeNumber(0));
BooleanFormula selectGTEmin1 = imgr.greaterOrEquals(selected1, imgr.makeNumber(-1));
IntegerFormula selected2 = amgr.select(array2, imgr.makeNumber(1));
BooleanFormula arr2LT0 = imgr.lessOrEquals(selected2, imgr.makeNumber(0));
BooleanFormula select2GTEmin1 = imgr.greaterOrEquals(selected2, imgr.makeNumber(-1));
// arr1[1] > 0 -> arr1[1] = 0
// obviously false => arr[1] <= 0
BooleanFormula assert1 = bmgr.implication(selectGT0, selectEq0);
// arr1[1] > 0 -> arr2[1] <= 1
// left holds because of the first assertion => arr2[1] <= 0
BooleanFormula assert2 = bmgr.implication(bmgr.not(selectGT0), arr2LT0);
// if now arr2[1] >= -1 -> arr1[1] >= -1
// holds
BooleanFormula assert3 = bmgr.implication(select2GTEmin1, selectGTEmin1);
BooleanFormula assert4 = imgr.greaterThan(selected2, imgr.makeNumber(-2));
// basicly just says that: -1 <= arr[1] <= 0 & -1 <= arr2[1] <= 0 up to this point
// make the 2 array[1] values unequal
BooleanFormula assert5 = bmgr.not(imgr.equal(selected1, selected2));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(bmgr.and(assert1, assert2, assert3, assert4, assert5));
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
if (m.evaluate(selected1).equals(BigInteger.valueOf(-1))) {
assertThat(m.evaluate(selected1)).isEqualTo(BigInteger.valueOf(-1));
assertThat(m.evaluate(selected2)).isEqualTo(BigInteger.valueOf(0));
} else {
assertThat(m.evaluate(selected1)).isEqualTo(BigInteger.valueOf(0));
assertThat(m.evaluate(selected2)).isEqualTo(BigInteger.valueOf(-1));
}
}
}
}
private void testModelIterator(BooleanFormula f) throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(m).inOrder();
}
}
}
private void testModelGetters(
BooleanFormula constraint, Formula variable, Object expectedValue, String varName)
throws SolverException, InterruptedException {
testModelGetters(constraint, variable, expectedValue, varName, false);
}
private void testModelGetters(
BooleanFormula constraint,
Formula variable,
Object expectedValue,
String varName,
boolean isArray)
throws SolverException, InterruptedException {
List<BooleanFormula> modelAssignments = new ArrayList<>();
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(constraint);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
System.out.println(m);
assertThat(m.evaluate(variable)).isEqualTo(expectedValue);
for (ValueAssignment va : m) {
modelAssignments.add(va.getAssignmentAsFormula());
}
List<ValueAssignment> relevantAssignments =
prover.getModelAssignments().stream()
.filter(assignment -> assignment.getName().equals(varName))
.collect(Collectors.toList());
assertThat(relevantAssignments).isNotEmpty();
if (isArray) {
List<ValueAssignment> arrayAssignments =
relevantAssignments.stream()
.filter(assignment -> expectedValue.equals(assignment.getValue()))
.collect(Collectors.toList());
assertThat(arrayAssignments)
.isNotEmpty(); // at least one assignment should have the wanted value
} else {
// normal variables or UFs have exactly one evaluation assigned to their name
assertThat(relevantAssignments).hasSize(1);
ValueAssignment assignment = Iterables.getOnlyElement(relevantAssignments);
assertThat(assignment.getValue()).isEqualTo(expectedValue);
assertThat(m.evaluate(assignment.getKey())).isEqualTo(expectedValue);
}
}
}
// This can't work in Boolector with ufs as it always crashes with:
// [btorslvfun] add_function_inequality_constraints: equality over non-array lambdas not
// supported yet
// TODO: only filter out UF formulas here, not all
if (solver != Solvers.BOOLECTOR) {
assertThatFormula(bmgr.and(modelAssignments)).implies(constraint);
}
}
@Test
public void ufTest() throws SolverException, InterruptedException {
requireQuantifiers();
requireBitvectors();
// only Z3 fulfills these requirements
assume()
.withMessage("solver does not implement optimisation")
.that(solverToUse())
.isEqualTo(Solvers.Z3);
BitvectorType t32 = FormulaType.getBitvectorTypeWithSize(32);
FunctionDeclaration<BitvectorFormula> si1 = fmgr.declareUF("*signed_int@1", t32, t32);
FunctionDeclaration<BitvectorFormula> si2 = fmgr.declareUF("*signed_int@2", t32, t32);
BitvectorFormula ctr = bvmgr.makeVariable(t32, "*signed_int@1@counter");
BitvectorFormula adr = bvmgr.makeVariable(t32, "__ADDRESS_OF_test");
BitvectorFormula num0 = bvmgr.makeBitvector(32, 0);
BitvectorFormula num4 = bvmgr.makeBitvector(32, 4);
BitvectorFormula num10 = bvmgr.makeBitvector(32, 10);
BooleanFormula a11 =
bmgr.implication(
bmgr.and(
bvmgr.lessOrEquals(adr, ctr, false),
bvmgr.lessThan(ctr, bvmgr.add(adr, num10), false)),
bvmgr.equal(fmgr.callUF(si2, ctr), num0));
BooleanFormula a21 =
bmgr.not(
bmgr.and(
bvmgr.lessOrEquals(adr, ctr, false),
bvmgr.lessThan(ctr, bvmgr.add(adr, num10), false)));
BooleanFormula body =
bmgr.and(
a11, bmgr.implication(a21, bvmgr.equal(fmgr.callUF(si2, ctr), fmgr.callUF(si1, ctr))));
BooleanFormula a1 = qmgr.forall(ctr, body);
BooleanFormula a2 =
bvmgr.equal(fmgr.callUF(si1, bvmgr.add(adr, bvmgr.multiply(num4, num0))), num0);
BooleanFormula f = bmgr.and(a1, bvmgr.lessThan(num0, adr, true), bmgr.not(a2));
checkModelIteration(f, true);
checkModelIteration(f, false);
}
@SuppressWarnings("resource")
private void checkModelIteration(BooleanFormula f, boolean useOptProver)
throws SolverException, InterruptedException {
ImmutableList<ValueAssignment> assignments;
try (BasicProverEnvironment<?> prover =
useOptProver
? context.newOptimizationProverEnvironment(ProverOptions.GENERATE_MODELS)
: context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(f);
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
for (@SuppressWarnings("unused") ValueAssignment assignment : m) {
// Check that we can iterate through with no crashes.
}
assertThat(prover.getModelAssignments()).containsExactlyElementsIn(m).inOrder();
assignments = prover.getModelAssignments();
}
}
assertThat(assignments.size())
.isEqualTo(assignments.stream().map(ValueAssignment::getKey).distinct().count());
List<BooleanFormula> assignmentFormulas = new ArrayList<>();
for (ValueAssignment va : assignments) {
assignmentFormulas.add(va.getAssignmentAsFormula());
assertThatFormula(va.getAssignmentAsFormula())
.isEqualTo(makeAssignment(va.getKey(), va.getValueAsFormula()));
assertThat(va.getValue().getClass())
.isIn(ImmutableList.of(Boolean.class, BigInteger.class, Rational.class, Double.class));
}
// Check that model is not contradicting
assertThatFormula(bmgr.and(assignmentFormulas)).isSatisfiable();
// Check that model does not contradict formula.
// Check for implication is not possible, because formula "x=y" does not imply "{x=0,y=0}" and
// formula "A = (store EMPTY x y)" is not implied by "{x=0,y=0,(select A 0)=0}" (EMPTY != A).
assertThatFormula(bmgr.and(f, bmgr.and(assignmentFormulas))).isSatisfiable();
}
/**
* Short-cut in cases where the type of the formula is unknown. Delegates to the corresponding
* [boolean, integer, bitvector, ...] formula manager.
*/
@SuppressWarnings("unchecked")
private BooleanFormula makeAssignment(Formula pFormula1, Formula pFormula2) {
FormulaType<?> pType = mgr.getFormulaType(pFormula1);
assertWithMessage(
"Trying to equalize two formulas %s and %s of different types %s and %s",
pFormula1, pFormula2, pType, mgr.getFormulaType(pFormula2))
.that(mgr.getFormulaType(pFormula1).equals(mgr.getFormulaType(pFormula2)))
.isTrue();
if (pType.isBooleanType()) {
return bmgr.equivalence((BooleanFormula) pFormula1, (BooleanFormula) pFormula2);
} else if (pType.isIntegerType()) {
return imgr.equal((IntegerFormula) pFormula1, (IntegerFormula) pFormula2);
} else if (pType.isRationalType()) {
return rmgr.equal((RationalFormula) pFormula1, (RationalFormula) pFormula2);
} else if (pType.isBitvectorType()) {
return bvmgr.equal((BitvectorFormula) pFormula1, (BitvectorFormula) pFormula2);
} else if (pType.isFloatingPointType()) {
return fpmgr.assignment((FloatingPointFormula) pFormula1, (FloatingPointFormula) pFormula2);
} else if (pType.isArrayType()) {
@SuppressWarnings("rawtypes")
ArrayFormula f2 = (ArrayFormula) pFormula2;
return amgr.equivalence((ArrayFormula<?, ?>) pFormula1, f2);
}
throw new IllegalArgumentException(
"Cannot make equality of formulas with type " + pType + " in the Solver!");
}
@Test
public void quantifierTestShort() throws SolverException, InterruptedException {
requireQuantifiers();
requireIntegers();
IntegerFormula ctr = imgr.makeVariable("x");
BooleanFormula body = imgr.equal(ctr, imgr.makeNumber(0));
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
// exists x : x==0
prover.push(qmgr.exists(ctr, body));
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
for (ValueAssignment v : m) {
// a value-assignment might have a different name, but the value should be "0".
assertThat(BigInteger.ZERO.equals(v.getValue())).isTrue();
}
}
prover.pop();
prover.push(body);
assertThat(prover.isUnsat()).isFalse();
try (Model m = prover.getModel()) {
ValueAssignment v = m.iterator().next();
assertThat("x".equals(v.getName())).isTrue();
assertThat(BigInteger.ZERO.equals(v.getValue())).isTrue();
}
}
}
private static final String SMALL_ARRAY_QUERY =
"(declare-fun A1 () (Array Int Int))"
+ "(declare-fun A2 () (Array Int Int))"
+ "(declare-fun X () Int)"
+ "(declare-fun Y () Int)"
+ "(assert (= A1 (store A2 X Y)))";
private static final String BIG_ARRAY_QUERY =
"(declare-fun |V#2@| () Int)"
+ "(declare-fun z3name!115 () Int)"
+ "(declare-fun P42 () Bool)"
+ "(declare-fun M@3 () Int)"
+ "(declare-fun P43 () Bool)"
+ "(declare-fun |V#1@| () Int)"
+ "(declare-fun z3name!114 () Int)"
+ "(declare-fun P44 () Bool)"
+ "(declare-fun M@2 () Int)"
+ "(declare-fun P45 () Bool)"
+ "(declare-fun |It15@5| () Int)"
+ "(declare-fun |It13@5| () Int)"
+ "(declare-fun |H@12| () (Array Int Int))"
+ "(declare-fun |H@13| () (Array Int Int))"
+ "(declare-fun |It14@5| () Int)"
+ "(declare-fun |IN@5| () Int)"
+ "(declare-fun |It12@5| () Int)"
+ "(declare-fun |It11@5| () Int)"
+ "(declare-fun |It9@5| () Int)"
+ "(declare-fun |H@11| () (Array Int Int))"
+ "(declare-fun |It10@5| () Int)"
+ "(declare-fun |It8@5| () Int)"
+ "(declare-fun |Anew@3| () Int)"
+ "(declare-fun |Aprev@3| () Int)"
+ "(declare-fun |H@10| () (Array Int Int))"
+ "(declare-fun |At7@5| () Int)"
+ "(declare-fun |H@9| () (Array Int Int))"
+ "(declare-fun |At6@5| () Int)"
+ "(declare-fun |Anext@3| () Int)"
+ "(declare-fun |H@8| () (Array Int Int))"
+ "(declare-fun |At5@5| () Int)"
+ "(declare-fun |H@7| () (Array Int Int))"
+ "(declare-fun |At4@5| () Int)"
+ "(declare-fun |at3@5| () Int)"
+ "(declare-fun |ahead@3| () Int)"
+ "(declare-fun |anew@3| () Int)"
+ "(declare-fun gl@ () Int)"
+ "(declare-fun |It7@5| () Int)"
+ "(declare-fun |It6@5| () Int)"
+ "(declare-fun |It5@5| () Int)"
+ "(declare-fun |Ivalue@3| () Int)"
+ "(declare-fun i@2 () (Array Int Int))"
+ "(declare-fun i@3 () (Array Int Int))"
+ "(declare-fun P46 () Bool)"
+ "(declare-fun |It4@5| () Int)"
+ "(declare-fun |It4@3| () Int)"
+ "(declare-fun |IT@5| () Int)"
+ "(declare-fun |gl_read::T@4| () Int)"
+ "(declare-fun __VERIFIER_nondet_int@4 () Int)"
+ "(declare-fun |It15@3| () Int)"
+ "(declare-fun |It13@3| () Int)"
+ "(declare-fun |H@6| () (Array Int Int))"
+ "(declare-fun |It14@3| () Int)"
+ "(declare-fun |IN@3| () Int)"
+ "(declare-fun |It12@3| () Int)"
+ "(declare-fun |It11@3| () Int)"
+ "(declare-fun |It9@3| () Int)"
+ "(declare-fun |H@5| () (Array Int Int))"
+ "(declare-fun |It10@3| () Int)"
+ "(declare-fun |It8@3| () Int)"
+ "(declare-fun |Anew@2| () Int)"
+ "(declare-fun |Aprev@2| () Int)"
+ "(declare-fun |H@4| () (Array Int Int))"
+ "(declare-fun |At7@3| () Int)"
+ "(declare-fun |H@3| () (Array Int Int))"
+ "(declare-fun |At6@3| () Int)"
+ "(declare-fun |Anext@2| () Int)"
+ "(declare-fun |H@2| () (Array Int Int))"
+ "(declare-fun |At5@3| () Int)"
+ "(declare-fun |H@1| () (Array Int Int))"
+ "(declare-fun |At4@3| () Int)"
+ "(declare-fun |at3@3| () Int)"
+ "(declare-fun |ahead@2| () Int)"
+ "(declare-fun |anew@2| () Int)"
+ "(declare-fun |It7@3| () Int)"
+ "(declare-fun |It6@3| () Int)"
+ "(declare-fun |It5@3| () Int)"
+ "(declare-fun |Ivalue@2| () Int)"
+ "(declare-fun i@1 () (Array Int Int))"
+ "(declare-fun P47 () Bool)"
+ "(declare-fun |IT@3| () Int)"
+ "(declare-fun |gl_read::T@3| () Int)"
+ "(declare-fun __VERIFIER_nondet_int@2 () Int)"
+ "(assert "
+ " (and (not (<= gl@ 0))"
+ " (not (<= gl@ (- 64)))"
+ " (= |gl_read::T@3| __VERIFIER_nondet_int@2)"
+ " (= |Ivalue@2| |gl_read::T@3|)"
+ " (= |It4@3| 20)"
+ " (= |IT@3| z3name!114)"
+ " (not (<= |V#1@| 0))"
+ " (= |IN@3| |IT@3|)"
+ " (not (<= |V#1@| (+ 64 gl@)))"
+ " (not (<= |V#1@| (- 160)))"
+ " (not (<= (+ |V#1@| (* 8 |It4@3|)) 0))"
+ " (or (and P47 (not (<= |IN@3| 0))) (and (not P47) (not (>= |IN@3| 0))))"
+ " (= i@2 (store i@1 |IN@3| |Ivalue@2|))"
+ " (= |It5@3| |IN@3|)"
+ " (= |It6@3| (+ 4 |It5@3|))"
+ " (= |It7@3| |It6@3|)"
+ " (= |anew@2| |It7@3|)"
+ " (= |ahead@2| gl@)"
+ " (= |at3@3| (select |H@1| |ahead@2|))"
+ " (= |Anew@2| |anew@2|)"
+ " (= |Aprev@2| |ahead@2|)"
+ " (= |Anext@2| |at3@3|)"
+ " (= |At4@3| |Anext@2|)"
+ " (= |At5@3| (+ 4 |At4@3|))"
+ " (= |H@2| (store |H@1| |At5@3| |Anew@2|))"
+ " (= |H@3| (store |H@2| |Anew@2| |Anext@2|))"
+ " (= |At6@3| |Anew@2|)"
+ " (= |At7@3| (+ 4 |At6@3|))"
+ " (= |H@4| (store |H@3| |At7@3| |Aprev@2|))"
+ " (= |H@5| (store |H@4| |Aprev@2| |Anew@2|))"
+ " (= |It8@3| |IN@3|)"
+ " (= |It9@3| (+ 12 |It8@3|))"
+ " (= |It10@3| |IN@3|)"
+ " (= |It11@3| (+ 12 |It10@3|))"
+ " (= |H@6| (store |H@5| |It9@3| |It11@3|))"
+ " (= |It12@3| |IN@3|)"
+ " (= |It13@3| (+ 12 |It12@3|))"
+ " (= |It14@3| |IN@3|)"
+ " (= |It15@3| (+ 12 |It14@3|))"
+ " (= |H@7| (store |H@6| |It13@3| |It15@3|))"
+ " (= |gl_read::T@4| __VERIFIER_nondet_int@4)"
+ " (= |Ivalue@3| |gl_read::T@4|)"
+ " (= |It4@5| 20)"
+ " (= |IT@5| z3name!115)"
+ " (not (<= |V#2@| 0))"
+ " (= |IN@5| |IT@5|)"
+ " (not (<= |V#2@| (+ |V#1@| (* 8 |It4@3|))))"
+ " (not (<= |V#2@| (+ 160 |V#1@|)))"
+ " (not (<= |V#2@| (- 160)))"
+ " (not (<= (+ |V#2@| (* 8 |It4@5|)) 0))"
+ " (or (and P46 (not (<= |IN@5| 0))) (and (not P46) (not (>= |IN@5| 0))))"
+ " (= i@3 (store i@2 |IN@5| |Ivalue@3|))"
+ " (= |It5@5| |IN@5|)"
+ " (= |It6@5| (+ 4 |It5@5|))"
+ " (= |It7@5| |It6@5|)"
+ " (= |anew@3| |It7@5|)"
+ " (= |ahead@3| gl@)"
+ " (= |at3@5| (select |H@7| |ahead@3|))"
+ " (= |Anew@3| |anew@3|)"
+ " (= |Aprev@3| |ahead@3|)"
+ " (= |Anext@3| |at3@5|)"
+ " (= |At4@5| |Anext@3|)"
+ " (= |At5@5| (+ 4 |At4@5|))"
+ " (= |H@8| (store |H@7| |At5@5| |Anew@3|))"
+ " (= |H@9| (store |H@8| |Anew@3| |Anext@3|))"
+ " (= |At6@5| |Anew@3|)"
+ " (= |At7@5| (+ 4 |At6@5|))"
+ " (= |H@10| (store |H@9| |At7@5| |Aprev@3|))"
+ " (= |H@11| (store |H@10| |Aprev@3| |Anew@3|))"
+ " (= |It8@5| |IN@5|)"
+ " (= |It9@5| (+ 12 |It8@5|))"
+ " (= |It10@5| |IN@5|)"
+ " (= |It11@5| (+ 12 |It10@5|))"
+ " (= |H@12| (store |H@11| |It9@5| |It11@5|))"
+ " (= |It12@5| |IN@5|)"
+ " (= |It13@5| (+ 12 |It12@5|))"
+ " (= |It14@5| |IN@5|)"
+ " (= |It15@5| (+ 12 |It14@5|))"
+ " (= |H@13| (store |H@12| |It13@5| |It15@5|))"
+ " (or (and P45 (not (= M@2 0))) (and (not P45) (= z3name!114 0)))"
+ " (or (and P44 (= M@2 0)) (and (not P44) (= z3name!114 |V
+ " (or (and P43 (not (= M@3 0))) (and (not P43) (= z3name!115 0)))"
+ " (or (and P42 (= M@3 0)) (and (not P42) (= z3name!115 |V
private static final String MEDIUM_ARRAY_QUERY =
"(declare-fun |H@1| () (Array Int Int))"
+ "(declare-fun |H@2| () (Array Int Int))"
+ "(declare-fun |H@3| () (Array Int Int))"
+ "(declare-fun |H@4| () (Array Int Int))"
+ "(declare-fun |H@5| () (Array Int Int))"
+ "(declare-fun |H@6| () (Array Int Int))"
+ "(declare-fun |H@7| () (Array Int Int))"
+ "(declare-fun |H@8| () (Array Int Int))"
+ "(declare-fun |H@9| () (Array Int Int))"
+ "(declare-fun |H@10| () (Array Int Int))"
+ "(declare-fun |H@11| () (Array Int Int))"
+ "(declare-fun |H@12| () (Array Int Int))"
+ "(declare-fun |H@13| () (Array Int Int))"
+ "(declare-fun I10 () Int)"
+ "(declare-fun I11 () Int)"
+ "(declare-fun I12 () Int)"
+ "(declare-fun I13 () Int)"
+ "(declare-fun I14 () Int)"
+ "(declare-fun I15 () Int)"
+ "(declare-fun |at3@5| () Int)"
+ "(declare-fun |at3@3| () Int)"
+ "(declare-fun |At5@3| () Int)"
+ "(declare-fun |At7@3| () Int)"
+ "(declare-fun |At7@5| () Int)"
+ "(declare-fun |ahead@3| () Int)"
+ "(declare-fun |ahead@2| () Int)"
+ "(declare-fun |At5@5| () Int)"
+ "(assert "
+ " (and (not (<= |ahead@2| 0))"
+ " (= |H@2| (store |H@1| |At5@3| 1))"
+ " (= |H@3| (store |H@2| 3 1))"
+ " (= |H@4| (store |H@3| 4 1))"
+ " (= |H@5| (store |H@4| 5 1))"
+ " (= |H@6| (store |H@5| 6 1))"
+ " (= |H@7| (store |H@6| 7 1))"
+ " (= |H@8| (store |H@7| 8 1))"
+ " (= |at3@3| (select |H@1| |ahead@2|))"
+ " (= |at3@5| (select |H@7| |ahead@3|))"
+ " (= I11 (+ 12 I10))"
+ " (= I13 (+ 12 I12))"
+ " (= I15 (+ 12 I14))"
+ " ))";
private static final String UGLY_ARRAY_QUERY =
"(declare-fun V () Int)"
+ "(declare-fun W () Int)"
+ "(declare-fun A () Int)"
+ "(declare-fun B () Int)"
+ "(declare-fun U () Int)"
+ "(declare-fun G () Int)"
+ "(declare-fun ARR () (Array Int Int))"
+ "(declare-fun EMPTY () (Array Int Int))"
+ "(assert "
+ " (and (> (+ V U) 0)"
+ " (not (= B (- 4)))"
+ " (= ARR (store (store (store EMPTY G B) B G) A W))"
+ " ))";
private static final String UGLY_ARRAY_QUERY_2 =
"(declare-fun A () Int)"
+ "(declare-fun B () Int)"
+ "(declare-fun ARR () (Array Int Int))"
+ "(declare-fun EMPTY () (Array Int Int))"
+ "(assert (and (= A 0) (= B 0) (= ARR (store (store EMPTY A 1) B 2))))";
private static final String SMALL_BV_FLOAT_QUERY =
"(declare-fun |f@2| () (_ FloatingPoint 8 23))"
+ "(declare-fun |p@3| () (_ BitVec 32))"
+ "(declare-fun *float@1 () (Array (_ BitVec 32) (_ FloatingPoint 8 23)))"
+ "(declare-fun |i@33| () (_ BitVec 32))"
+ "(declare-fun |Ai@| () (_ BitVec 32))"
+ "(declare-fun *unsigned_int@1 () (Array (_ BitVec 32) (_ BitVec 32)))"
+ "(assert (and (bvslt #x00000000 |Ai@|)"
+ " (bvslt #x00000000 (bvadd |Ai@| #x00000020))"
+ " (= |i@33| #x00000000)"
+ " (= |p@3| |Ai@|)"
+ " (= (select *unsigned_int@1 |Ai@|) |i@33|)"
+ " (= |f@2| (select *float@1 |p@3|))"
+ " (not (fp.eq ((_ to_fp 11 52) roundNearestTiesToEven |f@2|)"
+ " (_ +zero 11 52)))))";
private static final String SMALL_BV_FLOAT_QUERY2 =
"(declare-fun a () (_ FloatingPoint 8 23))"
+ "(declare-fun A () (Array (_ BitVec 32) (_ FloatingPoint 8 23)))"
+ "(assert (= a (select A #x00000000)))";
@Test
public void arrayTest1() throws SolverException, InterruptedException {
requireParser();
requireArrays();
for (String query :
ImmutableList.of(
SMALL_ARRAY_QUERY, MEDIUM_ARRAY_QUERY, UGLY_ARRAY_QUERY, UGLY_ARRAY_QUERY_2)) {
BooleanFormula formula = context.getFormulaManager().parse(query);
checkModelIteration(formula, false);
}
}
@Test
public void arrayTest2() throws SolverException, InterruptedException {
requireParser();
requireArrays();
requireOptimization();
requireFloats();
requireBitvectors();
// only Z3 fulfills these requirements
for (String query :
ImmutableList.of(BIG_ARRAY_QUERY, SMALL_BV_FLOAT_QUERY, SMALL_BV_FLOAT_QUERY2)) {
BooleanFormula formula = context.getFormulaManager().parse(query);
checkModelIteration(formula, true);
checkModelIteration(formula, false);
}
}
private static final String ARRAY_QUERY_INT =
"(declare-fun i () Int)"
+ "(declare-fun X () (Array Int Int))"
+ "(declare-fun Y () (Array Int Int))"
+ "(declare-fun Z () (Array Int Int))"
+ "(assert (and "
+ " (= Y (store X i 0))"
+ " (= (select Y 5) 1)"
+ " (= Z (store Y 5 2))"
+ "))";
private static final String ARRAY_QUERY_BV =
"(declare-fun v () (_ BitVec 64))"
+ "(declare-fun A () (Array (_ BitVec 64) (_ BitVec 32)))"
+ "(declare-fun B () (Array (_ BitVec 64) (_ BitVec 32)))"
+ "(declare-fun C () (Array (_ BitVec 64) (_ BitVec 32)))"
+ "(assert (and "
+ " (= B (store A v (_ bv0 32)))"
+ " (= (select B (_ bv5 64)) (_ bv1 32))"
+ " (= C (store B (_ bv5 64) (_ bv2 32)))"
+ "))";
@Test
public void arrayTest3() throws SolverException, InterruptedException {
requireParser();
requireArrays();
BooleanFormula formula = context.getFormulaManager().parse(ARRAY_QUERY_INT);
checkModelIteration(formula, false);
}
@Test
public void arrayTest4() throws SolverException, InterruptedException {
requireParser();
requireArrays();
requireBitvectors();
BooleanFormula formula = context.getFormulaManager().parse(ARRAY_QUERY_BV);
checkModelIteration(formula, false);
}
@Test
public void arrayTest5()
throws SolverException, InterruptedException, IllegalArgumentException, IOException {
requireParser();
requireArrays();
requireBitvectors();
assume()
.withMessage("Solver %s sadly fails on this test.", solverToUse())
.that(solverToUse())
.isNotEqualTo(Solvers.PRINCESS);
BooleanFormula formula =
context
.getFormulaManager()
.parse(
Files.readString(Path.of("src/org/sosy_lab/java_smt/test/SMT2_UF_and_Array.smt2")));
checkModelIteration(formula, false);
}
@Test
@SuppressWarnings("resource")
public void multiCloseTest() throws SolverException, InterruptedException {
Formula x;
BooleanFormula eq;
if (imgr != null) {
x = imgr.makeVariable("x");
eq = imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(1));
} else {
// Boolector only has bitvectors
x = bvmgr.makeVariable(8, "x");
eq = bvmgr.equal(bvmgr.makeVariable(8, "x"), bvmgr.makeBitvector(8, 1));
}
ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS);
try {
prover.push(eq);
assertThat(prover).isSatisfiable();
Model m = prover.getModel();
try {
assertThat(m.evaluate(x)).isEqualTo(BigInteger.ONE);
// close the model several times
} finally {
for (int i = 0; i < 10; i++) {
m.close();
}
}
} finally {
// close the prover several times
for (int i = 0; i < 10; i++) {
prover.close();
}
}
}
@Test
@SuppressWarnings("resource")
public void modelAfterSolverCloseTest() throws SolverException, InterruptedException {
ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS);
if (imgr != null) {
prover.push(imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(1)));
} else {
prover.push(bvmgr.equal(bvmgr.makeVariable(8, "x"), bvmgr.makeBitvector(8, 1)));
}
assertThat(prover).isSatisfiable();
Model m = prover.getModel();
// close prover first
prover.close();
// try to access model, this should either fail fast or succeed
try {
if (imgr != null) {
assertThat(m.evaluate(imgr.makeVariable("x"))).isEqualTo(BigInteger.ONE);
} else {
assertThat(m.evaluate(bvmgr.makeVariable(8, "x"))).isEqualTo(BigInteger.ONE);
}
} catch (IllegalStateException e) {
// ignore
} finally {
m.close();
}
}
@SuppressWarnings("resource")
@Test(expected = IllegalStateException.class)
public void testGenerateModelsOption() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment()) { // no option
assertThat(prover).isSatisfiable();
prover.getModel();
assert_().fail();
}
}
@Test(expected = IllegalStateException.class)
public void testGenerateModelsOption2() throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment()) { // no option
assertThat(prover).isSatisfiable();
prover.getModelAssignments();
assert_().fail();
}
}
@Test
public void testGetSmallIntegers1() throws SolverException, InterruptedException {
requireIntegers();
evaluateInModel(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(10)),
imgr.add(imgr.makeVariable("x"), imgr.makeVariable("x")),
BigInteger.valueOf(20));
}
@Test
public void testGetSmallIntegers2() throws SolverException, InterruptedException {
requireIntegers();
evaluateInModel(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(10)),
imgr.add(imgr.makeVariable("x"), imgr.makeNumber(1)),
BigInteger.valueOf(11));
}
@Test
public void testGetNegativeIntegers1() throws SolverException, InterruptedException {
requireIntegers();
evaluateInModel(
imgr.equal(imgr.makeVariable("x"), imgr.makeNumber(-10)),
imgr.add(imgr.makeVariable("x"), imgr.makeNumber(1)),
BigInteger.valueOf(-9));
}
@Test
public void testGetSmallIntegralRationals1() throws SolverException, InterruptedException {
requireRationals();
evaluateInModel(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(1)),
rmgr.add(rmgr.makeVariable("x"), rmgr.makeVariable("x")),
Rational.of(2));
}
@Test
public void testGetRationals1() throws SolverException, InterruptedException {
requireRationals();
evaluateInModel(
rmgr.equal(rmgr.makeVariable("x"), rmgr.makeNumber(Rational.ofString("1/3"))),
rmgr.divide(rmgr.makeVariable("x"), rmgr.makeNumber(2)),
Rational.ofString("1/6"));
}
@Test
public void testGetBooleans1() throws SolverException, InterruptedException {
evaluateInModel(bmgr.makeVariable("x"), bmgr.makeBoolean(true), true);
evaluateInModel(bmgr.makeVariable("x"), bmgr.makeBoolean(false), false);
evaluateInModel(
bmgr.makeVariable("x"),
bmgr.or(bmgr.makeVariable("x"), bmgr.not(bmgr.makeVariable("x"))),
true);
evaluateInModel(
bmgr.makeVariable("x"),
bmgr.and(bmgr.makeVariable("x"), bmgr.not(bmgr.makeVariable("x"))),
false);
}
private void evaluateInModel(BooleanFormula constraint, Formula variable, Object expectedValue)
throws SolverException, InterruptedException {
try (ProverEnvironment prover = context.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
prover.push(constraint);
assertThat(prover).isSatisfiable();
try (Model m = prover.getModel()) {
assertThat(m.evaluate(variable)).isEqualTo(expectedValue);
}
}
}
}
|
package belight;
import com.amazon.speech.speechlet.Session;
/**
* Created 4/16/16. Description...
*
* @author Neo Li. <neo.siqi.li@hotmail.com>
*/
public class ResponseGenerator {
public static String getInitialPrompt(Session session) {
return "I don't know. What did you have so far?";
}
public static String getResponse(Session session, FoodItem foodItem) {
final int residualInCalories = SessionHelper.getResidualInCalories(session, foodItem);
if (residualInCalories <= 0) {
return String.format("You ate %s. %d calories over your goal. Stop it. American " +
"say yes.", foodItem.getName(), foodItem
.getCalories());
else if(foodItem.isBadFood()) {
return String.format("%s is bad. It is %d calories. Be careful. Be light");
} else {
return String.format("%s is %d calories. You are doing great." +
"Be light", foodItem.getName(),
foodItem.getCalories());
}
}
public static String getWhatElseCanIEat(Session session) {
String eatenAlready = SessionHelper.getCurrentIntakeFoodNames(session);
int residualInCalories = SessionHelper.caloriesMax - SessionHelper.getCurrentIntakeCalories
(session);
String response = "You had eaten " + eatenAlready + ". Total intake calories are " +
residualInCalories;
// increase already eat too much, or can't find a suitable items.
String recommendation = "Sorry, I don't know. I'll find out.";
for(FoodItem item : FoodDAO.foodItems.values()) {
if(!eatenAlready.contains(item.getName()) && residualInCalories + item.getCalories() <
SessionHelper.caloriesMax) {
recommendation = "I recommend " + item.getName() + ", which is " + item
.getCalories() + " calories. And you can buy it from " + item.getBuyAt()
+ ". Do you want me to order?";
}
}
return response + recommendation;
}
}
|
package pathfinding.astar.arcs;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import config.Config;
import config.ConfigInfo;
import config.DynamicConfigurable;
import container.Service;
import container.dependances.HighPFClass;
import container.dependances.LowPFClass;
import graphic.Fenetre;
import graphic.PrintBufferInterface;
import graphic.printable.Couleur;
import graphic.printable.Layer;
import graphic.printable.Printable;
import pathfinding.SensFinal;
import robot.Cinematique;
import robot.RobotReal;
import table.GameElementNames;
import utils.Log;
import utils.Log.Verbose;
import utils.Vec2RO;
import utils.Vec2RW;
public class CercleArrivee implements Service, Printable, HighPFClass, LowPFClass, DynamicConfigurable
{
public Vec2RO position;
public double rayon;
public Vec2RO arriveeDStarLite;
public SensFinal sens;
private boolean graphic;
private boolean symetrie = false;
private double distanceMax, distanceMin, angleMax, angleMin;
public List<Double> anglesAttaquesPossibles = new ArrayList<Double>();
protected Log log;
private PrintBufferInterface buffer;
public CercleArrivee(Log log, PrintBufferInterface buffer, Config config)
{
this.log = log;
this.buffer = buffer;
graphic = config.getBoolean(ConfigInfo.GRAPHIC_CERCLE_ARRIVEE);
distanceMax = config.getDouble(ConfigInfo.DISTANCE_MAX_CRATERE);
distanceMin = config.getDouble(ConfigInfo.DISTANCE_MIN_CRATERE);
angleMax = config.getDouble(ConfigInfo.ANGLE_MAX_CRATERE);
angleMin = config.getDouble(ConfigInfo.ANGLE_MIN_CRATERE);
if(graphic)
buffer.add(this);
}
public void set(Vec2RO position, double orientationArriveeDStarLite, double rayon, SensFinal sens, List<Double> anglesAttaquesPossibles)
{
this.anglesAttaquesPossibles.clear();
if(anglesAttaquesPossibles != null)
this.anglesAttaquesPossibles.addAll(anglesAttaquesPossibles);
this.position = new Vec2RO(symetrie ? -position.getX() : position.getX(), position.getY());
this.arriveeDStarLite = new Vec2RW(rayon, symetrie ? Math.PI - orientationArriveeDStarLite : orientationArriveeDStarLite, false);
((Vec2RW) arriveeDStarLite).plus(position);
this.rayon = rayon;
this.sens = sens;
if(graphic)
synchronized(buffer)
{
buffer.notify();
}
// log.debug("arriveeDStarLite : "+arriveeDStarLite);
}
public void set(GameElementNames element, double rayon)
{
set(element.obstacle.getPosition(), element.orientationArriveeDStarLite, rayon, SensFinal.MARCHE_ARRIERE, null);
}
private Vec2RW tmp = new Vec2RW();
public boolean isAlmostArrived(Cinematique robot)
{
return isArrived(robot, -10, 10, 140, 260, false);
}
public boolean isArrivedAsser(Cinematique robot)
{
return isArrived(robot, angleMin, angleMax, distanceMin, distanceMax, Math.abs((robot.getPosition().distanceFast(position) - rayon)) < 40);
}
public boolean isArrivedPF(Cinematique robot)
{
return isArrived(robot, -1, 1, 195, 205, false);
}
private boolean isArrived(Cinematique robot, double angleMin, double angleMax, double distanceMin, double distanceMax, boolean verbose)
{
double deltaDist = robot.getPosition().distance(position);
if(deltaDist > distanceMax || deltaDist < distanceMin)
{
if(verbose)
log.debug("Mauvaise distance au cratère : "+deltaDist);
return false;
}
boolean accepted = anglesAttaquesPossibles.isEmpty();
for(int i = 0; i < anglesAttaquesPossibles.size() / 2; i++)
if(robot.orientationGeometrique >= anglesAttaquesPossibles.get(2 * i) && robot.orientationGeometrique <= anglesAttaquesPossibles.get(2 * i + 1))
{
accepted = true;
break;
}
if(!accepted)
{
if(verbose)
log.debug("L'orientation " + robot.orientationGeometrique + " n'est pas autorisée pour arriver sur le cratère !");
return false;
}
position.copy(tmp);
tmp.minus(robot.getPosition());
double o = tmp.getArgument();
double diffo = (o - robot.orientationGeometrique) % (2 * Math.PI);
if(diffo > Math.PI)
diffo -= 2 * Math.PI;
else if(diffo < -Math.PI)
diffo += 2 * Math.PI;
diffo *= 180. / Math.PI;
boolean out = diffo <= angleMax && diffo >= angleMin;
if(verbose)
log.debug("Arrivée sur cercle ? " + out + ". Delta orientation : " + diffo + ", delta distance : " + deltaDist, Verbose.SCRIPTS.masque);
return out;
}
@Override
public void print(Graphics g, Fenetre f, RobotReal robot)
{
if(position != null)
{
g.setColor(Couleur.ROUGE.couleur);
g.drawOval(f.XtoWindow(position.getX() - rayon), f.YtoWindow(position.getY() + rayon), f.distanceXtoWindow((int) (2 * rayon)), f.distanceYtoWindow((int) (2 * rayon)));
}
}
@Override
public Layer getLayer()
{
return Layer.FOREGROUND;
}
public boolean isInCircle(Vec2RO position2)
{
return position2.squaredDistance(position) < rayon * rayon;
}
@Override
public String toString()
{
return position + ", rayon " + rayon + ", arrivee " + arriveeDStarLite;
}
@Override
public void updateConfig(Config config)
{
symetrie = config.getSymmetry();
}
}
|
package br.com.dbsoft.core;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
public final class DBSSDK {
public static final String DOMAIN = "br.com.dbsoft";
public static final int VERDADEIRO = -1;
public static final int FALSO = 0;
public static final class UI
{
public static enum ID_PREFIX{
APPLICATION ("ap"),
MENU ("mn"),
FORM ("fr"),
TABLE ("tb"),
BUTTON ("bt"),
FIELD_CRUD ("fl"),
FIELD_FILTER ("ft"),
FIELD_AUX ("fx"),
OBJECT ("ob"),
DEAD_END ("de");
private String wName;
private ID_PREFIX(String pName) {
this.wName = pName;
}
public String getName() {
return wName;
}
public static ID_PREFIX get(String pPrefixo) {
String xString = pPrefixo.trim().toLowerCase();
if (xString.equals(APPLICATION.getName())){
return APPLICATION;
}else if (xString.equals(MENU.getName())){
return MENU;
}else if (xString.equals(FORM.getName())){
return FORM;
}else if (xString.equals(TABLE.getName())){
return TABLE;
}else if (xString.equals(BUTTON.getName())){
return BUTTON;
}else if (xString.equals(FIELD_CRUD.getName())){
return FIELD_CRUD;
}else if (xString.equals(FIELD_FILTER.getName())){
return FIELD_FILTER;
}else if (xString.equals(FIELD_AUX.getName())){
return FIELD_AUX;
}else if (xString.equals(DEAD_END.getName())){
return DEAD_END;
}
return null;
}
}
public static final class COMBOBOX{
public static final String NULL_VALUE = "";
public enum NULL_TEXT{
NAO_EXIBIR,
NENHUM,
NENHUMA,
DEFAULT,
PADRAO,
TODOS,
TODAS,
BRANCO,
INEXISTENTE,
NAO_SELECIONADO,
NAO_SELECIONADA;
String toString;
NULL_TEXT(String toString) {
this.toString = toString;
}
NULL_TEXT() {}
@Override
public String toString() {
switch (this) {
case NAO_EXIBIR:
return "";
case NENHUM:
return "(Nenhum)";
case NENHUMA:
return "(Nenhuma)";
case DEFAULT:
return "(Default)";
case PADRAO:
return "(Padrão)";
case TODOS:
return "(Todos)";
case TODAS:
return "(Todas)";
case BRANCO:
return "";
case INEXISTENTE:
return "(Inexistente)";
case NAO_SELECIONADO:
return "(Não selecionado)";
case NAO_SELECIONADA:
return "(Não selecionada)";
default:
return "";
}
}
}
}
}
public static final class ENCODE{
public static final String US_ASCII = "US-ASCII";
public static final String UTF_8 = "UTF-8";
public static final String ISO_8859_1 = "ISO-8859-1";
public static final String ISO_8859_6 = "ISO-8859-6";
}
public static final class CONTENT_TYPE{
public static final String APPLICATION_JSON = "application/json";
public static final String APPLICATION_JAVA_SERIALIZED_OBJECT = "application/x-java-serialized-object";
public static final String APPLICATION_PDF = "application/pdf";
public static final String APPLICATION_XML = "application/xml";
public static final String APPLICATION_XLS = "application/excel";
public static final String APPLICATION_XLSX = "application/excel";
public static final String TEXT_PLAIN = "text/plain";
public static final String TEXT_EVENT_STREAM = "text/event-stream";
public static final String TEXT_HTML = "text/html";
public static final String TEXT_JAVASCRIPT = "text/javascript";
}
public static final class FILE{
public enum TYPE{
HTML,
XML,
TXT,
CVS,
DOC,
XLS,
ZIP,
RAR,
BIN,
DMG,
FOLDER,
GENERAL;
}
public static class EXTENSION{
public static final String PDF = ".pdf";
public static final String HTML = ".html";
public static final String XML = ".xml";
public static final String XLS = ".xls";
public static final String XLSX = ".xlsx";
public static final String JASPER= ".jasper";
public static final String JRXML = ".jrxml";
public static final String ZIP = ".zip";
public static final String DOC = ".doc";
public static final String RAR = ".rar";
public static final String TXT = ".txt";
public static final String CSV = ".csv";
}
}
public static final class NETWORK{
public static enum PROTOCOL {
HTTP ("HTTP"),
HTTPS ("HTTPS"),
SSH ("SSH"),
SFTP ("SFTP"),
FTP ("FTP"),
FTPS ("FTPS"),
UDP ("UDP"),
SSL ("SSL"),
TLS ("TLS"),
STARTTLS ("STARTTLS");
private String wName;
public String getName() {return wName;}
private PROTOCOL(String pName) {
wName = pName;
}
public static PROTOCOL get(String pName) {
switch (pName) {
case "HTTP":
return HTTP;
case "HTTPS":
return HTTPS;
case "SSH":
return SSH;
case "SFTP":
return SFTP;
case "FTP":
return FTP;
case "FTPS":
return FTPS;
case "UDP":
return UDP;
case "SSL":
return SSL;
case "TLS":
return TLS;
case "STARTTLS":
return STARTTLS;
default:
return null;
}
}
}
public static enum METHOD {
POST ("POST"),
GET ("GET");
private String wName;
public String getName() {return wName;}
private METHOD(String pName) {
wName = pName;
}
public static METHOD get(String pName) {
switch (pName) {
case "POST":
return POST;
case "GET":
return GET;
default:
return null;
}
}
}
}
public static final class TABLE {
public static String FERIADO = "";
}
public static final class JDBC_DRIVER {
public static final String MYSQL = "com.mysql.jdbc.Driver";
public static final String ORACLE = "oracle.jdbc.driver.OracleDriver";
}
/**
* @author ricardo.villar
*
*/
public static final class SYSTEM_PROPERTY{
public static final String SERVER_BASE_DIR = "jboss.server.base.dir";
public static final String CONFIG_URL = "jboss.server.config.url";
public static final String BIND_ADDRESS = "jboss.bind.address";
public static final String USER_LANGUAGE = "user.language";
public static final String USER_LANGUAGE_FORMAT = "user.language.format";
public static final String USER_TIMEZONE = "user.timezone";
public static final String PATH_SEPARATOR = "path.separator";
public static final String JAVA_VERSION = "java.version";
}
public static final class SYS {
public enum APP_SERVER { //Aplication Server
JBOSS,
WEBSPHERE,
GLASSFISH,
WILDFLY;
}
public enum OS {
MACOS,
IOS,
ANDROID,
RIM,
LINUX,
WEBOS,
WINDOWS,
WINDOWSPHONE,
SYMBIAN;
}
public enum APP_CLIENT {
WEB,
DOTNET,
OBJC,
JAVA;
}
}
public static class COLUMN {
public enum VERTICALALIGNMENT{
TOP,
CENTER,
BOTTON;
}
public enum HORIZONTALALIGNMENT {
LEFT,
CENTER,
RIGHT;
}
}
public static final class IO {
public static final String VERSION_COLUMN_NAME = "VERSION";
public static enum DATATYPE {
NONE (Object.class),
STRING (String.class), //Tipo String, quando vazio(""), converte para Null.
DECIMAL (BigDecimal.class), //Tipo Decimal
INT (Integer.class), //Tipo Inteiro
DOUBLE (Double.class), //Tipo Double
DATE (Date.class), //Tipo de dado de Data, contendo somente a data. Desprezando hora, se hourver
DATETIME(Timestamp.class),
TIME (Time.class), //Tipo de dado de hora, contendo somente a data. Desprezando hora, se hourver
BOOLEAN (Boolean.class), //Tipo boleano, onde True=-1 e False=0
COMMAND (String.class),
PICTURE (Object.class), //Imagem
ID (Long.class);
Class<?> wJavaClass;
DATATYPE (Class<?> pJavaClass){
wJavaClass = pJavaClass;
}
public Class<?> getJavaClass(){
return wJavaClass;
}
}
public static enum DB_SERVER{
ORACLE,
SQLSERVER,
SYBASE,
MYSQL,
ACCESS,
DB2,
POSTGRESQL,
FIREBIRD,
INGRE,
APACHEDERBY,
SQLLITE
}
}
}
//package org.agoncal.sample.javaee.jbossutil;
//import org.apache.http.auth.AuthScope;
//import org.apache.http.auth.UsernamePasswordCredentials;
//import org.apache.http.client.CredentialsProvider;
//import org.apache.http.client.HttpClient;
//import org.apache.http.impl.client.BasicCredentialsProvider;
//import org.apache.http.impl.client.HttpClientBuilder;
//import org.jboss.resteasy.client.jaxrs.ResteasyClient;
//import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
//import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
//import javax.ws.rs.client.WebTarget;
//import javax.ws.rs.core.MediaType;
//import javax.ws.rs.core.Response;
//public class JBossUtil {
// public static final String JBOSS_ADMIN_USER = "admin";
// public static final String JBOSS_ADMIN_PASSWORD = "admin";
// /**
// * This method returns a connected HTTP client (user/password). This HTTP client is then used in all the following methods.
// *
// * @return A RestEasy HTTP client
// */
// private static ResteasyClient getClient() {
// // Setting digest credentials
// CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(JBOSS_ADMIN_USER, JBOSS_ADMIN_PASSWORD);
// credentialsProvider.setCredentials(AuthScope.ANY, credentials);
// HttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
// ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, true);
// // Creating HTTP client
// return new ResteasyClientBuilder().httpEngine(engine).build();
// // Used to test this class
// public static void main(String[] args) {
// System.out.println(isJBossUpAndRunning());
// System.out.println(isJBoss620EAP());
// System.out.println(isWebappDeployed("myWay"));
// System.out.println(isDatasourceDeployed("myDS"));
// System.out.println(isHTTPListenerOk());
// public static boolean isJBossUpAndRunning() {
// Response response;
// try {
// WebTarget target = getClient().target(JBOSS_MANAGEMENT_URL).queryParam("operation", "attribute").queryParam("name", "server-state");
// response = target.request(MediaType.APPLICATION_JSON).get();
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// return response.getStatus() == Response.Status.OK.getStatusCode() && response.readEntity(String.class).contains("running");
// public static boolean isJBoss620EAP() {
// Response response;
// try {
// WebTarget target = getClient().target(JBOSS_MANAGEMENT_URL).queryParam("operation", "attribute").queryParam("name", "product-version");
// response = target.request(MediaType.APPLICATION_JSON).get();
// } catch (Exception e) {
// return false;
// return response.getStatus() == Response.Status.OK.getStatusCode() && response.readEntity(String.class).contains("6.2.0.GA");
// public static boolean isWebappDeployed(String warName) {
// Response response;
// try {
// WebTarget target = getClient().target(JBOSS_MANAGEMENT_URL).path("deployment").path(warName).queryParam("operation", "attribute").queryParam("name", "status");
// response = target.request(MediaType.APPLICATION_JSON).get();
// } catch (Exception e) {
// return false;
// return response.getStatus() == Response.Status.OK.getStatusCode() && response.readEntity(String.class).contains("OK");
// public static boolean isDatasourceDeployed(String datasourceName) {
// Response response;
// try {
// WebTarget target = getClient().target(JBOSS_MANAGEMENT_URL).path("subsystem").path("datasources").path("data-source").path(datasourceName).queryParam("operation", "attribute").queryParam("name", "enabled");
// response = target.request(MediaType.APPLICATION_JSON).get();
// } catch (Exception e) {
// return false;
// return response.getStatus() == Response.Status.OK.getStatusCode() && response.readEntity(String.class).contains("true");
// public static boolean isHTTPListenerOk() {
// Response response;
// try {
// WebTarget target = getClient().target(JBOSS_MANAGEMENT_URL).path("subsystem").path("web").path("connector").path("http").queryParam("operation", "attribute").queryParam("name", "enabled");
// response = target.request(MediaType.APPLICATION_JSON).get();
// } catch (Exception e) {
// return false;
// return response.getStatus() == Response.Status.OK.getStatusCode() && response.readEntity(String.class).contains("true");
|
package com.emarsys.escher;
import com.emarsys.escher.util.DateTime;
import org.apache.http.client.utils.URIBuilder;
import javax.xml.bind.DatatypeConverter;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
public class Escher {
public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
public static final int DEFAULT_EXPIRES = 86400;
private String credentialScope;
private String algoPrefix = "ESR";
private String vendorKey = "Escher";
private String hashAlgo = "SHA256";
private Date currentTime = new Date();
private String authHeaderName = "X-Escher-Auth";
private String dateHeaderName = "X-Escher-Date";
private int clockSkew = 900;
public Escher(String credentialScope) {
this.credentialScope = credentialScope;
}
public EscherRequest signRequest(EscherRequest request, String accessKeyId, String secret, List<String> signedHeaders) throws EscherException {
Config config = createConfig();
Helper helper = new Helper(config);
helper.addMandatoryHeaders(request, currentTime);
helper.addMandatorySignedHeaders(signedHeaders);
String signature = calculateSignature(helper, request, secret, signedHeaders, currentTime);
String authHeader = helper.calculateAuthHeader(accessKeyId, currentTime, credentialScope, signedHeaders, signature);
helper.addAuthHeader(request, authHeader);
return request;
}
public String presignUrl(String url, String accessKeyId, String secret) throws EscherException{
return presignUrl(url, accessKeyId, secret, DEFAULT_EXPIRES);
}
public String presignUrl(String url, String accessKeyId, String secret, int expires) throws EscherException{
try {
Config config = createConfig();
Helper helper = new Helper(config);
URI uri = new URI(url);
URIBuilder uriBuilder = new URIBuilder(uri);
Map<String, String> params = helper.calculateSigningParams(accessKeyId, currentTime, credentialScope, expires);
params.forEach((key, value) -> uriBuilder.addParameter("X-" + vendorKey + "-" + key, value));
EscherRequest request = new PresignUrlDummyEscherRequest(uriBuilder.build());
String signature = calculateSignature(helper, request, secret, Arrays.asList("host"), currentTime);
uriBuilder.addParameter("X-" + vendorKey + "-" + "Signature", signature);
return uriBuilder.build().toString();
} catch (URISyntaxException e) {
throw new EscherException(e);
}
}
public String authenticate(EscherRequest request, Map<String, String> keyDb, InetSocketAddress address) throws EscherException {
Config config = createConfig();
Helper helper = new Helper(config);
AuthElements authElements = helper.parseAuthElements(request);
Date requestDate = helper.parseDate(request);
String hostHeader = helper.parseHostHeader(request);
AuthenticationValidator validator = new AuthenticationValidator(config);
validator.validateMandatorySignedHeaders(authElements.getSignedHeaders(), authElements.isFromHeaders());
validator.validateHashAlgo(authElements.getHashAlgo());
validator.validateDates(requestDate, DateTime.parseShortString(authElements.getCredentialDate()), currentTime, authElements.getExpires());
validator.validateHost(address, hostHeader);
validator.validateCredentialScope(credentialScope, authElements.getCredentialScope());
String secret = retrieveSecret(keyDb, authElements.getAccessKeyId());
request = authElements.isFromHeaders() ? request : new PresignUrlEscherRequestWrapper(request);
String calculatedSignature = calculateSignature(helper, request, secret, authElements.getSignedHeaders(), requestDate);
validator.validateSignature(calculatedSignature, authElements.getSignature());
return authElements.getAccessKeyId();
}
private String retrieveSecret(Map<String, String> keyDb, String accessKeyId) throws EscherException {
String secret = keyDb.get(accessKeyId);
if (secret == null) {
throw new EscherException("Invalid access key id");
}
return secret;
}
private String calculateSignature(Helper helper, EscherRequest request, String secret, List<String> signedHeaders, Date date) throws EscherException {
String canonicalizedRequest = helper.canonicalize(request, signedHeaders);
String stringToSign = helper.calculateStringToSign(date, credentialScope, canonicalizedRequest);
byte[] signingKey = helper.calculateSigningKey(secret, date, credentialScope);
String signature = helper.calculateSignature(signingKey, stringToSign);
Logger.log("Canonicalized request: " + canonicalizedRequest);
Logger.log("String to sign: " + stringToSign);
Logger.log("Signing key: " + DatatypeConverter.printHexBinary(signingKey));
Logger.log("Signature: " + signature);
return signature;
}
private Config createConfig() {
return Config.create()
.setVendorKey(vendorKey)
.setAlgoPrefix(algoPrefix)
.setHashAlgo(hashAlgo)
.setDateHeaderName(dateHeaderName)
.setAuthHeaderName(authHeaderName)
.setClockSkew(clockSkew);
}
public Escher setAlgoPrefix(String algoPrefix) {
this.algoPrefix = algoPrefix;
return this;
}
public Escher setVendorKey(String vendorKey) {
this.vendorKey = vendorKey;
return this;
}
public Escher setHashAlgo(String hashAlgo) {
this.hashAlgo = hashAlgo;
return this;
}
public Escher setCurrentTime(Date currentTime) {
this.currentTime = currentTime;
return this;
}
public Escher setAuthHeaderName(String authHeaderName) {
this.authHeaderName = authHeaderName;
return this;
}
public Escher setDateHeaderName(String dateHeaderName) {
this.dateHeaderName = dateHeaderName;
return this;
}
public Escher setClockSkew(int clockSkew) {
this.clockSkew = clockSkew;
return this;
}
public Escher setLogger(Consumer<String> logger) {
if (logger == null) {
throw new IllegalArgumentException("Logger is null");
}
Logger.setConsumer(logger);
return this;
}
}
|
package com.gildedrose;
class GildedRose {
private static final int QUALITY_FLOOR = 0;
private static final int QUALITY_CEILING = 50;
private static final String AGED_BRIE = "Aged Brie";
private static final String BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT = "Backstage passes to a TAFKAL80ETC concert";
private static final String SULFURAS_HAND_OF_RAGNAROS = "Sulfuras, Hand of Ragnaros";
Item[] items;
public GildedRose(Item[] items) {
this.items = items;
for (Item item : items) {
item.quality = (item.quality < 0) ? 0 : item.quality;
}
}
public void updateQuality() {
for (Item item : items) {
updateItem(item);
}
}
private void updateItem(Item item) {
if (isAgedBrie(item) || isBackstagePass(item)) {
incrementQuality(item);
if (isBackstagePass(item)) {
if (item.sellIn < 11) {
incrementQuality(item);
}
if (item.sellIn < 6) {
incrementQuality(item);
}
}
} else {
decrementQuality(item);
}
if (!isSulfurasHandOfRagnaros(item)) {
decrementDaysRemainingToSell(item);
}
if (item.sellIn < 0) {
if (!isAgedBrie(item)) {
if (!isBackstagePass(item)) {
decrementQuality(item);
} else {
makeWorthless(item);
}
} else {
incrementQuality(item);
}
}
}
private void decrementDaysRemainingToSell(Item item) {
item.sellIn = item.sellIn - 1;
}
private boolean isSulfurasHandOfRagnaros(Item item) {
return item.name.equals(SULFURAS_HAND_OF_RAGNAROS);
}
private boolean isAgedBrie(Item item) {
return item.name.equals(AGED_BRIE);
}
private boolean isBackstagePass(Item item) {
return item.name.equals(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT);
}
private void makeWorthless(Item item) {
item.quality = item.quality - item.quality;
}
private void incrementQuality(Item item) {
if (item.quality < QUALITY_CEILING) {
item.quality = item.quality + 1;
}
}
private void decrementQuality(Item item) {
if (item.quality > QUALITY_FLOOR) {
if (!isSulfurasHandOfRagnaros(item)) {
item.quality = item.quality - 1;
}
}
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-11-19");
this.setApiVersion("14.8.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:22-01-15");
this.setApiVersion("17.18.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-11-02");
this.setApiVersion("17.12.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-03-08");
this.setApiVersion("16.18.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:20-04-19");
this.setApiVersion("16.0.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:17-08-21");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* Kaltura API session
*
* @param ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param responseProfile
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package com.senac.petshop.app;
import com.senac.petshop.bean.Animal;
import com.senac.petshop.bean.CorPredominante;
import com.senac.petshop.bean.Dono;
import com.senac.petshop.bean.TipoAnimal;
import com.senac.petshop.infra.BancoDados;
import com.senac.petshop.infra.Propriedades;
import com.senac.petshop.rn.AnimalRN;
import com.senac.petshop.rn.DonoRN;
import com.senac.petshop.util.CadastradorAutomatico;
import com.senac.petshop.util.Console;
import com.senac.petshop.util.MenuConsole;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import javax.swing.JOptionPane;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger;
/**
*
* @author lossurdo
*/
public class App {
private static final Logger logger = Logger.getLogger(App.class);
public static void main(String[] args) throws Exception {
CadastradorAutomatico.popular();
logger.debug("Versão de Java: " + SystemUtils.JAVA_VERSION_FLOAT);
logger.debug("Java: " + SystemUtils.JAVA_VM_VENDOR);
logger.debug("Java instalado em: " + SystemUtils.JAVA_HOME);
logger.debug("Sistema operacional: " + SystemUtils.OS_NAME);
while (true) {
MenuConsole mc = new MenuConsole(
Propriedades.getInstance().get("sistema.nome"),
Propriedades.getInstance().get("sistema.descricao"),
App.class); // exemplo de uso de Propriedades
mc.adicionarAcao("Cadastrar Dono", "cadastrarDono");
mc.adicionarAcao("Cadastrar Animal", "cadastrarAnimal");
mc.adicionarAcao("Listar Animais vs. Donos", "listarTudo");
mc.adicionarAcao("Sobre", "sobre");
mc.adicionarAcao("Sair", "sair");
System.out.println(mc.getTexto());
Integer op = Console.lerInteger("Qual a sua opção:");
mc.executarAcao(op);
}
}
public void sobre() throws IOException {
String txtSobre = FileUtils.readFileToString(new File("sobre.txt"));
JOptionPane.showMessageDialog(null, txtSobre);
}
public void listarTudo() {
Console.cabecalho("Listando Animais vs. Donos");
for (Dono dono : BancoDados.getInstance().getListaDono()) {
logger.debug(dono);
}
}
public void cadastrarDono() throws Exception {
Console.cabecalho("Cadastro de Dono");
// dados do dono pra leitura via teclado
Integer codigo;
String nome;
String cpf;
String telefoneResidencial;
String telefoneCelular;
String email;
Date dataNascimento;
boolean cadastroOK = true;
do {
codigo = Console.lerInteger("Código");
nome = Console.lerString("Nome");
// formatando nome do animal
nome = StringUtils.capitalize(nome);
cpf = Console.lerString("CPF");
telefoneResidencial = Console.lerString("Tel. Residencial");
telefoneCelular = Console.lerString("Tel. Celular");
email = Console.lerString("Email");
String dataNascimentoTexto = Console.lerString("Data de Nascimento (ex. 31/12/2015)");
dataNascimento = new SimpleDateFormat("dd/MM/yyyy").parse(dataNascimentoTexto);
} while (!cadastroOK);
Dono dono = new Dono();
dono.setCodigo(codigo);
dono.setNome(nome);
dono.setCpf(cpf);
dono.setEmail(email);
dono.setTelefoneCelular(telefoneCelular);
dono.setTelefoneResidencial(telefoneResidencial);
dono.setDataNascimento(dataNascimento);
DonoRN rn = new DonoRN();
try {
rn.salvar(dono);
logger.debug("Dono cadastrado com sucesso!");
} catch (Exception e) {
logger.error("Problema no cadastramento", e);
}
}
public void cadastrarAnimal() throws Exception {
Console.cabecalho("Cadastro de Animal");
// dados do dono pra leitura via teclado
Integer codigo;
String nome;
Date dataNascimento;
String txtTipo;
TipoAnimal tipoAnimal;
String descricao;
String txtCor;
CorPredominante corPredominante;
Dono dono;
boolean cadastroOK = true;
do {
codigo = Console.lerInteger("Código");
nome = Console.lerString("Nome");
// formatando nome do animal
nome = StringUtils.capitalize(nome);
String dataNascimentoTexto = Console.lerString("Data de Nascimento (ex. 31/12/2015)");
dataNascimento = new SimpleDateFormat("dd/MM/yyyy").parse(dataNascimentoTexto);
txtTipo = Console.lerEnum("Tipo", TipoAnimal.class);
tipoAnimal = TipoAnimal.valueOf(txtTipo);
descricao = Console.lerString("Descrição");
txtCor = Console.lerEnum("Cor", CorPredominante.class);
corPredominante = CorPredominante.valueOf(txtCor);
Console.mensagem("Listagem de Donos");
HashMap<Integer, Dono> hm = new HashMap<>();
int o = 1;
for (Dono d : BancoDados.getInstance().getListaDono()) {
Console.mensagem(o + "-" + d.getNome());
hm.put(o, d);
o++;
}
int opcao = Console.lerInteger("Qual a sua opção?");
dono = hm.get(opcao);
Animal a = new Animal();
a.setCodigo(codigo);
a.setNome(nome);
a.setDataNascimento(dataNascimento);
a.setDescricao(descricao);
a.setCorPredominante(corPredominante);
a.setTipoAnimal(tipoAnimal);
// vinculando animal ao dono
dono.getAnimais().add(a);
AnimalRN rn = new AnimalRN();
try {
rn.salvar(a);
logger.debug("Animal cadastrado e vinculado ao seu Dono com sucesso!");
} catch (Exception e) {
logger.error("Problema no cadastramento", e);
}
} while (!cadastroOK);
}
public void sair() {
System.exit(0);
}
}
|
package com.timepath.io;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class BitBuffer {
private static final Logger LOG = Logger.getLogger(BitBuffer.class.getName());
/** Total number of bits */
private final int capacityBits;
/** The source of data */
private final ByteBuffer source;
/** Internal field holding the current byte in the source buffer */
private short b;
/** Position in bits */
private int position;
/** Stores bit access offset */
private int positionBit;
/** Internal field holding the remaining bits in the current byte */
private int remainingBits;
public BitBuffer(ByteBuffer bytes) {
source = bytes;
capacityBits = source.capacity() * 8;
}
public int capacity() { return capacityBits / 8; }
public void get(byte[] dst) { get(dst, 0, dst.length); }
public void get(byte[] dst, int offset, int length) {
for(int i = offset; i < ( offset + length ); i++) { dst[i] = getByte(); }
}
/** Loads source data into internal byte. */
protected void nextByte() {
b = (short) ( source.get() & 0xFF );
remainingBits = 8;
}
public long getBits(int n) {
long data = 0;
for(int i = 0; i < n; i++) {
if(remainingBits == 0) nextByte();
remainingBits
int m = 1 << ( positionBit++ % 8 );
if(( b & m ) != 0) {
data |= 1 << i;
}
}
position += n;
return data;
}
public boolean getBoolean() { return getBits(1) != 0; }
public byte getByte() { return (byte) getBits(8); }
public short getShort() { return (short) getBits(16); }
public int getInt() { return (int) getBits(32); }
public float getFloat() { return Float.intBitsToFloat(getInt()); }
public long getLong() { return getBits(64); }
public double getDouble() { return Double.longBitsToDouble(getLong()); }
public String getString(int limit) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for(byte c; ( c = getByte() ) != 0; ) baos.write(c);
if(limit > 0) get(new byte[limit - baos.size()]);
return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(baos.toByteArray())).toString();
}
public String getString() { return getString(0); }
/** @return true if more than 1 byte is available */
public boolean hasRemaining() { return remaining() > 0; }
/** @return the number of remaining bytes */
public int remaining() { return remainingBits() / 8; }
/** @return the number of remaining bits */
public int remainingBits() { return capacityBits - position; }
/** @return true if more than 1 bit is available */
public boolean hasRemainingBits() { return remainingBits() > 0; }
/** @return the limit in bytes */
public int limit() { return capacityBits / 8; }
/** Does nothing. */
public void order(ByteOrder bo) { }
/**
* Sets the position.
*
* @param newPosition
* the new position
*/
public void position(int newPosition) { position(newPosition, 0); }
/**
* Sets the position.
*
* @param newPosition
* the byte offset
* @param bits
* the bit offset
*/
public void position(int newPosition, int bits) {
source.position(newPosition);
position = newPosition * 8;
positionBit = bits;
remainingBits = 8 - bits;
}
/** @return the position in bytes */
public int position() { return positionBits() / 8; }
/** @return the position in bits */
public int positionBits() { return position; }
}
|
package com.tomgibara.perfect;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import com.tomgibara.bits.BitStore;
import com.tomgibara.bits.BitStore.BitMatches;
import com.tomgibara.bits.BitStore.Positions;
import com.tomgibara.bits.BitVector;
import com.tomgibara.bits.Operation;
import com.tomgibara.hashing.HashCode;
import com.tomgibara.hashing.HashSize;
import com.tomgibara.hashing.Hasher;
import com.tomgibara.hashing.Hashing;
import com.tomgibara.storage.Storage;
import com.tomgibara.storage.Store;
import com.tomgibara.storage.StoreType;
import com.tomgibara.streams.StreamSerializer;
// BMZ implementation based on:
final class BMZ<E> {
// statics
private static final Storage<Long> storage = StoreType.of(long.class).settingNullToDefault().storage();
// static helper methods
private static int a(long ab) {
return (int) (ab >> 32);
}
private static int b(long ab) {
return (int) ab;
}
private static long ab(int a, int b) {
return (long) a << 32 | 0xffffffffL & b;
}
// fields
private final Random random;
private final Hasher<E> hasher;
private final int maxTries;
private final double c;
// constructors
BMZ(Hasher<E> hasher, int maxTries, double c, Random random) {
this.hasher = hasher;
this.maxTries = maxTries;
this.c = c;
this.random = random;
}
Hasher<E> create(Collection<? extends E> elements) {
long max = (long) Math.ceil(c * elements.size());
if (max > Integer.MAX_VALUE) throw new IllegalArgumentException("elements too large");
int[] g = new int[(int) max];
for (int tries = 0; tries < maxTries; tries++) {
int seed1 = random.nextInt();
int seed2 = random.nextInt();
BMZHasher<E> bmz = new BMZHasher<E>(hasher, seed1, seed2, g, elements.size());
Graph graph = bmz.computeGraph(elements);
if (graph == null) continue; // duplicate edge detected
boolean assigned = graph.newAssigner(g).assignIntegersToVertices();
if (!assigned) continue; // failed to assign to critical vertices
return bmz;
}
throw new PerfectionException("failed to find minimal hash");
}
// inner classes
private static class BMZHasher<E> implements Hasher<E> {
private static final StreamSerializer<Integer> ser = (i, w) -> w.writeInt(i);
private final Hasher<E> hasher;
private final int seed1;
private final int seed2;
private final int[] g;
private final HashSize size;
private final Hasher<Integer> hasher1;
private final Hasher<Integer> hasher2;
BMZHasher(Hasher<E> hasher, int seed1, int seed2, int[] g, int size) {
this.hasher = hasher;
this.seed1 = seed1;
this.seed2 = seed2;
this.g = g;
this.size = HashSize.fromInt(size);
HashSize vertices = HashSize.fromInt(g.length);
hasher1 = Hashing.murmur3Int(seed1).hasher(ser).sized(vertices);
hasher2 = Hashing.murmur3Int(seed2).hasher(ser).sized(vertices);
}
public HashSize getSize() {
return size;
}
public HashCode hash(E e) throws IllegalArgumentException {
long ab = computeEdge(e);
int hash = g[a(ab)] + g[b(ab)];
return HashCode.fromInt(hash);
}
// returns null if the graph cannot be computed
Graph computeGraph(Collection<? extends E> elements) {
Graph graph = new Graph(g.length, elements.size());
int index = 0;
for (E element : elements) {
if (!graph.setEdge(index++, computeEdge(element))) return null;
}
return graph;
}
private long computeEdge(E e) {
int n = g.length;
int hc = hasher.intHashValue(e);
int h1 = hasher1.intHashValue(hc);
int h2 = hasher2.intHashValue(hc);
// this is necessary to avoid loops in the graph
if (h1 == h2) h2 = (h2 == n - 1) ? 0 : h2 + 1;
return ab(h1, h2);
}
}
private static final class Graph {
// the number of vertices
final int n;
// the number of edges
final int m;
// the two vertices are packed into a long
final Store<Long> edges;
// indexed by vertex, holds list of vertices that vertex is connected to
//TODO want storage based lists for efficient primitive storage
final List<Integer>[] adjacencyList;
Graph(int n, int m) {
assert(m <= n);
this.n = n;
this.m = m;
edges = storage.newStore(m);
adjacencyList = new List[n];
}
// true if the edge was added, false if it was a duplicate
boolean setEdge(int index, long e) {
int a = a(e);
int b = b(e);
if (getAdjacencyList(a).contains(b)) return false;
edges.set(index, e);
getAdjacencyList(a).add(b);
getAdjacencyList(b).add(a);
return true;
}
Assigner newAssigner(int[] g) {
// int max = 0;
// for (int i = 0; i < n; i++) {
// List<Integer> list = adjacencyList[i];
// int len = list == null ? 0 : list.size();
// if (len > max) max = len;
// System.out.println(n + " -> " + max);
return new Assigner(g);
}
// private utility methods
private List<Integer> getAdjacencyList(int forVertex) {
List<Integer> ret = adjacencyList[forVertex];
return ret == null ? (adjacencyList[forVertex] = new LinkedList<Integer>()) : ret;
}
// inner inner classes
private class Assigner {
// values assigned to each of the edges (has length m)
private final int[] g;
// those nodes that can't be linearized
//(ie. have degree greater than 2 or are in cycles)
private final BitVector criticalNodes;
// records the edges that have been assigned a value
private final BitVector assignedEdges;
Assigner(int[] g) {
this.g = g;
assert(g.length == n);
assignedEdges = new BitVector(m);
criticalNodes = findCriticalNodes();
}
boolean assignIntegersToVertices() {
if (!assignIntegersToCriticalVertices()) return false;
assignIntegersToNonCriticalVertices();
return true;
}
private BitVector findCriticalNodes() {
// calculate node degrees...
int[] degrees = new int[n];
for (Long edge : edges.asList()) {
degrees[a(edge)] ++;
degrees[b(edge)] ++;
}
// ...and trim the chains...
List<Integer> degreeOne = new LinkedList<Integer>();
for (int i = 0; i < n; ++i) {
if (degrees[i] == 1) degreeOne.add(i);
}
while (!degreeOne.isEmpty()) {
int v = degreeOne.remove(0);
degrees[v]
for (int adjacent : adjacencyList[v]) {
if (--degrees[adjacent] == 1) degreeOne.add(adjacent);
}
}
// ...and return a bitmap of critical vertices
BitVector ret = new BitVector(n);
for (int i = 0; i < n; ++i) if (degrees[i] > 1) ret.setBit(i, true);
return ret;
}
/** @returns false if we couldn't assign the integers */
private boolean assignIntegersToCriticalVertices() {
int x = 0;
List<Integer> toProcess = new LinkedList<Integer>();
BitVector assignedNodes = new BitVector(g.length);
while (!assignedNodes.equals(criticalNodes)) {
BitStore unprocessed = Operation.AND.stores(criticalNodes, assignedNodes.flipped());
toProcess.add(unprocessed.ones().first()); // start at the lowest unassigned critical vertex
// assign another "tree" of vertices - not all critical ones are necessarily connected!
x = processCriticalNodes(toProcess, x, assignedNodes);
if(x < 0) return false; // x is overloaded as a failure signal
}
return true;
}
/** process a single "tree" of connected critical nodes, rooted at the vertex in toProcess */
private int processCriticalNodes(List<Integer> toProcess, int x, BitVector assignedNodes) {
while(!toProcess.isEmpty()) {
int v = toProcess.remove(0);
if(v < 0 || assignedNodes.getBit(v)) continue; // there are no critical nodes || already done this vertex
if(adjacencyList[v] != null) {
x = getXThatSatifies(adjacencyList[v], x, assignedNodes);
for (int adjacent : adjacencyList[v]) {
if(!assignedNodes.getBit(adjacent) && criticalNodes.getBit(adjacent) && v!= adjacent) {
// give this one an integer, & note we shouldn't have loops - except if there is one key
toProcess.add(adjacent);
}
if(assignedNodes.getBit(adjacent)) {
int edgeXtoAdjacent = x + g[adjacent]; // if x is ok, then this edge is now taken
if(edgeXtoAdjacent >= edges.size()) return -1; // this edge is too big! we're only assigning between 0 & m-1
assignedEdges.setBit(edgeXtoAdjacent, true);
}
}
}
g[v] = x; assignedNodes.setBit(v, true); // assign candidate x to g
++x; // next v needs a new candidate x
}
return x; // will use this as a candidate for other "trees" of critical vertices
}
private void assignIntegersToNonCriticalVertices() {
List<Integer> toProcess = new LinkedList<Integer>( criticalNodes.ones().asSet() );
BitVector visited = criticalNodes.clone();
processNonCriticalNodes(toProcess, visited); // process the critical nodes
// we've done everything reachable from the critical nodes - but
// what about isolated chains?
for (Positions positions = visited.zeros().positions(); positions.hasNext(); ) {
toProcess.add(positions.nextPosition());
processNonCriticalNodes(toProcess, visited);
}
}
/** process everything in the list and all vertices reachable from it */
private void processNonCriticalNodes(List<Integer> toProcess, BitVector visited) {
BitMatches zeros = assignedEdges.zeros();
int nextEdge = zeros.first();
while(!toProcess.isEmpty()) {
int v = toProcess.remove(0);
if(v < 0) continue; // there are no critical nodes
if(adjacencyList[v] != null) {
for(int adjacent : adjacencyList[v]) {
if(!visited.getBit(adjacent) && v != adjacent) { // shouldn't have loops - only if one key
// we must give it a value
g[adjacent] = nextEdge - g[v]; // i.e. g[v] + g[a] = edge as needed
toProcess.add(adjacent);
assignedEdges.setBit(nextEdge, true);
nextEdge = zeros.next(nextEdge + 1);
}
}
}
visited.setBit(v, true);
}
}
private int getXThatSatifies(List<Integer> adjacencyList, int x, BitVector assignedNodes) {
for(int adjacent : adjacencyList) {
if (assignedNodes.getBit(adjacent) /*only covers critical nodes*/) {
int index = g[adjacent] + x;
if (index >= 0 && index < assignedEdges.size() && assignedEdges.getBit(index)) {
// if we assign x to v, then the edge between v & and 'adjacent' will
// be a duplicate - so our hash code won't be perfect! Try again with a new x:
return getXThatSatifies(adjacencyList, x + 1, assignedNodes);
}
}
}
return x; // this one satisfies all edges
}
}
}
}
|
package cyoastudio.gui;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.controlsfx.dialog.ExceptionDialog;
import org.slf4j.*;
import org.zeroturnaround.zip.ZipUtil;
import cyoastudio.data.*;
import cyoastudio.io.ProjectSerializer;
import cyoastudio.templating.*;
import javafx.beans.value.*;
import javafx.collections.FXCollections;
import javafx.event.EventHandler;
import javafx.fxml.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ListView.EditEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import javafx.stage.*;
import javafx.stage.FileChooser.ExtensionFilter;
public class MainWindow extends BorderPane {
final Logger logger = LoggerFactory.getLogger(MainWindow.class);
@FXML
private BorderPane contentPane;
@FXML
private ListView<String> sectionList;
@FXML
private ListView<String> optionList;
@FXML
private TabPane tabPane;
@FXML
private Tab previewTab;
@FXML
private WebView preview;
@FXML
private TextField projectTitleBox;
@FXML
private Tab styleTab;
private Stage stage;
private Project project = new Project();
private Path saveLocation;
private static boolean dirty = false;
private Section selectedSection;
private Option selectedOption;
private StyleEditor editor;
// TODO remove this hack and make dirty not global
public static void touch() {
dirty = true;
}
public MainWindow(Stage stage) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainWindow.fxml"));
loader.setController(this);
loader.setRoot(this);
try {
loader.load();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.stage = stage;
stage.setTitle("CYOA Studio");
Scene scene = new Scene(this, 800, 600);
stage.setScene(scene);
stage.show();
stage.setOnCloseRequest(event -> {
exitProgram();
event.consume();
});
}
@FXML
void initialize() {
sectionList.setCellFactory(v -> EditCell.createStringEditCell());
sectionList.setOnEditCommit(new EventHandler<ListView.EditEvent<String>>() {
@Override
public void handle(EditEvent<String> event) {
project.getSections().get(event.getIndex()).setTitle(event.getNewValue());
refreshSectionList();
sectionList.getSelectionModel().select(event.getIndex());
}
});
sectionList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (newValue != null) {
editSection();
}
}
});
optionList.setCellFactory(v -> EditCell.createStringEditCell());
optionList.setOnEditCommit(new EventHandler<ListView.EditEvent<String>>() {
@Override
public void handle(EditEvent<String> event) {
selectedSection.getOptions().get(event.getIndex()).setTitle(event.getNewValue());
refreshOptionList();
optionList.getSelectionModel().select(event.getIndex());
}
});
optionList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (newValue != null) {
editOption();
}
}
});
tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {
@Override
public void changed(ObservableValue<? extends Tab> observable, Tab oldValue, Tab newValue) {
if (newValue == previewTab) {
updatePreview();
}
}
});
projectTitleBox.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (!newValue.equals(project.getTitle())) {
touch();
project.setTitle(newValue);
}
}
});
editor = new StyleEditor();
styleTab.setContent(editor);
cleanUp();
}
private void editSection() {
int selectedIndex = sectionList.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0)
selectedSection = project.getSections().get(selectedIndex);
else
selectedSection = null;
refreshOptionList();
SectionEditor editor = new SectionEditor(selectedSection);
contentPane.setCenter(editor);
optionList.getSelectionModel().clearSelection();
}
private void editOption() {
int selectedIndex = optionList.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0)
selectedOption = selectedSection.getOptions().get(selectedIndex);
else
selectedOption = null;
OptionEditor editor = new OptionEditor(selectedOption, selectedSection);
contentPane.setCenter(editor);
sectionList.getSelectionModel().clearSelection();
}
@FXML
void exitProgram() {
if (!isUserSure("Exit")) {
return;
}
stage.close();
}
private boolean isUserSure(String action) {
if (!dirty) {
return true;
}
ButtonType continu = new ButtonType(action);
ButtonType saveFirst = new ButtonType("Save");
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Are you sure?");
alert.setHeaderText("Are you sure?");
alert.setContentText("There may be unsaved changed. Are you sure you want to continue?");
centerDialog(alert);
alert.getButtonTypes().setAll(continu, saveFirst, ButtonType.CANCEL);
Optional<ButtonType> result = alert.showAndWait();
if (!result.isPresent()) {
return false;
} else if (result.get() == ButtonType.CANCEL) {
return false;
} else if (result.get() == continu) {
return true;
} else if (result.get() == saveFirst) {
return saveProject();
} else {
return false;
}
}
@FXML
void exportImage() {
// TODO
}
@FXML
void exportHTML() {
// TODO
}
@FXML
void exportText() {
// TODO
}
@FXML
void newProject() {
if (!isUserSure("New project")) {
return;
}
project = new Project();
cleanUp();
saveLocation = null;
}
private void cleanUp() {
refreshSectionList();
updateStyleEditor();
updatePreview();
dirty = false;
selectedOption = null;
selectedSection = null;
projectTitleBox.setText(project.getTitle());
}
@FXML
void openProject() {
if (!isUserSure("Open project")) {
return;
}
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open project");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("CYOA Studio Project", "*.cyoa"),
new ExtensionFilter("All files", "*"));
File selected = fileChooser.showOpenDialog(stage);
if (selected != null) {
try {
project = ProjectSerializer.readFromZip(selected.toPath());
saveLocation = selected.toPath();
cleanUp();
} catch (IOException e) {
showError("Couldn't open file", e);
}
}
}
@FXML
boolean saveProject() {
if (saveLocation == null) {
selectSaveLocation();
}
if (saveLocation != null) {
save();
return true;
} else {
return false;
}
}
@FXML
void saveProjectAs() {
if (selectSaveLocation()) {
save();
}
}
private void save() {
assert saveLocation != null;
try {
Files.deleteIfExists(saveLocation);
Files.createFile(saveLocation);
ProjectSerializer.writeToZip(project, saveLocation);
dirty = false;
} catch (IOException e) {
saveLocation = null;
showError("Error while saving.", e);
}
}
private boolean selectSaveLocation() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("CYOA Studio Project", "*.cyoa"),
new ExtensionFilter("All files", "*"));
File selected = fileChooser.showSaveDialog(stage);
if (selected == null) {
return false;
} else {
saveLocation = selected.toPath();
return true;
}
}
@FXML
void newSection() {
touch();
project.getSections().add(new Section());
refreshSectionList();
// Make the new entry editable
sectionList.layout();
int i = sectionList.getItems().size() - 1;
sectionList.scrollTo(i);
sectionList.getSelectionModel().select(i);
sectionList.edit(i);
}
private void refreshSectionList() {
sectionList.setItems(FXCollections.observableList(
project.getSections().stream()
.map(x -> x.getTitle())
.collect(Collectors.toList())));
}
@FXML
void deleteSection() {
Alert a = new Alert(AlertType.CONFIRMATION);
a.getButtonTypes().setAll(ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
a.setTitle("Are you sure?");
a.setHeaderText("Are you sure?");
a.setContentText("Are you sure you want to delete this section?");
centerDialog(a);
Optional<ButtonType> result = a.showAndWait();
if (result.get() != ButtonType.YES)
return;
touch();
int i = sectionList.getSelectionModel().getSelectedIndex();
if (i >= 0) {
project.getSections().remove(i);
refreshSectionList();
if (i < sectionList.getItems().size()) {
sectionList.getSelectionModel().select(i);
} else if (i - 1 >= 0 && i - 1 < sectionList.getItems().size()) {
sectionList.getSelectionModel().select(i - 1);
}
}
}
@FXML
void newOption() {
touch();
if (selectedSection != null) {
selectedSection.getOptions().add(new Option());
refreshOptionList();
// Make the new entry editable
optionList.layout();
int i = optionList.getItems().size() - 1;
optionList.scrollTo(i);
optionList.getSelectionModel().select(i);
optionList.edit(i);
}
}
private void refreshOptionList() {
Section cur = selectedSection;
if (cur == null) {
optionList.setItems(FXCollections.emptyObservableList());
} else {
optionList.setItems(FXCollections.observableList(
cur.getOptions().stream()
.map(x -> x.getTitle())
.collect(Collectors.toList())));
}
}
@FXML
void deleteOption() {
Alert a = new Alert(AlertType.CONFIRMATION);
a.getButtonTypes().setAll(ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
a.setTitle("Are you sure?");
a.setHeaderText("Are you sure?");
a.setContentText("Are you sure you want to delete this option?");
centerDialog(a);
Optional<ButtonType> result = a.showAndWait();
if (result.get() != ButtonType.YES)
return;
touch();
if (selectedSection != null) {
int i = optionList.getSelectionModel().getSelectedIndex();
if (i >= 0) {
selectedSection.getOptions().remove(i);
refreshOptionList();
if (i < optionList.getItems().size()) {
optionList.getSelectionModel().select(i);
} else if (i - 1 >= 0 && i - 1 < optionList.getItems().size()) {
optionList.getSelectionModel().select(i - 1);
}
}
}
}
private void updatePreview() {
String website = project.getTemplate().render(project);
preview.getEngine().loadContent(website);
saveTemp(website);
}
public static void saveTemp(String website) {
// TODO remove
try {
File tempFile = File.createTempFile("rendered_site", ".html");
FileUtils.writeStringToFile(tempFile, website, Charset.forName("UTF-8"));
System.out.println(tempFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
private void updateStyleEditor() {
editor.editStyle(project.getStyle(), project.getTemplate());
}
private void showError(String message, IOException ex) {
logger.error(message, ex);
ExceptionDialog exceptionDialog = new ExceptionDialog(ex);
centerDialog(exceptionDialog);
exceptionDialog.show();
}
@FXML
void templateFromFile() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Import template");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("CYOA Studio Project", "*.cyoatemplate"),
new ExtensionFilter("All files", "*"));
File selected = fileChooser.showOpenDialog(stage);
if (selected != null) {
try {
Path tempDirectory = Files.createTempDirectory(null);
ZipUtil.unpack(selected, tempDirectory.toFile());
loadTemplate(tempDirectory);
FileUtils.deleteDirectory(tempDirectory.toFile());
} catch (IOException e) {
showError("Could not load template", e);
}
}
}
@FXML
void templateFromFolder() {
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle("Import template");
File selected = directoryChooser.showDialog(stage);
if (selected != null) {
try {
loadTemplate(selected.toPath());
} catch (IOException e) {
showError("Could not load template", e);
}
}
}
private void loadTemplate(Path path) throws IOException {
FileInputStream stream = new FileInputStream(path.resolve("page.html.mustache").toFile());
Template template = new Template(stream);
stream.close();
project.changeTemplate(template,
Style.parseStyleDefinition(path.resolve("style_options.json")));
updatePreview();
updateStyleEditor();
}
private void centerDialog(Dialog<?> dialog) {
double stageCenterX = stage.getX() + stage.getWidth() / 2;
double stageCenterY = stage.getY() + stage.getHeight() / 2;
dialog.widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
dialog.setX(stageCenterX - dialog.getWidth() / 2);
}
});
dialog.heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
dialog.setY(stageCenterY - dialog.getHeight() / 2);
}
});
}
}
|
package net.imagej;
import io.scif.config.SCIFIOConfig;
import java.io.IOException;
import java.util.List;
import net.imagej.display.ImageDisplay;
import net.imglib2.img.ImgFactory;
import net.imglib2.meta.AxisType;
import net.imglib2.meta.ImgPlus;
import net.imglib2.type.NativeType;
import net.imglib2.type.numeric.RealType;
import org.scijava.object.ObjectService;
/**
* Interface for service that works with {@link Dataset}s.
*
* @author Curtis Rueden
* @author Mark Hiner
*/
public interface DatasetService extends ImageJService {
ObjectService getObjectService();
/**
* Gets a list of all {@link Dataset}s. This method is a shortcut that
* delegates to {@link ObjectService}.
*/
List<Dataset> getDatasets();
/**
* Gets a list of {@link Dataset}s linked to the given {@link ImageDisplay}.
*/
List<Dataset> getDatasets(ImageDisplay display);
Dataset create(long[] dims, String name, AxisType[] axes, int bitsPerPixel,
boolean signed, boolean floating);
Dataset create(long[] dims, String name, AxisType[] axes, int bitsPerPixel,
boolean signed, boolean floating, boolean virtual);
/**
* Creates a new dataset.
*
* @param <T> The type of the dataset.
* @param type The type of the dataset.
* @param dims The dataset's dimensional extents.
* @param name The dataset's name.
* @param axes The dataset's dimensional axis labels.
* @return The newly created dataset.
*/
<T extends RealType<T> & NativeType<T>> Dataset create(T type, long[] dims,
String name, AxisType[] axes);
/**
* Creates a new dataset.
*
* @param <T> The type of the dataset.
* @param type The type of the dataset.
* @param dims The dataset's dimensional extents.
* @param name The dataset's name.
* @param axes The dataset's dimensional axis labels.
* @param virtual If true make a virtual dataset.
* @return The newly created dataset.
*/
<T extends RealType<T> & NativeType<T>> Dataset create(T type, long[] dims,
String name, AxisType[] axes, boolean virtual);
/**
* Creates a new dataset using the provided {@link ImgFactory}.
*
* @param <T> The type of the dataset.
* @param factory The ImgFactory to use to create the data.
* @param type The type of the dataset.
* @param dims The dataset's dimensional extents.
* @param name The dataset's name.
* @param axes The dataset's dimensional axis labels.
* @return The newly created dataset.
*/
<T extends RealType<T>> Dataset create(
ImgFactory<T> factory, T type, long[] dims, String name, AxisType[] axes);
/**
* Creates a new dataset using the provided {@link ImgPlus}.
*
* @param imgPlus The {@link ImgPlus} backing the dataset.
* @return The newly created dataset.
*/
<T extends RealType<T>> Dataset create(ImgPlus<T> imgPlus);
/**
* Determines whether the given source can be opened as a {@link Dataset}
* using the {@link #open(String)} method.
*/
boolean canOpen(String source);
/**
* Determines whether the given destination can be used to save a
* {@link Dataset} using the {@link #save(Dataset, String)} method.
*/
boolean canSave(String destination);
/** Loads a dataset from a source (such as a file on disk). */
Dataset open(String source) throws IOException;
/** As {@link #open(String)} with the given {@link SCIFIOConfig} */
Dataset open(String source, SCIFIOConfig config) throws IOException;
/** Reverts the given dataset to its original source. */
void revert(Dataset dataset) throws IOException;
/**
* Saves a dataset to a destination (such as a file on disk).
*
* @param dataset The dataset to save.
* @param destination Where the dataset should be saved (e.g., a file path on
* disk).
*/
void save(Dataset dataset, String destination) throws IOException;
/**
* Saves a dataset to a destination (such as a file on disk).
*
* @param dataset The dataset to save.
* @param destination Where the dataset should be saved (e.g., a file path on
* disk).
* @param config The SCIFIO configuration describing how the data should be
* saved.
*/
void save(Dataset dataset, String destination, SCIFIOConfig config)
throws IOException;
}
|
package nl.vpro.poel.domain;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Date;
/**
* A match for users to predict the outcome of. Matches can have limited periods in which they can be predicted.
*/
@Entity
@Data
@EqualsAndHashCode(exclude = "id")
@NoArgsConstructor
public class Match {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false)
private Long id;
@Column(nullable = false)
private String homeTeam;
@Column(nullable = false)
private String awayTeam;
// Both Hibernate 4.x and Freemarker 2.3.x are not ready for use with java.time.* yet, so let's use this old skool type
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date start = null;
@Embedded
private MatchResult matchResult;
public Match(String homeTeam, String awayTeam, Date start) {
this(homeTeam, awayTeam, start, null);
}
public Match(String homeTeam, String awayTeam, Date start, MatchResult matchResult) {
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.start = start;
this.matchResult = matchResult;
}
}
|
package org.jsoup.select;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
import org.jsoup.nodes.Node;
import java.util.*;
/**
A list of {@link Element}s, with methods that act on every element in the list.
<p/>
To get an {@code Elements} object, use the {@link Element#select(String)} method.
@author Jonathan Hedley, jonathan@hedley.net */
public class Elements extends ArrayList<Element> {
public Elements() {
}
public Elements(int initialCapacity) {
super(initialCapacity);
}
public Elements(Collection<Element> elements) {
super(elements);
}
public Elements(List<Element> elements) {
super(elements);
}
public Elements(Element... elements) {
super(Arrays.asList(elements));
}
/**
* Creates a deep copy of these elements.
* @return a deep copy
*/
@Override
public Elements clone() {
Elements clone = new Elements(size());
for(Element e : this)
clone.add(e.clone());
return clone;
}
// attribute methods
/**
Get an attribute value from the first matched element that has the attribute.
@param attributeKey The attribute key.
@return The attribute value from the first matched element that has the attribute.. If no elements were matched (isEmpty() == true),
or if the no elements have the attribute, returns empty string.
@see #hasAttr(String)
*/
public String attr(String attributeKey) {
for (Element element : this) {
if (element.hasAttr(attributeKey))
return element.attr(attributeKey);
}
return "";
}
/**
Checks if any of the matched elements have this attribute set.
@param attributeKey attribute key
@return true if any of the elements have the attribute; false if none do.
*/
public boolean hasAttr(String attributeKey) {
for (Element element : this) {
if (element.hasAttr(attributeKey))
return true;
}
return false;
}
/**
* Set an attribute on all matched elements.
* @param attributeKey attribute key
* @param attributeValue attribute value
* @return this
*/
public Elements attr(String attributeKey, String attributeValue) {
for (Element element : this) {
element.attr(attributeKey, attributeValue);
}
return this;
}
/**
* Remove an attribute from every matched element.
* @param attributeKey The attribute to remove.
* @return this (for chaining)
*/
public Elements removeAttr(String attributeKey) {
for (Element element : this) {
element.removeAttr(attributeKey);
}
return this;
}
/**
Add the class name to every matched element's {@code class} attribute.
@param className class name to add
@return this
*/
public Elements addClass(String className) {
for (Element element : this) {
element.addClass(className);
}
return this;
}
/**
Remove the class name from every matched element's {@code class} attribute, if present.
@param className class name to remove
@return this
*/
public Elements removeClass(String className) {
for (Element element : this) {
element.removeClass(className);
}
return this;
}
/**
Toggle the class name on every matched element's {@code class} attribute.
@param className class name to add if missing, or remove if present, from every element.
@return this
*/
public Elements toggleClass(String className) {
for (Element element : this) {
element.toggleClass(className);
}
return this;
}
/**
Determine if any of the matched elements have this class name set in their {@code class} attribute.
@param className class name to check for
@return true if any do, false if none do
*/
public boolean hasClass(String className) {
for (Element element : this) {
if (element.hasClass(className))
return true;
}
return false;
}
/**
* Get the form element's value of the first matched element.
* @return The form element's value, or empty if not set.
* @see Element#val()
*/
public String val() {
if (size() > 0)
return first().val();
else
return "";
}
/**
* Set the form element's value in each of the matched elements.
* @param value The value to set into each matched element
* @return this (for chaining)
*/
public Elements val(String value) {
for (Element element : this)
element.val(value);
return this;
}
/**
* Get the combined text of all the matched elements.
* <p>
* Note that it is possible to get repeats if the matched elements contain both parent elements and their own
* children, as the Element.text() method returns the combined text of a parent and all its children.
* @return string of all text: unescaped and no HTML.
* @see Element#text()
*/
public String text() {
StringBuilder sb = new StringBuilder();
for (Element element : this) {
if (sb.length() != 0)
sb.append(" ");
sb.append(element.text());
}
return sb.toString();
}
public boolean hasText() {
for (Element element: this) {
if (element.hasText())
return true;
}
return false;
}
/**
* Get the combined inner HTML of all matched elements.
* @return string of all element's inner HTML.
* @see #text()
* @see #outerHtml()
*/
public String html() {
StringBuilder sb = new StringBuilder();
for (Element element : this) {
if (sb.length() != 0)
sb.append("\n");
sb.append(element.html());
}
return sb.toString();
}
/**
* Get the combined outer HTML of all matched elements.
* @return string of all element's outer HTML.
* @see #text()
* @see #html()
*/
public String outerHtml() {
StringBuilder sb = new StringBuilder();
for (Element element : this) {
if (sb.length() != 0)
sb.append("\n");
sb.append(element.outerHtml());
}
return sb.toString();
}
/**
* Get the combined outer HTML of all matched elements. Alias of {@link #outerHtml()}.
* @return string of all element's outer HTML.
* @see #text()
* @see #html()
*/
@Override
public String toString() {
return outerHtml();
}
/**
* Update the tag name of each matched element. For example, to change each {@code <i>} to a {@code <em>}, do
* {@code doc.select("i").tagName("em");}
* @param tagName the new tag name
* @return this, for chaining
* @see Element#tagName(String)
*/
public Elements tagName(String tagName) {
for (Element element : this) {
element.tagName(tagName);
}
return this;
}
/**
* Set the inner HTML of each matched element.
* @param html HTML to parse and set into each matched element.
* @return this, for chaining
* @see Element#html(String)
*/
public Elements html(String html) {
for (Element element : this) {
element.html(html);
}
return this;
}
/**
* Add the supplied HTML to the start of each matched element's inner HTML.
* @param html HTML to add inside each element, before the existing HTML
* @return this, for chaining
* @see Element#prepend(String)
*/
public Elements prepend(String html) {
for (Element element : this) {
element.prepend(html);
}
return this;
}
/**
* Add the supplied HTML to the end of each matched element's inner HTML.
* @param html HTML to add inside each element, after the existing HTML
* @return this, for chaining
* @see Element#append(String)
*/
public Elements append(String html) {
for (Element element : this) {
element.append(html);
}
return this;
}
/**
* Insert the supplied HTML before each matched element's outer HTML.
* @param html HTML to insert before each element
* @return this, for chaining
* @see Element#before(String)
*/
public Elements before(String html) {
for (Element element : this) {
element.before(html);
}
return this;
}
/**
* Insert the supplied HTML after each matched element's outer HTML.
* @param html HTML to insert after each element
* @return this, for chaining
* @see Element#after(String)
*/
public Elements after(String html) {
for (Element element : this) {
element.after(html);
}
return this;
}
/**
Wrap the supplied HTML around each matched elements. For example, with HTML
{@code <p><b>This</b> is <b>Jsoup</b></p>},
<code>doc.select("b").wrap("<i></i>");</code>
becomes {@code <p><i><b>This</b></i> is <i><b>jsoup</b></i></p>}
@param html HTML to wrap around each element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
@return this (for chaining)
@see Element#wrap
*/
public Elements wrap(String html) {
Validate.notEmpty(html);
for (Element element : this) {
element.wrap(html);
}
return this;
}
/**
* Removes the matched elements from the DOM, and moves their children up into their parents. This has the effect of
* dropping the elements but keeping their children.
* <p/>
* This is useful for e.g removing unwanted formatting elements but keeping their contents.
* <p/>
* E.g. with HTML: {@code <div><font>One</font> <font><a href="/">Two</a></font></div>}<br/>
* {@code doc.select("font").unwrap();}<br/>
* HTML = {@code <div>One <a href="/">Two</a></div>}
*
* @return this (for chaining)
* @see Node#unwrap
*/
public Elements unwrap() {
for (Element element : this) {
element.unwrap();
}
return this;
}
/**
* Empty (remove all child nodes from) each matched element. This is similar to setting the inner HTML of each
* element to nothing.
* <p>
* E.g. HTML: {@code <div><p>Hello <b>there</b></p> <p>now</p></div>}<br>
* <code>doc.select("p").empty();</code><br>
* HTML = {@code <div><p></p> <p></p></div>}
* @return this, for chaining
* @see Element#empty()
* @see #remove()
*/
public Elements empty() {
for (Element element : this) {
element.empty();
}
return this;
}
/**
* Remove each matched element from the DOM. This is similar to setting the outer HTML of each element to nothing.
* <p>
* E.g. HTML: {@code <div><p>Hello</p> <p>there</p> <img /></div>}<br>
* <code>doc.select("p").remove();</code><br>
* HTML = {@code <div> <img /></div>}
* <p>
* Note that this method should not be used to clean user-submitted HTML; rather, use {@link org.jsoup.safety.Cleaner} to clean HTML.
* @return this, for chaining
* @see Element#empty()
* @see #empty()
*/
public Elements remove() {
for (Element element : this) {
element.remove();
}
return this;
}
// filters
/**
* Find matching elements within this element list.
* @param query A {@link Selector} query
* @return the filtered list of elements, or an empty list if none match.
*/
public Elements select(String query) {
return Selector.select(query, this);
}
/**
* Remove elements from this list that match the {@link Selector} query.
* <p>
* E.g. HTML: {@code <div class=logo>One</div> <div>Two</div>}<br>
* <code>Elements divs = doc.select("div").not("#logo");</code><br>
* Result: {@code divs: [<div>Two</div>]}
* <p>
* @param query the selector query whose results should be removed from these elements
* @return a new elements list that contains only the filtered results
*/
public Elements not(String query) {
Elements out = Selector.select(query, this);
return Selector.filterOut(this, out);
}
/**
* Get the <i>nth</i> matched element as an Elements object.
* <p>
* See also {@link #get(int)} to retrieve an Element.
* @param index the (zero-based) index of the element in the list to retain
* @return Elements containing only the specified element, or, if that element did not exist, an empty list.
*/
public Elements eq(int index) {
return size() > index ? new Elements(get(index)) : new Elements();
}
/**
* Test if any of the matched elements match the supplied query.
* @param query A selector
* @return true if at least one element in the list matches the query.
*/
public boolean is(String query) {
Elements children = select(query);
return !children.isEmpty();
}
/**
* Get all of the parents and ancestor elements of the matched elements.
* @return all of the parents and ancestor elements of the matched elements
*/
public Elements parents() {
HashSet<Element> combo = new LinkedHashSet<Element>();
for (Element e: this) {
combo.addAll(e.parents());
}
return new Elements(combo);
}
// list-like methods
/**
Get the first matched element.
@return The first matched element, or <code>null</code> if contents is empty.
*/
public Element first() {
return isEmpty() ? null : get(0);
}
/**
Get the last matched element.
@return The last matched element, or <code>null</code> if contents is empty.
*/
public Element last() {
return isEmpty() ? null : get(size() - 1);
}
/**
* Perform a depth-first traversal on each of the selected elements.
* @param nodeVisitor the visitor callbacks to perform on each node
* @return this, for chaining
*/
public Elements traverse(NodeVisitor nodeVisitor) {
Validate.notNull(nodeVisitor);
NodeTraversor traversor = new NodeTraversor(nodeVisitor);
for (Element el: this) {
traversor.traverse(el);
}
return this;
}
/**
* Get the {@link FormElement} forms from the selected elements, if any.
* @return a list of {@link FormElement}s pulled from the matched elements. The list will be empty if the elements contain
* no forms.
*/
public List<FormElement> forms() {
ArrayList<FormElement> forms = new ArrayList<FormElement>();
for (Element el: this)
if (el instanceof FormElement)
forms.add((FormElement) el);
return forms;
}
}
|
package org.jtrfp.trcl.tools;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.jtrfp.trcl.coll.BulkRemovable;
import org.jtrfp.trcl.coll.Repopulatable;
import com.ochafik.util.Adapter;
public class Util {
public static final Color [] DEFAULT_PALETTE = new Color []{
new Color(0,0,0,0),
new Color(7,7,7),
new Color(14,14,14),
new Color(22,22,22),
new Color(29,29,29),
new Color(36,36,36),
new Color(43,43,43),
new Color(51,51,51),
new Color(58,58,58),
new Color(65,65,65),
new Color(72,72,72),
new Color(79,79,79),
new Color(87,87,87),
new Color(94,94,94),
new Color(101,101,101),
new Color(108,108,108),
new Color(116,116,116),
new Color(123,123,123),
new Color(130,130,130),
new Color(137,137,137),
new Color(145,145,145),
new Color(152,152,152),
new Color(159,159,159),
new Color(166,166,166),
new Color(173,173,173),
new Color(181,181,181),
new Color(188,188,188),
new Color(195,195,195),
new Color(202,202,202),
new Color(210,210,210),
new Color(217,217,217),
new Color(224,224,224),
new Color(5,5,5),
new Color(10,9,9),
new Color(14,13,13),
new Color(19,18,18),
new Color(24,24,23),
new Color(29,28,26),
new Color(35,33,30),
new Color(40,40,35),
new Color(45,45,38),
new Color(50,51,42),
new Color(55,57,46),
new Color(58,62,49),
new Color(61,68,53),
new Color(64,75,56),
new Color(65,80,59),
new Color(67,88,63),
new Color(73,96,69),
new Color(80,106,75),
new Color(85,114,81),
new Color(90,123,86),
new Color(96,131,92),
new Color(102,141,98),
new Color(108,150,103),
new Color(113,157,110),
new Color(121,163,118),
new Color(130,170,127),
new Color(137,176,135),
new Color(145,182,143),
new Color(152,188,151),
new Color(161,194,161),
new Color(169,200,169),
new Color(173,204,173),
new Color(6,6,6),
new Color(11,10,10),
new Color(16,15,15),
new Color(20,19,19),
new Color(25,24,24),
new Color(31,28,28),
new Color(37,33,32),
new Color(42,37,37),
new Color(47,41,40),
new Color(53,45,44),
new Color(59,50,48),
new Color(65,54,52),
new Color(71,59,56),
new Color(77,62,58),
new Color(83,67,62),
new Color(90,72,65),
new Color(97,77,70),
new Color(107,85,76),
new Color(116,91,81),
new Color(127,99,86),
new Color(138,107,91),
new Color(148,114,95),
new Color(159,121,100),
new Color(167,131,108),
new Color(173,139,116),
new Color(180,149,125),
new Color(187,157,134),
new Color(193,165,142),
new Color(200,174,151),
new Color(206,184,161),
new Color(212,191,169),
new Color(218,199,179),
new Color(3,3,16),
new Color(5,5,28),
new Color(8,8,39),
new Color(10,10,51),
new Color(14,13,60),
new Color(18,17,70),
new Color(23,20,81),
new Color(28,24,91),
new Color(34,29,100),
new Color(39,34,109),
new Color(46,39,118),
new Color(52,44,127),
new Color(60,50,133),
new Color(66,56,141),
new Color(75,62,149),
new Color(83,73,156),
new Color(87,77,164),
new Color(91,80,171),
new Color(97,87,176),
new Color(107,95,180),
new Color(114,103,182),
new Color(122,111,186),
new Color(129,119,188),
new Color(137,128,191),
new Color(144,136,195),
new Color(151,143,198),
new Color(159,152,201),
new Color(167,160,205),
new Color(174,167,208),
new Color(181,175,212),
new Color(187,182,215),
new Color(195,190,219),
new Color(14,0,0),
new Color(27,0,0),
new Color(40,0,1),
new Color(53,0,1),
new Color(66,0,1),
new Color(79,0,1),
new Color(92,0,2),
new Color(105,0,2),
new Color(118,0,2),
new Color(131,0,2),
new Color(144,0,3),
new Color(157,0,3),
new Color(170,0,3),
new Color(183,0,3),
new Color(196,0,4),
new Color(199,15,7),
new Color(203,33,9),
new Color(208,52,11),
new Color(212,70,13),
new Color(216,89,16),
new Color(221,107,18),
new Color(225,126,20),
new Color(229,144,22),
new Color(233,163,24),
new Color(238,181,26),
new Color(242,200,29),
new Color(246,218,31),
new Color(251,237,33),
new Color(255,255,35),
new Color(255,255,108),
new Color(255,255,182),
new Color(255,255,255),
new Color(8,8,32),
new Color(16,16,64),
new Color(24,24,96),
new Color(32,32,128),
new Color(40,40,160),
new Color(48,48,192),
new Color(56,56,224),
new Color(63,63,255),
new Color(8,32,32),
new Color(16,64,64),
new Color(24,96,96),
new Color(32,128,128),
new Color(40,160,160),
new Color(48,192,192),
new Color(56,224,224),
new Color(63,255,255),
new Color(56,15,5),
new Color(70,22,7),
new Color(85,31,10),
new Color(98,41,13),
new Color(111,52,16),
new Color(125,65,20),
new Color(137,78,24),
new Color(149,91,28),
new Color(162,104,33),
new Color(173,118,38),
new Color(183,133,44),
new Color(195,150,50),
new Color(203,165,58),
new Color(204,176,73),
new Color(205,186,90),
new Color(207,194,105),
new Color(2,2,37),
new Color(10,5,44),
new Color(18,9,51),
new Color(26,12,58),
new Color(35,16,65),
new Color(43,19,72),
new Color(51,23,79),
new Color(59,26,86),
new Color(67,29,93),
new Color(75,33,100),
new Color(84,36,107),
new Color(92,40,114),
new Color(100,43,121),
new Color(108,46,128),
new Color(116,50,135),
new Color(124,53,142),
new Color(133,57,148),
new Color(141,60,155),
new Color(149,64,162),
new Color(157,67,169),
new Color(165,70,176),
new Color(173,74,183),
new Color(182,77,190),
new Color(190,81,197),
new Color(198,84,204),
new Color(206,87,211),
new Color(214,91,218),
new Color(222,94,225),
new Color(231,98,232),
new Color(239,101,239),
new Color(247,105,246),
new Color(255,108,253),
new Color(55,14,4),
new Color(81,24,6),
new Color(108,36,7),
new Color(136,51,9),
new Color(162,65,11),
new Color(188,84,13),
new Color(214,105,15),
new Color(241,129,16),
new Color(244,153,43),
new Color(245,174,70),
new Color(247,193,96),
new Color(248,209,123),
new Color(250,221,149),
new Color(252,234,177),
new Color(254,244,203),
new Color(255,253,232),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0),
new Color(0,0,0)
};
public static <T>void repopulate(Collection<T> dest, Collection<T> src){
if(dest instanceof Repopulatable)
((Repopulatable<T>)dest).repopulate(src);
else if(dest instanceof List){
final List<T> dst = (List<T>)dest;
if(dest.size()>src.size()){
Iterator<T> sIt = src.iterator();
ListIterator<T> dIt = dst.listIterator();
while(sIt.hasNext())
{dIt.next();dIt.set(sIt.next());}
dst.subList(src.size(), dst.size()).clear();//Truncate
} else if(dest.size()<src.size()){
Iterator<T> sIt = src.iterator();
ListIterator<T> dIt = dst.listIterator();
while(dIt.hasNext())
{dIt.next();dIt.set(sIt.next());}
final ArrayList<T> additional = new ArrayList<T>();
while(sIt.hasNext())
additional.add(sIt.next());
dest.addAll(additional);
}else {//Same size
Iterator<T> sIt = src.iterator();
ListIterator<T> dIt = dst.listIterator();
while(sIt.hasNext())
{dIt.next();dIt.set(sIt.next());}
}
}else{
dest.clear();
dest.addAll(src);
}
}//end repopulate(...)
public static <U,V> com.ochafik.util.listenable.Adapter<U,V> bidi2Forward(final com.ochafik.util.Adapter<U,V> bidi){
return new com.ochafik.util.listenable.Adapter<U,V>(){
@Override
public V adapt(U value) {
return bidi.adapt(value);
}
};
}//end bidi2Forward(...)
public static <U,V> com.ochafik.util.listenable.Adapter<V,U> bidi2Backward(final com.ochafik.util.Adapter<U,V> bidi){
return new com.ochafik.util.listenable.Adapter<V,U>(){
@Override
public U adapt(V value) {
return bidi.reAdapt(value);
}};
}//end bidi2Backward(...)
public static <U,V> Adapter<V,U> inverse(final Adapter<U,V> adapter){
return new Adapter<V,U>(){
@Override
public U adapt(V value) {
return adapter.reAdapt(value);
}
@Override
public V reAdapt(U value) {
return adapter.adapt(value);
}};
}
/**
* Remove a single instance (or none) of each supplied element in given Collection.
* Not the same as removeAll - only one instance removed.
* @param toRemove
* @since Jan 11, 2016
*/
public static <E> void bulkRemove(Collection<E> toRemove, Collection<E> target){
if(target instanceof BulkRemovable)
((BulkRemovable)target).bulkRemove(toRemove);
else
for(E e:toRemove)
target.remove(e);
}//end bulkRemove(...)
public static double quantize(double value, double interval){
return Math.rint(value / interval)*interval;
}
}//end Util
|
package org.neo4j.rdf.model;
public interface Value
{
}
|
package org.researchgraph.app;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.researchgraph.configuration.Properties;
import org.researchgraph.crosswalk.CrosswalkRG;
import org.researchgraph.graph.Graph;
import org.researchgraph.neo4j.Neo4jDatabase;
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
public class App {
private static CrosswalkRG crosswalkRG;
private static Neo4jDatabase neo4j;
private static Boolean verbose;
private static Boolean profilingEnabled;
public static void main(String[] args) {
try {
//Program arguments
Configuration properties = Properties.fromArgs(args);
String bucket = properties.getString(Properties.PROPERTY_S3_BUCKET);
String prefix = properties.getString(Properties.PROPERTY_S3_PREIFX);
String xmlFolder = properties.getString(Properties.PROPERTY_XML_FOLDER);
String xmlType = properties.getString(Properties.PROPERTY_XML_TYPE);
String source = properties.getString(Properties.PROPERTY_SOURCE);
String crosswalk = properties.getString(Properties.PROPERTY_CROSSWALK);
String versionFolder = properties.getString(Properties.PROPERTY_VERSIONS_FOLDER);
verbose = Boolean.parseBoolean( properties.getString(Properties.PROPERTY_VERBOSE));
profilingEnabled=Boolean.parseBoolean(properties.getString(Properties.PROPERTY_PROFILING));
System.out.println("Verbose: " + verbose.toString());
System.out.println("Profiling enabled: " + profilingEnabled.toString());
if (StringUtils.isEmpty(versionFolder))
System.out.println("Version folder: " + versionFolder);
//Set Neo4j connection
String neo4jFolder = properties.getString(Properties.PROPERTY_NEO4J_FOLDER);
if (StringUtils.isEmpty(neo4jFolder))
throw new IllegalArgumentException("Neo4j Folder can not be empty");
System.out.println("Neo4J: " + neo4jFolder);
neo4j = new Neo4jDatabase(neo4jFolder);
neo4j.setVerbose(verbose);
//Set Crosswalk settings
CrosswalkRG.XmlType type = CrosswalkRG.XmlType.valueOf(xmlType);
crosswalkRG = new CrosswalkRG();
crosswalkRG.setSource(source);
crosswalkRG.setType(type);
crosswalkRG.setVerbose(verbose);
//Set XSLT template
Templates template = null;
if (!StringUtils.isEmpty(crosswalk)) {
System.out.println("XSLT Crosswalk: " + crosswalk);
TransformerFactory transformerFactory = net.sf.saxon.TransformerFactoryImpl.newInstance();
template = transformerFactory.newTemplates(new StreamSource(crosswalk));
}
if (!StringUtils.isEmpty(bucket) && !StringUtils.isEmpty(prefix)) {
System.out.println("S3 Bucket: " + bucket);
System.out.println("S3 Prefix: " + prefix);
processS3Objects(bucket, prefix, template, versionFolder,source, verbose);
} else if (!StringUtils.isEmpty(xmlFolder)) {
System.out.println("XML: " + xmlFolder);
processFiles(xmlFolder, template);
} else
throw new IllegalArgumentException("Please provide either S3 Bucket and prefix OR a path to a XML Folder");
if (!StringUtils.isEmpty(crosswalk)) {
crosswalkRG.printStatistics(System.out);
}
neo4j.printStatistics(System.out);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static void processS3Objects(String bucket, String prefix, Templates template, String versionFolder, String source, Boolean verboseEnabled) throws Exception {
AmazonS3 s3client = new AmazonS3Client(new InstanceProfileCredentialsProvider());
ListObjectsRequest listObjectsRequest;
ObjectListing objectListing;
String file = prefix + "/latest.txt";
S3Object object = s3client.getObject(new GetObjectRequest(bucket, file));
String latest;
try (InputStream txt = object.getObjectContent()) {
latest = IOUtils.toString(txt, StandardCharsets.UTF_8).trim();
}
if (StringUtils.isEmpty(latest))
throw new Exception("Unable to find latest harvest in the S3 Bucket (latest.txt file is empty or not avaliable). Please check if you have access to S3 bucket and did you have completed the harvestring.");
String folder = prefix + "/" + latest + "/";
System.out.println("S3 Repository: " + latest);
listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucket)
.withPrefix(folder);
do {
objectListing = s3client.listObjects(listObjectsRequest);
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
file = objectSummary.getKey();
System.out.println("Processing file: " + file);
object = s3client.getObject(new GetObjectRequest(bucket, file));
InputStream xml = object.getObjectContent();
processFile(template, xml);
}
listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());
Files.write(Paths.get(versionFolder, source), latest.getBytes());
System.out.println(bucket + prefix + " is done.");
}
private static void processFiles(String xmlFolder, Templates template) throws Exception {
File[] files = new File(xmlFolder).listFiles();
for (File file : files)
if (file.isDirectory())
{
processFiles(file.getAbsolutePath(), template);
}else {
if (file.getName().endsWith(".xml") || file.getName().endsWith(".XML")) {
try (InputStream xml = new FileInputStream(file)) {
System.out.println("Processing file: " + file);
processFile(template, xml);
}
}
}
System.out.println(xmlFolder + " is done.");
}
private static void processFile(Templates template, InputStream xml) throws Exception {
Graph graph;
Long markTime = System.currentTimeMillis();
Long minorMarkTime;
Long deltaTime;
if (null != template) {
Source reader = new StreamSource(xml);
StringWriter writer = new StringWriter();
Transformer transformer = template.newTransformer();
minorMarkTime=System.currentTimeMillis(); //Used for performance profiling
transformer.transform(reader, new StreamResult(writer));
if (profilingEnabled) {
deltaTime = System.currentTimeMillis() - minorMarkTime;
System.out.println("transform in milliseconds:" + deltaTime);
}
InputStream stream = new ByteArrayInputStream(writer.toString().getBytes(StandardCharsets.UTF_8));
minorMarkTime=System.currentTimeMillis(); //Used for performance profiling
graph = crosswalkRG.process(stream);
if (profilingEnabled) {
deltaTime = System.currentTimeMillis() - minorMarkTime;
System.out.println("crosswalk.process in milliseconds:" + deltaTime);
}
} else {
minorMarkTime=System.currentTimeMillis(); //Used for performance profiling
graph = crosswalkRG.process(xml);
if (profilingEnabled) {
deltaTime = System.currentTimeMillis() - minorMarkTime;
System.out.println("crosswalk.process in milliseconds:" + deltaTime);
}
}
minorMarkTime=System.currentTimeMillis(); //Used for performance profiling
neo4j.importGraph(graph, profilingEnabled);
if (profilingEnabled) {
deltaTime = System.currentTimeMillis() - minorMarkTime;
System.out.println("neo4j.importGraph in milliseconds:" + deltaTime);
deltaTime = markTime == 0 ? 0 : (System.currentTimeMillis() - markTime);
System.out.println("completed in milliseconds:" + deltaTime);
}
}
}
|
package redis.clients.jedis;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.util.SafeEncoder;
public class Jedis extends BinaryJedis implements JedisCommands {
public Jedis(final String host) {
super(host);
}
public Jedis(final String host, final int port) {
super(host, port);
}
public Jedis(final String host, final int port, final int timeout) {
super(host, port, timeout);
}
public Jedis(JedisShardInfo shardInfo) {
super(shardInfo);
}
public String ping() {
checkIsInMulti();
client.ping();
return client.getStatusCodeReply();
}
/**
* Set the string value as value of the key. The string can't be longer than
* 1073741824 bytes (1 GB).
* <p>
* Time complexity: O(1)
*
* @param key
* @param value
* @return Status code reply
*/
public String set(final String key, String value) {
checkIsInMulti();
client.set(key, value);
return client.getStatusCodeReply();
}
/**
* Get the value of the specified key. If the key does not exist the special
* value 'nil' is returned. If the value stored at key is not a string an
* error is returned because GET can only handle string values.
* <p>
* Time complexity: O(1)
*
* @param key
* @return Bulk reply
*/
public String get(final String key) {
checkIsInMulti();
client.sendCommand(Protocol.Command.GET, key);
return client.getBulkReply();
}
/**
* Ask the server to silently close the connection.
*/
public String quit() {
checkIsInMulti();
client.quit();
return client.getStatusCodeReply();
}
/**
* Test if the specified key exists. The command returns "1" if the key
* exists, otherwise "0" is returned. Note that even keys set with an empty
* string as value will return "1".
*
* Time complexity: O(1)
*
* @param key
* @return Boolean reply, true if the key exists, otherwise false
*/
public Boolean exists(final String key) {
checkIsInMulti();
client.exists(key);
return client.getIntegerReply() == 1;
}
/**
* Remove the specified keys. If a given key does not exist no operation is
* performed for this key. The command returns the number of keys removed.
*
* Time complexity: O(1)
*
* @param keys
* @return Integer reply, specifically: an integer greater than 0 if one or
* more keys were removed 0 if none of the specified key existed
*/
public Long del(final String... keys) {
checkIsInMulti();
client.del(keys);
return client.getIntegerReply();
}
/**
* Return the type of the value stored at key in form of a string. The type
* can be one of "none", "string", "list", "set". "none" is returned if the
* key does not exist.
*
* Time complexity: O(1)
*
* @param key
* @return Status code reply, specifically: "none" if the key does not exist
* "string" if the key contains a String value "list" if the key
* contains a List value "set" if the key contains a Set value
* "zset" if the key contains a Sorted Set value "hash" if the key
* contains a Hash value
*/
public String type(final String key) {
checkIsInMulti();
client.type(key);
return client.getStatusCodeReply();
}
/**
* Delete all the keys of the currently selected DB. This command never
* fails.
*
* @return Status code reply
*/
public String flushDB() {
checkIsInMulti();
client.flushDB();
return client.getStatusCodeReply();
}
/**
* Returns all the keys matching the glob-style pattern as space separated
* strings. For example if you have in the database the keys "foo" and
* "foobar" the command "KEYS foo*" will return "foo foobar".
* <p>
* Note that while the time complexity for this operation is O(n) the
* constant times are pretty low. For example Redis running on an entry
* level laptop can scan a 1 million keys database in 40 milliseconds.
* <b>Still it's better to consider this one of the slow commands that may
* ruin the DB performance if not used with care.</b>
* <p>
* In other words this command is intended only for debugging and special
* operations like creating a script to change the DB schema. Don't use it
* in your normal code. Use Redis Sets in order to group together a subset
* of objects.
* <p>
* Glob style patterns examples:
* <ul>
* <li>h?llo will match hello hallo hhllo
* <li>h*llo will match hllo heeeello
* <li>h[ae]llo will match hello and hallo, but not hillo
* </ul>
* <p>
* Use \ to escape special chars if you want to match them verbatim.
* <p>
* Time complexity: O(n) (with n being the number of keys in the DB, and
* assuming keys and pattern of limited length)
*
* @param pattern
* @return Multi bulk reply
*/
public Set<String> keys(final String pattern) {
checkIsInMulti();
client.keys(pattern);
return BuilderFactory.STRING_SET
.build(client.getBinaryMultiBulkReply());
}
/**
* Return a randomly selected key from the currently selected DB.
* <p>
* Time complexity: O(1)
*
* @return Singe line reply, specifically the randomly selected key or an
* empty string is the database is empty
*/
public String randomKey() {
checkIsInMulti();
client.randomKey();
return client.getBulkReply();
}
/**
* Atomically renames the key oldkey to newkey. If the source and
* destination name are the same an error is returned. If newkey already
* exists it is overwritten.
* <p>
* Time complexity: O(1)
*
* @param oldkey
* @param newkey
* @return Status code repy
*/
public String rename(final String oldkey, final String newkey) {
checkIsInMulti();
client.rename(oldkey, newkey);
return client.getStatusCodeReply();
}
/**
* Rename oldkey into newkey but fails if the destination key newkey already
* exists.
* <p>
* Time complexity: O(1)
*
* @param oldkey
* @param newkey
* @return Integer reply, specifically: 1 if the key was renamed 0 if the
* target key already exist
*/
public Long renamenx(final String oldkey, final String newkey) {
checkIsInMulti();
client.renamenx(oldkey, newkey);
return client.getIntegerReply();
}
public Long expire(final String key, final int seconds) {
checkIsInMulti();
client.expire(key, seconds);
return client.getIntegerReply();
}
public Long expireAt(final String key, final long unixTime) {
checkIsInMulti();
client.expireAt(key, unixTime);
return client.getIntegerReply();
}
/**
* The TTL command returns the remaining time to live in seconds of a key
* that has an {@link #expire(String, int) EXPIRE} set. This introspection
* capability allows a Redis client to check how many seconds a given key
* will continue to be part of the dataset.
*
* @param key
* @return Integer reply, returns the remaining time to live in seconds of a
* key that has an EXPIRE. If the Key does not exists or does not
* have an associated expire, -1 is returned.
*/
public Long ttl(final String key) {
checkIsInMulti();
client.ttl(key);
return client.getIntegerReply();
}
/**
* Select the DB with having the specified zero-based numeric index. For
* default every new client connection is automatically selected to DB 0.
*
* @param index
* @return Status code reply
*/
public String select(final int index) {
checkIsInMulti();
client.select(index);
return client.getStatusCodeReply();
}
/**
* Move the specified key from the currently selected DB to the specified
* destination DB. Note that this command returns 1 only if the key was
* successfully moved, and 0 if the target key was already there or if the
* source key was not found at all, so it is possible to use MOVE as a
* locking primitive.
*
* @param key
* @param dbIndex
* @return Integer reply, specifically: 1 if the key was moved 0 if the key
* was not moved because already present on the target DB or was not
* found in the current DB.
*/
public Long move(final String key, final int dbIndex) {
checkIsInMulti();
client.move(key, dbIndex);
return client.getIntegerReply();
}
/**
* Delete all the keys of all the existing databases, not just the currently
* selected one. This command never fails.
*
* @return Status code reply
*/
public String flushAll() {
checkIsInMulti();
client.flushAll();
return client.getStatusCodeReply();
}
/**
* GETSET is an atomic set this value and return the old value command. Set
* key to the string value and return the old value stored at key. The
* string can't be longer than 1073741824 bytes (1 GB).
* <p>
* Time complexity: O(1)
*
* @param key
* @param value
* @return Bulk reply
*/
public String getSet(final String key, final String value) {
checkIsInMulti();
client.getSet(key, value);
return client.getBulkReply();
}
/**
* Get the values of all the specified keys. If one or more keys dont exist
* or is not of type String, a 'nil' value is returned instead of the value
* of the specified key, but the operation never fails.
* <p>
* Time complexity: O(1) for every key
*
* @param keys
* @return Multi bulk reply
*/
public List<String> mget(final String... keys) {
checkIsInMulti();
client.mget(keys);
return client.getMultiBulkReply();
}
/**
* SETNX works exactly like {@link #set(String, String) SET} with the only
* difference that if the key already exists no operation is performed.
* SETNX actually means "SET if Not eXists".
* <p>
* Time complexity: O(1)
*
* @param key
* @param value
* @return Integer reply, specifically: 1 if the key was set 0 if the key
* was not set
*/
public Long setnx(final String key, final String value) {
checkIsInMulti();
client.setnx(key, value);
return client.getIntegerReply();
}
/**
* The command is exactly equivalent to the following group of commands:
* {@link #set(String, String) SET} + {@link #expire(String, int) EXPIRE}.
* The operation is atomic.
* <p>
* Time complexity: O(1)
*
* @param key
* @param seconds
* @param value
* @return Status code reply
*/
public String setex(final String key, final int seconds, final String value) {
checkIsInMulti();
client.setex(key, seconds, value);
return client.getStatusCodeReply();
}
/**
* Set the the respective keys to the respective values. MSET will replace
* old values with new values, while {@link #msetnx(String...) MSETNX} will
* not perform any operation at all even if just a single key already
* exists.
* <p>
* Because of this semantic MSETNX can be used in order to set different
* keys representing different fields of an unique logic object in a way
* that ensures that either all the fields or none at all are set.
* <p>
* Both MSET and MSETNX are atomic operations. This means that for instance
* if the keys A and B are modified, another client talking to Redis can
* either see the changes to both A and B at once, or no modification at
* all.
*
* @see #msetnx(String...)
*
* @param keysvalues
* @return Status code reply Basically +OK as MSET can't fail
*/
public String mset(final String... keysvalues) {
checkIsInMulti();
client.mset(keysvalues);
return client.getStatusCodeReply();
}
/**
* Set the the respective keys to the respective values.
* {@link #mset(String...) MSET} will replace old values with new values,
* while MSETNX will not perform any operation at all even if just a single
* key already exists.
* <p>
* Because of this semantic MSETNX can be used in order to set different
* keys representing different fields of an unique logic object in a way
* that ensures that either all the fields or none at all are set.
* <p>
* Both MSET and MSETNX are atomic operations. This means that for instance
* if the keys A and B are modified, another client talking to Redis can
* either see the changes to both A and B at once, or no modification at
* all.
*
* @see #mset(String...)
*
* @param keysvalues
* @return Integer reply, specifically: 1 if the all the keys were set 0 if
* no key was set (at least one key already existed)
*/
public Long msetnx(final String... keysvalues) {
checkIsInMulti();
client.msetnx(keysvalues);
return client.getIntegerReply();
}
/**
* IDECRBY work just like {@link #decr(String) INCR} but instead to
* decrement by 1 the decrement is integer.
* <p>
* INCR commands are limited to 64 bit signed integers.
* <p>
* Note: this is actually a string operation, that is, in Redis there are
* not "integer" types. Simply the string stored at the key is parsed as a
* base 10 64 bit signed integer, incremented, and then converted back as a
* string.
* <p>
* Time complexity: O(1)
*
* @see #incr(String)
* @see #decr(String)
* @see #incrBy(String, long)
*
* @param key
* @param integer
* @return Integer reply, this commands will reply with the new value of key
* after the increment.
*/
public Long decrBy(final String key, final long integer) {
checkIsInMulti();
client.decrBy(key, integer);
return client.getIntegerReply();
}
/**
* Decrement the number stored at key by one. If the key does not exist or
* contains a value of a wrong type, set the key to the value of "0" before
* to perform the decrement operation.
* <p>
* INCR commands are limited to 64 bit signed integers.
* <p>
* Note: this is actually a string operation, that is, in Redis there are
* not "integer" types. Simply the string stored at the key is parsed as a
* base 10 64 bit signed integer, incremented, and then converted back as a
* string.
* <p>
* Time complexity: O(1)
*
* @see #incr(String)
* @see #incrBy(String, long)
* @see #decrBy(String, long)
*
* @param key
* @return Integer reply, this commands will reply with the new value of key
* after the increment.
*/
public Long decr(final String key) {
checkIsInMulti();
client.decr(key);
return client.getIntegerReply();
}
/**
* INCRBY work just like {@link #incr(String) INCR} but instead to increment
* by 1 the increment is integer.
* <p>
* INCR commands are limited to 64 bit signed integers.
* <p>
* Note: this is actually a string operation, that is, in Redis there are
* not "integer" types. Simply the string stored at the key is parsed as a
* base 10 64 bit signed integer, incremented, and then converted back as a
* string.
* <p>
* Time complexity: O(1)
*
* @see #incr(String)
* @see #decr(String)
* @see #decrBy(String, long)
*
* @param key
* @param integer
* @return Integer reply, this commands will reply with the new value of key
* after the increment.
*/
public Long incrBy(final String key, final long integer) {
checkIsInMulti();
client.incrBy(key, integer);
return client.getIntegerReply();
}
/**
* Increment the number stored at key by one. If the key does not exist or
* contains a value of a wrong type, set the key to the value of "0" before
* to perform the increment operation.
* <p>
* INCR commands are limited to 64 bit signed integers.
* <p>
* Note: this is actually a string operation, that is, in Redis there are
* not "integer" types. Simply the string stored at the key is parsed as a
* base 10 64 bit signed integer, incremented, and then converted back as a
* string.
* <p>
* Time complexity: O(1)
*
* @see #incrBy(String, long)
* @see #decr(String)
* @see #decrBy(String, long)
*
* @param key
* @return Integer reply, this commands will reply with the new value of key
* after the increment.
*/
public Long incr(final String key) {
checkIsInMulti();
client.incr(key);
return client.getIntegerReply();
}
/**
* If the key already exists and is a string, this command appends the
* provided value at the end of the string. If the key does not exist it is
* created and set as an empty string, so APPEND will be very similar to SET
* in this special case.
* <p>
* Time complexity: O(1). The amortized time complexity is O(1) assuming the
* appended value is small and the already present value is of any size,
* since the dynamic string library used by Redis will double the free space
* available on every reallocation.
*
* @param key
* @param value
* @return Integer reply, specifically the total length of the string after
* the append operation.
*/
public Long append(final String key, final String value) {
checkIsInMulti();
client.append(key, value);
return client.getIntegerReply();
}
/**
* Return a subset of the string from offset start to offset end (both
* offsets are inclusive). Negative offsets can be used in order to provide
* an offset starting from the end of the string. So -1 means the last char,
* -2 the penultimate and so forth.
* <p>
* The function handles out of range requests without raising an error, but
* just limiting the resulting range to the actual length of the string.
* <p>
* Time complexity: O(start+n) (with start being the start index and n the
* total length of the requested range). Note that the lookup part of this
* command is O(1) so for small strings this is actually an O(1) command.
*
* @param key
* @param start
* @param end
* @return Bulk reply
*/
public String substr(final String key, final int start, final int end) {
checkIsInMulti();
client.substr(key, start, end);
return client.getBulkReply();
}
/**
*
* Set the specified hash field to the specified value.
* <p>
* If key does not exist, a new key holding a hash is created.
* <p>
* <b>Time complexity:</b> O(1)
*
* @param key
* @param field
* @param value
* @return If the field already exists, and the HSET just produced an update
* of the value, 0 is returned, otherwise if a new field is created
* 1 is returned.
*/
public Long hset(final String key, final String field, final String value) {
checkIsInMulti();
client.hset(key, field, value);
return client.getIntegerReply();
}
/**
* If key holds a hash, retrieve the value associated to the specified
* field.
* <p>
* If the field is not found or the key does not exist, a special 'nil'
* value is returned.
* <p>
* <b>Time complexity:</b> O(1)
*
* @param key
* @param field
* @return Bulk reply
*/
public String hget(final String key, final String field) {
checkIsInMulti();
client.hget(key, field);
return client.getBulkReply();
}
/**
*
* Set the specified hash field to the specified value if the field not
* exists. <b>Time complexity:</b> O(1)
*
* @param key
* @param field
* @param value
* @return If the field already exists, 0 is returned, otherwise if a new
* field is created 1 is returned.
*/
public Long hsetnx(final String key, final String field, final String value) {
checkIsInMulti();
client.hsetnx(key, field, value);
return client.getIntegerReply();
}
/**
* Set the respective fields to the respective values. HMSET replaces old
* values with new values.
* <p>
* If key does not exist, a new key holding a hash is created.
* <p>
* <b>Time complexity:</b> O(N) (with N being the number of fields)
*
* @param key
* @param hash
* @return Return OK or Exception if hash is empty
*/
public String hmset(final String key, final Map<String, String> hash) {
checkIsInMulti();
client.hmset(key, hash);
return client.getStatusCodeReply();
}
/**
* Retrieve the values associated to the specified fields.
* <p>
* If some of the specified fields do not exist, nil values are returned.
* Non existing keys are considered like empty hashes.
* <p>
* <b>Time complexity:</b> O(N) (with N being the number of fields)
*
* @param key
* @param fields
* @return Multi Bulk Reply specifically a list of all the values associated
* with the specified fields, in the same order of the request.
*/
public List<String> hmget(final String key, final String... fields) {
checkIsInMulti();
client.hmget(key, fields);
return client.getMultiBulkReply();
}
/**
* Increment the number stored at field in the hash at key by value. If key
* does not exist, a new key holding a hash is created. If field does not
* exist or holds a string, the value is set to 0 before applying the
* operation. Since the value argument is signed you can use this command to
* perform both increments and decrements.
* <p>
* The range of values supported by HINCRBY is limited to 64 bit signed
* integers.
* <p>
* <b>Time complexity:</b> O(1)
*
* @param key
* @param field
* @param value
* @return Integer reply The new value at field after the increment
* operation.
*/
public Long hincrBy(final String key, final String field, final long value) {
checkIsInMulti();
client.hincrBy(key, field, value);
return client.getIntegerReply();
}
/**
* Test for existence of a specified field in a hash.
*
* <b>Time complexity:</b> O(1)
*
* @param key
* @param field
* @return Return 1 if the hash stored at key contains the specified field.
* Return 0 if the key is not found or the field is not present.
*/
public Boolean hexists(final String key, final String field) {
checkIsInMulti();
client.hexists(key, field);
return client.getIntegerReply() == 1;
}
/**
* Remove the specified field from an hash stored at key.
* <p>
* <b>Time complexity:</b> O(1)
*
* @param key
* @param field
* @return If the field was present in the hash it is deleted and 1 is
* returned, otherwise 0 is returned and no operation is performed.
*/
public Long hdel(final String key, final String field) {
checkIsInMulti();
client.hdel(key, field);
return client.getIntegerReply();
}
/**
* Return the number of items in a hash.
* <p>
* <b>Time complexity:</b> O(1)
*
* @param key
* @return The number of entries (fields) contained in the hash stored at
* key. If the specified key does not exist, 0 is returned assuming
* an empty hash.
*/
public Long hlen(final String key) {
checkIsInMulti();
client.hlen(key);
return client.getIntegerReply();
}
/**
* Return all the fields in a hash.
* <p>
* <b>Time complexity:</b> O(N), where N is the total number of entries
*
* @param key
* @return All the fields names contained into a hash.
*/
public Set<String> hkeys(final String key) {
checkIsInMulti();
client.hkeys(key);
return BuilderFactory.STRING_SET
.build(client.getBinaryMultiBulkReply());
}
/**
* Return all the values in a hash.
* <p>
* <b>Time complexity:</b> O(N), where N is the total number of entries
*
* @param key
* @return All the fields values contained into a hash.
*/
public List<String> hvals(final String key) {
checkIsInMulti();
client.hvals(key);
final List<String> lresult = client.getMultiBulkReply();
return lresult;
}
/**
* Return all the fields and associated values in a hash.
* <p>
* <b>Time complexity:</b> O(N), where N is the total number of entries
*
* @param key
* @return All the fields and values contained into a hash.
*/
public Map<String, String> hgetAll(final String key) {
checkIsInMulti();
client.hgetAll(key);
return BuilderFactory.STRING_MAP
.build(client.getBinaryMultiBulkReply());
}
/**
* Add the string value to the head (LPUSH) or tail (RPUSH) of the list
* stored at key. If the key does not exist an empty list is created just
* before the append operation. If the key exists but is not a List an error
* is returned.
* <p>
* Time complexity: O(1)
*
* @see Jedis#lpush(String, String)
*
* @param key
* @param string
* @return Integer reply, specifically, the number of elements inside the
* list after the push operation.
*/
public Long rpush(final String key, final String string) {
checkIsInMulti();
client.rpush(key, string);
return client.getIntegerReply();
}
/**
* Add the string value to the head (LPUSH) or tail (RPUSH) of the list
* stored at key. If the key does not exist an empty list is created just
* before the append operation. If the key exists but is not a List an error
* is returned.
* <p>
* Time complexity: O(1)
*
* @see Jedis#rpush(String, String)
*
* @param key
* @param string
* @return Integer reply, specifically, the number of elements inside the
* list after the push operation.
*/
public Long lpush(final String key, final String string) {
checkIsInMulti();
client.lpush(key, string);
return client.getIntegerReply();
}
/**
* Return the length of the list stored at the specified key. If the key
* does not exist zero is returned (the same behaviour as for empty lists).
* If the value stored at key is not a list an error is returned.
* <p>
* Time complexity: O(1)
*
* @param key
* @return The length of the list.
*/
public Long llen(final String key) {
checkIsInMulti();
client.llen(key);
return client.getIntegerReply();
}
/**
* Return the specified elements of the list stored at the specified key.
* Start and end are zero-based indexes. 0 is the first element of the list
* (the list head), 1 the next element and so on.
* <p>
* For example LRANGE foobar 0 2 will return the first three elements of the
* list.
* <p>
* start and end can also be negative numbers indicating offsets from the
* end of the list. For example -1 is the last element of the list, -2 the
* penultimate element and so on.
* <p>
* <b>Consistency with range functions in various programming languages</b>
* <p>
* Note that if you have a list of numbers from 0 to 100, LRANGE 0 10 will
* return 11 elements, that is, rightmost item is included. This may or may
* not be consistent with behavior of range-related functions in your
* programming language of choice (think Ruby's Range.new, Array#slice or
* Python's range() function).
* <p>
* LRANGE behavior is consistent with one of Tcl.
* <p>
* <b>Out-of-range indexes</b>
* <p>
* Indexes out of range will not produce an error: if start is over the end
* of the list, or start > end, an empty list is returned. If end is over
* the end of the list Redis will threat it just like the last element of
* the list.
* <p>
* Time complexity: O(start+n) (with n being the length of the range and
* start being the start offset)
*
* @param key
* @param start
* @param end
* @return Multi bulk reply, specifically a list of elements in the
* specified range.
*/
public List<String> lrange(final String key, final long start, final long end) {
checkIsInMulti();
client.lrange(key, start, end);
return client.getMultiBulkReply();
}
/**
* Trim an existing list so that it will contain only the specified range of
* elements specified. Start and end are zero-based indexes. 0 is the first
* element of the list (the list head), 1 the next element and so on.
* <p>
* For example LTRIM foobar 0 2 will modify the list stored at foobar key so
* that only the first three elements of the list will remain.
* <p>
* start and end can also be negative numbers indicating offsets from the
* end of the list. For example -1 is the last element of the list, -2 the
* penultimate element and so on.
* <p>
* Indexes out of range will not produce an error: if start is over the end
* of the list, or start > end, an empty list is left as value. If end over
* the end of the list Redis will threat it just like the last element of
* the list.
* <p>
* Hint: the obvious use of LTRIM is together with LPUSH/RPUSH. For example:
* <p>
* {@code lpush("mylist", "someelement"); ltrim("mylist", 0, 99); * }
* <p>
* The above two commands will push elements in the list taking care that
* the list will not grow without limits. This is very useful when using
* Redis to store logs for example. It is important to note that when used
* in this way LTRIM is an O(1) operation because in the average case just
* one element is removed from the tail of the list.
* <p>
* Time complexity: O(n) (with n being len of list - len of range)
*
* @param key
* @param start
* @param end
* @return Status code reply
*/
public String ltrim(final String key, final long start, final long end) {
checkIsInMulti();
client.ltrim(key, start, end);
return client.getStatusCodeReply();
}
/**
* Return the specified element of the list stored at the specified key. 0
* is the first element, 1 the second and so on. Negative indexes are
* supported, for example -1 is the last element, -2 the penultimate and so
* on.
* <p>
* If the value stored at key is not of list type an error is returned. If
* the index is out of range a 'nil' reply is returned.
* <p>
* Note that even if the average time complexity is O(n) asking for the
* first or the last element of the list is O(1).
* <p>
* Time complexity: O(n) (with n being the length of the list)
*
* @param key
* @param index
* @return Bulk reply, specifically the requested element
*/
public String lindex(final String key, final long index) {
checkIsInMulti();
client.lindex(key, index);
return client.getBulkReply();
}
/**
* Set a new value as the element at index position of the List at key.
* <p>
* Out of range indexes will generate an error.
* <p>
* Similarly to other list commands accepting indexes, the index can be
* negative to access elements starting from the end of the list. So -1 is
* the last element, -2 is the penultimate, and so forth.
* <p>
* <b>Time complexity:</b>
* <p>
* O(N) (with N being the length of the list), setting the first or last
* elements of the list is O(1).
*
* @see #lindex(String, long)
*
* @param key
* @param index
* @param value
* @return Status code reply
*/
public String lset(final String key, final long index, final String value) {
checkIsInMulti();
client.lset(key, index, value);
return client.getStatusCodeReply();
}
/**
* Remove the first count occurrences of the value element from the list. If
* count is zero all the elements are removed. If count is negative elements
* are removed from tail to head, instead to go from head to tail that is
* the normal behaviour. So for example LREM with count -2 and hello as
* value to remove against the list (a,b,c,hello,x,hello,hello) will lave
* the list (a,b,c,hello,x). The number of removed elements is returned as
* an integer, see below for more information about the returned value. Note
* that non existing keys are considered like empty lists by LREM, so LREM
* against non existing keys will always return 0.
* <p>
* Time complexity: O(N) (with N being the length of the list)
*
* @param key
* @param count
* @param value
* @return Integer Reply, specifically: The number of removed elements if
* the operation succeeded
*/
public Long lrem(final String key, final long count, final String value) {
checkIsInMulti();
client.lrem(key, count, value);
return client.getIntegerReply();
}
/**
* Atomically return and remove the first (LPOP) or last (RPOP) element of
* the list. For example if the list contains the elements "a","b","c" LPOP
* will return "a" and the list will become "b","c".
* <p>
* If the key does not exist or the list is already empty the special value
* 'nil' is returned.
*
* @see #rpop(String)
*
* @param key
* @return Bulk reply
*/
public String lpop(final String key) {
checkIsInMulti();
client.lpop(key);
return client.getBulkReply();
}
/**
* Atomically return and remove the first (LPOP) or last (RPOP) element of
* the list. For example if the list contains the elements "a","b","c" LPOP
* will return "a" and the list will become "b","c".
* <p>
* If the key does not exist or the list is already empty the special value
* 'nil' is returned.
*
* @see #lpop(String)
*
* @param key
* @return Bulk reply
*/
public String rpop(final String key) {
checkIsInMulti();
client.rpop(key);
return client.getBulkReply();
}
/**
* Atomically return and remove the last (tail) element of the srckey list,
* and push the element as the first (head) element of the dstkey list. For
* example if the source list contains the elements "a","b","c" and the
* destination list contains the elements "foo","bar" after an RPOPLPUSH
* command the content of the two lists will be "a","b" and "c","foo","bar".
* <p>
* If the key does not exist or the list is already empty the special value
* 'nil' is returned. If the srckey and dstkey are the same the operation is
* equivalent to removing the last element from the list and pusing it as
* first element of the list, so it's a "list rotation" command.
* <p>
* Time complexity: O(1)
*
* @param srckey
* @param dstkey
* @return Bulk reply
*/
public String rpoplpush(final String srckey, final String dstkey) {
checkIsInMulti();
client.rpoplpush(srckey, dstkey);
return client.getBulkReply();
}
/**
* Add the specified member to the set value stored at key. If member is
* already a member of the set no operation is performed. If key does not
* exist a new set with the specified member as sole member is created. If
* the key exists but does not hold a set value an error is returned.
* <p>
* Time complexity O(1)
*
* @param key
* @param member
* @return Integer reply, specifically: 1 if the new element was added 0 if
* the element was already a member of the set
*/
public Long sadd(final String key, final String member) {
checkIsInMulti();
client.sadd(key, member);
return client.getIntegerReply();
}
/**
* Return all the members (elements) of the set value stored at key. This is
* just syntax glue for {@link #sinter(String...) SINTER}.
* <p>
* Time complexity O(N)
*
* @param key
* @return Multi bulk reply
*/
public Set<String> smembers(final String key) {
checkIsInMulti();
client.smembers(key);
final List<String> members = client.getMultiBulkReply();
return new HashSet<String>(members);
}
/**
* Remove the specified member from the set value stored at key. If member
* was not a member of the set no operation is performed. If key does not
* hold a set value an error is returned.
* <p>
* Time complexity O(1)
*
* @param key
* @param member
* @return Integer reply, specifically: 1 if the new element was removed 0
* if the new element was not a member of the set
*/
public Long srem(final String key, final String member) {
checkIsInMulti();
client.srem(key, member);
return client.getIntegerReply();
}
/**
* Remove a random element from a Set returning it as return value. If the
* Set is empty or the key does not exist, a nil object is returned.
* <p>
* The {@link #srandmember(String)} command does a similar work but the
* returned element is not removed from the Set.
* <p>
* Time complexity O(1)
*
* @param key
* @return Bulk reply
*/
public String spop(final String key) {
checkIsInMulti();
client.spop(key);
return client.getBulkReply();
}
/**
* Move the specifided member from the set at srckey to the set at dstkey.
* This operation is atomic, in every given moment the element will appear
* to be in the source or destination set for accessing clients.
* <p>
* If the source set does not exist or does not contain the specified
* element no operation is performed and zero is returned, otherwise the
* element is removed from the source set and added to the destination set.
* On success one is returned, even if the element was already present in
* the destination set.
* <p>
* An error is raised if the source or destination keys contain a non Set
* value.
* <p>
* Time complexity O(1)
*
* @param srckey
* @param dstkey
* @param member
* @return Integer reply, specifically: 1 if the element was moved 0 if the
* element was not found on the first set and no operation was
* performed
*/
public Long smove(final String srckey, final String dstkey,
final String member) {
checkIsInMulti();
client.smove(srckey, dstkey, member);
return client.getIntegerReply();
}
/**
* Return the set cardinality (number of elements). If the key does not
* exist 0 is returned, like for empty sets.
*
* @param key
* @return Integer reply, specifically: the cardinality (number of elements)
* of the set as an integer.
*/
public Long scard(final String key) {
checkIsInMulti();
client.scard(key);
return client.getIntegerReply();
}
/**
* Return 1 if member is a member of the set stored at key, otherwise 0 is
* returned.
* <p>
* Time complexity O(1)
*
* @param key
* @param member
* @return Integer reply, specifically: 1 if the element is a member of the
* set 0 if the element is not a member of the set OR if the key
* does not exist
*/
public Boolean sismember(final String key, final String member) {
checkIsInMulti();
client.sismember(key, member);
return client.getIntegerReply() == 1;
}
/**
* Return the members of a set resulting from the intersection of all the
* sets hold at the specified keys. Like in
* {@link #lrange(String, long, long) LRANGE} the result is sent to the client
* as a multi-bulk reply (see the protocol specification for more
* information). If just a single key is specified, then this command
* produces the same result as {@link #smembers(String) SMEMBERS}. Actually
* SMEMBERS is just syntax sugar for SINTER.
* <p>
* Non existing keys are considered like empty sets, so if one of the keys
* is missing an empty set is returned (since the intersection with an empty
* set always is an empty set).
* <p>
* Time complexity O(N*M) worst case where N is the cardinality of the
* smallest set and M the number of sets
*
* @param keys
* @return Multi bulk reply, specifically the list of common elements.
*/
public Set<String> sinter(final String... keys) {
checkIsInMulti();
client.sinter(keys);
final List<String> members = client.getMultiBulkReply();
return new HashSet<String>(members);
}
/**
* This commnad works exactly like {@link #sinter(String...) SINTER} but
* instead of being returned the resulting set is sotred as dstkey.
* <p>
* Time complexity O(N*M) worst case where N is the cardinality of the
* smallest set and M the number of sets
*
* @param dstkey
* @param keys
* @return Status code reply
*/
public Long sinterstore(final String dstkey, final String... keys) {
checkIsInMulti();
client.sinterstore(dstkey, keys);
return client.getIntegerReply();
}
/**
* Return the members of a set resulting from the union of all the sets hold
* at the specified keys. Like in {@link #lrange(String, long, long) LRANGE}
* the result is sent to the client as a multi-bulk reply (see the protocol
* specification for more information). If just a single key is specified,
* then this command produces the same result as {@link #smembers(String)
* SMEMBERS}.
* <p>
* Non existing keys are considered like empty sets.
* <p>
* Time complexity O(N) where N is the total number of elements in all the
* provided sets
*
* @param keys
* @return Multi bulk reply, specifically the list of common elements.
*/
public Set<String> sunion(final String... keys) {
checkIsInMulti();
client.sunion(keys);
final List<String> members = client.getMultiBulkReply();
return new HashSet<String>(members);
}
/**
* This command works exactly like {@link #sunion(String...) SUNION} but
* instead of being returned the resulting set is stored as dstkey. Any
* existing value in dstkey will be over-written.
* <p>
* Time complexity O(N) where N is the total number of elements in all the
* provided sets
*
* @param dstkey
* @param keys
* @return Status code reply
*/
public Long sunionstore(final String dstkey, final String... keys) {
checkIsInMulti();
client.sunionstore(dstkey, keys);
return client.getIntegerReply();
}
/**
* Return the difference between the Set stored at key1 and all the Sets
* key2, ..., keyN
* <p>
* <b>Example:</b>
*
* <pre>
* key1 = [x, a, b, c]
* key2 = [c]
* key3 = [a, d]
* SDIFF key1,key2,key3 => [x, b]
* </pre>
*
* Non existing keys are considered like empty sets.
* <p>
* <b>Time complexity:</b>
* <p>
* O(N) with N being the total number of elements of all the sets
*
* @param keys
* @return Return the members of a set resulting from the difference between
* the first set provided and all the successive sets.
*/
public Set<String> sdiff(final String... keys) {
checkIsInMulti();
client.sdiff(keys);
return BuilderFactory.STRING_SET
.build(client.getBinaryMultiBulkReply());
}
/**
* This command works exactly like {@link #sdiff(String...) SDIFF} but
* instead of being returned the resulting set is stored in dstkey.
*
* @param dstkey
* @param keys
* @return Status code reply
*/
public Long sdiffstore(final String dstkey, final String... keys) {
checkIsInMulti();
client.sdiffstore(dstkey, keys);
return client.getIntegerReply();
}
/**
* Return a random element from a Set, without removing the element. If the
* Set is empty or the key does not exist, a nil object is returned.
* <p>
* The SPOP command does a similar work but the returned element is popped
* (removed) from the Set.
* <p>
* Time complexity O(1)
*
* @param key
* @return Bulk reply
*/
public String srandmember(final String key) {
checkIsInMulti();
client.srandmember(key);
return client.getBulkReply();
}
/**
* Add the specified member having the specifeid score to the sorted set
* stored at key. If member is already a member of the sorted set the score
* is updated, and the element reinserted in the right position to ensure
* sorting. If key does not exist a new sorted set with the specified member
* as sole member is crated. If the key exists but does not hold a sorted
* set value an error is returned.
* <p>
* The score value can be the string representation of a double precision
* floating point number.
* <p>
* Time complexity O(log(N)) with N being the number of elements in the
* sorted set
*
* @param key
* @param score
* @param member
* @return Integer reply, specifically: 1 if the new element was added 0 if
* the element was already a member of the sorted set and the score
* was updated
*/
public Long zadd(final String key, final double score, final String member) {
checkIsInMulti();
client.zadd(key, score, member);
return client.getIntegerReply();
}
public Set<String> zrange(final String key, final int start, final int end) {
checkIsInMulti();
client.zrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
return new LinkedHashSet<String>(members);
}
/**
* Remove the specified member from the sorted set value stored at key. If
* member was not a member of the set no operation is performed. If key does
* not not hold a set value an error is returned.
* <p>
* Time complexity O(log(N)) with N being the number of elements in the
* sorted set
*
*
*
* @param key
* @param member
* @return Integer reply, specifically: 1 if the new element was removed 0
* if the new element was not a member of the set
*/
public Long zrem(final String key, final String member) {
checkIsInMulti();
client.zrem(key, member);
return client.getIntegerReply();
}
/**
* If member already exists in the sorted set adds the increment to its
* score and updates the position of the element in the sorted set
* accordingly. If member does not already exist in the sorted set it is
* added with increment as score (that is, like if the previous score was
* virtually zero). If key does not exist a new sorted set with the
* specified member as sole member is crated. If the key exists but does not
* hold a sorted set value an error is returned.
* <p>
* The score value can be the string representation of a double precision
* floating point number. It's possible to provide a negative value to
* perform a decrement.
* <p>
* For an introduction to sorted sets check the Introduction to Redis data
* types page.
* <p>
* Time complexity O(log(N)) with N being the number of elements in the
* sorted set
*
* @param key
* @param score
* @param member
* @return The new score
*/
public Double zincrby(final String key, final double score,
final String member) {
checkIsInMulti();
client.zincrby(key, score, member);
String newscore = client.getBulkReply();
return Double.valueOf(newscore);
}
/**
* Return the rank (or index) or member in the sorted set at key, with
* scores being ordered from low to high.
* <p>
* When the given member does not exist in the sorted set, the special value
* 'nil' is returned. The returned rank (or index) of the member is 0-based
* for both commands.
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))
*
* @see #zrevrank(String, String)
*
* @param key
* @param member
* @return Integer reply or a nil bulk reply, specifically: the rank of the
* element as an integer reply if the element exists. A nil bulk
* reply if there is no such element.
*/
public Long zrank(final String key, final String member) {
checkIsInMulti();
client.zrank(key, member);
return client.getIntegerReply();
}
/**
* Return the rank (or index) or member in the sorted set at key, with
* scores being ordered from high to low.
* <p>
* When the given member does not exist in the sorted set, the special value
* 'nil' is returned. The returned rank (or index) of the member is 0-based
* for both commands.
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))
*
* @see #zrank(String, String)
*
* @param key
* @param member
* @return Integer reply or a nil bulk reply, specifically: the rank of the
* element as an integer reply if the element exists. A nil bulk
* reply if there is no such element.
*/
public Long zrevrank(final String key, final String member) {
checkIsInMulti();
client.zrevrank(key, member);
return client.getIntegerReply();
}
public Set<String> zrevrange(final String key, final int start,
final int end) {
checkIsInMulti();
client.zrevrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
return new LinkedHashSet<String>(members);
}
public Set<Tuple> zrangeWithScores(final String key, final int start,
final int end) {
checkIsInMulti();
client.zrangeWithScores(key, start, end);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrevrangeWithScores(final String key, final int start,
final int end) {
checkIsInMulti();
client.zrevrangeWithScores(key, start, end);
Set<Tuple> set = getTupledSet();
return set;
}
/**
* Return the sorted set cardinality (number of elements). If the key does
* not exist 0 is returned, like for empty sorted sets.
* <p>
* Time complexity O(1)
*
* @param key
* @return the cardinality (number of elements) of the set as an integer.
*/
public Long zcard(final String key) {
checkIsInMulti();
client.zcard(key);
return client.getIntegerReply();
}
/**
* Return the score of the specified element of the sorted set at key. If
* the specified element does not exist in the sorted set, or the key does
* not exist at all, a special 'nil' value is returned.
* <p>
* <b>Time complexity:</b> O(1)
*
* @param key
* @param member
* @return the score
*/
public Double zscore(final String key, final String member) {
checkIsInMulti();
client.zscore(key, member);
final String score = client.getBulkReply();
return (score != null ? new Double(score) : null);
}
public String watch(final String... keys) {
client.watch(keys);
return client.getStatusCodeReply();
}
/**
* Sort a Set or a List.
* <p>
* Sort the elements contained in the List, Set, or Sorted Set value at key.
* By default sorting is numeric with elements being compared as double
* precision floating point numbers. This is the simplest form of SORT.
*
* @see #sort(String, String)
* @see #sort(String, SortingParams)
* @see #sort(String, SortingParams, String)
*
*
* @param key
* @return Assuming the Set/List at key contains a list of numbers, the
* return value will be the list of numbers ordered from the
* smallest to the biggest number.
*/
public List<String> sort(final String key) {
checkIsInMulti();
client.sort(key);
return client.getMultiBulkReply();
}
/**
* Sort a Set or a List accordingly to the specified parameters.
* <p>
* <b>examples:</b>
* <p>
* Given are the following sets and key/values:
*
* <pre>
* x = [1, 2, 3]
* y = [a, b, c]
*
* k1 = z
* k2 = y
* k3 = x
*
* w1 = 9
* w2 = 8
* w3 = 7
* </pre>
*
* Sort Order:
*
* <pre>
* sort(x) or sort(x, sp.asc())
* -> [1, 2, 3]
*
* sort(x, sp.desc())
* -> [3, 2, 1]
*
* sort(y)
* -> [c, a, b]
*
* sort(y, sp.alpha())
* -> [a, b, c]
*
* sort(y, sp.alpha().desc())
* -> [c, a, b]
* </pre>
*
* Limit (e.g. for Pagination):
*
* <pre>
* sort(x, sp.limit(0, 2))
* -> [1, 2]
*
* sort(y, sp.alpha().desc().limit(1, 2))
* -> [b, a]
* </pre>
*
* Sorting by external keys:
*
* <pre>
* sort(x, sb.by(w*))
* -> [3, 2, 1]
*
* sort(x, sb.by(w*).desc())
* -> [1, 2, 3]
* </pre>
*
* Getting external keys:
*
* <pre>
* sort(x, sp.by(w*).get(k*))
* -> [x, y, z]
*
* sort(x, sp.by(w*).get(#).get(k*))
* -> [3, x, 2, y, 1, z]
* </pre>
*
* @see #sort(String)
* @see #sort(String, SortingParams, String)
*
* @param key
* @param sortingParameters
* @return a list of sorted elements.
*/
public List<String> sort(final String key,
final SortingParams sortingParameters) {
checkIsInMulti();
client.sort(key, sortingParameters);
return client.getMultiBulkReply();
}
/**
* BLPOP (and BRPOP) is a blocking list pop primitive. You can see this
* commands as blocking versions of LPOP and RPOP able to block if the
* specified keys don't exist or contain empty lists.
* <p>
* The following is a description of the exact semantic. We describe BLPOP
* but the two commands are identical, the only difference is that BLPOP
* pops the element from the left (head) of the list, and BRPOP pops from
* the right (tail).
* <p>
* <b>Non blocking behavior</b>
* <p>
* When BLPOP is called, if at least one of the specified keys contain a non
* empty list, an element is popped from the head of the list and returned
* to the caller together with the name of the key (BLPOP returns a two
* elements array, the first element is the key, the second the popped
* value).
* <p>
* Keys are scanned from left to right, so for instance if you issue BLPOP
* list1 list2 list3 0 against a dataset where list1 does not exist but
* list2 and list3 contain non empty lists, BLPOP guarantees to return an
* element from the list stored at list2 (since it is the first non empty
* list starting from the left).
* <p>
* <b>Blocking behavior</b>
* <p>
* If none of the specified keys exist or contain non empty lists, BLPOP
* blocks until some other client performs a LPUSH or an RPUSH operation
* against one of the lists.
* <p>
* Once new data is present on one of the lists, the client finally returns
* with the name of the key unblocking it and the popped value.
* <p>
* When blocking, if a non-zero timeout is specified, the client will
* unblock returning a nil special value if the specified amount of seconds
* passed without a push operation against at least one of the specified
* keys.
* <p>
* The timeout argument is interpreted as an integer value. A timeout of
* zero means instead to block forever.
* <p>
* <b>Multiple clients blocking for the same keys</b>
* <p>
* Multiple clients can block for the same key. They are put into a queue,
* so the first to be served will be the one that started to wait earlier,
* in a first-blpopping first-served fashion.
* <p>
* <b>blocking POP inside a MULTI/EXEC transaction</b>
* <p>
* BLPOP and BRPOP can be used with pipelining (sending multiple commands
* and reading the replies in batch), but it does not make sense to use
* BLPOP or BRPOP inside a MULTI/EXEC block (a Redis transaction).
* <p>
* The behavior of BLPOP inside MULTI/EXEC when the list is empty is to
* return a multi-bulk nil reply, exactly what happens when the timeout is
* reached. If you like science fiction, think at it like if inside
* MULTI/EXEC the time will flow at infinite speed :)
* <p>
* Time complexity: O(1)
*
* @see #brpop(int, String...)
*
* @param timeout
* @param keys
* @return BLPOP returns a two-elements array via a multi bulk reply in
* order to return both the unblocking key and the popped value.
* <p>
* When a non-zero timeout is specified, and the BLPOP operation
* timed out, the return value is a nil multi bulk reply. Most
* client values will return false or nil accordingly to the
* programming language used.
*/
public List<String> blpop(final int timeout, final String... keys) {
checkIsInMulti();
List<String> args = new ArrayList<String>();
for (String arg : keys) {
args.add(arg);
}
args.add(String.valueOf(timeout));
client.blpop(args.toArray(new String[args.size()]));
client.setTimeoutInfinite();
final List<String> multiBulkReply = client.getMultiBulkReply();
client.rollbackTimeout();
return multiBulkReply;
}
/**
* Sort a Set or a List accordingly to the specified parameters and store
* the result at dstkey.
*
* @see #sort(String, SortingParams)
* @see #sort(String)
* @see #sort(String, String)
*
* @param key
* @param sortingParameters
* @param dstkey
* @return The number of elements of the list at dstkey.
*/
public Long sort(final String key, final SortingParams sortingParameters,
final String dstkey) {
checkIsInMulti();
client.sort(key, sortingParameters, dstkey);
return client.getIntegerReply();
}
/**
* Sort a Set or a List and Store the Result at dstkey.
* <p>
* Sort the elements contained in the List, Set, or Sorted Set value at key
* and store the result at dstkey. By default sorting is numeric with
* elements being compared as double precision floating point numbers. This
* is the simplest form of SORT.
*
* @see #sort(String)
* @see #sort(String, SortingParams)
* @see #sort(String, SortingParams, String)
*
* @param key
* @param dstkey
* @return The number of elements of the list at dstkey.
*/
public Long sort(final String key, final String dstkey) {
checkIsInMulti();
client.sort(key, dstkey);
return client.getIntegerReply();
}
/**
* BLPOP (and BRPOP) is a blocking list pop primitive. You can see this
* commands as blocking versions of LPOP and RPOP able to block if the
* specified keys don't exist or contain empty lists.
* <p>
* The following is a description of the exact semantic. We describe BLPOP
* but the two commands are identical, the only difference is that BLPOP
* pops the element from the left (head) of the list, and BRPOP pops from
* the right (tail).
* <p>
* <b>Non blocking behavior</b>
* <p>
* When BLPOP is called, if at least one of the specified keys contain a non
* empty list, an element is popped from the head of the list and returned
* to the caller together with the name of the key (BLPOP returns a two
* elements array, the first element is the key, the second the popped
* value).
* <p>
* Keys are scanned from left to right, so for instance if you issue BLPOP
* list1 list2 list3 0 against a dataset where list1 does not exist but
* list2 and list3 contain non empty lists, BLPOP guarantees to return an
* element from the list stored at list2 (since it is the first non empty
* list starting from the left).
* <p>
* <b>Blocking behavior</b>
* <p>
* If none of the specified keys exist or contain non empty lists, BLPOP
* blocks until some other client performs a LPUSH or an RPUSH operation
* against one of the lists.
* <p>
* Once new data is present on one of the lists, the client finally returns
* with the name of the key unblocking it and the popped value.
* <p>
* When blocking, if a non-zero timeout is specified, the client will
* unblock returning a nil special value if the specified amount of seconds
* passed without a push operation against at least one of the specified
* keys.
* <p>
* The timeout argument is interpreted as an integer value. A timeout of
* zero means instead to block forever.
* <p>
* <b>Multiple clients blocking for the same keys</b>
* <p>
* Multiple clients can block for the same key. They are put into a queue,
* so the first to be served will be the one that started to wait earlier,
* in a first-blpopping first-served fashion.
* <p>
* <b>blocking POP inside a MULTI/EXEC transaction</b>
* <p>
* BLPOP and BRPOP can be used with pipelining (sending multiple commands
* and reading the replies in batch), but it does not make sense to use
* BLPOP or BRPOP inside a MULTI/EXEC block (a Redis transaction).
* <p>
* The behavior of BLPOP inside MULTI/EXEC when the list is empty is to
* return a multi-bulk nil reply, exactly what happens when the timeout is
* reached. If you like science fiction, think at it like if inside
* MULTI/EXEC the time will flow at infinite speed :)
* <p>
* Time complexity: O(1)
*
* @see #blpop(int, String...)
*
* @param timeout
* @param keys
* @return BLPOP returns a two-elements array via a multi bulk reply in
* order to return both the unblocking key and the popped value.
* <p>
* When a non-zero timeout is specified, and the BLPOP operation
* timed out, the return value is a nil multi bulk reply. Most
* client values will return false or nil accordingly to the
* programming language used.
*/
public List<String> brpop(final int timeout, final String... keys) {
checkIsInMulti();
List<String> args = new ArrayList<String>();
for (String arg : keys) {
args.add(arg);
}
args.add(String.valueOf(timeout));
client.brpop(args.toArray(new String[args.size()]));
client.setTimeoutInfinite();
List<String> multiBulkReply = client.getMultiBulkReply();
client.rollbackTimeout();
return multiBulkReply;
}
/**
* Request for authentication in a password protected Redis server. A Redis
* server can be instructed to require a password before to allow clients to
* issue commands. This is done using the requirepass directive in the Redis
* configuration file. If the password given by the client is correct the
* server replies with an OK status code reply and starts accepting commands
* from the client. Otherwise an error is returned and the clients needs to
* try a new password. Note that for the high performance nature of Redis it
* is possible to try a lot of passwords in parallel in very short time, so
* make sure to generate a strong and very long password so that this attack
* is infeasible.
*
* @param password
* @return Status code reply
*/
public String auth(final String password) {
checkIsInMulti();
client.auth(password);
return client.getStatusCodeReply();
}
public void subscribe(JedisPubSub jedisPubSub, String... channels) {
checkIsInMulti();
connect();
client.setTimeoutInfinite();
jedisPubSub.proceed(client, channels);
client.rollbackTimeout();
}
public Long publish(String channel, String message) {
checkIsInMulti();
client.publish(channel, message);
return client.getIntegerReply();
}
public void psubscribe(JedisPubSub jedisPubSub, String... patterns) {
checkIsInMulti();
connect();
client.setTimeoutInfinite();
jedisPubSub.proceedWithPatterns(client, patterns);
client.rollbackTimeout();
}
public Long zcount(final String key, final double min, final double max) {
checkIsInMulti();
client.zcount(key, min, max);
return client.getIntegerReply();
}
/**
* Return the all the elements in the sorted set at key with a score between
* min and max (including elements with score equal to min or max).
* <p>
* The elements having the same score are returned sorted lexicographically
* as ASCII strings (this follows from a property of Redis sorted sets and
* does not involve further computation).
* <p>
* Using the optional
* {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's
* possible to get only a range of the matching elements in an SQL-alike
* way. Note that if offset is large the commands needs to traverse the list
* for offset elements and this adds up to the O(M) figure.
* <p>
* The {@link #zcount(String, double, double) ZCOUNT} command is similar to
* {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead
* of returning the actual elements in the specified interval, it just
* returns the number of matching elements.
* <p>
* <b>Exclusive intervals and infinity</b>
* <p>
* min and max can be -inf and +inf, so that you are not required to know
* what's the greatest or smallest element in order to take, for instance,
* elements "up to a given value".
* <p>
* Also while the interval is for default closed (inclusive) it's possible
* to specify open intervals prefixing the score with a "(" character, so
* for instance:
* <p>
* {@code ZRANGEBYSCORE zset (1.3 5}
* <p>
* Will return all the values with score > 1.3 and <= 5, while for instance:
* <p>
* {@code ZRANGEBYSCORE zset (5 (10}
* <p>
* Will return all the values with score > 5 and < 10 (5 and 10 excluded).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and
* M the number of elements returned by the command, so if M is constant
* (for instance you always ask for the first ten elements with LIMIT) you
* can consider it O(log(N))
*
* @see #zrangeByScore(String, double, double)
* @see #zrangeByScore(String, double, double, int, int)
* @see #zrangeByScoreWithScores(String, double, double)
* @see #zrangeByScoreWithScores(String, String, String)
* @see #zrangeByScoreWithScores(String, double, double, int, int)
* @see #zcount(String, double, double)
*
* @param key
* @param min
* @param max
* @return Multi bulk reply specifically a list of elements in the specified
* score range.
*/
public Set<String> zrangeByScore(final String key, final double min,
final double max) {
checkIsInMulti();
client.zrangeByScore(key, min, max);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final String min,
final String max) {
checkIsInMulti();
client.zrangeByScore(key, min, max);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
/**
* Return the all the elements in the sorted set at key with a score between
* min and max (including elements with score equal to min or max).
* <p>
* The elements having the same score are returned sorted lexicographically
* as ASCII strings (this follows from a property of Redis sorted sets and
* does not involve further computation).
* <p>
* Using the optional
* {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's
* possible to get only a range of the matching elements in an SQL-alike
* way. Note that if offset is large the commands needs to traverse the list
* for offset elements and this adds up to the O(M) figure.
* <p>
* The {@link #zcount(String, double, double) ZCOUNT} command is similar to
* {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead
* of returning the actual elements in the specified interval, it just
* returns the number of matching elements.
* <p>
* <b>Exclusive intervals and infinity</b>
* <p>
* min and max can be -inf and +inf, so that you are not required to know
* what's the greatest or smallest element in order to take, for instance,
* elements "up to a given value".
* <p>
* Also while the interval is for default closed (inclusive) it's possible
* to specify open intervals prefixing the score with a "(" character, so
* for instance:
* <p>
* {@code ZRANGEBYSCORE zset (1.3 5}
* <p>
* Will return all the values with score > 1.3 and <= 5, while for instance:
* <p>
* {@code ZRANGEBYSCORE zset (5 (10}
* <p>
* Will return all the values with score > 5 and < 10 (5 and 10 excluded).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and
* M the number of elements returned by the command, so if M is constant
* (for instance you always ask for the first ten elements with LIMIT) you
* can consider it O(log(N))
*
* @see #zrangeByScore(String, double, double)
* @see #zrangeByScore(String, double, double, int, int)
* @see #zrangeByScoreWithScores(String, double, double)
* @see #zrangeByScoreWithScores(String, double, double, int, int)
* @see #zcount(String, double, double)
*
* @param key
* @param min
* @param max
* @return Multi bulk reply specifically a list of elements in the specified
* score range.
*/
public Set<String> zrangeByScore(final String key, final double min,
final double max, final int offset, final int count) {
checkIsInMulti();
client.zrangeByScore(key, min, max, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
/**
* Return the all the elements in the sorted set at key with a score between
* min and max (including elements with score equal to min or max).
* <p>
* The elements having the same score are returned sorted lexicographically
* as ASCII strings (this follows from a property of Redis sorted sets and
* does not involve further computation).
* <p>
* Using the optional
* {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's
* possible to get only a range of the matching elements in an SQL-alike
* way. Note that if offset is large the commands needs to traverse the list
* for offset elements and this adds up to the O(M) figure.
* <p>
* The {@link #zcount(String, double, double) ZCOUNT} command is similar to
* {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead
* of returning the actual elements in the specified interval, it just
* returns the number of matching elements.
* <p>
* <b>Exclusive intervals and infinity</b>
* <p>
* min and max can be -inf and +inf, so that you are not required to know
* what's the greatest or smallest element in order to take, for instance,
* elements "up to a given value".
* <p>
* Also while the interval is for default closed (inclusive) it's possible
* to specify open intervals prefixing the score with a "(" character, so
* for instance:
* <p>
* {@code ZRANGEBYSCORE zset (1.3 5}
* <p>
* Will return all the values with score > 1.3 and <= 5, while for instance:
* <p>
* {@code ZRANGEBYSCORE zset (5 (10}
* <p>
* Will return all the values with score > 5 and < 10 (5 and 10 excluded).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and
* M the number of elements returned by the command, so if M is constant
* (for instance you always ask for the first ten elements with LIMIT) you
* can consider it O(log(N))
*
* @see #zrangeByScore(String, double, double)
* @see #zrangeByScore(String, double, double, int, int)
* @see #zrangeByScoreWithScores(String, double, double)
* @see #zrangeByScoreWithScores(String, double, double, int, int)
* @see #zcount(String, double, double)
*
* @param key
* @param min
* @param max
* @return Multi bulk reply specifically a list of elements in the specified
* score range.
*/
public Set<Tuple> zrangeByScoreWithScores(final String key,
final double min, final double max) {
checkIsInMulti();
client.zrangeByScoreWithScores(key, min, max);
Set<Tuple> set = getTupledSet();
return set;
}
/**
* Return the all the elements in the sorted set at key with a score between
* min and max (including elements with score equal to min or max).
* <p>
* The elements having the same score are returned sorted lexicographically
* as ASCII strings (this follows from a property of Redis sorted sets and
* does not involve further computation).
* <p>
* Using the optional
* {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's
* possible to get only a range of the matching elements in an SQL-alike
* way. Note that if offset is large the commands needs to traverse the list
* for offset elements and this adds up to the O(M) figure.
* <p>
* The {@link #zcount(String, double, double) ZCOUNT} command is similar to
* {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead
* of returning the actual elements in the specified interval, it just
* returns the number of matching elements.
* <p>
* <b>Exclusive intervals and infinity</b>
* <p>
* min and max can be -inf and +inf, so that you are not required to know
* what's the greatest or smallest element in order to take, for instance,
* elements "up to a given value".
* <p>
* Also while the interval is for default closed (inclusive) it's possible
* to specify open intervals prefixing the score with a "(" character, so
* for instance:
* <p>
* {@code ZRANGEBYSCORE zset (1.3 5}
* <p>
* Will return all the values with score > 1.3 and <= 5, while for instance:
* <p>
* {@code ZRANGEBYSCORE zset (5 (10}
* <p>
* Will return all the values with score > 5 and < 10 (5 and 10 excluded).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and
* M the number of elements returned by the command, so if M is constant
* (for instance you always ask for the first ten elements with LIMIT) you
* can consider it O(log(N))
*
* @see #zrangeByScore(String, double, double)
* @see #zrangeByScore(String, double, double, int, int)
* @see #zrangeByScoreWithScores(String, double, double)
* @see #zrangeByScoreWithScores(String, double, double, int, int)
* @see #zcount(String, double, double)
*
* @param key
* @param min
* @param max
* @return Multi bulk reply specifically a list of elements in the specified
* score range.
*/
public Set<Tuple> zrangeByScoreWithScores(final String key,
final double min, final double max, final int offset,
final int count) {
checkIsInMulti();
client.zrangeByScoreWithScores(key, min, max, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
private Set<Tuple> getTupledSet() {
checkIsInMulti();
List<String> membersWithScores = client.getMultiBulkReply();
Set<Tuple> set = new LinkedHashSet<Tuple>();
Iterator<String> iterator = membersWithScores.iterator();
while (iterator.hasNext()) {
set
.add(new Tuple(iterator.next(), Double.valueOf(iterator
.next())));
}
return set;
}
public Set<String> zrevrangeByScore(final String key, final double max,
final double min) {
checkIsInMulti();
client.zrevrangeByScore(key, max, min);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrevrangeByScore(final String key, final String max,
final String min) {
checkIsInMulti();
client.zrevrangeByScore(key, max, min);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrevrangeByScore(final String key, final double max,
final double min, final int offset, final int count) {
checkIsInMulti();
client.zrevrangeByScore(key, max, min, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final double max, final double min) {
checkIsInMulti();
client.zrevrangeByScoreWithScores(key, max, min);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final double max, final double min, final int offset,
final int count) {
checkIsInMulti();
client.zrevrangeByScoreWithScores(key, max, min, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
/**
* Remove all elements in the sorted set at key with rank between start and
* end. Start and end are 0-based with rank 0 being the element with the
* lowest score. Both start and end can be negative numbers, where they
* indicate offsets starting at the element with the highest rank. For
* example: -1 is the element with the highest score, -2 the element with
* the second highest score and so forth.
* <p>
* <b>Time complexity:</b> O(log(N))+O(M) with N being the number of
* elements in the sorted set and M the number of elements removed by the
* operation
*
*/
public Long zremrangeByRank(final String key, final int start, final int end) {
checkIsInMulti();
client.zremrangeByRank(key, start, end);
return client.getIntegerReply();
}
/**
* Remove all the elements in the sorted set at key with a score between min
* and max (including elements with score equal to min or max).
* <p>
* <b>Time complexity:</b>
* <p>
* O(log(N))+O(M) with N being the number of elements in the sorted set and
* M the number of elements removed by the operation
*
* @param key
* @param start
* @param end
* @return Integer reply, specifically the number of elements removed.
*/
public Long zremrangeByScore(final String key, final double start,
final double end) {
checkIsInMulti();
client.zremrangeByScore(key, start, end);
return client.getIntegerReply();
}
/**
* Creates a union or intersection of N sorted sets given by keys k1 through
* kN, and stores it at dstkey. It is mandatory to provide the number of
* input keys N, before passing the input keys and the other (optional)
* arguments.
* <p>
* As the terms imply, the {@link #zinterstore(String, String...)
* ZINTERSTORE} command requires an element to be present in each of the
* given inputs to be inserted in the result. The
* {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all
* elements across all inputs.
* <p>
* Using the WEIGHTS option, it is possible to add weight to each input
* sorted set. This means that the score of each element in the sorted set
* is first multiplied by this weight before being passed to the
* aggregation. When this option is not given, all weights default to 1.
* <p>
* With the AGGREGATE option, it's possible to specify how the results of
* the union or intersection are aggregated. This option defaults to SUM,
* where the score of an element is summed across the inputs where it
* exists. When this option is set to be either MIN or MAX, the resulting
* set will contain the minimum or maximum score of an element across the
* inputs where it exists.
* <p>
* <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the
* sizes of the input sorted sets, and M being the number of elements in the
* resulting sorted set
*
* @see #zunionstore(String, String...)
* @see #zunionstore(String, ZParams, String...)
* @see #zinterstore(String, String...)
* @see #zinterstore(String, ZParams, String...)
*
* @param dstkey
* @param sets
* @return Integer reply, specifically the number of elements in the sorted
* set at dstkey
*/
public Long zunionstore(final String dstkey, final String... sets) {
checkIsInMulti();
client.zunionstore(dstkey, sets);
return client.getIntegerReply();
}
/**
* Creates a union or intersection of N sorted sets given by keys k1 through
* kN, and stores it at dstkey. It is mandatory to provide the number of
* input keys N, before passing the input keys and the other (optional)
* arguments.
* <p>
* As the terms imply, the {@link #zinterstore(String, String...)
* ZINTERSTORE} command requires an element to be present in each of the
* given inputs to be inserted in the result. The
* {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all
* elements across all inputs.
* <p>
* Using the WEIGHTS option, it is possible to add weight to each input
* sorted set. This means that the score of each element in the sorted set
* is first multiplied by this weight before being passed to the
* aggregation. When this option is not given, all weights default to 1.
* <p>
* With the AGGREGATE option, it's possible to specify how the results of
* the union or intersection are aggregated. This option defaults to SUM,
* where the score of an element is summed across the inputs where it
* exists. When this option is set to be either MIN or MAX, the resulting
* set will contain the minimum or maximum score of an element across the
* inputs where it exists.
* <p>
* <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the
* sizes of the input sorted sets, and M being the number of elements in the
* resulting sorted set
*
* @see #zunionstore(String, String...)
* @see #zunionstore(String, ZParams, String...)
* @see #zinterstore(String, String...)
* @see #zinterstore(String, ZParams, String...)
*
* @param dstkey
* @param sets
* @param params
* @return Integer reply, specifically the number of elements in the sorted
* set at dstkey
*/
public Long zunionstore(final String dstkey, final ZParams params,
final String... sets) {
checkIsInMulti();
client.zunionstore(dstkey, params, sets);
return client.getIntegerReply();
}
/**
* Creates a union or intersection of N sorted sets given by keys k1 through
* kN, and stores it at dstkey. It is mandatory to provide the number of
* input keys N, before passing the input keys and the other (optional)
* arguments.
* <p>
* As the terms imply, the {@link #zinterstore(String, String...)
* ZINTERSTORE} command requires an element to be present in each of the
* given inputs to be inserted in the result. The
* {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all
* elements across all inputs.
* <p>
* Using the WEIGHTS option, it is possible to add weight to each input
* sorted set. This means that the score of each element in the sorted set
* is first multiplied by this weight before being passed to the
* aggregation. When this option is not given, all weights default to 1.
* <p>
* With the AGGREGATE option, it's possible to specify how the results of
* the union or intersection are aggregated. This option defaults to SUM,
* where the score of an element is summed across the inputs where it
* exists. When this option is set to be either MIN or MAX, the resulting
* set will contain the minimum or maximum score of an element across the
* inputs where it exists.
* <p>
* <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the
* sizes of the input sorted sets, and M being the number of elements in the
* resulting sorted set
*
* @see #zunionstore(String, String...)
* @see #zunionstore(String, ZParams, String...)
* @see #zinterstore(String, String...)
* @see #zinterstore(String, ZParams, String...)
*
* @param dstkey
* @param sets
* @return Integer reply, specifically the number of elements in the sorted
* set at dstkey
*/
public Long zinterstore(final String dstkey, final String... sets) {
checkIsInMulti();
client.zinterstore(dstkey, sets);
return client.getIntegerReply();
}
/**
* Creates a union or intersection of N sorted sets given by keys k1 through
* kN, and stores it at dstkey. It is mandatory to provide the number of
* input keys N, before passing the input keys and the other (optional)
* arguments.
* <p>
* As the terms imply, the {@link #zinterstore(String, String...)
* ZINTERSTORE} command requires an element to be present in each of the
* given inputs to be inserted in the result. The
* {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all
* elements across all inputs.
* <p>
* Using the WEIGHTS option, it is possible to add weight to each input
* sorted set. This means that the score of each element in the sorted set
* is first multiplied by this weight before being passed to the
* aggregation. When this option is not given, all weights default to 1.
* <p>
* With the AGGREGATE option, it's possible to specify how the results of
* the union or intersection are aggregated. This option defaults to SUM,
* where the score of an element is summed across the inputs where it
* exists. When this option is set to be either MIN or MAX, the resulting
* set will contain the minimum or maximum score of an element across the
* inputs where it exists.
* <p>
* <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the
* sizes of the input sorted sets, and M being the number of elements in the
* resulting sorted set
*
* @see #zunionstore(String, String...)
* @see #zunionstore(String, ZParams, String...)
* @see #zinterstore(String, String...)
* @see #zinterstore(String, ZParams, String...)
*
* @param dstkey
* @param sets
* @param params
* @return Integer reply, specifically the number of elements in the sorted
* set at dstkey
*/
public Long zinterstore(final String dstkey, final ZParams params,
final String... sets) {
checkIsInMulti();
client.zinterstore(dstkey, params, sets);
return client.getIntegerReply();
}
public Long strlen(final String key) {
client.strlen(key);
return client.getIntegerReply();
}
public Long lpushx(final String key, final String string) {
client.lpushx(key, string);
return client.getIntegerReply();
}
/**
* Undo a {@link #expire(String, int) expire} at turning the expire key into
* a normal key.
* <p>
* Time complexity: O(1)
*
* @param key
* @return Integer reply, specifically: 1: the key is now persist. 0: the
* key is not persist (only happens when key not set).
*/
public Long persist(final String key) {
client.persist(key);
return client.getIntegerReply();
}
public Long rpushx(final String key, final String string) {
client.rpushx(key, string);
return client.getIntegerReply();
}
public String echo(final String string) {
client.echo(string);
return client.getBulkReply();
}
public Long linsert(final String key, final LIST_POSITION where,
final String pivot, final String value) {
client.linsert(key, where, pivot, value);
return client.getIntegerReply();
}
/**
* Pop a value from a list, push it to another list and return it; or block
* until one is available
*
* @param source
* @param destination
* @param timeout
* @return the element
*/
public String brpoplpush(String source, String destination, int timeout) {
client.brpoplpush(source, destination, timeout);
client.setTimeoutInfinite();
String reply = client.getBulkReply();
client.rollbackTimeout();
return reply;
}
/**
* Sets or clears the bit at offset in the string value stored at key
*
* @param key
* @param offset
* @param value
* @return
*/
public Boolean setbit(String key, long offset, boolean value) {
client.setbit(key, offset, value);
return client.getIntegerReply() == 1;
}
/**
* Returns the bit value at offset in the string value stored at key
*
* @param key
* @param offset
* @return
*/
public Boolean getbit(String key, long offset) {
client.getbit(key, offset);
return client.getIntegerReply() == 1;
}
public Long setrange(String key, long offset, String value) {
client.setrange(key, offset, value);
return client.getIntegerReply();
}
public String getrange(String key, long startOffset, long endOffset) {
client.getrange(key, startOffset, endOffset);
return client.getBulkReply();
}
/**
* Retrieve the configuration of a running Redis server. Not all the
* configuration parameters are supported.
* <p>
* CONFIG GET returns the current configuration parameters. This sub command
* only accepts a single argument, that is glob style pattern. All the
* configuration parameters matching this parameter are reported as a list
* of key-value pairs.
* <p>
* <b>Example:</b>
*
* <pre>
* $ redis-cli config get '*'
* 1. "dbfilename"
* 2. "dump.rdb"
* 3. "requirepass"
* 4. (nil)
* 5. "masterauth"
* 6. (nil)
* 7. "maxmemory"
* 8. "0\n"
* 9. "appendfsync"
* 10. "everysec"
* 11. "save"
* 12. "3600 1 300 100 60 10000"
*
* $ redis-cli config get 'm*'
* 1. "masterauth"
* 2. (nil)
* 3. "maxmemory"
* 4. "0\n"
* </pre>
*
* @param pattern
* @return Bulk reply.
*/
public List<String> configGet(final String pattern) {
client.configGet(pattern);
return client.getMultiBulkReply();
}
/**
* Alter the configuration of a running Redis server. Not all the
* configuration parameters are supported.
* <p>
* The list of configuration parameters supported by CONFIG SET can be
* obtained issuing a {@link #configGet(String) CONFIG GET *} command.
* <p>
* The configuration set using CONFIG SET is immediately loaded by the Redis
* server that will start acting as specified starting from the next
* command.
* <p>
*
* <b>Parameters value format</b>
* <p>
* The value of the configuration parameter is the same as the one of the
* same parameter in the Redis configuration file, with the following
* exceptions:
* <p>
* <ul>
* <li>The save paramter is a list of space-separated integers. Every pair
* of integers specify the time and number of changes limit to trigger a
* save. For instance the command CONFIG SET save "3600 10 60 10000" will
* configure the server to issue a background saving of the RDB file every
* 3600 seconds if there are at least 10 changes in the dataset, and every
* 60 seconds if there are at least 10000 changes. To completely disable
* automatic snapshots just set the parameter as an empty string.
* <li>All the integer parameters representing memory are returned and
* accepted only using bytes as unit.
* </ul>
*
* @param parameter
* @param value
* @return Status code reply
*/
public String configSet(final String parameter, final String value) {
client.configSet(parameter, value);
return client.getStatusCodeReply();
}
public Object eval(String script, int keyCount, String... params) {
client.setTimeoutInfinite();
client.eval(script, keyCount, params);
return getEvalResult();
}
private String[] getParams(List<String> keys, List<String> args){
int keyCount = keys.size();
int argCount = args.size();
String[] params = new String[keyCount + args.size()];
for(int i=0;i<keyCount;i++)
params[i] = keys.get(i);
for(int i=0;i<argCount;i++)
params[keyCount + i] = args.get(i);
return params;
}
public Object eval(String script, List<String> keys, List<String> args) {
return eval(script, keys.size(), getParams(keys, args));
}
public Object eval(String script) {
return eval(script,0);
}
public Object evalsha(String script) {
return evalsha(script,0);
}
private Object getEvalResult(){
Object result = client.getOne();
if(result instanceof byte[])
return SafeEncoder.encode((byte[])result);
if(result instanceof List<?>) {
List<?> list = (List<?>)result;
List<String> listResult = new ArrayList<String>(list.size());
for(Object bin: list)
listResult.add(SafeEncoder.encode((byte[])bin));
return listResult;
}
return result;
}
public Object evalsha(String sha1, List<String> keys, List<String> args) {
return evalsha(sha1, keys.size(), getParams(keys, args));
}
public Object evalsha(String sha1, int keyCount, String... params) {
checkIsInMulti();
client.evalsha(sha1, keyCount, params);
return getEvalResult();
}
public Boolean scriptExists(String sha1){
String[] a = new String[1];
a[0] = sha1;
return scriptExists(a).get(0);
}
public List<Boolean> scriptExists(String... sha1){
client.scriptExists(sha1);
List<Long> result = client.getIntegerMultiBulkReply();
List<Boolean> exists = new ArrayList<Boolean>();
for(Long value : result)
exists.add(value == 1);
return exists;
}
public String scriptLoad(String script){
client.scriptLoad(script);
return client.getBulkReply();
}
}
|
package us.corenetwork.limbo;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
public class Logs
{
public static void debug(String text)
{
if (Settings.DEBUG.bool())
sendLog("&f[&3Limbo&f]&f "+text);
}
public static void info(String text)
{
sendLog("&f[&fLimbo&f]&f "+text);
}
public static void warning(String text)
{
sendLog("&f[&eLimbo&f]&f " + text);
}
public static void severe(String text)
{
sendLog("&f[&cLimbo&f]&f " + text);
}
public static void sendLog(String text)
{
Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', text));
}
}
|
package mondrian.xmla;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import mondrian.olap.*;
import mondrian.rolap.RolapCube;
import mondrian.util.SAXHandler;
import org.xml.sax.SAXException;
/**
* <code>RowsetDefinition</code> defines a rowset, including the columns it
* should contain.
*
* <p>See "XML for Analysis Rowsets", page 38 of the XML for Analysis
* Specification, version 1.1.
*/
abstract class RowsetDefinition extends EnumeratedValues.BasicValue {
final Column[] columnDefinitions;
private static final String nl = Util.nl;
/** Returns a list of XML for Analysis data sources
* available on the server or Web Service. (For an
* example of how these may be published, see
* "XML for Analysis Implementation Walkthrough"
* in the XML for Analysis specification.) */
public static final int DISCOVER_DATASOURCES = 0;
public static final int DISCOVER_PROPERTIES = 1;
public static final int DISCOVER_SCHEMA_ROWSETS = 2;
public static final int DISCOVER_ENUMERATORS = 3;
public static final int DISCOVER_KEYWORDS = 4;
public static final int DISCOVER_LITERALS = 5;
public static final int DBSCHEMA_CATALOGS = 6;
public static final int DBSCHEMA_COLUMNS = 7;
public static final int DBSCHEMA_PROVIDER_TYPES = 8;
public static final int DBSCHEMA_TABLES = 9;
public static final int DBSCHEMA_TABLES_INFO = 10;
public static final int MDSCHEMA_ACTIONS = 11;
public static final int MDSCHEMA_CUBES = 12;
public static final int MDSCHEMA_DIMENSIONS = 13;
public static final int MDSCHEMA_FUNCTIONS = 14;
public static final int MDSCHEMA_HIERARCHIES = 15;
public static final int MDSCHEMA_LEVELS = 16;
public static final int MDSCHEMA_MEASURES = 17;
public static final int MDSCHEMA_MEMBERS = 18;
public static final int MDSCHEMA_PROPERTIES = 19;
public static final int MDSCHEMA_SETS = 20;
public static final int OTHER = 21;
public static final EnumeratedValues enumeration = new EnumeratedValues(
new RowsetDefinition[] {
DiscoverDatasourcesRowset.definition,
DiscoverEnumeratorsRowset.definition,
DiscoverPropertiesRowset.definition,
DiscoverSchemaRowsetsRowset.definition,
DiscoverKeywordsRowset.definition,
DiscoverLiteralsRowset.definition,
DbschemaCatalogsRowset.definition,
DbschemaColumnsRowset.definition,
DbschemaProviderTypesRowset.definition,
DbschemaTablesRowset.definition,
DbschemaTablesInfoRowset.definition,
MdschemaActionsRowset.definition,
MdschemaCubesRowset.definition,
MdschemaDimensionsRowset.definition,
MdschemaFunctionsRowset.definition,
MdschemaHierarchiesRowset.definition,
MdschemaLevelsRowset.definition,
MdschemaMeasuresRowset.definition,
MdschemaMembersRowset.definition,
MdschemaPropertiesRowset.definition,
MdschemaSetsRowset.definition,
}
);
RowsetDefinition(String name, int ordinal, String description, Column[] columnDefinitions) {
super(name, ordinal, description);
this.columnDefinitions = columnDefinitions;
}
public static RowsetDefinition getValue(String name) {
return (RowsetDefinition) enumeration.getValue(name, true);
}
public abstract Rowset getRowset(HashMap restrictions, Properties properties);
public Column lookupColumn(String name) {
for (int i = 0; i < columnDefinitions.length; i++) {
Column columnDefinition = columnDefinitions[i];
if (columnDefinition.name.equals(name)) {
return columnDefinition;
}
}
return null;
}
static class Type extends EnumeratedValues.BasicValue {
public static final int String_ORDINAL = 0;
public static final Type String = new Type("string", String_ORDINAL, "string");
public static final int StringArray_ORDINAL = 1;
public static final Type StringArray = new Type("StringArray", StringArray_ORDINAL, "string");
public static final int Array_ORDINAL = 2;
public static final Type Array = new Type("Array", Array_ORDINAL, "string");
public static final int Enumeration_ORDINAL = 3;
public static final Type Enumeration = new Type("Enumeration", Enumeration_ORDINAL, "string");
public static final int EnumerationArray_ORDINAL = 4;
public static final Type EnumerationArray = new Type("EnumerationArray", EnumerationArray_ORDINAL, "string");
public static final int EnumString_ORDINAL = 5;
public static final Type EnumString = new Type("EnumString", EnumString_ORDINAL, "string");
public static final int Boolean_ORDINAL = 6;
public static final Type Boolean = new Type("Boolean", Boolean_ORDINAL, "boolean");
public static final int StringSometimesArray_ORDINAL = 7;
public static final Type StringSometimesArray = new Type("StringSometimesArray", StringSometimesArray_ORDINAL, "string");
public static final int Integer_ORDINAL = 8;
public static final Type Integer = new Type("Integer", Integer_ORDINAL, "integer");
public static final int UnsignedInteger_ORDINAL = 9;
public static final Type UnsignedInteger = new Type("UnsignedInteger", UnsignedInteger_ORDINAL, "unsignedInteger");
public final String columnType;
public Type(String name, int ordinal, String columnType) {
super(name, ordinal, null);
this.columnType = columnType;
}
public static final EnumeratedValues enumeration = new EnumeratedValues(
new Type[] {
String, StringArray, Array, Enumeration, EnumerationArray, EnumString,
});
boolean isEnum() {
switch (ordinal) {
case Enumeration_ORDINAL:
case EnumerationArray_ORDINAL:
case EnumString_ORDINAL:
return true;
}
return false;
}
}
static class Column {
final String name;
final Type type;
final Enumeration enumeration;
final String description;
final boolean restriction;
final boolean nullable;
/**
* Creates a column.
* @param name
* @param type A {@link Type} value
* @param enumeratedType Must be specified for enumeration or array
* of enumerations
* @param description
* @param restriction
* @param nullable
* @pre type != null
* @pre (type == Type.Enumeration || type == Type.EnumerationArray || type == Type.EnumString) == (enumeratedType != null)
*/
Column(String name, Type type, Enumeration enumeratedType,
boolean restriction, boolean nullable, String description) {
Util.assertPrecondition(type != null, "Type.instance.isValid(type)");
Util.assertPrecondition((type == Type.Enumeration || type == Type.EnumerationArray || type == Type.EnumString) == (enumeratedType != null), "(type == Type.Enumeration || type == Type.EnumerationArray || type == Type.EnumString) == (enumeratedType != null)");
this.name = name;
this.type = type;
this.enumeration = enumeratedType;
this.description = description;
this.restriction = restriction;
this.nullable = nullable;
}
/**
* Retrieves a value of this column from a row. The base implementation
* uses reflection; a derived class may provide a different
* implementation.
*/
Object get(Object row) {
try {
String javaFieldName = name.substring(0, 1).toLowerCase() + name.substring(1);
Field field = row.getClass().getField(javaFieldName);
return field.get(row);
} catch (NoSuchFieldException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
} catch (SecurityException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
} catch (IllegalAccessException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
}
}
public String getColumnType() {
if (type.isEnum()) {
return enumeration.type.columnType;
}
return type.columnType;
}
}
// From this point on, just rowset classess.
static class DiscoverDatasourcesRowset extends Rowset {
private static final Column DataSourceName = new Column("DataSourceName", Type.String, null, true, false,
"The name of the data source, such as FoodMart 2000.");
private static final Column DataSourceDescription = new Column("DataSourceDescription", Type.String, null, false, true,
"A description of the data source, as entered by the publisher.");
private static final Column URL = new Column("URL", Type.String, null, true, true,
"The unique path that shows where to invoke the XML for Analysis methods for that data source.");
private static final Column DataSourceInfo = new Column("DataSourceInfo", Type.String, null, false, true,
"A string containing any additional information required to connect to the data source. This can include the Initial Catalog property or other information for the provider." + nl +
"Example: \"Provider=MSOLAP;Data Source=Local;\"");
private static final Column ProviderName = new Column("ProviderName", Type.String, null, true, true,
"The name of the provider behind the data source. " + nl +
"Example: \"MSDASQL\"");
private static final Column ProviderType = new Column("ProviderType", Type.EnumerationArray, Enumeration.ProviderType.enumeration, true, false,
"The types of data supported by the provider. May include one or more of the following types. Example follows this table." + nl +
"TDP: tabular data provider." + nl +
"MDP: multidimensional data provider." + nl +
"DMP: data mining provider. A DMP provider implements the OLE DB for Data Mining specification.");
private static final Column AuthenticationMode = new Column("AuthenticationMode", Type.EnumString, Enumeration.AuthenticationMode.enumeration, true, false,
"Specification of what type of security mode the data source uses. Values can be one of the following:" + nl +
"Unauthenticated: no user ID or password needs to be sent." + nl +
"Authenticated: User ID and Password must be included in the information required for the connection." + nl +
"Integrated: the data source uses the underlying security to determine authorization, such as Integrated Security provided by Microsoft Internet Information Services (IIS).");
static final RowsetDefinition definition = new RowsetDefinition(
"DISCOVER_DATASOURCES", DISCOVER_DATASOURCES,
"Returns a list of XML for Analysis data sources available on the server or Web Service.",
new Column[] {
DataSourceName,
DataSourceDescription,
URL,
DataSourceInfo,
ProviderName,
ProviderType,
AuthenticationMode,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DiscoverDatasourcesRowset(restrictions, properties);
}
};
public DiscoverDatasourcesRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
public void unparse(SAXHandler saxHandler) throws SAXException {
for (Iterator it = XmlaMediator.dataSourcesMap.values().iterator(); it.hasNext();) {
DataSourcesConfig.DataSource ds = (DataSourcesConfig.DataSource)it.next();
Row row = new Row();
row.set(DataSourceName.name, ds.getDataSourceName());
row.set(DataSourceDescription.name, ds.getDataSourceDescription());
row.set(URL.name, ds.getURL());
row.set(DataSourceInfo.name, ds.getDataSourceName());
row.set(ProviderName.name, ds.getProviderName());
row.set(ProviderType.name, ds.getProviderType());
row.set(AuthenticationMode.name, ds.getAuthenticationMode());
emit(row, saxHandler);
}
}
}
static class DiscoverSchemaRowsetsRowset extends Rowset {
private static final Column SchemaName = new Column("SchemaName", Type.StringArray, null, true, false, "The name of the schema/request. This returns the values in the RequestTypes enumeration, plus any additional types supported by the provider. The provider defines rowset structures for the additional types");
private static final Column Restrictions = new Column("Restrictions", Type.Array,null, false, true, "An array of the restrictions suppoted by provider. An example follows this table.");
private static final Column Description = new Column("Description", Type.String, null, false, true, "A localizable description of the schema");
private static RowsetDefinition definition = new RowsetDefinition(
"DISCOVER_SCHEMA_ROWSETS", DISCOVER_SCHEMA_ROWSETS,
"Returns the names, values, and other information of all supported RequestType enumeration values.",
new Column[] {
SchemaName,
Restrictions,
Description,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DiscoverSchemaRowsetsRowset(restrictions, properties);
}
};
public DiscoverSchemaRowsetsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
public void unparse(SAXHandler saxHandler) throws SAXException {
final RowsetDefinition[] rowsetDefinitions = (RowsetDefinition[])
enumeration.getValuesSortedByName().
toArray(new RowsetDefinition[0]);
for (int i = 0; i < rowsetDefinitions.length; i++) {
RowsetDefinition rowsetDefinition = rowsetDefinitions[i];
Row row = new Row();
row.set(SchemaName.name, rowsetDefinition.name);
row.set(Restrictions.name, getRestrictions(rowsetDefinition));
row.set(Description.name, rowsetDefinition.description);
emit(row, saxHandler);
}
}
private Rowset.XmlElement[] getRestrictions(RowsetDefinition rowsetDefinition) {
ArrayList restrictionList = new ArrayList();
final Column[] columns = rowsetDefinition.columnDefinitions;
for (int j = 0; j < columns.length; j++) {
Column column = columns[j];
if (column.restriction) {
restrictionList.add(
new Rowset.XmlElement(Restrictions.name, null, new Rowset.XmlElement[] {
new Rowset.XmlElement("Name", null, column.name),
new Rowset.XmlElement("Type", null, column.getColumnType())
}));
}
}
final Rowset.XmlElement[] restrictions = (Rowset.XmlElement[])
restrictionList.toArray(
new Rowset.XmlElement[restrictionList.size()]);
return restrictions;
}
}
static class DiscoverPropertiesRowset extends Rowset {
DiscoverPropertiesRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column PropertyName = new Column("PropertyName", Type.StringSometimesArray, null, true, false,
"The name of the property.");
private static final Column PropertyDescription = new Column("PropertyDescription", Type.String, null, false, true,
"A localizable text description of the property.");
private static final Column PropertyType = new Column("PropertyType", Type.String, null, false, true,
"The XML data type of the property.");
private static final Column PropertyAccessType = new Column("PropertyAccessType", Type.EnumString, Enumeration.Access.enumeration, false, false,
"Access for the property. The value can be Read, Write, or ReadWrite.");
private static final Column IsRequired = new Column("IsRequired", Type.Boolean, null, false, true,
"True if a property is required, false if it is not required.");
private static final Column Value = new Column("Value", Type.String, null, false, true,
"The current value of the property.");
public static final RowsetDefinition definition = new RowsetDefinition(
"DISCOVER_PROPERTIES", DISCOVER_PROPERTIES,
"Returns a list of information and values about the requested properties that are supported by the specified data source provider.",
new Column[] {
PropertyName,
PropertyDescription,
PropertyType,
PropertyAccessType,
IsRequired,
Value,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DiscoverPropertiesRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
final String[] propertyNames = PropertyDefinition.enumeration.getNames();
for (int i = 0; i < propertyNames.length; i++) {
PropertyDefinition propertyDefinition = PropertyDefinition.getValue(propertyNames[i]);
Row row = new Row();
row.set(PropertyName.name, propertyDefinition.name);
row.set(PropertyDescription.name, propertyDefinition.description);
row.set(PropertyType.name, propertyDefinition.type);
row.set(PropertyAccessType.name, propertyDefinition.access);
//row.set(IsRequired.name, false);
//row.set(Value.name, null);
emit(row, saxHandler);
}
}
}
static class DiscoverEnumeratorsRowset extends Rowset {
DiscoverEnumeratorsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column EnumName = new Column("EnumName", Type.StringArray, null, true, false,
"The name of the enumerator that contains a set of values.");
private static final Column EnumDescription = new Column("EnumDescription", Type.String, null, false, true,
"A localizable description of the enumerator.");
private static final Column EnumType = new Column("EnumType", Type.String, null, false, false,
"The data type of the Enum values.");
private static final Column ElementName = new Column("ElementName", Type.String, null, false, false,
"The name of one of the value elements in the enumerator set." + nl +
"Example: TDP");
private static final Column ElementDescription = new Column("ElementDescription", Type.String, null, false, true,
"A localizable description of the element (optional).");
private static final Column ElementValue = new Column("ElementValue", Type.String, null, false, true, "The value of the element." + nl +
"Example: 01");
public static final RowsetDefinition definition = new RowsetDefinition(
"DISCOVER_ENUMERATORS", DISCOVER_ENUMERATORS,
"Returns a list of names, data types, and enumeration values for enumerators supported by the provider of a specific data source.",
new Column[] {
EnumName,
EnumDescription,
EnumType,
ElementName,
ElementDescription,
ElementValue,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DiscoverEnumeratorsRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
Enumeration[] enumerators = getEnumerators();
for (int i = 0; i < enumerators.length; i++) {
Enumeration enumerator = enumerators[i];
final String[] valueNames = enumerator.getNames();
for (int j = 0; j < valueNames.length; j++) {
String valueName = valueNames[j];
final EnumeratedValues.Value value = enumerator.getValue(valueName, true);
Row row = new Row();
row.set(EnumName.name, enumerator.name);
row.set(EnumDescription.name, enumerator.description);
row.set(EnumType.name, enumerator.type);
row.set(ElementName.name, value.getName());
row.set(ElementDescription.name, value.getDescription());
switch (enumerator.type.ordinal) {
case RowsetDefinition.Type.String_ORDINAL:
case RowsetDefinition.Type.StringArray_ORDINAL:
// these don't have ordinals
break;
default:
row.set(ElementValue.name, value.getOrdinal());
break;
}
emit(row, saxHandler);
}
}
}
private static Enumeration[] getEnumerators() {
HashSet enumeratorSet = new HashSet();
final String[] rowsetNames = RowsetDefinition.enumeration.getNames();
for (int i = 0; i < rowsetNames.length; i++) {
String rowsetName = rowsetNames[i];
final RowsetDefinition rowsetDefinition = (RowsetDefinition)
RowsetDefinition.enumeration.getValue(rowsetName, true);
for (int j = 0; j < rowsetDefinition.columnDefinitions.length; j++) {
Column column = rowsetDefinition.columnDefinitions[j];
if (column.enumeration != null) {
enumeratorSet.add(column.enumeration);
}
}
}
final Enumeration[] enumerators = (Enumeration[])
enumeratorSet.toArray(new Enumeration[enumeratorSet.size()]);
Arrays.sort(enumerators, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Enumeration) o1).name.compareTo(
((Enumeration) o2).name);
}
});
return enumerators;
}
}
static class DiscoverKeywordsRowset extends Rowset {
DiscoverKeywordsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column Keyword = new Column("Keyword", Type.StringSometimesArray, null, true, false,
"A list of all the keywords reserved by a provider." + nl +
"Example: AND");
public static final RowsetDefinition definition = new RowsetDefinition(
"DISCOVER_KEYWORDS", DISCOVER_KEYWORDS,
"Returns an XML list of keywords reserved by the provider.",
new Column[] {
Keyword,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DiscoverKeywordsRowset(restrictions, properties);
}
};
private static final String[] keywords = new String[] {
"$AdjustedProbability", "$Distance", "$Probability",
"$ProbabilityStDev", "$ProbabilityStdDeV", "$ProbabilityVariance",
"$StDev", "$StdDeV", "$Support", "$Variance",
"AddCalculatedMembers", "Action", "After", "Aggregate", "All",
"Alter", "Ancestor", "And", "Append", "As", "ASC", "Axis",
"Automatic", "Back_Color", "BASC", "BDESC", "Before",
"Before_And_After", "Before_And_Self", "Before_Self_After",
"BottomCount", "BottomPercent", "BottomSum", "Break", "Boolean",
"Cache", "Calculated", "Call", "Case", "Catalog_Name", "Cell",
"Cell_Ordinal", "Cells", "Chapters", "Children",
"Children_Cardinality", "ClosingPeriod", "Cluster",
"ClusterDistance", "ClusterProbability", "Clusters",
"CoalesceEmpty", "Column_Values", "Columns", "Content",
"Contingent", "Continuous", "Correlation", "Cousin", "Covariance",
"CovarianceN", "Create", "CreatePropertySet", "CrossJoin", "Cube",
"Cube_Name", "CurrentMember", "CurrentCube", "Custom", "Cyclical",
"DefaultMember", "Default_Member", "DESC", "Descendents",
"Description", "Dimension", "Dimension_Unique_Name", "Dimensions",
"Discrete", "Discretized", "DrillDownLevel",
"DrillDownLevelBottom", "DrillDownLevelTop", "DrillDownMember",
"DrillDownMemberBottom", "DrillDownMemberTop", "DrillTrough",
"DrillUpLevel", "DrillUpMember", "Drop", "Else", "Empty", "End",
"Equal_Areas", "Exclude_Null", "ExcludeEmpty", "Exclusive",
"Expression", "Filter", "FirstChild", "FirstRowset",
"FirstSibling", "Flattened", "Font_Flags", "Font_Name",
"Font_size", "Fore_Color", "Format_String", "Formatted_Value",
"Formula", "From", "Generate", "Global", "Head", "Hierarchize",
"Hierarchy", "Hierary_Unique_name", "IIF", "IsEmpty",
"Include_Null", "Include_Statistics", "Inclusive", "Input_Only",
"IsDescendant", "Item", "Lag", "LastChild", "LastPeriods",
"LastSibling", "Lead", "Level", "Level_Unique_Name", "Levels",
"LinRegIntercept", "LinRegR2", "LinRegPoint", "LinRegSlope",
"LinRegVariance", "Long", "MaxRows", "Median", "Member",
"Member_Caption", "Member_Guid", "Member_Name", "Member_Ordinal",
"Member_Type", "Member_Unique_Name", "Members",
"Microsoft_Clustering", "Microsoft_Decision_Trees", "Mining",
"Model", "Model_Existence_Only", "Models", "Move", "MTD", "Name",
"Nest", "NextMember", "Non", "Normal", "Not", "Ntext", "Nvarchar",
"OLAP", "On", "OpeningPeriod", "OpenQuery", "Or", "Ordered",
"Ordinal", "Pages", "Pages", "ParallelPeriod", "Parent",
"Parent_Level", "Parent_Unique_Name", "PeriodsToDate", "PMML",
"Predict", "Predict_Only", "PredictAdjustedProbability",
"PredictHistogram", "Prediction", "PredictionScore",
"PredictProbability", "PredictProbabilityStDev",
"PredictProbabilityVariance", "PredictStDev", "PredictSupport",
"PredictVariance", "PrevMember", "Probability",
"Probability_StDev", "Probability_StdDev", "Probability_Variance",
"Properties", "Property", "QTD", "RangeMax", "RangeMid",
"RangeMin", "Rank", "Recursive", "Refresh", "Related", "Rename",
"Rollup", "Rows", "Schema_Name", "Sections", "Select", "Self",
"Self_And_After", "Sequence_Time", "Server", "Session", "Set",
"SetToArray", "SetToStr", "Shape", "Skip", "Solve_Order", "Sort",
"StdDev", "Stdev", "StripCalculatedMembers", "StrToSet",
"StrToTuple", "SubSet", "Support", "Tail", "Text", "Thresholds",
"ToggleDrillState", "TopCount", "TopPercent", "TopSum",
"TupleToStr", "Under", "Uniform", "UniqueName", "Use", "Value",
"Value", "Var", "Variance", "VarP", "VarianceP", "VisualTotals",
"When", "Where", "With", "WTD", "Xor",
};
public void unparse(SAXHandler saxHandler) throws SAXException {
for (int i = 0; i < keywords.length; i++) {
String keyword = keywords[i];
Row row = new Row();
row.set(Keyword.name, keyword);
emit(row, saxHandler);
}
}
}
static class DiscoverLiteralsRowset extends Rowset {
DiscoverLiteralsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
public static final RowsetDefinition definition = new RowsetDefinition(
"DISCOVER_LITERALS", DISCOVER_LITERALS,
"Returns information about literals supported by the provider.",
new Column[] {
new Column("LiteralName", Type.StringSometimesArray, null, true, false,
"The name of the literal described in the row." + nl +
"Example: DBLITERAL_LIKE_PERCENT"),
new Column("LiteralValue", Type.String, null, false, true,
"Contains the actual literal value." + nl +
"Example, if LiteralName is DBLITERAL_LIKE_PERCENT and the percent character (%) is used to match zero or more characters in a LIKE clause, this column's value would be \"%\"."),
new Column("LiteralInvalidChars", Type.String, null, false, true,
"The characters, in the literal, that are not valid." + nl +
"For example, if table names can contain anything other than a numeric character, this string would be \"0123456789\"."),
new Column("LiteralInvalidStartingChars", Type.String, null, false, true,
"The characters that are not valid as the first character of the literal. If the literal can start with any valid character, this is null."),
new Column("LiteralMaxLength", Type.Integer, null, false, true,
"The maximum number of characters in the literal. If there is no maximum or the maximum is unknown, the value is ?1."),
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DiscoverLiteralsRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
emit(Enumeration.Literal.enumeration, saxHandler);
}
}
static class DbschemaCatalogsRowset extends Rowset {
DbschemaCatalogsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, false, "Catalog name. Cannot be NULL.");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, false, true, "Human-readable description of the catalog.");
public static final RowsetDefinition definition = new RowsetDefinition(
"DBSCHEMA_CATALOGS", DBSCHEMA_CATALOGS,
"Returns information about literals supported by the provider.",
new Column[] {
CatalogName,
Description,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DbschemaCatalogsRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
Connection connection = XmlaMediator.getConnection(properties);
if (connection == null) {
return;
}
Row row = new Row();
final Schema schema = connection.getSchema();
row.set(CatalogName.name, schema.getName());
emit(row, saxHandler);
}
}
static class DbschemaColumnsRowset extends Rowset {
DbschemaColumnsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column TableCatalog = new Column("TABLE_CATALOG", Type.String, null, true, false, null);
private static final Column TableSchema = new Column("TABLE_SCHEMA", Type.String, null, true, false, null);
private static final Column TableName = new Column("TABLE_NAME", Type.String, null, true, false, null);
private static final Column ColumnName = new Column("COLUMN_NAME", Type.String, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"DBSCHEMA_COLUMNS", DBSCHEMA_COLUMNS, null, new Column[] {
TableCatalog,
TableSchema,
TableName,
ColumnName,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DbschemaColumnsRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
//TODO
throw new UnsupportedOperationException();
}
}
static class DbschemaProviderTypesRowset extends Rowset {
DbschemaProviderTypesRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column DataType = new Column("DATA_TYPE", Type.UnsignedInteger, null, true, false, null);
private static final Column BestMatch = new Column("BEST_MATCH", Type.Boolean, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"DBSCHEMA_PROVIDER_TYPES", DBSCHEMA_PROVIDER_TYPES, null, new Column[] {
DataType,
BestMatch,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DbschemaProviderTypesRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
//TODO
throw new UnsupportedOperationException();
}
}
static class DbschemaTablesRowset extends Rowset {
DbschemaTablesRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column TableCatalog = new Column("TABLE_CATALOG", Type.String, null, true, false, null);
private static final Column TableSchema = new Column("TABLE_SCHEMA", Type.String, null, true, false, null);
private static final Column TableName = new Column("TABLE_NAME", Type.String, null, true, false, null);
private static final Column TableType = new Column("TABLE_TYPE", Type.String, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"DBSCHEMA_TABLES", DBSCHEMA_TABLES, null, new Column[] {
TableCatalog,
TableSchema,
TableName,
TableType,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DbschemaTablesRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
//TODO
throw new UnsupportedOperationException();
}
}
static class DbschemaTablesInfoRowset extends Rowset {
DbschemaTablesInfoRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column TableCatalog = new Column("TABLE_CATALOG", Type.String, null, true, false, null);
private static final Column TableSchema = new Column("TABLE_SCHEMA", Type.String, null, true, false, null);
private static final Column TableName = new Column("TABLE_NAME", Type.String, null, true, false, null);
private static final Column TableType = new Column("TABLE_TYPE", Type.String, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"DBSCHEMA_TABLES_INFO", DBSCHEMA_TABLES_INFO, null, new Column[] {
TableCatalog,
TableSchema,
TableName,
TableType,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new DbschemaTablesInfoRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
//TODO
throw new UnsupportedOperationException();
}
}
static class MdschemaActionsRowset extends Rowset {
MdschemaActionsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column Coordinate = new Column("COORDINATE", Type.String, null, true, false, null);
private static final Column CoordinateType = new Column("COORDINATE_TYPE", Type.String, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_ACTIONS", MDSCHEMA_ACTIONS, null, new Column[] {
CubeName,
Coordinate,
CoordinateType,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaActionsRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
//TODO
throw new UnsupportedOperationException();
}
}
static class MdschemaCubesRowset extends Rowset {
MdschemaCubesRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final String MD_CUBTYPE_CUBE = "CUBE";
private static final String MD_CUBTYPE_VIRTUAL_CUBE = "VIRTUAL CUBE";
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, false, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column CubeType = new Column("CUBE_TYPE", Type.String, null, true, false, "Cube type.");
private static final Column IsDrillthroughEnabled = new Column("IS_DRILLTHROUGH_ENABLED", Type.Boolean, null, false, false,
"Describes whether DRILLTHROUGH can be performed on the members of a cube");
private static final Column IsWriteEnabled = new Column("IS_WRITE_ENABLED", Type.Boolean, null, false, false,
"Describes whether a cube is write-enabled");
private static final Column IsLinkable = new Column("IS_LINKABLE", Type.Boolean, null, false, false,
"Describes whether a cube can be used in a linked cube");
private static final Column IsSqlAllowed = new Column("IS_SQL_ALLOWED", Type.Boolean, null, false, false,
"Describes whether or not SQL can be used on the cube");
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_CUBES", MDSCHEMA_CUBES, null, new Column[] {
CatalogName,
SchemaName,
CubeName,
CubeType,
IsDrillthroughEnabled,
IsWriteEnabled,
IsLinkable,
IsSqlAllowed,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaCubesRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
final Connection connection = XmlaMediator.getConnection(properties);
final Cube[] cubes = connection.getSchema().getCubes();
for (int i = 0; i < cubes.length; i++) {
Cube cube = cubes[i];
Row row = new Row();
row.set(CatalogName.name, cube.getSchema().getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(CubeType.name, ((RolapCube)cube).isVirtual() ? MD_CUBTYPE_VIRTUAL_CUBE : MD_CUBTYPE_CUBE);
row.set(IsDrillthroughEnabled.name, true);
row.set(IsWriteEnabled.name, false);
row.set(IsLinkable.name, false);
row.set(IsSqlAllowed.name, false);
emit(row, saxHandler);
}
}
}
static class MdschemaDimensionsRowset extends Rowset {
MdschemaDimensionsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
public static final int MD_DIMTYPE_OTHER = 3;
public static final int MD_DIMTYPE_MEASURE = 2;
public static final int MD_DIMTYPE_TIME = 1;
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, false, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column DimensionName = new Column("DIMENSION_NAME", Type.String, null, true, false, null);
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column DimensionCaption = new Column("DIMENSION_CAPTION", Type.String, null, true, false, null);
private static final Column DimensionOrdinal = new Column("DIMENSION_ORDINAL", Type.Integer, null, true, false, null);
private static final Column DimensionType = new Column("DIMENSION_TYPE", Type.Integer, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_DIMENSIONS", MDSCHEMA_DIMENSIONS, null, new Column[] {
CatalogName,
SchemaName,
CubeName,
DimensionName,
DimensionUniqueName,
DimensionCaption,
DimensionOrdinal,
DimensionType,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaDimensionsRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
final Connection connection = XmlaMediator.getConnection(properties);
final Cube[] cubes = connection.getSchema().getCubes();
for (int i = 0; i < cubes.length; i++) {
Cube cube = cubes[i];
final Dimension[] dimensions = cube.getDimensions();
for (int j = 0; j < dimensions.length; j++) {
Dimension dimension = dimensions[j];
Row row = new Row();
row.set(CatalogName.name, cube.getSchema().getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionName.name, dimension.getName());
row.set(DimensionUniqueName.name, dimension.getUniqueName());
row.set(DimensionCaption.name, dimension.getCaption());
row.set(DimensionOrdinal.name, dimension.getOrdinal(cube));
row.set(DimensionType.name, getDimensionType(dimension));
emit(row, saxHandler);
}
}
}
}
static int getDimensionType(Dimension dim) {
if (dim.isMeasures())
return MdschemaDimensionsRowset.MD_DIMTYPE_MEASURE;
else if (mondrian.olap.DimensionType.TimeDimension.equals(dim.getDimensionType())) {
return MdschemaDimensionsRowset.MD_DIMTYPE_TIME;
} else {
return MdschemaDimensionsRowset.MD_DIMTYPE_OTHER;
}
}
static class MdschemaFunctionsRowset extends Rowset {
MdschemaFunctionsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column LibraryName = new Column("LIBRARY_NAME", Type.String, null, true, true, null);
private static final Column InterfaceName = new Column("INTERFACE_NAME", Type.String, null, true, true, null);
private static final Column FunctionName = new Column("FUNCTION_NAME", Type.String, null, true, true, null);
private static final Column Origin = new Column("ORIGIN", Type.Integer, null, true, true, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_FUNCTIONS", MDSCHEMA_FUNCTIONS, null, new Column[] {
LibraryName,
InterfaceName,
FunctionName,
Origin,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaFunctionsRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
//TODO
throw new UnsupportedOperationException();
}
}
static class MdschemaHierarchiesRowset extends Rowset {
MdschemaHierarchiesRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, false, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column HierarchyName = new Column("HIERARCHY_NAME", Type.String, null, true, false, null);
private static final Column HierarchyUniqueName = new Column("HIERARCHY_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column HierarchyCaption = new Column("HIERARCHY_CAPTION", Type.String, null, true, false, null);
private static final Column DimensionType = new Column("DIMENSION_TYPE", Type.Integer, null, true, false, null);
private static final Column DefaultMember = new Column("DEFAULT_MEMBER", Type.String, null, true, true, null);
private static final Column AllMember = new Column("ALL_MEMBER", Type.String, null, true, true, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_HIERARCHIES", MDSCHEMA_HIERARCHIES, null, new Column[] {
CatalogName,
SchemaName,
CubeName,
DimensionUniqueName,
HierarchyName,
HierarchyUniqueName,
HierarchyCaption,
DimensionType,
DefaultMember,
AllMember,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaHierarchiesRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
final Connection connection = XmlaMediator.getConnection(properties);
final Cube[] cubes = connection.getSchema().getCubes();
for (int i = 0; i < cubes.length; i++) {
Cube cube = cubes[i];
final Dimension[] dimensions = cube.getDimensions();
for (int j = 0; j < dimensions.length; j++) {
Dimension dimension = dimensions[j];
final Hierarchy[] hierarchies = dimension.getHierarchies();
for (int k = 0; k < hierarchies.length; k++) {
HierarchyBase hierarchy = (HierarchyBase)hierarchies[k];
Row row = new Row();
row.set(CatalogName.name, cube.getSchema().getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionUniqueName.name, dimension.getUniqueName());
row.set(HierarchyName.name, hierarchy.getName());
row.set(HierarchyUniqueName.name, hierarchy.getUniqueName());
row.set(HierarchyCaption.name, hierarchy.getCaption());
row.set(DimensionType.name, getDimensionType(dimension));
row.set(DefaultMember.name, hierarchy.getDefaultMember());
if (hierarchy.hasAll()) {
row.set(AllMember.name, Util.implode(new String[] {
hierarchy.getName(),
hierarchy.getAllMemberName()}));
}
emit(row, saxHandler);
}
}
}
}
}
static class MdschemaLevelsRowset extends Rowset {
MdschemaLevelsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
public static final int MDLEVEL_TYPE_UNKNOWN = 0x0000;
public static final int MDLEVEL_TYPE_REGULAR = 0x0000;
public static final int MDLEVEL_TYPE_ALL = 0x0001;
public static final int MDLEVEL_TYPE_CALCULATED = 0x0002;
public static final int MDLEVEL_TYPE_TIME = 0x0004;
public static final int MDLEVEL_TYPE_RESERVED1 = 0x0008;
public static final int MDLEVEL_TYPE_TIME_YEARS = 0x0014;
public static final int MDLEVEL_TYPE_TIME_HALF_YEAR = 0x0024;
public static final int MDLEVEL_TYPE_TIME_QUARTERS = 0x0044;
public static final int MDLEVEL_TYPE_TIME_MONTHS = 0x0084;
public static final int MDLEVEL_TYPE_TIME_WEEKS = 0x0104;
public static final int MDLEVEL_TYPE_TIME_DAYS = 0x0204;
public static final int MDLEVEL_TYPE_TIME_HOURS = 0x0304;
public static final int MDLEVEL_TYPE_TIME_MINUTES = 0x0404;
public static final int MDLEVEL_TYPE_TIME_SECONDS = 0x0804;
public static final int MDLEVEL_TYPE_TIME_UNDEFINED = 0x1004;
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, false, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column HierarchyUniqueName = new Column("HIERARCHY_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column LevelName = new Column("LEVEL_NAME", Type.String, null, true, false, null);
private static final Column LevelUniqueName = new Column("LEVEL_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column LevelCaption = new Column("LEVEL_CAPTION", Type.String, null, true, false, null);
private static final Column LevelNumber = new Column("LEVEL_NUMBER", Type.Integer, null, true, false, null);
private static final Column LevelType = new Column("LEVEL_TYPE", Type.Integer, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_LEVELS", MDSCHEMA_LEVELS, null, new Column[] {
CatalogName,
SchemaName,
CubeName,
DimensionUniqueName,
HierarchyUniqueName,
LevelName,
LevelUniqueName,
LevelCaption,
LevelNumber,
LevelType,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaLevelsRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
final Connection connection = XmlaMediator.getConnection(properties);
final Cube[] cubes = connection.getSchema().getCubes();
for (int i = 0; i < cubes.length; i++) {
Cube cube = cubes[i];
final Dimension[] dimensions = cube.getDimensions();
for (int j = 0; j < dimensions.length; j++) {
Dimension dimension = dimensions[j];
final Hierarchy[] hierarchies = dimension.getHierarchies();
for (int k = 0; k < hierarchies.length; k++) {
Hierarchy hierarchy = hierarchies[k];
final Level[] levels = hierarchy.getLevels();
for (int m = 0; m < levels.length; m++) {
Level level = levels[m];
Row row = new Row();
row.set(CatalogName.name, cube.getSchema().getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionUniqueName.name, dimension.getUniqueName());
row.set(HierarchyUniqueName.name, hierarchy.getUniqueName());
row.set(LevelName.name, level.getName());
row.set(LevelUniqueName.name, level.getUniqueName());
row.set(LevelCaption.name, level.getCaption());
row.set(LevelNumber.name, level.getDepth()); // see notes on this #getDepth()
row.set(LevelType.name, getLevelType(level));
emit(row, saxHandler);
}
}
}
}
}
private int getLevelType(Level lev) {
if (lev.isAll()) {
return MDLEVEL_TYPE_ALL;
} else {
mondrian.olap.LevelType type = lev.getLevelType();
switch(type.getOrdinal()) {
case mondrian.olap.LevelType.RegularORDINAL:
return MDLEVEL_TYPE_REGULAR;
case mondrian.olap.LevelType.TimeDaysORDINAL:
return MDLEVEL_TYPE_TIME_DAYS;
case mondrian.olap.LevelType.TimeMonthsORDINAL:
return MDLEVEL_TYPE_TIME_MONTHS;
case mondrian.olap.LevelType.TimeQuartersORDINAL:
return MDLEVEL_TYPE_TIME_QUARTERS;
case mondrian.olap.LevelType.TimeWeeksORDINAL:
return MDLEVEL_TYPE_TIME_WEEKS;
case mondrian.olap.LevelType.TimeYearsORDINAL:
return MDLEVEL_TYPE_TIME_YEARS;
default:
return MDLEVEL_TYPE_UNKNOWN;
}
}
}
}
static class MdschemaMeasuresRowset extends Rowset {
MdschemaMeasuresRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, false, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column MeasureName = new Column("MEASURE_NAME", Type.String, null, true, false, null);
private static final Column MeasureUniqueName = new Column("MEASURE_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column MeasureCaption = new Column("MEASURE_CAPTION", Type.String, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_MEASURES", MDSCHEMA_MEASURES, null, new Column[] {
CatalogName,
SchemaName,
CubeName,
MeasureName,
MeasureUniqueName,
MeasureCaption,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaMeasuresRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
// return both stored and calculated members on hierarchy [Measures]
final Connection connection = XmlaMediator.getConnection(properties);
final Role role = connection.getRole();
final Cube[] cubes = connection.getSchema().getCubes();
for (int i = 0; i < cubes.length; i++) {
Cube cube = cubes[i];
SchemaReader schemaReader = cube.getSchemaReader(role);
final Dimension measuresDimension = cube.getDimensions()[0];
final Hierarchy measuresHierarchy = measuresDimension.getHierarchies()[0];
Member[] storedMembers = schemaReader.getLevelMembers(measuresHierarchy.getLevels()[0]);
for (int j = 0; j < storedMembers.length; j++) {
emitMember(saxHandler, storedMembers[j], cube);
}
List calculatedMembers = schemaReader.getCalculatedMembers(measuresHierarchy);
for (Iterator it = calculatedMembers.iterator(); it.hasNext();){
emitMember(saxHandler, (Member)it.next(), cube);
}
}
}
private void emitMember(SAXHandler saxHandler, Member member, Cube cube) throws SAXException {
Row row = new Row();
row.set(CatalogName.name, cube.getSchema().getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(MeasureName.name, member.getName());
row.set(MeasureUniqueName.name, member.getUniqueName());
row.set(MeasureCaption.name, member.getCaption());
emit(row, saxHandler);
}
}
static class MdschemaMembersRowset extends Rowset {
MdschemaMembersRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, false, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column HierarchyUniqueName = new Column("HIERARCHY_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column LevelUniqueName = new Column("LEVEL_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column LevelNumber = new Column("LEVEL_NUMBER", Type.UnsignedInteger, null, true, false, null);
private static final Column MemberName = new Column("MEMBER_NAME", Type.String, null, true, false, null);
private static final Column MemberOrdinal = new Column("MEMBER_ORDINAL", Type.Integer, null, true, false, null);
private static final Column MemberUniqueName = new Column("MEMBER_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column MemberType = new Column("MEMBER_TYPE", Type.Integer, null, true, false, null);
private static final Column MemberCaption = new Column("MEMBER_CAPTION", Type.String, null, true, false, null);
private static final Column ChildrenCardinality = new Column("CHILDREN_CARDINALITY", Type.Integer, null, true, false, null);
private static final Column ParentLevel = new Column("PARENT_LEVEL", Type.Integer, null, false, false, null);
private static final Column ParentUniqueName = new Column("PARENT_UNIQUE_NAME", Type.String, null, true, true, null);
private static final Column TreeOp = new Column("TREE_OP", Type.Enumeration, Enumeration.TreeOp.enumeration, true, true, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_MEMBERS", MDSCHEMA_MEMBERS, null, new Column[] {
CatalogName,
SchemaName,
CubeName,
DimensionUniqueName,
HierarchyUniqueName,
LevelUniqueName,
LevelNumber,
MemberName,
MemberOrdinal,
MemberUniqueName,
MemberType,
MemberCaption,
ChildrenCardinality,
ParentLevel,
ParentUniqueName,
TreeOp,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaMembersRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
final Connection connection = XmlaMediator.getConnection(properties);
final Cube[] cubes = connection.getSchema().getCubes();
for (int i = 0; i < cubes.length; i++) {
Cube cube = cubes[i];
if (!passesRestriction(CubeName, cube.getName())) {
continue;
}
if (isRestricted(MemberUniqueName)) {
final String memberUniqueName = (String)
restrictions.get(MemberUniqueName.name);
final String[] nameParts = Util.explode(memberUniqueName);
Member member = cube.getSchemaReader(null).
getMemberByUniqueName(nameParts, false);
if (member != null) {
String treeOp0 = (String) restrictions.get(TreeOp.name);
int treeOp = Enumeration.TreeOp.Self.ordinal;
if (treeOp0 != null) {
try {
treeOp = Integer.parseInt(treeOp0);
} catch (NumberFormatException e) {
// stay with default value
}
}
unparseMember(connection, cube, member, saxHandler, treeOp);
}
continue;
}
final Dimension[] dimensions = cube.getDimensions();
for (int j = 0; j < dimensions.length; j++) {
Dimension dimension = dimensions[j];
if (!passesRestriction(DimensionUniqueName,
dimension.getUniqueName())) {
continue;
}
final Hierarchy[] hierarchies = dimension.getHierarchies();
for (int k = 0; k < hierarchies.length; k++) {
Hierarchy hierarchy = hierarchies[k];
if (!passesRestriction(HierarchyUniqueName,
hierarchy.getUniqueName())) {
continue;
}
final Member[] rootMembers =
connection.getSchemaReader().
getHierarchyRootMembers(hierarchy);
for (int m = 0; m < rootMembers.length; m++) {
Member member = rootMembers[m];
// Note that we ignore treeOp, because
// MemberUniqueName was not restricted, and
// therefore we have nothing to work relative to.
// We supply our own treeOp expression here, for
// our own devious purposes.
unparseMember(connection, cube, member, saxHandler,
Enumeration.TreeOp.Self.ordinal |
Enumeration.TreeOp.Descendants.ordinal);
}
}
}
}
}
/**
* Returns whether a value contains all of the bits in a mask.
*/
private static boolean mask(int value, int mask) {
return (value & mask) == mask;
}
/**
* Outputs a member and, depending upon the <code>treeOp</code>
* parameter, other relatives of the member. This method recursively
* invokes itself to walk up, down, or across the hierarchy.
*/
private void unparseMember(final Connection connection, Cube cube,
Member member, SAXHandler saxHandler,
int treeOp) throws SAXException {
// Visit node itself.
if (mask(treeOp, Enumeration.TreeOp.Self.ordinal)) {
emitMember(member, connection, cube, saxHandler);
}
// Visit node's siblings (not including itself).
if (mask(treeOp, Enumeration.TreeOp.Siblings.ordinal)) {
final Member parent =
connection.getSchemaReader().getMemberParent(member);
final Member[] siblings;
if (parent == null) {
siblings = connection.getSchemaReader().
getHierarchyRootMembers(member.getHierarchy());
} else {
siblings = connection.getSchemaReader().
getMemberChildren(parent);
}
for (int i = 0; i < siblings.length; i++) {
Member sibling = siblings[i];
if (sibling == member) {
continue;
}
unparseMember(connection, cube, sibling, saxHandler,
Enumeration.TreeOp.Self.ordinal);
}
}
// Visit node's descendants or its immediate children, but not both.
if (mask(treeOp, Enumeration.TreeOp.Descendants.ordinal)) {
final Member[] children =
connection.getSchemaReader().getMemberChildren(member);
for (int i = 0; i < children.length; i++) {
Member child = children[i];
unparseMember(connection, cube, child, saxHandler,
Enumeration.TreeOp.Self.ordinal |
Enumeration.TreeOp.Descendants.ordinal);
}
} else if (mask(treeOp, Enumeration.TreeOp.Children.ordinal)) {
final Member[] children =
connection.getSchemaReader().getMemberChildren(member);
for (int i = 0; i < children.length; i++) {
Member child = children[i];
unparseMember(connection, cube, child, saxHandler,
Enumeration.TreeOp.Self.ordinal);
}
}
// Visit node's ancestors or its immediate parent, but not both.
if (mask(treeOp, Enumeration.TreeOp.Ancestors.ordinal)) {
final Member parent =
connection.getSchemaReader().getMemberParent(member);
if (parent != null) {
unparseMember(connection, cube, parent, saxHandler,
Enumeration.TreeOp.Self.ordinal |
Enumeration.TreeOp.Ancestors.ordinal);
}
} else if (mask(treeOp, Enumeration.TreeOp.Parent.ordinal)) {
final Member parent =
connection.getSchemaReader().getMemberParent(member);
if (parent != null) {
unparseMember(connection, cube, parent, saxHandler,
Enumeration.TreeOp.Self.ordinal);
}
}
}
protected ArrayList pruneRestrictions(ArrayList list) {
// If they've restricted TreeOp, we don't want to literally filter
// the result on TreeOp (because it's not an output column) or
// on MemberUniqueName (because TreeOp will have caused us to
// generate other members than the one asked for).
if (list.contains(TreeOp)) {
list.remove(TreeOp);
list.remove(MemberUniqueName);
}
return list;
}
private void emitMember(Member member, final Connection connection,
Cube cube, SAXHandler saxHandler) throws SAXException {
final Level level = member.getLevel();
final Hierarchy hierarchy = level.getHierarchy();
final Dimension dimension = hierarchy.getDimension();
Rowset.Row row = new Rowset.Row();
row.set(CatalogName.name, cube.getSchema().getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionUniqueName.name, dimension.getUniqueName());
row.set(HierarchyUniqueName.name, hierarchy.getUniqueName());
row.set(LevelUniqueName.name, level.getUniqueName());
row.set(LevelNumber.name, level.getDepth());
row.set(MemberName.name, member.getName());
row.set(MemberOrdinal.name, member.getOrdinal());
row.set(MemberUniqueName.name, member.getUniqueName());
row.set(MemberType.name, member.getMemberType());
row.set(MemberCaption.name, member.getCaption());
row.set(ChildrenCardinality.name, member.getPropertyValue(Property.CHILDREN_CARDINALITY.name));
row.set(ParentLevel.name, member.getParentMember() == null ? 0 : member.getParentMember().getDepth());
row.set(ParentUniqueName.name, member.getParentUniqueName());
emit(row, saxHandler);
}
}
static class MdschemaSetsRowset extends Rowset {
MdschemaSetsRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, false, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column SetName = new Column("SET_NAME", Type.String, null, true, false, null);
private static final Column Scope = new Column("SCOPE", Type.Integer, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_SETS", MDSCHEMA_SETS, null, new Column[] {
CatalogName,
SchemaName,
CubeName,
SetName,
Scope,
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaSetsRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
throw new UnsupportedOperationException();
}
}
static class MdschemaPropertiesRowset extends Rowset {
MdschemaPropertiesRowset(HashMap restrictions, Properties properties) {
super(definition, restrictions, properties);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, false, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column HierarchyUniqueName = new Column("HIERARCHY_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column LevelUniqueName = new Column("LEVEL_UNIQUE_NAME", Type.String, null, true, false, null);
private static final Column MemberUniqueName = new Column("MEMBER_UNIQUE_NAME", Type.String, null, true, true, null);
private static final Column PropertyName = new Column("PROPERTY_NAME", Type.String, null, true, false, null);
private static final Column PropertyType = new Column("PROPERTY_TYPE", Type.Integer, null, true, false, null);
private static final Column PropertyContentType = new Column("PROPERTY_CONTENT_TYPE", Type.Integer, null, true, false, null);
private static final Column PropertyCaption = new Column("PROPERTY_CAPTION", Type.String, null, true, false, null);
public static final RowsetDefinition definition = new RowsetDefinition(
"MDSCHEMA_PROPERTIES", MDSCHEMA_PROPERTIES, null, new Column[] {
CatalogName,
SchemaName,
CubeName,
DimensionUniqueName,
HierarchyUniqueName,
LevelUniqueName,
MemberUniqueName,
PropertyName,
PropertyType,
PropertyContentType,
PropertyCaption
}) {
public Rowset getRowset(HashMap restrictions, Properties properties) {
return new MdschemaPropertiesRowset(restrictions, properties);
}
};
public void unparse(SAXHandler saxHandler) throws SAXException {
final Connection connection = XmlaMediator.getConnection(properties);
final Cube[] cubes = connection.getSchema().getCubes();
for (int i = 0; i < cubes.length; i++) {
Cube cube = cubes[i];
final Dimension[] dimensions = cube.getDimensions();
for (int j = 0; j < dimensions.length; j++) {
final Dimension dimension = dimensions[j];
final Hierarchy[] hierarchies = dimension.getHierarchies();
for (int k = 0; k < hierarchies.length; k++) {
Hierarchy hierarchy = hierarchies[k];
Level[] levels = hierarchy.getLevels();
for (int l = 0; l < levels.length; l++) {
Level level = levels[l];
Property[] properties = level.getProperties();
for (int m = 0; m < properties.length; m++) {
Property property = properties[m];
Row row = new Row();
row.set(CatalogName.name, cube.getSchema().getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionUniqueName.name, dimension.getUniqueName());
row.set(HierarchyUniqueName.name, hierarchy.getUniqueName());
row.set(LevelUniqueName.name, level.getUniqueName());
// row.set(MemberUniqueName.name, null);
row.set(PropertyName.name, property.getName());
row.set(PropertyType.name, property.getType());
row.set(PropertyContentType.name, 0);
row.set(PropertyCaption.name, property.getCaption());
emit(row, saxHandler);
}
}
}
}
}
}
}
}
// End RowsetDefinition.java
|
package org.testng;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Simple ITestListener adapter.
*
* @author Cedric Beust, Aug 6, 2004
*
*/
public class TestListenerAdapter implements ITestListener {
private List<ITestNGMethod> m_allTestMethods = Collections.synchronizedList(new ArrayList<ITestNGMethod>());
private List<ITestResult> m_passedTests = Collections.synchronizedList(new ArrayList<ITestResult>());
private List<ITestResult> m_failedTests = Collections.synchronizedList(new ArrayList<ITestResult>());
private List<ITestResult> m_skippedTests = Collections.synchronizedList(new ArrayList<ITestResult>());
private List<ITestResult> m_failedButWithinSuccessPercentageTests
= Collections.synchronizedList(new ArrayList<ITestResult>());
public void onTestSuccess(ITestResult tr) {
m_allTestMethods.add(tr.getMethod());
m_passedTests.add(tr);
}
public void onTestFailure(ITestResult tr) {
m_allTestMethods.add(tr.getMethod());
m_failedTests.add(tr);
}
public void onTestSkipped(ITestResult tr) {
m_allTestMethods.add(tr.getMethod());
m_skippedTests.add(tr);
}
public void onTestFailedButWithinSuccessPercentage(ITestResult tr) {
m_allTestMethods.add(tr.getMethod());
m_failedButWithinSuccessPercentageTests.add(tr);
}
protected ITestNGMethod[] getAllTestMethods() {
return m_allTestMethods.toArray(new ITestNGMethod[m_allTestMethods.size()]);
}
public void onStart(ITestContext testContext) {
}
public void onFinish(ITestContext testContext) {
}
/**
* @return Returns the failedButWithinSuccessPercentageTests.
*/
public List<ITestResult> getFailedButWithinSuccessPercentageTests() {
return m_failedButWithinSuccessPercentageTests;
}
/**
* @return Returns the failedTests.
*/
public List<ITestResult> getFailedTests() {
return m_failedTests;
}
/**
* @return Returns the passedTests.
*/
public List<ITestResult> getPassedTests() {
return m_passedTests;
}
/**
* @return Returns the skippedTests.
*/
public List<ITestResult> getSkippedTests() {
return m_skippedTests;
}
private static void ppp(String s) {
System.out.println("[TestListenerAdapter] " + s);
}
/**
* @param allTestMethods The allTestMethods to set.
*/
public void setAllTestMethods(List<ITestNGMethod> allTestMethods) {
m_allTestMethods = allTestMethods;
}
/**
* @param failedButWithinSuccessPercentageTests The failedButWithinSuccessPercentageTests to set.
*/
public void setFailedButWithinSuccessPercentageTests(
List<ITestResult> failedButWithinSuccessPercentageTests) {
m_failedButWithinSuccessPercentageTests = failedButWithinSuccessPercentageTests;
}
/**
* @param failedTests The failedTests to set.
*/
public void setFailedTests(List<ITestResult> failedTests) {
m_failedTests = failedTests;
}
/**
* @param passedTests The passedTests to set.
*/
public void setPassedTests(List<ITestResult> passedTests) {
m_passedTests = passedTests;
}
/**
* @param skippedTests The skippedTests to set.
*/
public void setSkippedTests(List<ITestResult> skippedTests) {
m_skippedTests = skippedTests;
}
public void onTestStart(ITestResult result) {
}
}
|
package org.tigris.subversion.javahl;
/**
* This class describes one property managed by Subversion.
*/
public class PropertyData
{
/**
* the name of the property
*/
private String name;
/**
* the string value of the property
*/
private String value;
/**
* the byte array value of the property
*/
private byte[] data;
/**
* path of the subversion to change or delete this property
*/
private String path;
/**
* reference to the creating SVNClient object to change or delete this
* property
*/
private SVNClient client;
/**
* Standard subversion known properties
*/
/**
* mime type of the entry, used to flag binary files
*/
public static final String MIME_TYPE = "svn:mime-type";
/**
* list of filenames with wildcards which should be ignored by add and
* status
*/
public static final String IGNORE = "svn:ignore";
/**
* how the end of line code should be treated during retrieval
*/
public static final String EOL_STYLE = "svn:eol-style";
/**
* list of keywords to be expanded during retrieval
*/
public static final String KEYWORDS = "svn:keywords";
/**
* flag if the file should be made excutable during retrieval
*/
public static final String EXECUTABLE = "svn:executable";
/**
* value for svn:executable
*/
public static final String EXECUTABLE_VALUE = "*";
/**
* list of directory managed outside of this working copy
*/
public static final String EXTERNALS = "svn:externals";
/**
* the author of the revision
*/
public static final String REV_AUTHOR = "svn:author";
/**
* the log message of the revision
*/
public static final String REV_LOG = "svn:log";
/**
* the date of the revision
*/
public static final String REV_DATE = "svn:date";
/**
* the original date of the revision
*/
public static final String REV_ORIGINAL_DATE = "svn:original-date";
/**
* @since 1.2
* flag property if a lock is needed to modify this node
*/
public static final String NEEDS_LOCK = "svn:needs-lock";
/**
* this constructor is only used by the JNI code
* @param cl the client object, which created this object
* @param p the path of the item owning this property
* @param n the name of the property
* @param v the string value of the property
* @param d the byte array value of the property
*/
PropertyData(SVNClient cl, String p, String n, String v, byte[] d)
{
path = p;
name = n;
value = v;
client = cl;
data = d;
}
/**
* this contructor is used when building a thin wrapper around other
* property retreival methods
* @param p the path of the item owning this property
* @param n the name of the property
* @param v the string value of the property
*/
PropertyData(String p, String n, String v)
{
path = p;
name = n;
value = v;
client = null;
data = v.getBytes();
}
/**
* Returns the name of the property
* @return the name
*/
public String getName()
{
return name;
}
/**
* Returns the string value of the property.
* There is no protocol if a property is a string or a binary value
* @return the string value
*/
public String getValue()
{
return value;
}
/**
* Return the path of the item which owns this property
* @return the path
*/
public String getPath()
{
return path;
}
/**
* Returns the byte array value of the property
* There is no protocol if a property is a string or a binary value
* @return the byte array value
*/
public byte[] getData()
{
return data;
}
/**
* modify the string value of a property
* The byte array value is cleared
* @param newValue the new string value
* @param recurse if operation should recurse directories
* @throws ClientException
*/
public void setValue(String newValue, boolean recurse)
throws ClientException
{
client.propertySet(path, name, newValue, recurse);
value = newValue;
data = null;
}
/**
* modify the byte array value of a property
* The string array value is cleared
* @param newValue the new byte array value
* @param recurse if operation should recurse directories
* @throws ClientException
*/
public void setValue(byte[] newValue, boolean recurse)
throws ClientException
{
client.propertySet(path, name, newValue, recurse);
data = newValue;
value = null;
}
/**
* remove this property from subversion
* @param recurse if operation should recurse directories
* @throws ClientException
*/
public void remove(boolean recurse) throws ClientException
{
client.propertyRemove(path, name, recurse);
}
}
|
package com.uber.tchannel.schemes;
import io.netty.buffer.ByteBuf;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class JSONSerializerTest {
private Serializer.SerializerInterface serializer;
@org.junit.Before
public void setUp() throws Exception {
this.serializer = new JSONSerializer();
}
@Test
public void testEncodeDecodeEndpoint() throws Exception {
}
@Test
public void testEncodeDecodeHeaders() throws Exception {
Map<String, String> headers = new HashMap<String, String>() {{
put("foo", "bar");
}};
ByteBuf binaryHeaders = serializer.encodeHeaders(headers);
Map<String, String> decodedHeaders = serializer.decodeHeaders(binaryHeaders);
assertEquals(headers, decodedHeaders);
}
@Test
public void testEncodeDecodeBody() throws Exception {
}
@org.junit.After
public void tearDown() throws Exception {
this.serializer = null;
}
}
|
package com.mx3;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class GithubUsers extends Activity {
static {
System.loadLibrary("mx3_android");
}
private Api mApi;
private UserListVmHandle mUserListHandle;
private GithubUserAdapter mAdapter;
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("USERS", "Starting application");
Http httpImpl = new AndroidHttp();
EventLoop mainThread = new AndroidEventLoop();
ThreadLauncher threadLauncher = new AndroidThreadLauncher();
mApi = Api.createApi(this.getFilesDir().getAbsolutePath(), mainThread, httpImpl, threadLauncher);
mUserListHandle = mApi.observerUserList();
mUserListHandle.start(new UserListVmObserver() {
@Override
public void onUpdate(ArrayList<ListChange> changes, final UserListVm newData) {
mAdapter = new GithubUserAdapter(GithubUsers.this, newData);
Log.d("USERS", "count: " + mAdapter.getCount());
mListView.setAdapter(mAdapter);
mListView.deferNotifyDataSetChanged();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
newData.deleteRow(position);
}
});
}
});
setContentView(R.layout.activity_github_users);
mListView = (ListView)findViewById(R.id.github_user_list);
}
@Override
protected void onStop() {
mUserListHandle.stop();
super.onStop();
}
private class GithubUserAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private UserListVm mListVm;
public GithubUserAdapter(Context context, UserListVm viewModel) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mListVm = viewModel;
}
@Override
public int getCount() {
return mListVm.count();
}
@Override
public long getItemId(int pos) {
return pos;
}
@Override
public Object getItem(int i) {
return mListVm.get(i);
}
@Override
public View getView(int i, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.github_user_cell, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.name_label);
textView.setText(mListVm.get(i).getName());
return convertView;
}
}
}
|
package controller;
import model.SimulationFire;
import model.SimulationLife;
import model.SimulationSegregation;
import view.SimulationScreen;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
//private CellSocietyController myCellSocietyController;
public static final int HEIGHT = 600;
public static final int WIDTH = 600;
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("Cell Society");
//myCellSocietyController = new CellSocietyController(WIDTH, HEIGHT);
SimulationScreen simScreen = new SimulationScreen();
Group root = new Group();
root.getChildren().add(simScreen.initSimScreen(WIDTH, HEIGHT));
stage.setScene(new Scene(root, WIDTH, HEIGHT));
stage.show();
Integer[][] treeGrid = new Integer[][]{
{0,0,0,0},
{0,1,1,1},
{0,0,1,1},
{0,0,0,0},
};
SimulationSegregation simFire = new SimulationSegregation(null, treeGrid, simScreen);
for(int i = 0; i < 2; i++){
simFire.updateGrid();
}
// KeyFrame frame = myCellSocietyController.getKeyFrame(60);
// Timeline animationTimeline = new Timeline();
// animationTimeline.setCycleCount(Timeline.INDEFINITE);
// animationTimeline.getKeyFrames().add(frame);
// animationTimeline.play();
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.dmdirc.ui.swing.dialogs.actionsmanager;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.harness.ui.ButtonTextFinder;
import com.dmdirc.harness.ui.ClassFinder;
import com.dmdirc.ui.swing.components.StandardInputDialog;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
import org.fest.swing.core.matcher.JLabelByTextMatcher;
import org.fest.swing.finder.WindowFinder;
import org.fest.swing.fixture.DialogFixture;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ActionsManagerDialogTest {
private DialogFixture window;
private static final Runnable runner = new Runnable() {
@Override
public void run() {
// Dummy
}
};
@Before
public void setUp() {
IdentityManager.load();
ActionManager.loadActions();
if (ActionManager.getGroups().containsKey("amd-ui-test1")) {
ActionManager.removeGroup("amd-ui-test1");
}
window = new DialogFixture(ActionsManagerDialog.getActionsManagerDialog());
window.show();
}
@After
public void tearDown() {
if (window != null) {
window.cleanUp();
}
if (ActionManager.getGroups().containsKey("amd-ui-test1")) {
ActionManager.removeGroup("amd-ui-test1");
}
}
@Test
public void testAddGroup() throws InterruptedException, InvocationTargetException {
window.panel(new ClassFinder<JPanel>(JPanel.class, null))
.button(new ButtonTextFinder("Add")).click();
DialogFixture newwin = WindowFinder.findDialog(StandardInputDialog.class)
.withTimeout(5000).using(window.robot);
newwin.requireVisible();
assertEquals("New action group", newwin.target.getTitle());
newwin.button(new ButtonTextFinder("Cancel")).click();
SwingUtilities.invokeAndWait(runner);
newwin.requireNotVisible();
window.panel(new ClassFinder<JPanel>(JPanel.class, null))
.button(new ButtonTextFinder("Add")).click();
newwin = WindowFinder.findDialog(StandardInputDialog.class)
.withTimeout(5000).using(window.robot);
newwin.requireVisible();
assertEquals("New action group", newwin.target.getTitle());
newwin.button(new ButtonTextFinder("OK")).requireDisabled();
newwin.textBox(new ClassFinder<JTextComponent>(javax.swing.JTextField.class, null))
.enterText("amd-ui-test1");
SwingUtilities.invokeAndWait(runner);
System.out.println(newwin.textBox(
new ClassFinder<JTextComponent>(javax.swing.JTextField.class, null))
.target.getText());
System.out.println(newwin.label(JLabelByTextMatcher.withText(null))
.target.getToolTipText());
newwin.button(new ButtonTextFinder("OK")).requireEnabled().click();
SwingUtilities.invokeAndWait(runner);
// Ensure it's added
window.list().selectItem("amd-ui-test1").requireSelectedItems("amd-ui-test1");
}
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(ActionsManagerDialogTest.class);
}
}
|
package org.codehaus.groovy.grails.commons;
import java.net.URL;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import junit.framework.TestCase;
public class GrailsResourceUtilsTests extends TestCase {
private static final String TEST_URL = "file:///test/grails/app/grails-app/domain/Test.groovy";
private static final String TEST_CONTROLLER_URL = "file:///test/grails/app/grails-app/controllers/TestController.groovy";
private static final String TEST_PLUGIN_CTRL = "file:///test/grails/app/plugins/myplugin/grails-app/controllers/TestController.groovy";
private static final String WEBINF_CONTROLLER = "file:///test/grails/app/WEB-INF/grails-app/controllers/TestController.groovy";
private static final String WEBINF_PLUGIN_CTRL = "file:///test/grails/app/WEB-INF/plugins/myplugin/grails-app/controllers/TestController.groovy";
private static final String UNIT_TESTS_URL = "file:///test/grails/app/grails-tests/SomeTests.groovy";
protected void setUp() throws Exception {
super.setUp();
}
public void testIsDomainClass() throws Exception {
URL testUrl = new URL(TEST_URL);
assertTrue(GrailsResourceUtils.isDomainClass(testUrl));
}
public void testGetClassNameResource() throws Exception {
Resource r = new UrlResource(new URL(TEST_URL));
assertEquals("Test", GrailsResourceUtils.getClassName(r));
}
public void testGetClassNameString() {
assertEquals("Test", GrailsResourceUtils.getClassName(TEST_URL));
}
public void testIsGrailsPath() {
assertTrue(GrailsResourceUtils.isGrailsPath(TEST_URL));
}
public void testIsTestPath() {
assertTrue(GrailsResourceUtils.isGrailsPath(UNIT_TESTS_URL));
}
public void testGetTestNameResource() throws Exception {
Resource r = new UrlResource(new URL(UNIT_TESTS_URL));
assertEquals("SomeTests", GrailsResourceUtils.getClassName(r));
}
public void testGetTestNameString() {
assertEquals("SomeTests", GrailsResourceUtils.getClassName(UNIT_TESTS_URL));
}
public void testGetViewsDirForURL() throws Exception {
Resource viewsDir = GrailsResourceUtils.getViewsDir(new UrlResource(TEST_CONTROLLER_URL));
assertEquals("file:/test/grails/app/grails-app/views", viewsDir.getURL().toString());
viewsDir = GrailsResourceUtils.getViewsDir(new UrlResource(TEST_URL));
assertEquals("file:/test/grails/app/grails-app/views", viewsDir.getURL().toString());
}
public void testGetAppDir() throws Exception {
Resource appDir = GrailsResourceUtils.getAppDir(new UrlResource(TEST_CONTROLLER_URL));
assertEquals("file:/test/grails/app/grails-app", appDir.getURL().toString());
appDir = GrailsResourceUtils.getAppDir(new UrlResource(TEST_URL));
assertEquals("file:/test/grails/app/grails-app", appDir.getURL().toString());
}
public void testGetDirWithinWebInf() throws Exception {
Resource viewsDir = GrailsResourceUtils.getViewsDir(new UrlResource(TEST_CONTROLLER_URL));
Resource pluginViews = GrailsResourceUtils.getViewsDir(new UrlResource(TEST_PLUGIN_CTRL));
Resource webInfViews = GrailsResourceUtils.getViewsDir(new UrlResource(WEBINF_CONTROLLER));
Resource webInfPluginViews = GrailsResourceUtils.getViewsDir(new UrlResource(WEBINF_PLUGIN_CTRL));
assertEquals("file:/test/grails/app/grails-app/views", viewsDir.getURL().toString());
assertEquals("file:/test/grails/app/plugins/myplugin/grails-app/views", pluginViews.getURL().toString());
assertEquals("file:/test/grails/app/WEB-INF/grails-app/views", webInfViews.getURL().toString());
assertEquals("file:/test/grails/app/WEB-INF/plugins/myplugin/grails-app/views", webInfPluginViews.getURL().toString());
assertEquals("/WEB-INF/grails-app/views", GrailsResourceUtils.getRelativeInsideWebInf(webInfViews));
assertEquals("/WEB-INF/plugins/myplugin/grails-app/views", GrailsResourceUtils.getRelativeInsideWebInf(webInfPluginViews));
assertEquals("/WEB-INF/plugins/myplugin/grails-app/views", GrailsResourceUtils.getRelativeInsideWebInf(pluginViews));
assertEquals("/WEB-INF/grails-app/views", GrailsResourceUtils.getRelativeInsideWebInf(viewsDir));
}
}
|
package ch.hsr.ifs.pystructure.tests.typeinference;
import java.io.File;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.python.pydev.parser.jython.ast.Expr;
import ch.hsr.ifs.pystructure.typeinference.basetype.IType;
import ch.hsr.ifs.pystructure.typeinference.inferencer.PythonTypeInferencer;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module;
import ch.hsr.ifs.pystructure.typeinference.visitors.ExpressionAtLineVisitor;
import ch.hsr.ifs.pystructure.typeinference.visitors.Workspace;
class ExpressionTypeAssertion extends Assert {
private final String correctClassRef;
public final String filename;
public final String expression;
public final int line;
public ExpressionTypeAssertion(String fileName, String expression,
int line, String correctClassRef) {
this.filename = fileName;
this.expression = expression;
assertNotNull(expression);
this.line = line;
this.correctClassRef = correctClassRef;
}
public void check(File file, PythonTypeInferencer inferencer, Workspace workspace) {
Module module = workspace.getModule(file);
ExpressionAtLineVisitor visitor = new ExpressionAtLineVisitor(line);
Expr expression = visitor.run(module.getNode());
if (expression == null) {
throw new RuntimeException("Unable to find node for expresssion '" + this.expression + "'");
}
IType type = inferencer.evaluateType(workspace, module, expression.value);
if (!correctClassRef.equals("recursion")) {
if (type == null) {
throw new AssertionFailedError(
"null type fetched, but "
+ correctClassRef + " expected");
}
assertNotNull(type);
assertType(correctClassRef, type.getTypeName());
}
}
private void assertType(final String expected, final String actual) {
if (!expected.equals(actual)) {
throw new AssertionFailedError() {
private static final long serialVersionUID = 1L;
public String toString() {
String s
= "Type of <" + expression + ">: expected <" + expected
+ "> but was <" + actual
+ "> (" + filename + ":" + line + ")";
return s;
}
};
}
}
}
|
package ca.eqv.maven.plugins.tsc.mojo;
import org.apache.commons.io.FileUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.repository.LocalArtifactRequest;
import org.eclipse.aether.repository.LocalArtifactResult;
import org.eclipse.aether.repository.LocalRepositoryManager;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.ArtifactResult;
import org.twdata.maven.mojoexecutor.MojoExecutor.Element;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration;
import static org.twdata.maven.mojoexecutor.MojoExecutor.element;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment;
import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin;
@Mojo(name = "compile", defaultPhase = LifecyclePhase.COMPILE)
public class CompileMojo extends AbstractMojo {
/** Root of TypeScript source tree (working directory) */
@Parameter(defaultValue = "${project.basedir}/src/main/typescript")
private File sourceRoot;
/** Top-level source files to compile, relative to sourceRoot */
@Parameter(defaultValue = "references.ts")
private String[] sources;
/** Output file */
@Parameter(defaultValue = "${project.build.directory}/app.js")
private File outputFile;
/** Target language level */
@Parameter(defaultValue = "ES5")
private String targetLanguageLevel;
/** Generate source map files */
@Parameter(defaultValue = "true")
private boolean generateSourceMap;
/** (Advanced) Arguments to tsc. <b>This overrides all other command line argument options.</b> */
@Parameter
private String[] overrideArguments;
@Component
private RepositorySystem repoSystem;
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repoSession;
@Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true)
private List<RemoteRepository> projectRepoList;
@Component
private ArchiverManager archiverManager;
/** (Internal) Temporary directory where the TypeScript distribution will be unpacked */
@Parameter(defaultValue = "${project.build.directory}/tsc-maven/typescript")
private File typescriptHome;
/** (Internal) Maven groupId for the TypeScript distribution that's been re-packaged as a Maven artifact */
@Parameter(defaultValue = "ca.eqv.maven.plugins.tsc")
private String typescriptGroupId;
/** (Internal) Maven artifactId for the TypeScript distribution that's been re-packaged as a Maven artifact */
@Parameter(defaultValue = "typescript")
private String typescriptArtifactId;
/** (Internal) Maven classifier for the TypeScript distribution that's been re-packaged as a Maven artifact */
@Parameter(defaultValue = "")
private String typescriptClassifier;
/** (Internal) Maven extension for the TypeScript distribution that's been re-packaged as a Maven artifact */
@Parameter(defaultValue = "zip")
private String typescriptExtension;
/** (Internal) Maven version for the TypeScript distribution that's been re-packaged as a Maven artifact */
@Parameter(defaultValue = "1.4.1")
private String typescriptVersion;
/** (Internal) Relative path to tsc */
@Parameter(defaultValue = "bin/tsc")
private String typescriptTscPath;
/** (Internal) Maven version for the Avatar.js artifact */
@Parameter(defaultValue = "0.10.32-SNAPSHOT")
private String avatarJsVersion;
/** (Internal) Temporary directory where the Avatar.js native library will be copied */
@Parameter(defaultValue = "${project.build.directory}/tsc-maven/avatar-js")
private File avatarJsHome;
/** (Internal) Maven version for the org.codehaus.mojo:exec-maven-plugin artifact */
@Parameter(defaultValue = "1.3.2")
private String execMavenPluginVersion;
@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject mavenProject;
@Parameter(defaultValue = "${session}", readonly = true)
private MavenSession mavenSession;
@Component
private BuildPluginManager pluginManager;
@Override
public void execute() throws MojoExecutionException {
if (!typescriptHome.isDirectory()) {
unpackCompiler();
}
else {
getLog().debug("Skipping tsc extraction");
}
if (!avatarJsHome.isDirectory()) {
prepareAvatarJsNativeLibrary();
}
else {
getLog().debug("Skipping Avatar.js preparation");
}
executeCompiler();
}
private void unpackCompiler() throws MojoExecutionException {
final File file = getArtifact(typescriptGroupId, typescriptArtifactId, typescriptClassifier, typescriptExtension, typescriptVersion);
final UnArchiver unarchiver;
try {
unarchiver = archiverManager.getUnArchiver(file);
}
catch (final NoSuchArchiverException e) {
throw new MojoExecutionException("Unsupported archive type for artifact " + file.getName());
}
final boolean createdDirectory = typescriptHome.mkdirs();
if (!createdDirectory) {
throw new MojoExecutionException("Unable to create tsc directory " + typescriptHome.getAbsolutePath());
}
getLog().info("Extracting tsc to " + typescriptHome.getAbsolutePath());
unarchiver.setSourceFile(file);
unarchiver.setDestDirectory(typescriptHome);
unarchiver.extract();
}
private void prepareAvatarJsNativeLibrary() throws MojoExecutionException {
final AvatarJsNativeLibraryPlatform platform = AvatarJsNativeLibraryPlatform.detect();
final String artifactId = "libavatar-js-" + platform.artifactIdSuffix;
final File repoFile = getArtifact("com.oracle", artifactId, null, platform.extension, avatarJsVersion);
final boolean createdDirectory = avatarJsHome.mkdirs();
if (!createdDirectory) {
throw new MojoExecutionException("Unable to create Avatar.js directory " + avatarJsHome.getAbsolutePath());
}
final String homePath = avatarJsHome.getAbsolutePath();
final String nativeLibFilename = "libavatar-js." + platform.extension;
final File nativeLibFile = new File(homePath + File.separator + nativeLibFilename);
try {
getLog().info("Preparing Avatar.js native library in " + avatarJsHome.getAbsolutePath());
FileUtils.copyFile(repoFile, nativeLibFile);
}
catch (final IOException e) {
throw new MojoExecutionException("Unable to prepare Avatar.js native library", e);
}
}
private void executeCompiler() throws MojoExecutionException {
getLog().info("Starting TypeScript compiler...");
executeMojo(
plugin("org.codehaus.mojo", "exec-maven-plugin", execMavenPluginVersion),
"exec",
configuration(
element("executable", "java"),
element("workingDirectory", sourceRoot.getAbsolutePath()),
element("arguments", getTscArgumentElements())
),
executionEnvironment(mavenProject, mavenSession, pluginManager)
);
getLog().info("TypeScript compiler exited successfully.");
}
private File getArtifact(final String groupId, final String artifactId, final String classifier, final String extension, final String version) throws MojoExecutionException {
final DefaultArtifact artifact = new DefaultArtifact(groupId, artifactId, classifier, extension, version);
final LocalArtifactRequest localRequest = new LocalArtifactRequest(artifact, projectRepoList, null);
final LocalRepositoryManager localManager = repoSession.getLocalRepositoryManager();
final LocalArtifactResult localResult = localManager.find(repoSession, localRequest);
if (localResult.isAvailable()) {
return localResult.getFile();
}
try {
final ArtifactRequest remoteRequest = new ArtifactRequest(artifact, projectRepoList, null);
final ArtifactResult remoteResult = repoSystem.resolveArtifact(repoSession, remoteRequest);
return remoteResult.getArtifact().getFile();
}
catch (final ArtifactResolutionException e) {
throw new MojoExecutionException("Could not retrieve artifact", e);
}
}
private Element[] getTscArgumentElements() throws MojoExecutionException {
final File avatarJs = getArtifact("com.oracle", "avatar-js", null, "jar", avatarJsVersion);
final List<String> arguments = new ArrayList<>();
arguments.addAll(Arrays.asList(
"-Djava.library.path=" + avatarJsHome.getAbsolutePath(),
"-jar", avatarJs.getAbsolutePath(),
typescriptHome.getAbsolutePath() + File.separator + typescriptTscPath
));
if (overrideArguments != null && overrideArguments.length > 0) {
arguments.addAll(Arrays.asList(overrideArguments));
}
else {
arguments.addAll(Arrays.asList(
"--out", outputFile.getAbsolutePath(),
"--target", targetLanguageLevel
));
if (generateSourceMap) {
arguments.add("--sourceMap");
}
arguments.addAll(Arrays.asList(sources));
}
getLog().info("Executing with arguments: " + arguments.stream().collect(Collectors.joining(", ")));
return arguments.stream().map(arg -> element("argument", arg)).toArray(Element[]::new);
}
}
|
package twitter4j.examples.oauth;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;
import java.io.*;
import java.util.Properties;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Twitter4J 2.1.7
*/
public class GetAccessToken {
/**
* Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
* @param args message
*/
public static void main(String[] args) {
File file = new File("twitter4j.properties");
Properties prop = new Properties();
InputStream is = null;
OutputStream os = null;
try{
if (file.exists()) {
is = new FileInputStream(file);
prop.load(is);
}
if(args.length < 2){
if (null == prop.getProperty("oauth.consumerKey")
&& null == prop.getProperty("oauth.consumerSecret")) {
// consumer key/secret are not set in twitter4j.properties
System.out.println(
"Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]");
System.exit(-1);
}
}else{
prop.setProperty("oauth.consumerKey", args[0]);
prop.setProperty("oauth.consumerSecret", args[1]);
os = new FileOutputStream("twitter4j.properties");
prop.store(os, "twitter4j.properties");
}
}catch(IOException ioe){
ioe.printStackTrace();
System.exit(-1);
}finally{
if(null != is){
try {
is.close();
} catch (IOException ignore) {
}
}
if(null != os){
try {
os.close();
} catch (IOException ignore) {
}
}
}
try {
Twitter twitter = new TwitterFactory().getInstance();
RequestToken requestToken = twitter.getOAuthRequestToken();
System.out.println("Got request token.");
System.out.println("Request token: "+ requestToken.getToken());
System.out.println("Request token secret: "+ requestToken.getTokenSecret());
AccessToken accessToken = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null == accessToken) {
System.out.println("Open the following URL and grant access to your account:");
System.out.println(requestToken.getAuthorizationURL());
System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
String pin = br.readLine();
try{
if(pin.length() > 0){
accessToken = twitter.getOAuthAccessToken(requestToken, pin);
}else{
accessToken = twitter.getOAuthAccessToken(requestToken);
}
} catch (TwitterException te) {
if(401 == te.getStatusCode()){
System.out.println("Unable to get the access token.");
}else{
te.printStackTrace();
}
}
}
System.out.println("Got access token.");
System.out.println("Access token: " + accessToken.getToken());
System.out.println("Access token secret: " + accessToken.getTokenSecret());
try {
prop.setProperty("oauth.accessToken", accessToken.getToken());
prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
os = new FileOutputStream(file);
prop.store(os, "twitter4j.properties");
os.close();
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
} finally {
if (null != os) {
try {
os.close();
} catch (IOException ignore) {
}
}
}
System.out.println("Successfully stored access token to " + file.getAbsolutePath()+ ".");
System.exit(0);
} catch (TwitterException te) {
System.out.println("Failed to get accessToken: " + te.getMessage());
System.exit( -1);
} catch (IOException ioe) {
System.out.println("Failed to read the system input.");
System.exit( -1);
}
}
}
|
// AbstractSwingUI.java
package imagej.ui.swing;
import imagej.ImageJ;
import imagej.event.EventService;
import imagej.event.EventSubscriber;
import imagej.ext.display.Display;
import imagej.ext.display.DisplayPanel;
import imagej.ext.display.event.DisplayCreatedEvent;
import imagej.ext.display.event.DisplayDeletedEvent;
import imagej.ext.menu.MenuService;
import imagej.ext.menu.ShadowMenu;
import imagej.ext.ui.swing.SwingJMenuBarCreator;
import imagej.platform.event.AppMenusCreatedEvent;
import imagej.platform.event.AppQuitEvent;
import imagej.ui.AbstractUserInterface;
import imagej.ui.OutputWindow;
import imagej.ui.swing.display.SwingDisplayPanel;
import imagej.ui.swing.display.SwingDisplayWindow;
import imagej.util.Prefs;
import java.awt.BorderLayout;
import java.awt.dnd.DropTarget;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
/**
* Abstract superclass for Swing-based user interfaces.
*
* @author Curtis Rueden
* @author Barry DeZonia
* @author Grant Harris
*/
public abstract class AbstractSwingUI extends AbstractUserInterface {
public static final String LAST_X_KEY =
"ImageJ.SwingApplicationFrame.lastXLocation";
public static final String LAST_Y_KEY =
"ImageJ.SwingApplicationFrame.lastYLocation";
private SwingApplicationFrame appFrame;
private SwingToolBar toolBar;
private SwingStatusBar statusBar;
protected final EventService eventService;
private ArrayList<EventSubscriber<?>> subscribers;
public AbstractSwingUI() {
// At this stage, the userIntService field is not initialized
eventService = ImageJ.get(EventService.class);
}
// -- UserInterface methods --
@Override
public SwingApplicationFrame getApplicationFrame() {
return appFrame;
}
@Override
public SwingToolBar getToolBar() {
return toolBar;
}
@Override
public SwingStatusBar getStatusBar() {
return statusBar;
}
@Override
public void createMenus() {
final JMenuBar menuBar = createMenuBar(appFrame);
eventService.publish(new AppMenusCreatedEvent(menuBar));
}
@Override
public OutputWindow newOutputWindow(final String title) {
return new SwingOutputWindow(title);
}
// -- Internal methods --
@Override
protected void createUI() {
appFrame = new SwingApplicationFrame("ImageJ");
toolBar = new SwingToolBar(eventService);
statusBar = new SwingStatusBar(eventService);
createMenus();
setupAppFrame();
appFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
appFrame.addWindowListener(new WindowAdapter() {
@Override
@SuppressWarnings("synthetic-access")
public void windowClosing(final WindowEvent evt) {
Prefs.put(LAST_X_KEY, appFrame.getX());
Prefs.put(LAST_Y_KEY, appFrame.getY());
getUIService().getEventService().publish(new AppQuitEvent());
}
});
appFrame.getContentPane().add(toolBar, BorderLayout.NORTH);
appFrame.getContentPane().add(statusBar, BorderLayout.SOUTH);
appFrame.pack();
appFrame.setVisible(true);
// setup drag and drop targets
final SwingDropListener dropListener = new SwingDropListener();
new DropTarget(toolBar, dropListener);
new DropTarget(statusBar, dropListener);
new DropTarget(appFrame, dropListener);
subscribeToEvents();
}
protected abstract void setupAppFrame();
/**
* Creates a {@link JMenuBar} from the master {@link ShadowMenu} structure,
* and adds it to the given {@link JFrame}.
*/
protected JMenuBar createMenuBar(final JFrame f) {
final MenuService menuService = ImageJ.get(MenuService.class);
final JMenuBar menuBar =
menuService.createMenus(new SwingJMenuBarCreator(), new JMenuBar());
f.setJMenuBar(menuBar);
f.validate();
return menuBar;
}
protected void deleteMenuBar(final JFrame f) {
f.setJMenuBar(null);
// HACK - w/o this next call the JMenuBars do not get garbage collected.
// I hunted on web and have found multiple people with the same problem.
// The Apple ScreenMenus don't GC when a Frame disposes. Their workaround
// was exactly the same. I have not found any official documentation of
// this issue.
f.setMenuBar(null);
}
// -- Helper methods --
private void subscribeToEvents() {
subscribers = new ArrayList<EventSubscriber<?>>();
if (getUIService().getPlatformService().isMenuBarDuplicated()) {
// NB: If menu bars are supposed to be duplicated across all window
// frames, listen for display creations and deletions and clone the menu
// bar accordingly.
final EventSubscriber<DisplayCreatedEvent> createSubscriber =
new EventSubscriber<DisplayCreatedEvent>() {
@Override
public void onEvent(final DisplayCreatedEvent event) {
final SwingDisplayWindow displayWindow =
getDisplayWindow(event.getObject());
// add a copy of the JMenuBar to the new display
if (displayWindow != null && displayWindow.getJMenuBar() == null) {
createMenuBar(displayWindow);
}
}
};
subscribers.add(createSubscriber);
eventService.subscribe(DisplayCreatedEvent.class, createSubscriber);
final EventSubscriber<DisplayDeletedEvent> deleteSubscriber =
new EventSubscriber<DisplayDeletedEvent>() {
@Override
public void onEvent(final DisplayDeletedEvent event) {
final SwingDisplayWindow displayWindow =
getDisplayWindow(event.getObject());
if (displayWindow != null) deleteMenuBar(displayWindow);
}
};
subscribers.add(deleteSubscriber);
eventService.subscribe(DisplayDeletedEvent.class, deleteSubscriber);
}
}
// -- Helper methods --
protected SwingDisplayWindow getDisplayWindow(final Display<?> display) {
final DisplayPanel panel = display.getPanel();
if (!(panel instanceof SwingDisplayPanel)) return null;
final SwingDisplayPanel swingPanel = (SwingDisplayPanel) panel;
// CTR FIXME - Clear up confusion surrounding SwingDisplayPanel and
// SwingDisplayWindow in SDI vs. MDI contexts. Avoid casting!
final SwingDisplayWindow displayWindow =
(SwingDisplayWindow) SwingUtilities.getWindowAncestor(swingPanel);
return displayWindow;
}
}
|
import controls.sunburst.*;
import helpers.ISourceStrategy;
import helpers.SourceStrategyMockup;
import helpers.SourceStrategySQL;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import org.controlsfx.control.SegmentedButton;
import java.util.ArrayList;
import java.util.List;
public class SunburstViewShowcase extends javafx.application.Application {
/**
* Launchable
*
* @param args
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("Sunburst View");
BorderPane pane = new BorderPane();
SunburstView sunburstView = new SunburstView();
// Create all the available color strategies once to be able to use them at runtime.
ColorStrategyRandom colorStrategyRandom = new ColorStrategyRandom();
ColorStrategySectorShades colorStrategyShades = new ColorStrategySectorShades();
WeightedTreeItem<String> rootData;
// Define a strategy by which the data should be received.
ISourceStrategy sourceStrategy = new SourceStrategyMockup();
//ISourceStrategy sourceStrategy = new SourceStrategySQL();
if(sourceStrategy instanceof SourceStrategySQL){
Parameters parameters = getParameters();
if(parameters.getUnnamed().size() < 3){
throw new IllegalArgumentException("In order for this sourceStrategy to succeed, there have to be the following arguments: databasename, user, password");
}else{
String databasename = parameters.getUnnamed().get(0);
String user = parameters.getUnnamed().get(1);
String password = parameters.getUnnamed().get(2);
rootData = sourceStrategy.getData(databasename, user, password);
}
}else{
rootData = sourceStrategy.getData(null, null, null);
}
for (WeightedTreeItem<String> eatable : rootData.getChildrenWeighted()){
System.out.println(eatable.getValue() + ": " + eatable.getRelativeWeight());
}
sunburstView.setRootItem(rootData);
// Example Controls
ToggleButton btnCSRandom = new ToggleButton("Random Color Strategy");
btnCSRandom.setOnAction(event -> {
sunburstView.setColorStrategy(colorStrategyRandom);
});
ToggleButton btnCSShades = new ToggleButton("Shades Color Strategy");
btnCSShades.setOnAction(event -> {
sunburstView.setColorStrategy(colorStrategyShades);
});
ToggleButton btnShowLegend = new ToggleButton("Show Legend");
btnShowLegend.setSelected(true);
btnShowLegend.setOnAction(event -> {
sunburstView.setLegendVisibility(true);
});
ToggleButton btnHideLegend = new ToggleButton("Hide Legend");
btnHideLegend.setOnAction(event -> {
sunburstView.setLegendVisibility(false);
});
Slider slider = new Slider();
slider.setMin(0);
slider.setMax(10);
slider.setValue(sunburstView.getMaxDeepness());
slider.setShowTickLabels(true);
slider.setShowTickMarks(true);
slider.setMajorTickUnit(5);
slider.setMinorTickCount(1);
slider.setBlockIncrement(1);
slider.valueProperty().addListener(x -> sunburstView.setMaxDeepness((int)slider.getValue()));
HBox toolbar = new HBox(20);
BorderPane.setMargin(toolbar, new Insets(10));
SegmentedButton colorStrategies = new SegmentedButton();
colorStrategies.getButtons().addAll(btnCSRandom, btnCSShades);
SegmentedButton legendVisibility = new SegmentedButton();
legendVisibility.getButtons().addAll(btnShowLegend, btnHideLegend);
toolbar.getChildren().addAll(colorStrategies, slider, legendVisibility);
pane.setTop(toolbar);
pane.setCenter(sunburstView);
stage.setScene(new Scene(pane, 1080, 800));
stage.show();
}
/**
* Build test data model
* @return
*/
private WeightedTreeItem<String> getDataL1(){
WeightedTreeItem<String> root = new WeightedTreeItem(1, "eatables");
WeightedTreeItem<String> meat = new WeightedTreeItem(3, "meat");
WeightedTreeItem<String> potato = new WeightedTreeItem(5, "potato");
WeightedTreeItem<String> fruits = new WeightedTreeItem(10, "fruits");
root.getChildren().addAll(fruits, meat, potato);
return root;
}
}
|
// read a zip archive
package test.special;
import java.io.*;
import java.util.Set;
import com.sun.tools.javac.zip.ZipFileIndex;
public class ZipRead {
// Edit this to point to rt.jar
public static final String RT_PATH = "/Applicgggations/Xcode.app/Contents/Applications/Application Loader.app/Contents/MacOS/itms/java/lib/rt.jar";
public static void main(String[] args) throws IOException {
File zip = new File(RT_PATH);
ZipFileIndex zfi = ZipFileIndex.getZipFileIndex(zip,0,false,null,false);
Set<String> dirs = zfi.getAllDirectories();
System.out.println(dirs.size() + " dirs in the zip, first 5 are:");
int i = 0;
for (String dir : dirs){
System.out.println(dir);
++i;
if (i == 5) break;
}
}
}
|
package JavaProject;
import epic.sequences.SemiCRF;
import epic.sequences.SemiConllNerPipeline;
import org.apache.commons.lang3.math.NumberUtils;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InfoDensTester {
public static void main(String[] args) {
String[] sentence1 = {"jknsjksjkdfskjs sdsdhdshjsd fsda ","I like that malware", "I like that malware", "Is that an attack?",
"This office is where I am seated", "Intruders are dangerous",
"Intruders are dangerous", "A malware attack", "There is a bug in my hair",
"Fear the malicious robot", "You are safe from danger under my aegis", "Encryption is hard",
"Cat is happy", "Cat is happy","Cat is happy", "Cat is happy", "Get to the malware", "Get to the malware"};
String[] sentence2 = {" burt snurt flurt", "I like that virus", "I like that hat", "That is an attack", "I am here",
"Malware pose a danger", "That is a nice panda", "Kitten beauty cafe", "My computer has a bug",
"Malwares are to be feared", "I protect from all menaces", "Hacking is harder",
"Dog is pleased","Kitten is pleased", "Panda does yoga", "Robot destroys underworld", "Undulate towards malignancy", "Gett too teh mawlare"};
CalculateSimilarity cs = new CalculateSimilarity();
WordVec allWordsVec = InformationDensity.createWordVec(args[0], 300);
File fileNameWordFreq = new File("/Users/" + args[0] + "/Dropbox/Exjobb/PythonThings/wordFreq.txt");
double similarities[];
double delta = Double.parseDouble(args[1]);
List<WordFreq> wordFreqs = new ArrayList<WordFreq>();
String line;
try {
FileReader fileReader = new FileReader(fileNameWordFreq);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] tmp = line.split(" ");
wordFreqs.add(new WordFreq(tmp[0],Double.parseDouble(tmp[1])));
}
}catch(IOException ex){
System.out.println("Creating wordsFreqs something went wrong: "+ ex);
}
List<double[]> wordVecs1;
List<double[]> wordVecs2;
String objectSentence;
String pairSentence;
if (args.length>2){
objectSentence = args[2].toLowerCase();
pairSentence = args[3].toLowerCase();
wordVecs1 = InformationDensity.createSentenceWordVector(objectSentence, allWordsVec);
wordVecs2 = InformationDensity.createSentenceWordVector(pairSentence, allWordsVec);
similarities = cs.CalculateSimilarity(objectSentence, pairSentence, wordFreqs, allWordsVec, wordVecs1, wordVecs2);
System.out.println(similarities[0] * delta + (1-similarities[1]) * (1 - delta));
}
for (int i = 0; i < sentence1.length; i++) {
objectSentence = sentence1[i].toLowerCase();
objectSentence = objectSentence.replaceAll("\\p{Punct}+", "");
wordVecs1 = InformationDensity.createSentenceWordVector(objectSentence, allWordsVec);
pairSentence = sentence2[i].toLowerCase();
pairSentence = pairSentence.replaceAll("\\p{Punct}+", "");
wordVecs2 = InformationDensity.createSentenceWordVector(pairSentence, allWordsVec);
similarities = cs.CalculateSimilarity(objectSentence, pairSentence, wordFreqs, allWordsVec, wordVecs1, wordVecs2);
System.out.println(similarities[0] * delta + (1-similarities[1]) * (1 - delta));
}
}
}
|
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.io.IOException;
public class Cliente {
JFrame ventana_chat=null;
//conectar sesion
static JButton btn_conectar = null;
JPanel contenedor_btnConnect = null;
static String nickname = null;
//enviar mensaje
static JButton btn_enviar = null;
static JTextField txt_mensaje = null;
static JTextField txt_ip_dm = null;
JPanel contenedor_btntxt= null;
//Area de Mensajes del chat
static JTextArea area_chat = null;
JScrollPane scroll = null;
JPanel contenedor_areachat = null;
static boolean connect = false;
//conexion
static DatagramSocket yo = null; // Socket del cliente para comunicarse con el servidor
static InetAddress dirServidor = null;
static final int PUERTO = 5000; //puerto para con servidor
public Cliente(){
hacerInterfaz();
}
public void hacerInterfaz(){
//JFRAME
ventana_chat = new JFrame("Chat");
//conectar
btn_conectar = new JButton("Conectar");
contenedor_btnConnect = new JPanel();
contenedor_btnConnect.setLayout(new GridLayout(1,1));
contenedor_btnConnect.add(btn_conectar);
//ver mensajes
area_chat = new JTextArea(25,12); //10 filas, 12 columna
area_chat.setEditable(false);
scroll = new JScrollPane(area_chat);
contenedor_areachat = new JPanel(); //constructor
contenedor_areachat.setLayout(new GridLayout(1,1)); //un layout de una fila por columna (nada mas cabe una columna
contenedor_areachat.add(scroll);
//escribir mensaje
txt_mensaje = new JTextField();
txt_ip_dm = new JTextField();
btn_enviar = new JButton("Enviar"); // boton enviar
contenedor_btntxt = new JPanel();
contenedor_btntxt.setLayout(new GridLayout(1,3));
contenedor_btntxt.add(txt_mensaje);
contenedor_btntxt.add(txt_ip_dm);
contenedor_btntxt.add(btn_enviar);
//ventana
ventana_chat.setLayout(new BorderLayout());
ventana_chat.add(contenedor_areachat, BorderLayout.NORTH);
ventana_chat.add(contenedor_btntxt, BorderLayout.CENTER);
ventana_chat.add(contenedor_btnConnect, BorderLayout.SOUTH);
ventana_chat.setSize(500, 500);
ventana_chat.setVisible(true);
ventana_chat.setResizable(false);
ventana_chat.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void conectar(){
btn_conectar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String nombre = JOptionPane.showInputDialog("Nickname: ");
nickname = nombre;
if (nombre == ""){
connect = false;
}
connect = true;
}
});
}
public static void enviarMensajeServidor(){
btn_enviar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if(txt_mensaje != null && txt_ip_dm == null){
String enviar = txt_mensaje.getText();
String message = nickname+"π"+enviar;
byte[] bufferSend = new byte[80];
bufferSend = message.getBytes();
DatagramPacket paq = new DatagramPacket(bufferSend, bufferSend.length, dirServidor, PUERTO);;
try{
yo.send(paq);
}catch(IOException ex){
System.out.println(ex.getMessage());
System.exit(1);
}
}
}
});
}
public static void main(String[] args) {
new Cliente();
boolean connect = false;
DatagramPacket paquete;
byte [] buffer;
try{
if (args[0] == ""){}
}catch (Exception e){
System.out.println("Olvidaste especificar la ip del servidor");
System.exit(1);
}
conectar();
if(connect){
try{
dirServidor = InetAddress.getByName(args[0]);
}catch(UnknownHostException ex){
System.out.println(ex.getMessage());
System.exit(1);
}
//conectarse
try{
yo = new DatagramSocket();
}catch(SocketException e){
System.out.println(e.getMessage());
System.exit(1);
}
String message="";
while(true){
//enviar mensaje
enviarMensajeServidor();
//recibir paquete
try{
buffer = new byte [80];
paquete = new DatagramPacket(buffer, buffer.length);
yo.receive(paquete);
message = new String(paquete.getData());
area_chat.append(""+message+"\n");
}catch(IOException e)
{
System.out.println(e.getMessage());
System.exit(1);
}
}
}
}
}
|
package org.wings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wings.plaf.ComponentCG;
import org.wings.plaf.Update;
import org.wings.util.SStringBuilder;
/**
* Default implementation of the reload manager.
*
* @author Stephan Schuster
*/
public class DefaultReloadManager implements ReloadManager {
private final transient static Log log = LogFactory.getLog(DefaultReloadManager.class);
private int updateCount = 0;
private boolean updateMode = false;
private boolean acceptChanges = true;
private final Map<SComponent, PotentialUpdate> fullReplaceUpdates = new HashMap<SComponent, PotentialUpdate>(256);
private final Map<SComponent, Set<PotentialUpdate>> fineGrainedUpdates = new HashMap<SComponent, Set<PotentialUpdate>>(64);
/**
* All the components to reload. A LinkedHashSet to have an ordered
* sequence that allows for fast lookup.
*/
private final Set<SComponent> componentsToReload = new LinkedHashSet<SComponent>();
public void reload(SComponent component) {
if (component == null)
throw new IllegalArgumentException("Component must not be null!");
if (updateMode) {
addUpdate(component, null);
} else {
if (!componentsToReload.contains(component)) {
componentsToReload.add(component);
}
}
}
public void addUpdate(SComponent component, Update update) {
if (component == null)
throw new IllegalArgumentException("Component must not be null!");
if (update == null) {
update = component.getCG().getComponentUpdate(component);
if (update == null) {
SFrame frame = component.getParentFrame();
if (frame != null)
fullReplaceUpdates.put(frame, null);
return;
}
}
component = update.getComponent();
if (acceptChanges) {
PotentialUpdate potentialUpdate = new PotentialUpdate(update);
if ((update.getProperty() & Update.FULL_REPLACE_UPDATE) == Update.FULL_REPLACE_UPDATE) {
fullReplaceUpdates.put(component, potentialUpdate);
} else {
Set<PotentialUpdate> potentialUpdates = getFineGrainedUpdates(component);
potentialUpdates.remove(potentialUpdate);
potentialUpdates.add(potentialUpdate);
fineGrainedUpdates.put(component, potentialUpdates);
}
} else if (log.isDebugEnabled()) {
//log.debug("Component " + component + " changed after invalidation of frames.");
}
}
@SuppressWarnings({"unchecked"})
public List<Update> getUpdates() {
if (!componentsToReload.isEmpty()) {
for (SComponent aComponentsToReload : componentsToReload) {
boolean tmp = acceptChanges;
acceptChanges = true;
addUpdate(aComponentsToReload, null);
acceptChanges = tmp;
}
}
filterUpdates();
List<PotentialUpdate> filteredUpdates = new ArrayList<PotentialUpdate>(fullReplaceUpdates.values());
for (Set<PotentialUpdate> updates : fineGrainedUpdates.values()) {
filteredUpdates.addAll(updates);
}
Collections.sort(filteredUpdates, getUpdateComparator());
return (List) filteredUpdates;
}
public Set<SComponent> getDirtyComponents() {
final Set<SComponent> dirtyComponents = new HashSet<SComponent>();
dirtyComponents.addAll(fullReplaceUpdates.keySet());
dirtyComponents.addAll(fineGrainedUpdates.keySet());
dirtyComponents.addAll(componentsToReload);
return dirtyComponents;
}
public Set<SFrame> getDirtyFrames() {
final Set<SFrame> dirtyFrames = new HashSet<SFrame>(5);
for (Object o : getDirtyComponents()) {
SFrame parentFrame = ((SComponent) o).getParentFrame();
if (parentFrame != null) {
dirtyFrames.add(parentFrame);
}
}
return dirtyFrames;
}
public void invalidateFrames() {
Iterator i = getDirtyFrames().iterator();
while (i.hasNext()) {
((SFrame) i.next()).invalidate();
i.remove();
}
acceptChanges = false;
}
public void notifyCGs() {
for (SComponent component : getDirtyComponents()) {
ComponentCG componentCG = component.getCG();
if (componentCG != null) {
componentCG.componentChanged(component);
}
}
}
public void clear() {
updateCount = 0;
updateMode = false;
acceptChanges = true;
fullReplaceUpdates.clear();
fineGrainedUpdates.clear();
componentsToReload.clear();
}
public boolean isUpdateMode() {
return updateMode;
}
public void setUpdateMode(boolean updateMode) {
this.updateMode = updateMode;
}
public boolean isReloadRequired(SFrame frame) {
if (updateMode)
return fullReplaceUpdates.containsKey(frame);
else
return true;
}
protected Set<PotentialUpdate> getFineGrainedUpdates(SComponent component) {
Set<PotentialUpdate> potentialUpdates = fineGrainedUpdates.get(component);
if (potentialUpdates == null) {
potentialUpdates = new HashSet<PotentialUpdate>(5);
}
return potentialUpdates;
}
protected void filterUpdates() {
if (log.isDebugEnabled())
printAllUpdates("Potential updates:");
fineGrainedUpdates.keySet().removeAll(fullReplaceUpdates.keySet());
SortedMap<String, SComponent> componentHierarchy = new TreeMap<String, SComponent>(new PathComparator());
for (SComponent component : getDirtyComponents()) {
if ((!component.isRecursivelyVisible() && !(component instanceof SMenu)) ||
component.getParentFrame() == null) {
fullReplaceUpdates.remove(component);
fineGrainedUpdates.remove(component);
} else {
componentHierarchy.put(getPath(component).toString(), component);
}
}
for (Iterator i = componentHierarchy.keySet().iterator(); i.hasNext();) {
String topPath = (String) i.next();
if (fullReplaceUpdates.containsKey(componentHierarchy.get(topPath))) {
while (i.hasNext()) {
String subPath = (String) i.next();
if (subPath.startsWith(topPath + "/")) {
fullReplaceUpdates.remove(componentHierarchy.get(subPath));
fineGrainedUpdates.remove(componentHierarchy.get(subPath));
i.remove();
}
}
}
i = componentHierarchy.tailMap(topPath + "\0").keySet().iterator();
}
if (log.isDebugEnabled())
printAllUpdates("Effective updates:");
}
private SStringBuilder getPath(SComponent component) {
if (component == null) {
return new SStringBuilder();
} else {
if (component instanceof SMenuItem) {
SMenuItem menuItem = (SMenuItem) component;
return getPath(menuItem.getParentMenu()).append("/").append(component.getName());
} else if (component instanceof SSpinner.DefaultEditor) {
SSpinner.DefaultEditor defaultEditor = (SSpinner.DefaultEditor) component;
return getPath(defaultEditor.getSpinner()).append("/").append(component.getName());
} else {
return getPath(component.getParent()).append("/").append(component.getName());
}
}
}
private void printAllUpdates(String header) {
log.debug(header);
int numberOfUpdates = 0;
SStringBuilder output = new SStringBuilder(512);
for (SComponent component : getDirtyComponents()) {
output.setLength(0);
output.append(" ").append(component + ":");
if (fullReplaceUpdates.containsKey(component)) {
output.append(" " + fullReplaceUpdates.get(component));
if (fullReplaceUpdates.get(component) == null) {
output.append(" [no component update supported --> reload frame!!!]");
}
++numberOfUpdates;
}
for (PotentialUpdate potentialUpdate : getFineGrainedUpdates(component)) {
output.append(" " + potentialUpdate);
++numberOfUpdates;
}
log.debug(output.toString());
}
log.debug(" --> " + numberOfUpdates + " updates");
}
private final class PotentialUpdate implements Update {
private Update update;
private int position;
public PotentialUpdate(Update update) {
this.update = update;
this.position = updateCount++;
}
public SComponent getComponent() {
return update.getComponent();
}
public Handler getHandler() {
return update.getHandler();
}
public int getProperty() {
return update.getProperty();
}
public int getPriority() {
return update.getPriority();
}
public int getPosition() {
return position;
}
@Override
public boolean equals(Object object) {
if (object == this)
return true;
if (object == null || object.getClass() != this.getClass())
return false;
PotentialUpdate other = (PotentialUpdate) object;
return update.equals(other.update);
}
@Override
public int hashCode() {
return update.hashCode();
}
@Override
public String toString() {
String clazz = update.getClass().getName();
int index = clazz.lastIndexOf("$");
if (index < 0)
index = clazz.lastIndexOf(".");
return clazz.substring(++index) + "[" + getPriority() + "|" + getPosition() + "]";
}
}
private Comparator<PotentialUpdate> getUpdateComparator() {
return
new CombinedComparator<PotentialUpdate>(
new InverseComparator<PotentialUpdate>(new PriorityComparator()),
new PositionComparator()
);
}
private static class PathComparator implements Comparator<String> {
public int compare(String path1, String path2) {
int depthOfPath1 = (new StringTokenizer(path1, ":")).countTokens();
int depthOfPath2 = (new StringTokenizer(path2, ":")).countTokens();
if (depthOfPath1 < depthOfPath2) return -1;
if (depthOfPath1 > depthOfPath2) return 1;
return path1.compareTo(path2);
}
}
private static class PositionComparator implements Comparator<PotentialUpdate> {
public int compare(PotentialUpdate object1, PotentialUpdate object2) {
if (object1.getPosition() < object2.getPosition()) return -1;
if (object1.getPosition() > object2.getPosition()) return 1;
return 0;
}
}
private static class PriorityComparator implements Comparator<PotentialUpdate> {
public int compare(PotentialUpdate object1, PotentialUpdate object2) {
if (object1.getPriority() < object2.getPriority()) return -1;
if (object1.getPriority() > object2.getPriority()) return 1;
return 0;
}
}
private static class CombinedComparator<T> implements Comparator<T> {
private Comparator<T> comparator1;
private Comparator<T> comparator2;
public CombinedComparator(Comparator<T> c1, Comparator<T> c2) {
this.comparator1 = c1;
this.comparator2 = c2;
}
public int compare(T object1, T object2) {
int result = comparator1.compare(object1, object2);
if (result == 0)
return comparator2.compare(object1, object2);
else
return result;
}
}
private static class InverseComparator<T> implements Comparator<T> {
private Comparator<T> comparator;
public InverseComparator(Comparator<T> c) {
this.comparator = c;
}
public int compare(T object1, T object2) {
return -comparator.compare(object1, object2);
}
}
}
|
import java.util.ArrayList;
/**
* @author lcartercondon
*
*/
public class DayTwo {
/**
* @param none
* Day two of class
* Talking about basic types, casting, basic operators
*/
public static void main(String[] args) {
Integer change = 99;
ArrayList<Integer> coins = new ArrayList<Integer>();
coins.add(25);
coins.add(10);
coins.add(5);
coins.add(1);
ArrayList<Integer> handover = greedy(change, coins);
System.out.println("Change for " + change + " cents is "
+ handover.get(0) + " quarters, "
+ handover.get(1) + " dimes, "
+ handover.get(2) + " nickels, and "
+ handover.get(3) + " pennies."
);
}
private static ArrayList<Integer> greedy(Integer a, ArrayList<Integer> b){
ArrayList<Integer> retval = new ArrayList<Integer>();
for(int i = 0; i < b.size(); i++){
retval.add(a/b.get(i));
a %= b.get(i);
}
return retval;
}
}
|
package mmlib4j.images.impl;
import java.util.LinkedList;
import mmlib4j.images.ColorImage;
import mmlib4j.images.GrayScaleImage;
import mmlib4j.segmentation.Labeling;
import mmlib4j.utils.AdjacencyRelation;
import mmlib4j.utils.ImageUtils;
/**
* MMLib4J - Mathematical Morphology Library for Java
* @author Wonder Alexandre Luz Alves
*
*/
public abstract class AbstractGrayScale extends AbstractImage2D implements GrayScaleImage{
protected Statistics stats = null;
//protected int padding = Integer.MIN_VALUE;
public void paintBoundBox(int x1, int y1, int x2, int y2, int color){
int w = x2 - x1;
int h = y2 - y1;
for(int i=0; i < w; i++){
for(int j=0; j < h; j++){
if(i == 0 || j == 0 || i == w-1 || j == h-1)
setPixel(x1 + i, y1 + j, color);
}
}
}
public int countPixels(int color) {
int area =0;
for(int p=0; p < getSize(); p++){
if(getPixel(p) == color){
area++;
}
}
return area;
}
/**
* Inicializar todos os pixel da imagem para um dado nivel de cinza
* @param color
*/
public void initImage(int color){
for(int p=0; p < getSize(); p++){
setPixel(p, color);
}
}
/**
* modifica todos os niveis de cinza de uma dada cor para uma outra cor
* @param colorOld
* @param colorNew
*/
public void replaceValue(int colorOld, int colorNew){
for(int i=0; i < this.getSize(); i++){
if(getPixel(i) == colorOld)
setPixel(i, colorNew);
}
}
/*
public int getValuePixel(int x, int y) {
return isPixelValid(x, y) ? getPixel(x, y): padding;
}
public int getValuePixel(int i) {
return isPixelValid(i) ? getPixel(i): padding;
}
*/
public int getValue(int x, int y) {
return getPixel( getPixelIndexer().getIndex(x, y) );
}
public int getValue(int p) {
return getPixel( getPixelIndexer().getIndex(p) );
}
/**
* Pega um histograma da imagem
* @return int[]
*/
public int[] getHistogram() {
int result[] = new int[(int)Math.pow(2, getDepth())];
for(int p=0; p < getSize(); p++){
result[getPixel(p)]++;
}
return result;
}
public LinkedList<Integer>[] getPixelsOfHistogram(){
LinkedList<Integer> result[] = new LinkedList[(int)Math.pow(2, getDepth())];
for(int p=0; p < this.getSize(); p++){
if(result[this.getPixel(p)] == null)
result[this.getPixel(p)] = new LinkedList<Integer>();
result[this.getPixel(p)].add(p);
}
return result;
}
/**
* Pega o quantidade de valores diferente na imagem
*/
public int numValues() {
int h[] = getHistogram();
int numPixel = 0;
for(int i=0; i < h.length; i++)
if(h[i] > 0) numPixel++;
return numPixel;
}
/*
public void setPadding(int value){
this.padding = value;
}*/
/**
* Verifica se duas imagens sao iguais
* @param img - IGrayScaleImage
* @return true se forem iguais false caso contrario
*/
public boolean equals(Object o){
GrayScaleImage img = (GrayScaleImage) o;
for(int p=0; p < getSize(); p++){
if(getPixel(p) != img.getPixel(p))
return false;
}
return true;
}
public void add(int a){
int maxValue = (int) Math.pow(2, getDepth()) - 1;
for(int p=0; p < getSize(); p++){
if(getPixel(p) + a > maxValue){
setPixel(p, maxValue);
}
else if(getPixel(p) + a < 0){
setPixel(p, 0);
}
else{
setPixel(p, getPixel(p) + a);
}
}
}
public void multiply(double a){
int maxValue = (int) Math.pow(2, getDepth()) - 1;
for(int p=0; p < getSize(); p++){
if(getPixel(p) * a > maxValue){
setPixel(p, maxValue);
}
else if(getPixel(p) * a < 0){
setPixel(p, 0);
}
else{
setPixel(p, (int) (getPixel(p) * a));
}
}
}
public void invert(){
int maxValue = (int) Math.pow(2, getDepth()) - 1;
for(int p=0; p < getSize(); p++){
setPixel(p, maxValue - this.getPixel(p));
}
}
public GrayScaleImage getInvert(){
GrayScaleImage imgOut = this.duplicate();
imgOut.invert();
return imgOut;
}
public ColorImage randomColor(int alpha){
int max = this.maxValue();
int r[] = new int[max+1];
int g[] = new int[max+1];
int b[] = new int[max+1];
for(int i=1; i <= max; i++){
r[i] = ImageUtils.randomInteger(0, 255);
g[i] = ImageUtils.randomInteger(0, 255);
b[i] = ImageUtils.randomInteger(0, 255);
}
ColorImage imgOut = new RGBImage(this.getWidth(), this.getHeight());
imgOut.setAlpha(alpha);
for(int i=0; i < imgOut.getSize(); i++){
imgOut.setRed(i, r[i]);
imgOut.setGreen(i, g[i]);
imgOut.setBlue(i, b[i]);
}
return imgOut;
}
public ColorImage randomColor(){
int max = this.maxValue();
int r[] = new int[max+1];
int g[] = new int[max+1];
int b[] = new int[max+1];
for(int i= 1; i <= max; i++){
r[i] = ImageUtils.randomInteger(0, 255);
g[i] = ImageUtils.randomInteger(0, 255);
b[i] = ImageUtils.randomInteger(0, 255);
}
ColorImage imgOut = new RGBImage(this.getWidth(), this.getHeight());
for(int i=0; i < imgOut.getSize(); i++){
imgOut.setRed(i, r[this.getPixel(i)]);
imgOut.setGreen(i, g[this.getPixel(i)]);
imgOut.setBlue(i, b[this.getPixel(i)]);
}
return imgOut;
}
/**
* Pega o valor do maior pixel da imagem
*/
public int maxValue() {
if(stats == null)
loadStatistics();
return stats.max;
}
/**
* Pega o valor da media dos pixels da imagem
*/
public float meanValue() {
if(stats == null)
loadStatistics();
return stats.mean;
}
public float standerDeviationValue() {
if(stats == null)
loadStatistics();
if(stats.sd == Float.NaN){
for(int p=0; p < getSize(); p++){
stats.sd += Math.pow(getPixel(p) - stats.mean, 2);
}
stats.sd = (float) Math.sqrt( stats.sd / getSize() );
}
return stats.mean;
}
/**
* Pega o valor menor pixel da imagem
*/
public int minValue() {
if(stats == null)
loadStatistics();
return stats.min;
}
public ColorImage labeling(AdjacencyRelation adj){
return Labeling.labeling(this, adj).randomColor();
}
/**
* Pega o maior pixel da imagem
*/
public int maxPixel() {
if(this.stats == null)
loadStatistics();
return stats.pixelMax;
}
/**
* Pega o menor pixel da imagem
*/
public int minPixel() {
if(stats == null)
loadStatistics();
return stats.pixelMin;
}
/**
* Devolve o valor do pixel (x, y) interpolado
* @param x
* @param y
* @return
*/
public double getInterpolatedPixel(double x, double y) {
int xbase = (int)x;
int ybase = (int)y;
double xFraction = x - xbase;
double yFraction = y - ybase;
int offset = ybase * width + xbase;
int lowerLeft = getPixel(offset);// pixels[offset]&255;
if ((xbase>=(width-1))||(ybase>=(height-1)))
return lowerLeft;
int lowerRight = getPixel(offset + 1);// pixels[offset + 1]&255;
int upperRight = getPixel(offset + width + 1); //pixels[offset + width + 1]&255;
int upperLeft = getPixel(offset + width); // pixels[offset + width]&255;
double upperAverage = upperLeft + xFraction * (upperRight - upperLeft);
double lowerAverage = lowerLeft + xFraction * (lowerRight - lowerLeft);
return lowerAverage + yFraction * (upperAverage - lowerAverage);
}
public void drawLine(int x1, int y1, int x2, int y2, int grayLine){
//algoritmo de bresenham
if(Math.abs( x2 - x1 ) > Math.abs( y2 - y1 )){
if(x1 > x2) drawLine(x2, y2, x1, y1, grayLine);
int a = x2 - x1;
int b = y2 -y1;
int inc = 1;
if(b<0){
inc = -1;
b = -b;
}
int v = 2 * a + b;
int neg = 2 * b;
int pos = 2 * (b - a);
int x = x1;
int y = y1;
this.setPixel(x, y, grayLine);
while (x<= x2){
if(isPixelValid(x, y))
this.setPixel(x, y, grayLine);
x= x + 1;
if(v <= 0){
v = v + neg;
}else{
y = y + inc;
v = v+ pos;
}
}
}else{
if(y1 > y2) drawLine(x2, y2, x1, y1, grayLine);
int b = x2 - x1;
int a = y2 - y1;
int inc = 1;
if( b < 0){
inc = -1;
b = -b;
}
int v = 2 * b - a;
int neg = 2 * b;
int pos = 2 * (b - a);
int x = x1;
int y = y1;
this.setPixel(x, y, grayLine);
while(y <= y2){
if(isPixelValid(x, y))
this.setPixel(x, y, grayLine);
y = y + 1;
if(v <= 0){
v = v + neg;
}else{
x = x + inc;
v = v + pos;
}
}
}
}
public void loadStatistics(){
this.stats = new Statistics();
}
class Statistics{
int min;
int max;
int pixelMin;
int pixelMax;
float mean;
float sd=Float.NaN;
Statistics(){
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
int sum=0;
for (int i = 0; i < getSize(); i++){
sum += getPixel(i);
if(getPixel(i) < min){
min = getPixel(i);
pixelMin = i;
}
if(getPixel(i) > max){
max = getPixel(i);
pixelMax = i;
}
}
mean = sum / (float) (getWidth() * getHeight());
}
}
}
|
package net.kevxu.senselib;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
/**
* Class for providing orientation information. start() and stop() must be
* explicitly called to start and stop the internal thread.
*
* @author Kaiwen Xu
*/
public class OrientationService extends SensorService implements SensorEventListener {
private static final String TAG = "SensorService";
private Context mContext;
private SensorManager mSensorManager;
private List<OrientationServiceListener> mOrientationServiceListeners;
private Sensor mGravitySensor;
private Sensor mMagneticFieldSensor;
private OrientationSensorThread mOrientationSensorThread;
public interface OrientationServiceListener {
public void onOrientationChanged(float[] values);
public void onRotationMatrixChanged(float[] R, float[] I);
/**
* Called when magnetic field changes.
* <p>
* values[0], values[1] and values[2] represents the magnetic field
* along the x, y and z axis correspondingly. The unit is uT.
*
* @param values array of float length of 3.
*/
public void onMagneticFieldChanged(float[] values);
}
protected OrientationService(Context context) throws SensorNotAvailableException {
this(context, null);
}
protected OrientationService(Context context, OrientationServiceListener orientationServiceListener) throws SensorNotAvailableException {
mContext = context;
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> gravitySensors = mSensorManager.getSensorList(Sensor.TYPE_GRAVITY);
List<Sensor> magneticFieldSensor = mSensorManager.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);
int notAvailabelSensors = 0;
if (gravitySensors.size() == 0) {
// Gravity sensor not available
notAvailabelSensors = notAvailabelSensors | Sensor.TYPE_GRAVITY;
} else {
// Assume the first in the list is the default sensor
// Assumption may not be true though
mGravitySensor = gravitySensors.get(0);
}
if (magneticFieldSensor.size() == 0) {
// Magnetic Field sensor not available
notAvailabelSensors = notAvailabelSensors | Sensor.TYPE_MAGNETIC_FIELD;
} else {
// Assume the first in the list is the default sensor
// Assumption may not be true though
mMagneticFieldSensor = magneticFieldSensor.get(0);
}
if (notAvailabelSensors != 0) {
// Some sensors are not available
throw new SensorNotAvailableException(notAvailabelSensors, "Orientation Service");
}
mOrientationServiceListeners = new ArrayList<OrientationServiceListener>();
if (orientationServiceListener != null) {
mOrientationServiceListeners.add(orientationServiceListener);
}
}
/**
* Call this when start or resume.
*/
@Override
protected void start() {
if (mOrientationSensorThread == null) {
mOrientationSensorThread = new OrientationSensorThread();
mOrientationSensorThread.start();
Log.i(TAG, "OrientationSensorThread started.");
}
if (mSensorManager == null) {
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
}
mSensorManager.registerListener(this, mGravitySensor, SensorManager.SENSOR_DELAY_GAME);
Log.i(TAG, "Gravity sensor registered.");
mSensorManager.registerListener(this, mMagneticFieldSensor, SensorManager.SENSOR_DELAY_GAME);
Log.i(TAG, "Magnetic field sensor registered.");
Log.i(TAG, "OrientationService started.");
}
/**
* Call this when pause.
*/
@Override
protected void stop() {
mOrientationSensorThread.terminate();
Log.i(TAG, "Waiting for OrientationSensorThread to stop.");
try {
mOrientationSensorThread.join();
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage(), e);
}
Log.i(TAG, "OrientationSensorThread stopped.");
mOrientationSensorThread = null;
mSensorManager.unregisterListener(this);
Log.i(TAG, "Sensors unregistered.");
Log.i(TAG, "OrientationService stopped.");
}
private final class OrientationSensorThread extends AbstractSensorWorkerThread {
private float[] gravity;
private float[] geomagnetic;
private float[] orientation;
private float[] R;
private float[] I;
public OrientationSensorThread() {
this(DEFAULT_INTERVAL);
}
public OrientationSensorThread(long interval) {
super(interval);
orientation = new float[3];
R = new float[9];
I = new float[9];
}
public synchronized void pushGravity(float[] values) {
if (gravity == null) {
gravity = new float[3];
}
System.arraycopy(values, 0, gravity, 0, 3);
}
public synchronized void pushGeomagnetic(float[] values) {
if (geomagnetic == null) {
geomagnetic = new float[3];
}
System.arraycopy(values, 0, geomagnetic, 0, 3);
}
public synchronized float[] getGravity() {
return gravity;
}
public synchronized float[] getGeomagnetic() {
return geomagnetic;
}
@Override
public void run() {
while (!isTerminated()) {
if (getGravity() != null && getGeomagnetic() != null) {
SensorManager.getRotationMatrix(R, I, getGravity(), getGeomagnetic());
SensorManager.getOrientation(R, orientation);
}
for (OrientationServiceListener listener : mOrientationServiceListeners) {
listener.onOrientationChanged(orientation);
listener.onRotationMatrixChanged(R, I);
if (getGeomagnetic() != null) {
listener.onMagneticFieldChanged(getGeomagnetic());
}
}
try {
Thread.sleep(getInterval());
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage(), e);
}
}
}
}
public OrientationService addListener(OrientationServiceListener orientationServiceListener) {
if (orientationServiceListener != null) {
mOrientationServiceListeners.add(orientationServiceListener);
return this;
} else {
throw new NullPointerException("OrientationServiceListener is null.");
}
}
protected OrientationService removeListeners() {
mOrientationServiceListeners.clear();
return this;
}
@Override
public void onSensorChanged(SensorEvent event) {
synchronized (this) {
if (mOrientationSensorThread != null) {
Sensor sensor = event.sensor;
int type = sensor.getType();
if (type == Sensor.TYPE_GRAVITY) {
mOrientationSensorThread.pushGravity(event.values);
} else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
mOrientationSensorThread.pushGeomagnetic(event.values);
}
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Not used
}
}
|
package org.exist.storage;
import org.apache.log4j.Logger;
import org.exist.management.Agent;
import org.exist.management.AgentFactory;
import org.exist.storage.cache.Cache;
import org.exist.util.DatabaseConfigurationException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
/**
* CacheManager maintains a global memory pool available
* to all page caches. All caches start with a low default
* setting, but CacheManager can grow individual caches
* until the total memory is reached. Caches can also be
* shrinked if their "load" remains below a given threshold
* between check intervals.The check interval is determined
* by the global sync background thread.
*
* The class computes the available memory in terms of
* pages.
*
* @author wolf
*
*/
public class DefaultCacheManager implements CacheManager {
private final static Logger LOG = Logger.getLogger(DefaultCacheManager.class);
/**
* The maximum fraction of the total memory that can
* be used by a single cache.
*/
public final static double MAX_MEM_USE = 0.9;
/**
* The minimum size a cache needs to have to be
* considered for shrinking, defined in terms of a fraction
* of the overall memory.
*/
public final static double MIN_SHRINK_FACTOR = 0.5;
/**
* The amount by which a large cache will be shrinked if
* other caches request a resize.
*/
public final static double SHRINK_FACTOR = 0.7;
/**
* The minimum number of pages that must be read from a
* cache between check intervals to be not considered for
* shrinking. This is a measure for the "load" of the cache. Caches
* with high load will never be shrinked.
*/
public final static int SHRINK_THRESHOLD = 10000;
public static int DEFAULT_CACHE_SIZE = 64;
public static final String CACHE_SIZE_ATTRIBUTE = "cacheSize";
public static final String PROPERTY_CACHE_SIZE = "db-connection.cache-size";
/** Caches maintained by this class */
private List caches = new ArrayList();
private long totalMem;
/**
* The total maximum amount of pages shared between
* all caches.
*/
private int totalPageCount;
/**
* The number of pages currently used by the active caches.
*/
private int currentPageCount = 0;
/**
* The maximum number of pages that can be allocated by a
* single cache.
*/
private int maxCacheSize;
/**
* Signals that a resize had been requested by a cache, but
* the request could not be accepted during normal operations.
* The manager might try to shrink the largest cache during the
* next sync event.
*/
private Cache lastRequest = null;
private String instanceName;
public DefaultCacheManager(BrokerPool pool) {
this.instanceName = pool.getId();
int pageSize, cacheSize;
if ((pageSize = pool.getConfiguration().getInteger(NativeBroker.PROPERTY_PAGE_SIZE)) < 0)
//TODO : should we share the page size with the native broker ?
pageSize = NativeBroker.DEFAULT_PAGE_SIZE;
if ((cacheSize = pool.getConfiguration().getInteger(PROPERTY_CACHE_SIZE)) < 0) {
cacheSize = DEFAULT_CACHE_SIZE;
}
totalMem = cacheSize * 1024 * 1024;
int buffers = (int) (totalMem / pageSize);
this.totalPageCount = buffers;
this.maxCacheSize = (int) (totalPageCount * MAX_MEM_USE);
NumberFormat nf = NumberFormat.getNumberInstance();
LOG.info("Cache settings: totalPages: " + nf.format(totalPageCount) +
"; maxCacheSize: " + nf.format(maxCacheSize));
registerMBean();
}
public void registerCache(Cache cache) {
currentPageCount += cache.getBuffers();
caches.add(cache);
cache.setCacheManager(this);
registerMBean(cache);
}
public void deregisterCache(Cache cache) {
Cache next;
for (int i = 0; i < caches.size(); i++) {
next = (Cache) caches.get(i);
if (cache == next) {
caches.remove(i);
break;
}
}
currentPageCount -= cache.getBuffers();
}
public int requestMem(Cache cache) {
if (currentPageCount >= totalPageCount) {
if (cache.getBuffers() < maxCacheSize)
lastRequest = cache;
// no free pages available
// LOG.debug("Cache " + cache.getFileName() + " cannot be resized");
return -1;
}
if (cache.getGrowthFactor() > 1.0
&& cache.getBuffers() < maxCacheSize) {
synchronized (this) {
if (currentPageCount >= totalPageCount)
// another cache has been resized. Give up
return -1;
// calculate new cache size
int newCacheSize = (int)(cache.getBuffers() * cache.getGrowthFactor());
if (newCacheSize > maxCacheSize)
// new cache size is too large: adjust
newCacheSize = maxCacheSize;
if (currentPageCount + newCacheSize > totalPageCount)
// new cache size exceeds total: adjust
newCacheSize = cache.getBuffers() + (totalPageCount - currentPageCount);
if (LOG.isDebugEnabled()) {
NumberFormat nf = NumberFormat.getNumberInstance();
LOG.debug("Growing cache " + cache.getFileName() + " (a " + cache.getClass().getName() +
") from " + nf.format(cache.getBuffers()) +
" to " + nf.format(newCacheSize));
}
currentPageCount -= cache.getBuffers();
// resize the cache
cache.resize(newCacheSize);
currentPageCount += newCacheSize;
// LOG.debug("currentPageCount = " + currentPageCount + "; max = " + totalPageCount);
return newCacheSize;
}
}
return -1;
}
/**
* Called from the global major sync event to check if caches can
* be shrinked. To be shrinked, the size of a cache needs to be
* larger than the factor defined by {@link #MIN_SHRINK_FACTOR}
* and its load needs to be lower than {@link #SHRINK_THRESHOLD}.
*
* If shrinked, the cache will be reset to the default initial cache size.
*/
public void checkCaches() {
int minSize = (int) (totalPageCount * MIN_SHRINK_FACTOR);
Cache cache;
int load;
for (int i = 0; i < caches.size(); i++) {
cache = (Cache) caches.get(i);
if (cache.getGrowthFactor() > 1.0) {
load = cache.getLoad();
if (cache.getBuffers() > minSize && load < SHRINK_THRESHOLD) {
if (LOG.isDebugEnabled()) {
NumberFormat nf = NumberFormat.getNumberInstance();
LOG.debug("Shrinking cache: " + cache.getFileName() + " (a " + cache.getClass().getName() +
") to " + nf.format(cache.getBuffers()));
}
currentPageCount -= cache.getBuffers();
cache.resize(getDefaultInitialSize());
currentPageCount += getDefaultInitialSize();
}
}
}
}
public void checkDistribution() {
if (lastRequest == null)
return;
int minSize = (int) (totalPageCount * MIN_SHRINK_FACTOR);
Cache cache;
for (int i = 0; i < caches.size(); i++) {
cache = (Cache) caches.get(i);
if (cache.getBuffers() >= minSize) {
int newSize = (int) (cache.getBuffers() * SHRINK_FACTOR);
if (LOG.isDebugEnabled()) {
NumberFormat nf = NumberFormat.getNumberInstance();
LOG.debug("Shrinking cache: " + cache.getFileName() + " (a " + cache.getClass().getName() +
") to " + nf.format(newSize));
}
currentPageCount -= cache.getBuffers();
cache.resize(newSize);
currentPageCount += newSize;
break;
}
}
lastRequest = null;
}
public long getMaxTotal() {
return totalPageCount;
}
public long getCurrentSize() {
return currentPageCount;
}
public long getMaxSingle() {
return maxCacheSize;
}
public long getTotalMem() {
return totalMem;
}
/**
* Returns the default initial size for all caches.
*
* @return Default initial size 64.
*/
public int getDefaultInitialSize() {
return DEFAULT_CACHE_SIZE;
}
private void registerMBean() {
Agent agent = AgentFactory.getInstance();
try {
agent.addMBean("org.exist.management." + instanceName +
":type=CacheManager",
new org.exist.management.CacheManager(this));
} catch (DatabaseConfigurationException e) {
LOG.warn("Exception while registering cache mbean.", e);
}
}
private void registerMBean(Cache cache) {
Agent agent = AgentFactory.getInstance();
try {
agent.addMBean("org.exist.management." + instanceName + ":type=CacheManager.Cache,name=" +
cache.getFileName() + ",cache-type=" + cache.getType(),
new org.exist.management.Cache(cache));
} catch (DatabaseConfigurationException e) {
LOG.warn("Exception while registering cache mbean.", e);
}
}
}
|
package org.exist.xquery.util;
import org.exist.Namespaces;
import org.exist.xquery.ErrorCodes;
import org.exist.xquery.Expression;
import org.exist.xquery.XPathException;
import org.exist.xquery.functions.fn.FnModule;
import org.exist.xquery.value.NodeValue;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.util.Properties;
/**
* Serializer utilities used by several XQuery functions.
*/
public class SerializerUtils {
/**
* Parse output:serialization-parameters XML fragment into serialization
* properties as defined by the fn:serialize function.
*
* @param parent the parent expression calling this method
* @param parameters root node of the XML fragment
* @param properties parameters are added to the given properties
*/
public static void getSerializationOptions(final Expression parent, final NodeValue parameters, final Properties properties) throws XPathException {
try {
final XMLStreamReader reader = parent.getContext().getXMLStreamReader(parameters);
while (reader.hasNext() && (reader.next() != XMLStreamReader.START_ELEMENT)) {
}
if (!Namespaces.XSLT_XQUERY_SERIALIZATION_NS.equals(reader.getNamespaceURI())) {
throw new XPathException(parent, FnModule.SENR0001, "serialization parameter elements should be in the output namespace");
}
while (reader.hasNext()) {
final int status = reader.next();
if (status == XMLStreamReader.START_ELEMENT) {
final String key = reader.getLocalName();
if (properties.contains(key)) {
throw new XPathException(parent, FnModule.SEPM0019, "serialization parameter specified twice: " + key);
}
String value = reader.getAttributeValue("", "value");
if (value == null) {
// backwards compatibility: use element text as value
value = reader.getElementText();
}
properties.put(key, value);
}
}
} catch (final XMLStreamException | IOException e) {
throw new XPathException(parent, ErrorCodes.EXXQDY0001, e.getMessage());
}
}
}
|
package org.htmlcleaner;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.net.URL;
public class ConfigFileTagProvider extends HashMap implements ITagInfoProvider {
// obtaining instance of the SAX parser factory
static SAXParserFactory parserFactory = SAXParserFactory.newInstance();
static {
parserFactory.setValidating(false);
parserFactory.setNamespaceAware(false);
}
// tells whether to generate code of the tag provider class based on XML configuration file
// to the standard output
private boolean generateCode = false;
private ConfigFileTagProvider() {
}
public ConfigFileTagProvider(InputSource inputSource) {
try {
new ConfigParser(this).parse(inputSource);
} catch (Exception e) {
throw new HtmlCleanerException("Error parsing tag configuration file!", e);
}
}
public ConfigFileTagProvider(File file) {
try {
new ConfigParser(this).parse(new InputSource(new FileReader(file)));
} catch (Exception e) {
throw new HtmlCleanerException("Error parsing tag configuration file!", e);
}
}
public ConfigFileTagProvider(URL url) {
try {
Object content = url.getContent();
if (content instanceof InputStream) {
InputStreamReader reader = new InputStreamReader((InputStream)content);
new ConfigParser(this).parse(new InputSource(reader));
}
} catch (Exception e) {
throw new HtmlCleanerException("Error parsing tag configuration file!", e);
}
}
public TagInfo getTagInfo(String tagName) {
return (TagInfo) get(tagName);
}
/**
* Generates code for tag provider class from specified configuration XML file.
* In order to create custom tag info provider, make config file and call this main method
* with the specified file. Output will be generated on the standard output. This way default
* tag provider (class DefaultTagProvider) is generated from default.xml which which is packaged
* in the source distribution.
*
* @param args
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
final ConfigFileTagProvider provider = new ConfigFileTagProvider();
provider.generateCode = true;
File configFile = new File("default.xml");
String packagePath = "org.htmlcleaner";
String className = "DefaultTagProvider";
final ConfigParser parser = provider.new ConfigParser(provider);
System.out.println("package " + packagePath + ";");
System.out.println("import java.util.HashMap;");
System.out.println("public class " + className + " extends HashMap implements ITagInfoProvider {");
System.out.println("public " + className + "() {");
System.out.println("TagInfo tagInfo;");
parser.parse( new InputSource(new FileReader(configFile)) );
System.out.println("}");
System.out.println("}");
}
/**
* SAX parser for tag configuration files.
*/
private class ConfigParser extends DefaultHandler {
private TagInfo tagInfo = null;
private String dependencyName = null;
private Map tagInfoMap;
ConfigParser(Map tagInfoMap) {
this.tagInfoMap = tagInfoMap;
}
public void parse(InputSource in) throws ParserConfigurationException, SAXException, IOException {
SAXParser parser = parserFactory.newSAXParser();
parser.parse(in, this);
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (tagInfo != null) {
String value = new String(ch, start, length).trim();
if ( "fatal-tags".equals(dependencyName) ) {
tagInfo.defineFatalTags(value);
if (generateCode) {
System.out.println("tagInfo.defineFatalTags(\"" + value + "\");");
}
} else if ( "req-enclosing-tags".equals(dependencyName) ) {
tagInfo.defineRequiredEnclosingTags(value);
if (generateCode) {
System.out.println("tagInfo.defineRequiredEnclosingTags(\"" + value + "\");");
}
} else if ( "forbidden-tags".equals(dependencyName) ) {
tagInfo.defineForbiddenTags(value);
if (generateCode) {
System.out.println("tagInfo.defineForbiddenTags(\"" + value + "\");");
}
} else if ( "allowed-children-tags".equals(dependencyName) ) {
tagInfo.defineAllowedChildrenTags(value);
if (generateCode) {
System.out.println("tagInfo.defineAllowedChildrenTags(\"" + value + "\");");
}
} else if ( "higher-level-tags".equals(dependencyName) ) {
tagInfo.defineHigherLevelTags(value);
if (generateCode) {
System.out.println("tagInfo.defineHigherLevelTags(\"" + value + "\");");
}
} else if ( "close-before-copy-inside-tags".equals(dependencyName) ) {
tagInfo.defineCloseBeforeCopyInsideTags(value);
if (generateCode) {
System.out.println("tagInfo.defineCloseBeforeCopyInsideTags(\"" + value + "\");");
}
} else if ( "close-inside-copy-after-tags".equals(dependencyName) ) {
tagInfo.defineCloseInsideCopyAfterTags(value);
if (generateCode) {
System.out.println("tagInfo.defineCloseInsideCopyAfterTags(\"" + value + "\");");
}
} else if ( "close-before-tags".equals(dependencyName) ) {
tagInfo.defineCloseBeforeTags(value);
if (generateCode) {
System.out.println("tagInfo.defineCloseBeforeTags(\"" + value + "\");");
}
}
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ( "tag".equals(qName) ) {
String name = attributes.getValue("name");
String content = attributes.getValue("content");
String section = attributes.getValue("section");
String deprecated = attributes.getValue("deprecated");
String unique = attributes.getValue("unique");
String ignorePermitted = attributes.getValue("ignore-permitted");
tagInfo = new TagInfo(name,
"all".equals(content) ? TagInfo.CONTENT_ALL : ("none".equals(content) ? TagInfo.CONTENT_NONE : TagInfo.CONTENT_TEXT),
"all".equals(section) ? TagInfo.HEAD_AND_BODY : ("head".equals(section) ? TagInfo.HEAD : TagInfo.BODY),
deprecated != null && "true".equals(deprecated),
unique != null && "true".equals(unique),
ignorePermitted != null && "true".equals(ignorePermitted), CloseTag.required, Display.any );
if (generateCode) {
String s = "tagInfo = new TagInfo(\"#1\", #2, #3, #4, #5, #6);";
s = s.replaceAll("#1", name);
s = s.replaceAll("#2", "all".equals(content) ? "TagInfo.CONTENT_ALL" : ("none".equals(content) ? "TagInfo.CONTENT_NONE" : " TagInfo.CONTENT_TEXT"));
s = s.replaceAll("#3", "all".equals(section) ? "TagInfo.HEAD_AND_BODY" : ("head".equals(section) ? "TagInfo.HEAD" : "TagInfo.BODY"));
s = s.replaceAll("#4", Boolean.toString(deprecated != null && "true".equals(deprecated)));
s = s.replaceAll("#5", Boolean.toString(unique != null && "true".equals(unique)));
s = s.replaceAll("#6", Boolean.toString(ignorePermitted != null && "true".equals(ignorePermitted)));
System.out.println(s);
}
} else if ( !"tags".equals(qName) ) {
dependencyName = qName;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if ( "tag".equals(qName) ) {
if (tagInfo != null) {
tagInfoMap.put(tagInfo.getName(), tagInfo);
if (generateCode) {
System.out.println("this.put(\"" + tagInfo.getName() + "\", tagInfo);\n");
}
}
tagInfo = null;
} else if ( !"tags".equals(qName) ) {
dependencyName = null;
}
}
}
}
|
package ro.kuberam.xcrypt;
import java.util.List;
import java.util.Map;
import org.exist.xquery.AbstractInternalModule;
import org.exist.xquery.FunctionDef;
import java.util.List;
import java.util.Map;
import org.exist.xquery.XPathException;
/**
* Cryptographic module for eXist.
*
* @author Claudius Teodorescu (claud108@yahoo.com)
*/
public class XcryptModule extends AbstractInternalModule {
public final static String NAMESPACE_URI = "http://kuberam.ro/ns/x-crypt";
public final static String PREFIX = "x-crypt";
public final static String INCLUSION_DATE = "2010-12-17";
public final static String RELEASED_IN_VERSION = "eXist-1.5";
public final static FunctionDef[] functions = {
new FunctionDef(GenerateXMLSignatureFunction.signatures[0], GenerateXMLSignatureFunction.class),
new FunctionDef(GenerateXMLSignatureFunction.signatures[1], GenerateXMLSignatureFunction.class),
new FunctionDef(GenerateXMLSignatureFunction.signatures[2], GenerateXMLSignatureFunction.class),
new FunctionDef(GenerateXMLSignatureFunction.signatures[3], GenerateXMLSignatureFunction.class),
new FunctionDef(ValidateSignatureFunction.signature, ValidateSignatureFunction.class),
new FunctionDef(EncryptionFunctions.signatures[0], EncryptionFunctions.class),
new FunctionDef(EncryptionFunctions.signatures[1], EncryptionFunctions.class)
};
public XcryptModule(Map<String, List<? extends Object>> parameters) throws XPathException {
super(functions, parameters);
}
public String getNamespaceURI() {
return NAMESPACE_URI;
}
public String getDefaultPrefix() {
return PREFIX;
}
public String getDescription() {
return "A module with cryptographic functions.";
}
public String getReleaseVersion() {
return RELEASED_IN_VERSION;
}
}
|
import gui.CustomProgressVBox;
import javafx.application.Platform;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TextArea;
import javafx.scene.paint.Color;
public class RocketRunnable implements Runnable {
/**
* holds the time difference between every calculation
*/
private static int TIME_INTERVAL;
/**
* holds a factor that adjusts the time to write rocket info to the screen
*/
private static int DISPLAY_INTERVAL;
/**
* holds the value for adjustment of y coordinates
*/
public static double COORD_Y_FACTOR;
/**
* holds the value for adjustment of x coordinates
*/
public static double COORD_X_FACTOR;
private static final int TIME_INTERVAL_FOR_ACCELERATION = 500;
/**
* Holds the passed textarea
*/
TextArea mTextArea;
/**
* Holds the passed GraphicsContext for the Canvas
*/
GraphicsContext mGC;
/**
* holds the passed rocket
*/
Rocket mRocket;
/**
* holds the passed planet
*/
Planet mPlanet;
/**
* holds the passed canvas
*/
Canvas mCanvas;
/**
* hold the interface
*/
Interface mInterface;
/**
* The constructor for {@link RocketRunnable}
* @param pRocket the rocket which is to be calculated
* @param pInterface holds all nodes of the application interface
*/
public RocketRunnable(Rocket pRocket, Interface pInterface){
mInterface = pInterface;
mRocket = pRocket;
mPlanet = pInterface.mPlanetDropDown.getValue();
mTextArea = pInterface.mTextArea;
mGC = pInterface.mGC;
mCanvas = pInterface.mCanvas;
COORD_Y_FACTOR = mCanvas.getHeight()/pRocket.getInitDistance();
/* Use this X Factor for approximate landing in the middle
COORD_X_FACTOR = mRocket.getCurSpeed().getX() == 0 ? 1 :
(mCanvas.getWidth() / 3) / (mRocket.getCurSpeed().getX() *
Math.cos(Math.toRadians(mRocket.getCurSpeed().getAngleXAxis())) * mPlanet.getMaxLandingTime());
*/
COORD_X_FACTOR = COORD_Y_FACTOR * 0.05;
DISPLAY_INTERVAL = mPlanet.getMaxLandingTime()/10;
TIME_INTERVAL = (int) Math.ceil((double) mPlanet.getMaxLandingTime() / 10000);
mRocket.setInitCoordinates(new Coordinate2D(mCanvas.getWidth() / 2 / COORD_X_FACTOR,
mRocket.getInitCoordinates().getY() / COORD_Y_FACTOR));
}
@Override
public void run() {
Platform.runLater(this::updateProgressIndicator);
while (mRocket.getCurCoordinates().getY() < mRocket.getInitDistance()
&& mRocket.mTime < mPlanet.getMaxLandingTime()
&& mRocket.getCurFuelLevel() >= 0) {
Platform.runLater(() -> {
// different color for each rocket
mGC.setStroke((Color) RocketConstants.COLOR_PALETTE[mRocket.getRocketID()][0]);
Coordinate2D oldCoord = mRocket.getCurCoordinates();
calcNewCoordinates();
Coordinate2D newCoord = mRocket.getCurCoordinates();
mGC.strokeLine(oldCoord.getX() * COORD_X_FACTOR, oldCoord.getY() * COORD_Y_FACTOR,
newCoord.getX() * COORD_X_FACTOR, newCoord.getY() * COORD_Y_FACTOR);
if (mRocket.mTime != 0 && mRocket.mTime % DISPLAY_INTERVAL == 0) {
//mGC.fillOval(newCoord.getX() * COORD_X_FACTOR - 2, newCoord.getY() * COORD_Y_FACTOR - 2, 4, 4);
}
if(mRocket.mTime % 500 == 0 && mRocket.getRocketID() == 0){
//mTextArea.appendText("NOW \n");
}
mRocket.mTime += TIME_INTERVAL;
mRocket.setTime(mRocket.mTime);
mRocket.setProcessSpeed();
updateProgressIndicator();
});
// Sleep for a ms to not spam the application thread with runnables
try {
Thread.sleep(1);
} catch (InterruptedException e) {
mTextArea.appendText(e.getMessage());
}
// Setting process speed on every second
mRocket.setProcessSpeed();
}
mRocket.setCurCoordinates(mRocket.getCurCoordinates().getX(),
mRocket.getCurCoordinates().getY() < 0 ? 0 : mRocket.getCurCoordinates().getY());
Platform.runLater(() -> {
mGC.setFill((Color) RocketConstants.COLOR_PALETTE[mRocket.getRocketID()][0]);
mGC.setStroke((Color) RocketConstants.COLOR_PALETTE[mRocket.getRocketID()][0]);
mGC.fillOval(mRocket.getCurCoordinates().getX() * COORD_X_FACTOR - 3,
mRocket.getCurCoordinates().getY() * COORD_Y_FACTOR - 3, 6, 6);
mGC.strokeText(String.valueOf(mRocket.getRocketID()), mRocket.getCurCoordinates().getX() * COORD_X_FACTOR - 3,
mRocket.getCurCoordinates().getY() * COORD_Y_FACTOR - 3);
});
}
/**
* The mass of the Rocket is not accounted for in this calculation
* F = (G * m * M)/r^2
* F = m * a
* => a = (G * M)/r^2 || (m^3 * kg)/(kg * s^2 * m^2) => m/s^2
* @return
*/
public double calculateGravitationalAcceleration(){
double distance = calcDistance();
return (Planet.GRAVITATIONAL_CONSTANT * mPlanet.getMass())/(distance * distance);
}
/**
* distance to surface: initial distance minus Y Coordinate
* plus planet radius for simplification
* @return
*/
public double calcDistance() {
return mRocket.getInitDistance() - mRocket.getCurCoordinates().getY() + mPlanet.getRadius();
}
private double calcDistanceToSurface() {
return mRocket.getInitDistance() - mRocket.getCurCoordinates().getY();
}
/**
* Calculate acceleration by getting processAcceleration value
*/
public void calcCurAcceleration() {
if ((mRocket.mTime / TIME_INTERVAL_FOR_ACCELERATION) < mRocket.getProcessAcc().size()) {
if(mRocket.mTime % TIME_INTERVAL_FOR_ACCELERATION == 0){
// Take Value out of array from array[counter]
mRocket.setCurAcceleration(mRocket.getProcessAcc().get(mRocket.getProcessAccIndex()));
mRocket.setProcessAccIndex(mRocket.getProcessAccIndex() + 1);
}
} else {
System.out.println(mRocket.getRocketID() + ": Not enough mTime" + mRocket.mTime);
mRocket.setCurAcceleration(new Coordinate2D((Math.random() * ((5)) - 2.5), Math.random() * ((300)) - 150));
mRocket.addCurAccToProcessAcc();
}
}
/**
* TODO implement variable rocket acceleration
* this method calculates and sets the new coordinates and speed of the rocket
*/
public void calcNewCoordinates() {
// get the next Acceleration from the generated List or create a new one
calcCurAcceleration();
// Variables for the calculation of speed and coordinates
// gravitational acceleration
double g = calculateGravitationalAcceleration();
// inherent acceleration in x direction
double aX = mRocket.getCurAcceleration().getX();
// inherent acceleration in y direction
double aY = mRocket.getCurAcceleration().getY();
// current speed in x-direction
double vX = mRocket.getCurSpeed().getX();
// current speed in y-direction
double vY = mRocket.getCurSpeed().getY();
// cosine of angle to x-axis
double cosAlpha = Math.cos(Math.toRadians(mRocket.getCurSpeed().getAngleXAxis()));
// sinus of angle to x-axis
double sinAlpha = Math.sin(Math.toRadians(mRocket.getCurSpeed().getAngleXAxis()));
// Calculation of the new Coordinates
// v * cos(alpha) * t + 0.5 * aX * t^2
double newXCoord = mRocket.getCurCoordinates().getX() + vX * TIME_INTERVAL * cosAlpha + 0.5 * aX * TIME_INTERVAL * TIME_INTERVAL;
// v * sin(alpha) * t + 0.5 * (g + aY) * t^2
double newYCoord = mRocket.getCurCoordinates().getY() + vY * TIME_INTERVAL * sinAlpha + 0.5 * (g + aY) * TIME_INTERVAL * TIME_INTERVAL;
mRocket.setCurCoordinates(newXCoord, newYCoord);
// Calculation of the new Speed
// v * cos(alpha) + aX * t
double newXSpeed = vX * cosAlpha + aX * TIME_INTERVAL;
// v * sin(alpha) + (g + aY) * t
double newYSpeed = vY * sinAlpha + (g + aY) * TIME_INTERVAL;
mRocket.setCurSpeed(new Coordinate2D(newXSpeed, newYSpeed));
// calculate the fuel consumption according to the current acceleration
calcNewFuelLevel();
}
/**
* this method sets the current fuel level of the rocket depending on the current acceleration
*/
private void calcNewFuelLevel() {
mRocket.setCurFuelLevel(mRocket.getCurFuelLevel() - (RocketConstants.FUEL_PER_ACCELERATION * mRocket.getCurAcceleration().abs() * TIME_INTERVAL));
}
/**
* This method updates the progress box for each individial rocket
*/
private void updateProgressIndicator() {
double d = calcDistanceToSurface();
String col = "rgba(" + RocketConstants.COLOR_PALETTE[mRocket.getRocketID()][1] + "," + 0.6 + ")";
CustomProgressVBox box = mInterface.mProgressIndicatorMap.get(mRocket.getRocketID());
box.setStyle(
"-fx-background-color: " + col + ";" +
"-fx-border-style: solid;" +
"-fx-border-width: 2;" +
"-fx-border-color: black;"
);
// update time Label
box.getLabelDistance().setText(String.format("%.2f", d < 0 ? 0 : d));
// set rocket label
box.getLabelRocketId().setText("Rocket" + mRocket.getRocketID() + ":");
//box.getLabelRocketId().setTextFill(RocketConstants.COLOR_PALETTE[mRocket.getRocketID()]);
// set fuel level
box.getProgressBarFuelLevel().setProgress(mRocket.getCurFuelLevel() / mRocket.mInitFuelLevel);
// set time label
box.getLabelTime().setText(mRocket.mTime > mPlanet.getMaxLandingTime() ?
String.valueOf(mPlanet.getMaxLandingTime()) : String.valueOf(mRocket.mTime));
box.getLabelSpeed().setText(String.format("%.2f", mRocket.getCurSpeed().abs()));
}
}
|
package org.jpos.ee.pm.struts;
import java.util.HashMap;
import java.util.Map;
import org.jpos.ee.pm.core.EntityContainer;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.util.MessageResources;
import org.jpos.ee.pm.core.Entity;
import org.jpos.ee.pm.core.EntityFilter;
import org.jpos.ee.pm.core.EntitySupport;
import org.jpos.ee.pm.core.Field;
import org.jpos.ee.pm.core.Highlight;
import org.jpos.ee.pm.core.Operation;
import org.jpos.ee.pm.core.PMContext;
import org.jpos.ee.pm.core.PMCoreConstants;
import org.jpos.ee.pm.core.PMException;
import org.jpos.ee.pm.core.PMSession;
import org.jpos.ee.pm.core.PaginatedList;
import org.jpos.ee.pm.core.PresentationManager;
import org.jpos.ee.pm.core.operations.OperationScope;
/**
* Helper class for internal use.
*
* @author jpaoletti
* @see EntitySupport
*/
public class PMEntitySupport extends EntitySupport implements PMCoreConstants, PMStrutsConstants {
private String context_path;
private static PMEntitySupport instance;
private HttpServletRequest request;
public static final Map<String, String> htmlConversions = new HashMap<String, String>();
/* TODO Externalize this values into a resource */
static {
htmlConversions.put("á", "á");
htmlConversions.put("é", "é");
htmlConversions.put("í", "í");
htmlConversions.put("ó", "ó");
htmlConversions.put("ú", "ú");
htmlConversions.put("Á", "Á");
htmlConversions.put("É", "É");
htmlConversions.put("Í", "Í");
htmlConversions.put("Ó", "Ó");
htmlConversions.put("Ú", "Ú");
htmlConversions.put("ñ", "ñ");
htmlConversions.put("Ñ", "Ñ");
htmlConversions.put("º", "º");
htmlConversions.put("ª", "ª");
htmlConversions.put("ü", "ü");
htmlConversions.put("Ü", "Ü");
htmlConversions.put("ç", "ç");
htmlConversions.put("Ç", "Ç");
}
/**
* Singleton getter
* @return The PMEntitySupport
*/
public synchronized static PMEntitySupport getInstance() {
if (instance == null) {
instance = new PMEntitySupport();
}
return instance;
}
/**
* Return the container that is in the given request
*
* @param request The request
* @return The container
*/
public EntityContainer getContainer() throws PMStrutsException {
if (request == null) {
throw new PMStrutsException("request.not.found");
}
String pmid = (String) request.getAttribute(PM_ID);
return getPMSession().getContainer(pmid);
}
public PMSession getPMSession() throws PMStrutsException {
if (request == null) {
throw new PMStrutsException("request.not.found");
}
return (PMSession) request.getSession().getAttribute(PMSESSION);
}
/**
* Inserts the container entity into the request
*
* @param request The request
* @return The entity
* @throws PMStrutsException when the request was not setted
*/
public Entity getEntity() throws PMStrutsException {
EntityContainer container = getContainer();
if (container != null) {
return container.getEntity();
}
return null;
}
/**
* Inserts the container list into the request
* @param request The request
* @return The list
* @throws PMStrutsException when request has no container
*/
public PaginatedList getList() throws PMStrutsException {
EntityContainer container = getContainer();
if (container == null) {
throw new PMStrutsException("container.not.found");
}
PaginatedList list = container.getList();
return list;
}
/**
* Insert the container selected instance into the request
* @param request The request
* @return The list
* @throws PMStrutsException when request has no container
*/
public Object getSelected() throws PMStrutsException {
EntityContainer container = getContainer();
if (container == null) {
throw new PMStrutsException("container.not.found");
}
Object r = container.getSelected().getInstance();
return r;
}
/**
* Returns the filter applied
*
* @return The filter
* @throws PMStrutsException when request has no container
*/
public EntityFilter getFilter() throws PMStrutsException {
EntityContainer container = getContainer();
if (container == null) {
throw new PMStrutsException("container.not.found");
}
return container.getFilter();
}
/**
* Setter for context path
*
* @param context_path The context_path
*/
public void setContext_path(String context_path) {
this.context_path = context_path;
}
/**
* Getter for context path
*
* @return The context_path
*/
public String getContext_path() {
return context_path;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public Integer getListTotalDigits() {
try {
return (getList().getTotal() == null || getList().getTotal() == 0) ? 1 : (int) Math.log10(getList().getTotal()) + 1;
} catch (PMStrutsException ex) {
return 0;
}
}
public String getWelcomePage() {
return PresentationManager.getPm().getCfg().get("welcome-page", "pages/welcome.jsp");
}
public String getNavigationList(final EntityContainer container) {
final StringBuilder sb = new StringBuilder();
if (container != null && container.getSelected() != null) {
sb.append(getNavigationList(container.getOwner()));
sb.append(" > ");
sb.append("<a href='");
sb.append(getContext_path());
sb.append("/");
sb.append(container.getOperation().getId());
sb.append(".do?pmid=");
sb.append(container.getEntity().getId()).append("' >");
final Object inst = container.getSelected().getInstance();
if (inst == null) {
sb.append("");
} else {
sb.append(toHtml(inst.toString()));
}
sb.append("</a>");
}
return sb.toString();
}
public String getListItemOperations(final PMStrutsContext ctx, MessageResources messages, Object item, int i) throws PMException {
final StringBuilder sb = new StringBuilder();
sb.append("<span style='white-space: nowrap;' class='operationspopup'>");
for (Operation itemOperation : ctx.getOperations(item, ctx.getOperation()).getOperations()) {
if (ctx.getPMSession().getUser().hasPermission(itemOperation.getPerm())) {
//if operation is at item scope
if (OperationScope.ITEM.is(itemOperation.getScope())) {
String furl = "";
if (itemOperation.getUrl() != null) {
furl = itemOperation.getUrl();
} else {
furl = getContext_path() + "/" + itemOperation.getId() + ".do?pmid=" + ctx.getEntity().getId() + "&item=" + i;
}
sb.append("<a class='confirmable_");
sb.append(itemOperation.getConfirm());
sb.append("' href='");
sb.append(furl);
sb.append("' id='operation");
sb.append(itemOperation.getId());
sb.append("' title='");
sb.append(messages.getMessage("operation." + itemOperation.getId()));
sb.append("'><img src='");
sb.append(getContext_path());
sb.append("/templates/");
sb.append(ctx.getPresentationManager().getTemplate());
sb.append("/img/").append(itemOperation.getId());
sb.append(".gif' alt='");
sb.append(itemOperation.getId());
sb.append("' /></a>");
}
}
}
sb.append(" </span>");
return sb.toString();
}
public PMContext prepareForConversion(Field field, Object item, Object field_value) {
final PMContext ctx = (PMContext) request.getAttribute(PM_CONTEXT);
ctx.setField(field);
if (field_value != null) {
ctx.setFieldValue(field_value);
} else {
ctx.setFieldValue(ctx.getPresentationManager().get(item, field.getProperty()));
}
ctx.setEntityInstance(item);
ctx.put(PM_EXTRA_DATA, "");
request.setAttribute("ctx", ctx);
return ctx;
}
public String getHighlight(Entity entity, Field field, Object item, Object field_value) {
final Highlight highlight = entity.getHighlight(field, item);
if (highlight != null) {
return highlight.getStyle();
} else {
return "";
}
}
public static String toHtml(final String s) {
if (s == null) {
return null;
}
if (PresentationManager.getPm().getCfg().getBoolean("html-convert", true)) {
String tmp = s;
for (Map.Entry<String, String> entry : htmlConversions.entrySet()) {
tmp = tmp.replace(entry.getKey(), entry.getValue());
}
return tmp;
} else {
return s;
}
}
/**
* This method show a tooltip if the key is defined
* @param key Key
*/
public static String getTooltip(final String key) {
if (key == null) {
return "";
}
final String message = PresentationManager.getMessage(key);
if (key.equals(message)) {
return "";
}
return "<img class='tooltip' title='" + message + "' alt='?' src='" + getInstance().getContext_path() + "/templates/" + getInstance().getPM().getTemplate() + "/img/tooltip.gif' />";
}
/**
* Getter for PMSession from http session
*/
public static PMSession getPMSession(final HttpServletRequest request) {
return (PMSession) request.getSession().getAttribute(PMSESSION);
}
}
|
/*
* $Id: GoslingCrawlerImpl.java,v 1.23 2003-05-30 01:49:02 aalto Exp $
*/
package org.lockss.crawler;
import java.io.*;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
import org.lockss.daemon.*;
import org.lockss.util.*;
import org.lockss.plugin.*;
/**
* The crawler.
*
* @author Thomas S. Robertson
* @version 0.0
*/
public class GoslingCrawlerImpl implements Crawler {
/**
* TODO
* 1) write state to harddrive using whatever system we come up for for the
* rest of LOCKSS
* 2) check deadline and die if we run too long
*/
private static final String IMGTAG = "img";
private static final String ATAG = "a";
private static final String FRAMETAG = "frame";
private static final String LINKTAG = "link";
private static final String SCRIPTTAG = "script";
private static final String SCRIPTTAGEND = "/script";
private static final String BODYTAG = "body";
private static final String TABLETAG = "table";
private static final String TDTAG = "tc";
private static final String ASRC = "href";
private static final String SRC = "src";
private static final String BACKGROUNDSRC = "background";
private static Logger logger = Logger.getLogger("GoslingCrawlerImpl");
private ArchivalUnit au;
private List startUrls;
private boolean followLinks;
private long startTime = -1;
private long endTime = -1;
private int numUrlsFetched = 0;
private int numUrlsParsed = 0;
/**
* Construct a crawl object; does NOT start the crawl
* @param au {@link ArchivalUnit} that this crawl will happen on
* @param startUrls List of Strings representing the starting urls for crawl
* @param followLinks whether or not to extract and follow links
*/
public GoslingCrawlerImpl(ArchivalUnit au, List startUrls,
boolean followLinks) {
if (au == null) {
throw new IllegalArgumentException("Called with a null ArchivalUnit");
} else if (startUrls == null) {
throw new IllegalArgumentException("Called with a null start url list");
}
this.au = au;
this.startUrls = startUrls;
this.followLinks = followLinks;
}
public long getNumFetched() {
return numUrlsFetched;
}
public long getNumParsed() {
return numUrlsParsed;
}
public long getStartTime() {
return startTime;
}
public long getEndTime() {
return endTime;
}
public ArchivalUnit getAU() {
return au;
}
/**
* Main method of the crawler; it loops through crawling and caching
* urls.
*
* @param deadline when to terminate by
* @return true if no errors
*/
public boolean doCrawl(Deadline deadline) {
if (deadline == null) {
throw new IllegalArgumentException("Called with a null Deadline");
}
boolean wasError = false;
logger.info("Beginning crawl of "+au);
startTime = TimeBase.nowMs();
CachedUrlSet cus = au.getAUCachedUrlSet();
Set parsedPages = new HashSet();
Set extractedUrls = new HashSet();
Iterator it = startUrls.iterator();
while (it.hasNext() && !deadline.expired()) {
String url = (String)it.next();
//catch and warn if there's a url in the start urls
//that we shouldn't cache
if (au.shouldBeCached(url)) {
if (!doCrawlLoop(url, extractedUrls, parsedPages, cus, true)) {
wasError = true;
}
} else {
logger.warning("Called with a starting url we aren't suppose to "
+"cache: "+url);
}
}
while (!extractedUrls.isEmpty() && !deadline.expired()) {
String url = (String)extractedUrls.iterator().next();
extractedUrls.remove(url);
if (!doCrawlLoop(url, extractedUrls, parsedPages, cus, false)) {
wasError = true;
}
}
logger.info("Finished crawl of "+au);
endTime = TimeBase.nowMs();
return !wasError;
}
/**
* This is the meat of the crawl. Fetches the specified url and adds
* any urls it harvests from it to extractedUrls
* @param url url to fetch
* @param extractedUrls set to write harvested urls to
* @param parsedPages set containing all the pages that have already
* been parsed (to make sure we don't loop)
* @param cus cached url set that the url belongs to
* @param overWrite true if overwriting is desired
* @return true if there were no errors
*/
protected boolean doCrawlLoop(String url, Set extractedUrls,
Set parsedPages, CachedUrlSet cus,
boolean overWrite) {
boolean wasError = false;
logger.debug("Dequeued url from list: "+url);
UrlCacher uc = cus.makeUrlCacher(url);
// don't cache if already cached, unless overwriting
if (overWrite || !uc.getCachedUrl().hasContent()) {
try {
logger.debug("caching "+uc);
uc.cache(); //IOException if there is a caching problem
numUrlsFetched++;
} catch (FileNotFoundException e) {
logger.warning(uc+" not found on publisher's site");
} catch (IOException ioe) {
//XXX handle this better. Requeue?
logger.error("Problem caching "+uc+". Ignoring", ioe);
wasError = true;
}
}
else {
if (!parsedPages.contains(uc.getUrl())) {
logger.debug2(uc+" exists, not caching");
}
}
try {
if (followLinks && !parsedPages.contains(uc.getUrl())) {
CachedUrl cu = uc.getCachedUrl();
//XXX quick fix; if statement should be removed when we rework
//handling of error condition
if (cu.hasContent()) {
addUrlsToSet(cu, extractedUrls, parsedPages);//IOException if the CU can't be read
parsedPages.add(uc.getUrl());
numUrlsParsed++;
}
}
} catch (IOException ioe) {
//XXX handle this better. Requeue?
logger.error("Problem parsing "+uc+". Ignoring", ioe);
wasError = true;
}
logger.debug("Removing from list: "+uc.getUrl());
return !wasError;
}
/**
* Method which will parse the html file represented by cu and add all
* urls in it which should be cached to set
*
* @param cu object representing a html file in the local file system
* @param set set to which all the urs in cu should be added
* @param urlsToIgnore urls which should not be added to set
* @throws IOException
*/
protected void addUrlsToSet(CachedUrl cu, Set set, Set urlsToIgnore)
throws IOException {
if (shouldExtractLinksFromCachedUrl(cu)) {
String cuStr = cu.getUrl();
if (cuStr == null) {
logger.error("CachedUrl has null getUrl() value: "+cu);
return;
}
InputStream is = cu.openForReading();
Reader reader = new InputStreamReader(is); //should do this elsewhere
URL srcUrl = new URL(cuStr);
logger.debug("Extracting urls from srcUrl");
String nextUrl = null;
while ((nextUrl = extractNextLink(reader, srcUrl)) != null) {
logger.debug("Extracted "+nextUrl);
//should check if this is something we should cache first
if (!set.contains(nextUrl)
&& !urlsToIgnore.contains(nextUrl)
&& au.shouldBeCached(nextUrl)) {
set.add(nextUrl);
}
}
}
}
/**
* Determine if this is a CachedUrl that we can parse for new urls; currently
* this is just done by verifying that the "content-type" property exists
* and equals "text/html"
*
* @param cu CachedUrl representing the web page we may parse
* @return true if cu has "content-type" set to "text/html", false otherwise
*/
protected static boolean shouldExtractLinksFromCachedUrl(CachedUrl cu) {
boolean returnVal = false;
Properties props = cu.getProperties();
if (props != null) {
String contentType = props.getProperty("content-type");
if (contentType != null) {
//XXX check if the string starts with this
returnVal = contentType.toLowerCase().startsWith("text/html");
}
}
if (returnVal) {
logger.debug("I should try to extract links from "+cu);
} else {
logger.debug("I shouldn't try to extract links from "+cu);
}
return returnVal;
}
/**
* Read through the reader stream, extract and return the next url found
*
* @param reader Reader object to extract the link from
* @param srcUrl URL object representing the page we are looking at
* (for resolving relative links)
* @return String representing the next url in reader
* @throws IOException
* @throws MalformedURLException
*/
protected static String extractNextLink(Reader reader, URL srcUrl)
throws IOException, MalformedURLException {
if (reader == null) {
return null;
}
boolean inscript = false; //FIXME or I will break when we look at scripts
String nextLink = null;
int c = 0;
StringBuffer lineBuf = new StringBuffer();
while(nextLink == null && c >=0) {
//skip to the next tag
do {
c = reader.read();
} while (c >= 0 && c != '<');
if (c == '<') {
int pos = 0;
c = reader.read();
while (c >= 0 && c != '>') {
if(pos==2 && c=='-' && lineBuf.charAt(0)=='!'
&& lineBuf.charAt(1)=='-') {
// we're in a HTML comment
pos = 0;
int lc1 = 0;
int lc2 = 0;
while((c = reader.read()) >= 0
&& (c != '>' || lc1 != '-' || lc2 != '-')) {
lc1 = lc2;
lc2 = c;
}
break;
}
lineBuf.append((char)c);
pos++;
c = reader.read();
}
if (inscript) {
//FIXME when you deal with the script problems
// if(lookingAt(lineBuf, 0, pos, scripttagend)) {
inscript = false;
} else if (lineBuf.length() >= 5) { //see if the lineBuf has a link tag
nextLink = parseLink(lineBuf, srcUrl);
}
lineBuf = new StringBuffer();
}
}
return nextLink;
}
protected static String parseLink(StringBuffer link, URL srcUrl)
throws MalformedURLException {
String returnStr = null;
switch (link.charAt(0)) {
case 'a':
case 'A':
if (StringUtil.getIndexIgnoringCase(link.toString(),
ATAG+" ") == 0) {
returnStr = getAttributeValue(ASRC, link.toString());
}
break;
case 'f': //<frame src=frame1.html>
case 'F':
if (StringUtil.getIndexIgnoringCase(link.toString(),
FRAMETAG+" ") == 0) {
returnStr = getAttributeValue(SRC, link.toString());
}
break;
case 'i': //<img src=image.gif>
case 'I':
if (StringUtil.getIndexIgnoringCase(link.toString(),
IMGTAG+" ") == 0) {
returnStr = getAttributeValue(SRC, link.toString());
}
break;
case 'l': //<link href=blah.css>
case 'L':
if (StringUtil.getIndexIgnoringCase(link.toString(),
LINKTAG+" ") == 0) {
returnStr = getAttributeValue(ASRC, link.toString());
}
break;
case 'b': //<body backgroung=background.gif>
case 'B':
if (StringUtil.getIndexIgnoringCase(link.toString(),
BODYTAG+" ") == 0) {
returnStr = getAttributeValue(BACKGROUNDSRC, link.toString());
}
break;
case 's': //<script src=blah.js>
case 'S':
if (StringUtil.getIndexIgnoringCase(link.toString(),
SCRIPTTAG+" ") == 0) {
returnStr = getAttributeValue(SRC, link.toString());
}
break;
case 't': //<tc background=back.gif> or <table background=back.gif>
case 'T':
if (StringUtil.getIndexIgnoringCase(link.toString(),
TABLETAG+" ") == 0 ||
StringUtil.getIndexIgnoringCase(link.toString(),
TDTAG+" ") == 0) {
returnStr = getAttributeValue(BACKGROUNDSRC, link.toString());
}
break;
default:
return null;
}
if (returnStr != null) {
returnStr = StringUtil.trimAfterChars(returnStr, "
logger.debug("Generating url from: "+srcUrl+" and "+returnStr);
URL retUrl = new URL(srcUrl, returnStr);
returnStr = retUrl.toString();
logger.debug("Parsed: "+returnStr);
return returnStr;
}
return null;
}
private static String getAttributeValue(String attribute, String src) {
logger.debug("looking for "+attribute+" in "+src);
StringTokenizer st = new StringTokenizer(src, " =\"", true);
String lastToken = null;
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (!token.equals("=")) {
if (!token.equals(" ") && !token.equals("\"")) {
lastToken = token;
}
} else {
if (attribute.equalsIgnoreCase(lastToken))
while (st.hasMoreTokens()) {
token = st.nextToken();
if (!token.equals(" ") && !token.equals("\"")) {
return token;
}
}
}
}
return null;
}
}
|
package org.obd.ws.application;
import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.Router;
public class OBDApplication extends Application {
public OBDApplication(Context context){
super(context);
}
@Override
public Restlet createRoot() {
final Router router = new Router(this.getContext());
// URL mappings
router.attach("/phenoscape/term/{termID}", org.obd.ws.resources.TermResource.class);
router.attach("/phenoscape/term/search/{text}?name=[true|false]&syn=[true|false]&def=[true|false]" +
"&ontology=[TTO, TAO, ZFA, PATO, OBO_RO, SPATIAL, UNIT, SEQUENCE, COLLECTION, PHENOSCAPE]",
org.obd.ws.resources.AutoCompleteResource.class);
return router;
}
}
|
package edu.umd.cs.findbugs.gui;
import java.io.File;
import java.util.*;
import javax.swing.tree.DefaultTreeModel;
import edu.umd.cs.findbugs.*;
import org.apache.bcel.Repository;
import org.apache.bcel.util.ClassPath;
import org.apache.bcel.util.SyntheticRepository;
/**
* Representation of a run of the FindBugs analysis on a Project.
* This class has convenient methods which can be used to extract
* bug reports in various interesting ways.
*
* @author David Hovemeyer
*/
public class AnalysisRun {
/**
* Our BugReporter just puts the reported BugInstances into a HashSet.
*/
private class Reporter extends AbstractBugReporter {
private HashSet<BugInstance> bugSet = new HashSet<BugInstance>();
public void finish() { }
public void reportBug(edu.umd.cs.findbugs.BugInstance bugInstance) {
bugSet.add(bugInstance);
}
// TODO: implement these
public void beginReport() { }
public void reportLine(String msg) { }
public void endReport() { }
}
private Project project;
private ConsoleLogger logger;
private FindBugs findBugs;
private Reporter reporter;
private HashMap<String, DefaultTreeModel> treeModelMap;
/** Creates a new instance of AnalysisRun. */
public AnalysisRun(Project project, ConsoleLogger logger) {
this.project = project;
this.logger = logger;
reporter = new Reporter();
findBugs = new FindBugs(reporter);
treeModelMap = new HashMap<String, DefaultTreeModel>();
}
/**
* Run the analysis.
* This should be done in a separate thread (not the GUI event thread).
* The progress callback can be used to update the user interface to
* reflect the progress of the analysis. The GUI may cancel the analysis
* by interrupting the analysis thread, in which case InterruptedException
* will be thrown by this method.
*
* @param progressCallback the progress callback
* @throws java.io.IOException if an I/O error occurs during the analysis
* @throws InterruptedException if the analysis thread is interrupted
*/
public void execute(FindBugsProgress progressCallback) throws java.io.IOException, InterruptedException {
findBugs.setProgressCallback(progressCallback);
// Create a ClassPath and SyntheticRepository to reflect the exact classpath
// that should be used for the analysis.
// Add aux class path entries specified in project
StringBuffer buf = new StringBuffer();
List auxClasspathEntryList = project.getAuxClasspathEntryList();
Iterator i = auxClasspathEntryList.iterator();
while (i.hasNext()) {
String entry = (String) i.next();
buf.append(entry);
buf.append(File.pathSeparatorChar);
}
// Add the system classpath entries
buf.append(ClassPath.getClassPath());
// Set up the Repository to use the combined classpath
ClassPath classPath = new ClassPath(buf.toString());
SyntheticRepository repository = SyntheticRepository.getInstance(classPath);
Repository.setRepository(repository);
// Run the analysis!
findBugs.execute(project.getJarFileArray());
}
/**
* Return the collection of BugInstances.
*/
public java.util.Collection<BugInstance> getBugInstances() {
return reporter.bugSet;
}
/**
* Set the tree model to be used in the BugTree.
* @param groupByOrder the grouping order that the tree model will conform to
* @param treeModel the tree model
*/
public void setTreeModel(String groupByOrder, DefaultTreeModel treeModel) {
treeModelMap.put(groupByOrder, treeModel);
}
/**
* Get the tree model to be used in the BugTree.
* @param groupByOrder the grouping order that the tree model conforms to
* @return the tree model
*/
public DefaultTreeModel getTreeModel(String groupByOrder) {
return (DefaultTreeModel) treeModelMap.get(groupByOrder);
}
/**
* Look up the source file for given class.
* @return the source file name, or null if we don't have a source filename
* for the class
*/
public String getSourceFile(String className) {
return findBugs.getSourceFile(className);
}
}
|
package edu.umd.cs.findbugs.workflow;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Pattern;
import edu.umd.cs.findbugs.AppVersion;
import edu.umd.cs.findbugs.BugCollection;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.DetectorFactoryCollection;
import edu.umd.cs.findbugs.Project;
import edu.umd.cs.findbugs.SortedBugCollection;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.ba.SourceFinder;
import edu.umd.cs.findbugs.config.CommandLine;
import edu.umd.cs.findbugs.filter.FilterException;
import edu.umd.cs.findbugs.filter.Matcher;
/**
* Java main application to filter/transform an XML bug collection
* or bug history collection.
*
* @author William Pugh
*/
public class Filter {
static SourceFinder sourceFinder = new SourceFinder();
static class FilterCommandLine extends CommandLine {
Pattern className,bugPattern;
public boolean notSpecified = false;
public boolean not = false;
long first;
String firstAsString;
long after;
String afterAsString;
long before;
String beforeAsString;
long last;
String lastAsString;
long alive;
String aliveAsString;
long dead;
String deadAsString;
String annotation;
String revisionName = null;
public boolean activeSpecified = false;
public boolean active = false;
public boolean withSource = false;
public boolean withSourceSpecified = false;
public boolean introducedByChange = false;
public boolean introducedByChangeSpecified = false;
public boolean removedByChange = false;
public boolean removedByChangeSpecified = false;
public boolean newCode = false;
public boolean newCodeSpecified = false;
public boolean removedCode = false;
public boolean removedCodeSpecified = false;
public boolean classified = false;
public boolean classifiedSpecified = false;
public boolean unclassified = false;
public boolean unclassifiedSpecified = false;
public boolean serious = false;
public boolean seriousSpecified = false;
public List<String> sourcePaths = new LinkedList<String>();
private Matcher includeFilter, excludeFilter;
String category;
int priority = 3;
FilterCommandLine() {
addSwitch("-not", "reverse (all) switches for the filter");
addSwitch("-withSource", "only warnings for switch source is available");
addOption("-exclude", "filter file", "exclude bugs matching given filter");
addOption("-include", "filter file", "include only bugs matching given filter");
addOption("-after", "when", "allow only warnings that first occurred after this version");
addOption("-before", "when", "allow only warnings that first occurred before this version");
addOption("-first", "when", "allow only warnings that first occurred in this sequence number");
addOption("-first", "when", "allow only warnings that first occurred in this sequence number");
addOption("-setRevisionName", "name", "set the name of the last revision in this database");
addOption("-annotation", "text", "allow only warnings containing this text in an annotation");
addSwitch("-classified", "allow only classified warnings");
addSwitch("-serious", "allow only warnings classified as serious");
addSwitch("-unclassified", "allow only unclassified warnings");
addOption("-last", "when", "allow only warnings that last occurred in this sequence number");
addOption("-alive", "when", "allow only warnings alive in this sequence number");
addOption("-dead", "when", "allow only warnings dead in this sequence number");
addOption("-source", "directory", "Add this directory to the source search path");
addOption("-priority", "level", "allow only warnings with this priority or higher");
addSwitchWithOptionalExtraPart("-active", "truth", "allow only warnings alive in the last sequence number");
addSwitchWithOptionalExtraPart("-introducedByChange", "truth",
"allow only warnings introduced by a change of an existing class");
addSwitchWithOptionalExtraPart("-removedByChange", "truth",
"allow only warnings removed by a change of a persisting class");
addSwitchWithOptionalExtraPart("-newCode", "truth",
"allow only warnings introduced by the addition of a new class");
addSwitchWithOptionalExtraPart("-removedCode", "truth",
"allow only warnings removed by removal of a class");
addOption("-class", "pattern", "allow only bugs whose primary class name matches this pattern");
addOption("-bugPattern", "pattern", "allow only bugs whose type matches this pattern");
addOption("-category", "category", "allow only warnings with a category that starts with this string");
}
static long getVersionNum(Map<String, AppVersion> versions,
SortedMap<Long, AppVersion> timeStamps , String val, boolean roundToLaterVersion) {
if (val == null) return -1;
AppVersion v = versions.get(val);
if (v != null) return v.getSequenceNumber();
try {
long time = Date.parse(val);
return getAppropriateSeq(timeStamps, time, roundToLaterVersion);
} catch (IllegalArgumentException e) {
try {
return Long.parseLong(val);
}
catch (NumberFormatException e1) {
throw new IllegalArgumentException("Could not interprete version specification of '" + val + "'");
}
}
}
// timeStamps contains 0 10 20 30
// if roundToLater == true, ..0 = 0, 1..10 = 1, 11..20 = 2, 21..30 = 3, 31.. = Long.MAX
// if roundToLater == false, ..-1 = Long.MIN, 0..9 = 0, 10..19 = 1, 20..29 = 2, 30..39 = 3, 40 .. = 4
static private long getAppropriateSeq(SortedMap<Long, AppVersion> timeStamps, long when, boolean roundToLaterVersion) {
if (roundToLaterVersion) {
SortedMap<Long, AppVersion> geq = timeStamps.tailMap(when);
if (geq.isEmpty()) return Long.MAX_VALUE;
return geq.get(geq.firstKey()).getSequenceNumber();
} else {
SortedMap<Long, AppVersion> leq = timeStamps.headMap(when);
if (leq.isEmpty()) return Long.MIN_VALUE;
return leq.get(leq.lastKey()).getSequenceNumber();
}
}
void adjustFilter(BugCollection collection) {
Map<String, AppVersion> versions = new HashMap<String, AppVersion>();
SortedMap<Long, AppVersion> timeStamps = new TreeMap<Long, AppVersion>();
for(Iterator<AppVersion> i = collection.appVersionIterator(); i.hasNext(); ) {
AppVersion v = i.next();
versions.put(v.getReleaseName(), v);
timeStamps.put(v.getTimestamp(), v);
}
first = getVersionNum(versions, timeStamps, firstAsString, true);
last = getVersionNum(versions, timeStamps, lastAsString, true);
before = getVersionNum(versions, timeStamps, beforeAsString, true);
after = getVersionNum(versions, timeStamps, afterAsString, false);
alive = getVersionNum(versions, timeStamps, aliveAsString, true);
dead = getVersionNum(versions, timeStamps, deadAsString, true);
}
boolean accept(BugInstance bug) {
boolean result = evaluate(bug);
if (not) return !result;
return result;
}
boolean evaluate(BugInstance bug) {
if (includeFilter != null && !includeFilter.match(bug)) return false;
if (excludeFilter != null && excludeFilter.match(bug)) return false;
if (annotation != null && bug.getAnnotationText().indexOf(annotation) == -1)
return false;
if (bug.getPriority() > priority)
return false;
if (firstAsString != null && bug.getFirstVersion() != first)
return false;
if (afterAsString != null && bug.getFirstVersion() <= after)
return false;
if (beforeAsString != null && bug.getFirstVersion() >= before)
return false;
if (lastAsString != null && bug.getLastVersion() != last)
return false;
if (aliveAsString != null && !bugLiveAt(bug, alive))
return false;
if (deadAsString != null && bugLiveAt(bug, dead))
return false;
if (activeSpecified && active != (bug.getLastVersion() == -1))
return false;
if (removedByChangeSpecified
&& bug.isRemovedByChangeOfPersistingClass() != removedByChange)
return false;
if (introducedByChangeSpecified
&& bug.isIntroducedByChangeOfExistingClass() != introducedByChange)
return false;
if (newCodeSpecified && newCode != (!bug.isIntroducedByChangeOfExistingClass() && bug.getFirstVersion() != 0))
return false;
if (removedCodeSpecified && removedCode != (!bug.isRemovedByChangeOfPersistingClass() && bug.getLastVersion() != -1))
return false;
if (bugPattern != null && !bugPattern.matcher(bug.getType()).find())
return false;
if (className != null && !className.matcher(bug.getPrimaryClass().getClassName()).find())
return false;
if (category != null && !bug.getBugPattern().getCategory().startsWith(category))
return false;
if (withSourceSpecified) {
boolean hasSource = false;
SourceLineAnnotation srcLine = bug.getPrimarySourceLineAnnotation();
if (srcLine != null) {
String sourceFile = srcLine.getSourceFile();
if (sourceFile != null && !sourceFile.equals("<Unknown>")) {
try {
InputStream in = sourceFinder.openSource(srcLine.getPackageName(), sourceFile);
in.close();
hasSource = true;
} catch (IOException e) {
assert true; // ignore it -- couldn't find source file
}
}
}
if (hasSource != withSource) return false;
}
if (classifiedSpecified && !isClassified(bug)) {
return false;
}
if (unclassifiedSpecified && isClassified(bug)) {
return false;
}
if (seriousSpecified) {
Set<String> words = bug.getTextAnnotationWords();
if ( !words.contains("BUG")
|| (words.contains("NOT_BUG") || words.contains("HARMLESS"))) {
return false;
}
}
return true;
}
private boolean isClassified(BugInstance bug) {
Set<String> words = bug.getTextAnnotationWords();
return words.contains("BUG") || words.contains("NOT_BUG");
}
private boolean bugLiveAt(BugInstance bug, long now) {
if (now < bug.getFirstVersion())
return false;
if (bug.getLastVersion() != -1 && bug.getLastVersion() < now)
return false;
return true;
}
@Override
protected void handleOption(String option, String optionExtraPart) throws IOException {
option = option.substring(1);
if (optionExtraPart.length() == 0)
setField(option, true);
else
setField(option, Boolean.parseBoolean(optionExtraPart));
setField(option+"Specified", true);
}
private void setField(String fieldName, boolean value) {
try {
Field f = FilterCommandLine.class.getField(fieldName);
f.setBoolean(this, value);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected void handleOptionWithArgument(String option, String argument) throws IOException {
if (option.equals("-priority")) {
int i = " HMLE".indexOf(argument);
if (i == -1)
i = " 1234".indexOf(argument);
if (i == -1)
throw new IllegalArgumentException("Bad priority: " + argument);
priority = i;
}
else if (option.equals("-source"))
sourcePaths.add(argument);
else if (option.equals("-first"))
firstAsString = argument;
else if (option.equals("-last"))
lastAsString = argument;
else if (option.equals("-after"))
afterAsString = argument;
else if (option.equals("-before"))
beforeAsString = argument;
else if (option.equals("-alive"))
aliveAsString = argument;
else if (option.equals("-dead"))
deadAsString = argument;
else if (option.equals("-setRevisionName"))
revisionName = argument;
else if (option.equals("-category"))
category = argument;
else if (option.equals("-class"))
className = Pattern.compile(argument);
else if (option.equals("-bugPattern"))
bugPattern = Pattern.compile(argument);
else if (option.equals("-annotation"))
annotation = argument;
else if (option.equals("-include")) {
try {
includeFilter = new edu.umd.cs.findbugs.filter.Filter(argument);
} catch (FilterException e) {
throw new IllegalArgumentException("Error processing include file: " + argument, e);
}
} else if (option.equals("-exclude")) {
try {
excludeFilter = new edu.umd.cs.findbugs.filter.Filter(argument);
} catch (FilterException e) {
throw new IllegalArgumentException("Error processing include file: " + argument, e);
}
} else throw new IllegalArgumentException("can't handle command line argument of " + option);
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
DetectorFactoryCollection.instance();
final FilterCommandLine commandLine = new FilterCommandLine();
int argCount = commandLine.parse(args, 0, 2, "Usage: " + Filter.class.getName()
+ " [options] [<orig results> [<new results]] ");
Project project = new Project();
BugCollection origCollection = new SortedBugCollection();
if (argCount == args.length)
origCollection.readXML(System.in, project);
else
origCollection.readXML(args[argCount++], project);
boolean verbose = argCount < args.length;
BugCollection resultCollection = origCollection.createEmptyCollectionWithMetadata();
int passed = 0;
int dropped = 0;
for(String source : commandLine.sourcePaths)
project.addSourceDir(source);
sourceFinder.setSourceBaseList(project.getSourceDirList());
if (commandLine.revisionName != null)
resultCollection.setReleaseName(commandLine.revisionName);
commandLine.adjustFilter(resultCollection);
resultCollection.getProjectStats().clearBugCounts();
for (BugInstance bug : origCollection.getCollection())
if (commandLine.accept(bug)) {
resultCollection.add(bug, false);
if (bug.getLastVersion() == -1 )
resultCollection.getProjectStats().addBug(bug);
passed++;
} else
dropped++;
if (verbose)
System.out.println(passed + " warnings passed through, " + dropped
+ " warnings dropped");
if (argCount == args.length) {
assert !verbose;
resultCollection.writeXML(System.out, project);
}
else {
resultCollection.writeXML(args[argCount++], project);
}
}
}
// vim:ts=4
|
package org.pentaho.di.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.DBCache;
import org.pentaho.di.core.DBCacheEntry;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.map.DatabaseConnectionMap;
import org.pentaho.di.core.database.util.DatabaseUtil;
import org.pentaho.di.core.exception.KettleDatabaseBatchException;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database implements VariableSpace
{
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
// private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private RowMetaInterface rowMeta;
private int written;
private LogWriter log;
/**
* Counts the number of rows written to a batch for a certain PreparedStatement.
*/
private Map<PreparedStatement, Integer> batchCounterMap;
/**
* Number of times a connection was opened using this object.
* Only used in the context of a database connection map
*/
private int opened;
/**
* The copy is equal to opened at the time of creation.
*/
private int copy;
private String connectionGroup;
private boolean performRollbackAtLastDisconnect;
private String partitionId;
private VariableSpace variables = new Variables();
/**
* Construct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
shareVariablesWith(inf);
batchCounterMap = new HashMap<PreparedStatement, Integer>();
pstmt = null;
rowMeta = null;
dbmd = null;
rowlimit=0;
written=0;
performRollbackAtLastDisconnect=false;
log.logDetailed(toString(), "New database connection defined");
}
public boolean equals(Object obj)
{
Database other = (Database) obj;
return other.databaseMeta.equals(other.databaseMeta);
}
/**
* Allows for the injection of a "life" connection, generated by a piece of software outside of Kettle.
* @param connection
*/
public void setConnection(Connection connection) {
this.connection = connection;
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect() throws KettleDatabaseException
{
connect(null);
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect(String partitionId) throws KettleDatabaseException
{
connect(null, partitionId);
}
public synchronized void connect(String group, String partitionId) throws KettleDatabaseException
{
// Before anything else, let's see if we already have a connection defined for this group/partition!
// The group is called after the thread-name of the transformation or job that is running
// The name of that threadname is expected to be unique (it is in Kettle)
// So the deal is that if there is another thread using that, we go for it.
if (!Const.isEmpty(group))
{
this.connectionGroup = group;
this.partitionId = partitionId;
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
// Try to find the conection for the group
Database lookup = map.getDatabase(group, partitionId, this);
if (lookup==null) // We already opened this connection for the partition & database in this group
{
// Do a normal connect and then store this database object for later re-use.
normalConnect(partitionId);
opened++;
copy = opened;
map.storeDatabase(group, partitionId, this);
}
else
{
connection = lookup.getConnection();
lookup.setOpened(lookup.getOpened()+1); // if this counter hits 0 again, close the connection.
copy = lookup.getOpened();
}
}
else
{
// Proceed with a normal connect
normalConnect(partitionId);
}
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void normalConnect(String partitionId) throws KettleDatabaseException
{
if (databaseMeta==null)
{
throw new KettleDatabaseException("No valid database connection defined!");
}
try
{
// First see if we use connection pooling...
if ( databaseMeta.isUsingConnectionPool() && // default = false for backward compatibility
databaseMeta.getAccessType()!=DatabaseMeta.TYPE_ACCESS_JNDI // JNDI does pooling on it's own.
)
{
try
{
this.connection = ConnectionPoolUtil.getConnection(databaseMeta, partitionId);
}
catch (Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
else
{
connectUsingClass(databaseMeta.getDriverClass(), partitionId );
log.logDetailed(toString(), "Connected to database.");
// See if we need to execute extra SQL statemtent...
String sql = environmentSubstitute( databaseMeta.getConnectSQL() );
// only execute if the SQL is not empty, null and is not just a bunch of spaces, tabs, CR etc.
if (!Const.isEmpty(sql) && !Const.onlySpaces(sql))
{
execStatements(sql);
log.logDetailed(toString(), "Executed connect time SQL statements:"+Const.CR+sql);
}
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
private void initWithJNDI(String jndiName) throws KettleDatabaseException {
connection = null;
try {
DataSource dataSource = DatabaseUtil.getDataSourceFromJndi(jndiName);
if (dataSource != null) {
connection = dataSource.getConnection();
if (connection == null) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} else {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} catch (Exception e) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName + " : " + e.getMessage()); //$NON-NLS-1$
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException
{
// Install and load the jdbc Driver
// first see if this is a JNDI connection
if( databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI ) {
initWithJNDI( environmentSubstitute(databaseMeta.getDatabaseName()) );
return;
}
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
String url;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
url = environmentSubstitute(databaseMeta.getURL(partitionId));
}
else
{
url = environmentSubstitute(databaseMeta.getURL());
}
String clusterUsername=null;
String clusterPassword=null;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
// Get the cluster information...
PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId);
if (partition!=null)
{
clusterUsername = partition.getUsername();
clusterPassword = partition.getPassword();
}
}
String username;
String password;
if (!Const.isEmpty(clusterUsername))
{
username = clusterUsername;
password = clusterPassword;
}
else
{
username = environmentSubstitute(databaseMeta.getUsername());
password = environmentSubstitute(databaseMeta.getPassword());
}
if (databaseMeta.supportsOptionsInURL())
{
if (!Const.isEmpty(username) || !Const.isEmpty(password))
{
// also allow for empty username with given password, in this case username must be given with one space
connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, ""));
}
else
{
// Perhaps the username is in the URL or no username is required...
connection = DriverManager.getConnection(url);
}
}
else
{
Properties properties = databaseMeta.getConnectionProperties();
if (!Const.isEmpty(username)) properties.put("user", username);
if (!Const.isEmpty(password)) properties.put("password", password);
connection = DriverManager.getConnection(url, properties);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public synchronized void disconnect()
{
try
{
if (connection==null)
{
return ; // Nothing to do...
}
if (connection.isClosed())
{
return ; // Nothing to do...
}
if (pstmt !=null)
{
pstmt.close();
pstmt=null;
}
if (prepStatementLookup!=null)
{
prepStatementLookup.close();
prepStatementLookup=null;
}
if (prepStatementInsert!=null)
{
prepStatementInsert.close();
prepStatementInsert=null;
}
if (prepStatementUpdate!=null)
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
if (pstmt_seq!=null)
{
pstmt_seq.close();
pstmt_seq=null;
}
// See if there are other steps using this connection in a connection group.
// If so, we will hold commit & connection close until then.
if (!Const.isEmpty(connectionGroup))
{
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
Database lookup = map.getDatabase(connectionGroup, partitionId, this);
if (lookup!=null)
{
lookup.opened
if (lookup.opened>0)
{
return;
}
else
{
map.removeConnection(connectionGroup, partitionId, this); // remove the trace of it.
// Before we close perform commit or rollback.
if (performRollbackAtLastDisconnect)
{
rollback(true);
}
else
{
commit(true);
}
}
}
}
else
{
if (!isAutoCommit()) // Do we really still need this commit??
{
commit();
}
}
if (connection!=null)
{
connection.close();
if (!databaseMeta.isUsingConnectionPool())
{
connection=null;
}
}
log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
log.logError(toString(), Const.getStackTracker(ex));
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
log.logError(toString(), Const.getStackTracker(dbe));
}
}
/**
* Cancel the open/running queries on the database connection
* @throws KettleDatabaseException
*/
public void cancelQuery() throws KettleDatabaseException
{
cancelStatement(pstmt);
cancelStatement(sel_stmt);
}
/**
* Cancel an open/running SQL statement
* @param statement the statement to cancel
* @throws KettleDatabaseException
*/
public void cancelStatement(Statement statement) throws KettleDatabaseException
{
try
{
if (statement!=null)
{
statement.cancel();
}
log.logDetailed(toString(), "Statement canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling statement", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit() throws KettleDatabaseException
{
commit(false);
}
private void commit(boolean force) throws KettleDatabaseException
{
try
{
// Don't do the commit, wait until the end of the transformation.
// When the last database copy (opened counter) is about to be closed, we do a commit
// There is one catch, we need to catch the rollback
// The transformation will stop everything and then we'll do the rollback.
// The flag is in "performRollback", private only
if (!Const.isEmpty(connectionGroup) && !force)
{
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
connection.commit();
}
else
{
log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions())
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback() throws KettleDatabaseException
{
rollback(false);
}
private void rollback(boolean force) throws KettleDatabaseException
{
try
{
if (!Const.isEmpty(connectionGroup) && !force)
{
performRollbackAtLastDisconnect=true;
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
if (connection!=null) connection.rollback();
}
else
{
log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The row metadata to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String tableName) throws KettleDatabaseException
{
prepareInsert(rowMeta, null, tableName);
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The metadata row to determine which values need to be inserted
* @param schemaName The name of the schema in which we want to insert rows
* @param tableName The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String schemaName, String tableName) throws KettleDatabaseException
{
if (rowMeta.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(schemaName, tableName, rowMeta);
log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database. (does not return generated keys)
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
return prepareSQL(sql, false);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @param returnKeys set to true if you want to return generated keys from an insert statement
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException
{
try
{
if (returnKeys)
{
return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
pstmt=null;
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, pstmt);
}
public void setValues(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData());
}
public void setValuesInsert(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementInsert);
}
public void setValuesInsert(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), prepStatementInsert);
}
public void setValuesUpdate(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementUpdate);
}
public void setValuesLookup(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementLookup);
}
public void setProcValues(RowMetaInterface rowMeta, Object[] data, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException
{
int pos;
if (result) pos=2; else pos=1;
for (int i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT"))
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(argnrs[i]);
Object value = data[argnrs[i]];
setValue(cstmt, valueMeta, value, pos);
pos++;
} else {
pos++; //next parameter when OUT
}
}
}
public void setValue(PreparedStatement ps, ValueMetaInterface v, Object object, int pos) throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case ValueMetaInterface.TYPE_NUMBER :
if (object!=null)
{
debug="Number, not null, getting number from value";
double num = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
debug="Number, rounding to precision ["+v.getPrecision()+"]";
num = Const.round(num, v.getPrecision());
}
debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement";
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case ValueMetaInterface.TYPE_INTEGER:
debug="Integer";
if (object!=null)
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, v.getInteger(object).longValue() );
}
else
{
double d = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, d );
}
else
{
ps.setDouble(pos, Const.round( d, v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.INTEGER);
}
break;
case ValueMetaInterface.TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (object!=null)
{
ps.setString(pos, v.getString(object));
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (object!=null)
{
String string = v.getString(object);
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = string.length();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = string.substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
debug="Date";
if (object!=null)
{
long dat = v.getInteger(object).longValue(); // converts using Date.getTime()
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
ps.setNull(pos, java.sql.Types.TIMESTAMP);
}
}
break;
case ValueMetaInterface.TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (object!=null)
{
ps.setBoolean(pos, v.getBoolean(object).booleanValue());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (object!=null)
{
ps.setString(pos, v.getBoolean(object).booleanValue()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
debug="BigNumber";
if (object!=null)
{
ps.setBigDecimal(pos, v.getBigNumber(object));
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case ValueMetaInterface.TYPE_BINARY:
debug="Binary";
if (object!=null)
{
ps.setBytes(pos, v.getBinary(object));
}
else
{
ps.setNull(pos, java.sql.Types.BINARY);
}
break;
default:
debug="default";
// placeholder
ps.setNull(pos, java.sql.Types.VARCHAR);
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
public void setValues(RowMetaAndData row, PreparedStatement ps) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), ps);
}
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps) throws KettleDatabaseException
{
// now set the values in the row!
for (int i=0;i<rowMeta.size();i++)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
/**
* Sets the values of the preparedStatement pstmt.
* @param rowMeta
* @param data
*/
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps, int ignoreThisValueIndex) throws KettleDatabaseException
{
// now set the values in the row!
int index=0;
for (int i=0;i<rowMeta.size();i++)
{
if (i!=ignoreThisValueIndex)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, index+1);
index++;
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
}
/**
* @param ps The prepared insert statement to use
* @return The generated keys in auto-increment fields
* @throws KettleDatabaseException in case something goes wrong retrieving the keys.
*/
public RowMetaAndData getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException
{
ResultSet keys = null;
try
{
keys=ps.getGeneratedKeys(); // 1 row of keys
ResultSetMetaData resultSetMetaData = keys.getMetaData();
RowMetaInterface rowMeta = getRowInfo(resultSetMetaData, false, false);
return new RowMetaAndData(rowMeta, getRow(keys, resultSetMetaData, rowMeta));
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex);
}
finally
{
if (keys!=null)
{
try
{
keys.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e);
}
}
}
}
public Long getNextSequenceValue(String sequenceName, String keyfield) throws KettleDatabaseException
{
return getNextSequenceValue(null, sequenceName, keyfield);
}
public Long getNextSequenceValue(String schemaName, String sequenceName, String keyfield) throws KettleDatabaseException
{
Long retval=null;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(schemaSequence)));
}
ResultSet rs=null;
try
{
rs = pstmt_seq.executeQuery();
if (rs.next())
{
retval = Long.valueOf( rs.getLong(1) );
}
}
finally
{
if ( rs != null ) rs.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+schemaSequence, ex);
}
return retval;
}
public void insertRow(String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields, data);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, RowMetaInterface fields)
{
return getInsertStatement(null, tableName, fields);
}
public String getInsertStatement(String schemaName, String tableName, RowMetaInterface fields)
{
StringBuffer ins=new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append('(');
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
ins.append(" ?");
}
ins.append(')');
return ins.toString();
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* @param batchCounterMap The batch counter map to set.
*/
public void setBatchCounterMap(Map<PreparedStatement, Integer> batchCounterMap)
{
this.batchCounterMap = batchCounterMap;
}
/**
* @return Returns the batch counter map.
*/
public Map<PreparedStatement, Integer> getBatchCounterMap()
{
return batchCounterMap;
}
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commit size)
* @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
* @throws KettleDatabaseException
*/
public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
String debug="insertRow start";
boolean rowsAreSafe=false;
Integer batchCounter = null;
try
{
// Unique connections and Batch inserts don't mix when you want to roll back on certain databases.
// That's why we disable the batch insert in that case.
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates() && Const.isEmpty(connectionGroup);
// Add support for batch inserts...
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
// Increment the counter...
batchCounter = batchCounterMap.get(ps);
if (batchCounter==null) {
batchCounterMap.put(ps, 1);
}
else {
batchCounterMap.put(ps, Integer.valueOf(batchCounter.intValue()+1));
}
ps.addBatch(); // Add the batch, but don't forget to run the batch
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
batchCounterMap.put(ps, Integer.valueOf(0));
}
else
{
debug="insertRow normal commit";
commit();
}
rowsAreSafe=true;
}
return rowsAreSafe;
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
// 'seed' the loop with the root exception
SQLException nextException = ex;
do
{
exceptions.add(nextException);
// while current exception has next exception, add to list
}
while ((nextException = nextException.getNextException())!=null);
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
// log.logError(toString(), Const.getStackTracker(ex));
throw new KettleDatabaseException("Error inserting row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
/**
* Empty and close a prepared statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing (typically true for this method)
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*/
public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Get the batch counter. This counter is unique per Prepared Statement.
// It is increased in method insertRow()
Integer batchCounter = batchCounterMap.get(ps);
// Execute the batch or just perform a commit.
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter!=null && batchCounter.intValue()>0)
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
finally
{
// Remove the batch counter to avoid memory leaks in the database driver
batchCounterMap.remove(ps);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql) throws KettleDatabaseException
{
return execStatement(sql, null, null);
}
public Result execStatement(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, data, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
String sqlStripped = databaseMeta.stripCR(sql);
// log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]");
Statement stmt = connection.createStatement();
resultSet = stmt.execute(sqlStripped);
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput(count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated(count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted(count);
}
}
// See if a cache needs to be cleared...
if (sql.toUpperCase().startsWith("ALTER TABLE") ||
sql.toUpperCase().startsWith("DROP TABLE") ||
sql.toUpperCase().startsWith("CREATE TABLE")
)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script) throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat;
if (to<=length) stat = all.substring(from, to);
else stat = all.substring(from);
// If it ends with a ; remove that ;
// Oracle for example can't stand it when this happens...
if (stat.length()>0 && stat.charAt(stat.length()-1)==';')
{
stat = stat.substring(0,stat.length()-1);
}
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = null;
try
{
rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs);
while (row!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
if (log.isDetailed()) log.logDetailed(toString(), rowMeta.getString(row));
row = getRow(rs);
}
}
else
{
if (log.isDebug()) log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
} catch (KettleValueException e) {
throw new KettleDatabaseException(e); // just pass the error upwards.
}
finally
{
try
{
if ( rs != null ) rs.close();
}
catch (SQLException ex )
{
if (log.isDebug()) log.logDebug(toString(), "Error closing query: "+Const.CR+sql);
}
}
}
else // any kind of statement
{
log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql) throws KettleDatabaseException
{
return openQuery(sql, null, null);
}
/**
* Open a query on the database with a set of parameters stored in a Kettle Row
* @param sql The SQL to launch with question marks (?) as placeholders for the parameters
* @param params The parameters or null if no parameters are used.
* @data the parameter data to open the query with
* @return A JDBC ResultSet
* @throws KettleDatabaseException when something goes wrong with the query.
*/
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
return openQuery(sql, params, data, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode) throws KettleDatabaseException
{
return openQuery(sql, params, data, fetch_mode, false);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode, boolean lazyConversion) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params, data); // set the dates etc!
if (canWeSetFetchSize(pstmt) )
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
pstmt.setFetchSize(Integer.MIN_VALUE);
}
else
pstmt.setFetchSize(fs);
}
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (canWeSetFetchSize(sel_stmt))
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(fs);
}
debug = "Set fetch direction";
sel_stmt.setFetchDirection(fetch_mode);
}
debug = "Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "openQuery : get rowinfo";
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, lazyConversion);
}
catch(SQLException ex)
{
// log.logError(toString(), "ERROR executing ["+sql+"]");
// log.logError(toString(), "ERROR in part: ["+debug+"]");
// printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
private boolean canWeSetFetchSize(Statement statement) throws SQLException
{
return databaseMeta.isFetchSizeSupported() &&
( statement.getMaxRows()>0 ||
databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES ||
( databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults() )
);
}
public ResultSet openQuery(PreparedStatement ps, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, data, ps); // set the parameters!
if (canWeSetFetchSize(ps))
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
ps.setFetchSize(Integer.MIN_VALUE);
}
else
{
ps.setFetchSize(fs);
}
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ getRowInfo()";
// rowinfo = getRowInfo(res.getMetaData());
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, false);
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public RowMetaInterface getTableFields(String tablename) throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public RowMetaInterface getQueryFields(String sql, boolean param) throws KettleDatabaseException
{
return getQueryFields(sql, param, null, null);
}
/**
* See if the table specified exists by reading
* @param tablename The name of the table to check.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename) throws KettleDatabaseException
{
try
{
log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
// Just try to read from the table.
String sql = databaseMeta.getSQLTableExists(tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
/*
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
*/
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException
{
return checkSequenceExists(null, sequenceName);
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String schemaName, String sequenceName) throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
// Get the info from the data dictionary...
String sql = databaseMeta.getSQLSequenceExists(schemaSequence);
ResultSet res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+schemaSequence+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tableName The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tableName, String idx_fields[]) throws KettleDatabaseException
{
return checkIndexExists(null, tableName, idx_fields);
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String schemaName, String tableName, String idx_fields[]) throws KettleDatabaseException
{
String tablename = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
if (!checkTableExists(tablename)) return false;
log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
// Get the info from the data dictionary...
StringBuffer sql = new StringBuffer(128);
sql.append("select i.name table_name, c.name column_name ");
sql.append("from sysindexes i, sysindexkeys k, syscolumns c ");
sql.append("where i.name = '"+tablename+"' ");
sql.append("AND i.id = k.id ");
sql.append("AND i.id = c.id ");
sql.append("AND k.colid = c.colid ");
ResultSet res = null;
try
{
res = openQuery(sql.toString());
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
// Get the info from the data dictionary...
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tableName+"'";
ResultSet res = null;
try {
res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
log.logError(toString(), Const.getStackTracker(e));
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
return getCreateIndexStatement(null, tablename, indexname, idx_fields, tk, unique, bitmap, semi_colon);
}
public String getCreateIndexStatement(String schemaname, String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" ";
cr_index += "ON ";
// assume table has already been quoted (and possibly includes schema)
cr_index += tablename;
cr_index += Const.CR + "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace());
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, start_at, increment_by, max_value, semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequenceName, long start_at, long increment_by, long max_value, boolean semi_colon)
{
String cr_seq="";
if (Const.isEmpty(sequenceName)) return cr_seq;
if (databaseMeta.supportsSequences())
{
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
cr_seq += "CREATE SEQUENCE "+schemaSequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value>0) cr_seq += "MAXVALUE "+max_value+Const.CR;
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public RowMetaInterface getQueryFields(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
// String debug="";
PreparedStatement preparedStatement = null;
try
{
preparedStatement = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSetMetaData rsmd = preparedStatement.getMetaData();
fields = getRowInfo(rsmd, false, false);
/*
if (inform==null
// Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214)
&& databaseMeta.getDatabaseType()!=DatabaseMeta.TYPE_DATABASE_MSSQL
)
{
debug="inform==null";
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug="isFetchSizeSupported()";
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
debug = "Set fetchsize";
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(1);
}
}
debug = "Set max rows to 1";
if (databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(1);
debug = "exec query";
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
debug = "getQueryFields get row info";
fields = getRowInfo(r.getMetaData(), false, false);
debug="close resultset";
r.close();
debug="close statement";
sel_stmt.close();
sel_stmt=null;
}
else
{
debug="prepareStatement";
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
RowMetaInterface par = inform;
debug="getParameterMetaData()";
if (par==null || par.isEmpty()) par = getParameterMetaData(ps);
debug="getParameterMetaData()";
if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform, data);
setValues(par, data, ps);
}
debug="executeQuery()";
ResultSet r = ps.executeQuery();
debug="getRowInfo";
fields=getRowInfo(ps.getMetaData(), false, false);
debug="close resultset";
r.close();
debug="close preparedStatement";
ps.close();
}
*/
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Couldn't get field info", e);
}
finally
{
if (preparedStatement!=null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
throw new KettleDatabaseException("Unable to close prepared statement after determining SQL layout", e);
}
}
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
public void closeQuery(ResultSet res) throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
/**
* Build the row using ResultSetMetaData rsmd
* @param rm The resultset metadata to inquire
* @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem)
* @param lazyConversion true if lazy conversion needs to be enabled where possible
*/
private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException
{
if (rm==null) return null;
rowMeta = new RowMeta();
try
{
// TODO If we do lazy conversion, we need to find out about the encoding
int fieldNr = 1;
int nrcols=rm.getColumnCount();
for (int i=1;i<=nrcols;i++)
{
String name=new String(rm.getColumnName(i));
// Check the name, sometimes it's empty.
if (Const.isEmpty(name) || Const.onlySpaces(name))
{
name = "Field"+fieldNr;
fieldNr++;
}
ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion);
rowMeta.addValueMeta(v);
}
return rowMeta;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
private ValueMetaInterface getValueFromSQLType(String name, ResultSetMetaData rm, int index, boolean ignoreLength, boolean lazyConversion) throws SQLException
{
int length=-1;
int precision=-1;
int valtype=ValueMetaInterface.TYPE_NONE;
boolean isClob = false;
int type = rm.getColumnType(index);
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=ValueMetaInterface.TYPE_STRING;
if (!ignoreLength) length=rm.getColumnDisplaySize(index);
break;
case java.sql.Types.CLOB:
valtype=ValueMetaInterface.TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
isClob=true;
break;
case java.sql.Types.BIGINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
break;
case java.sql.Types.INTEGER:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=ValueMetaInterface.TYPE_NUMBER;
length=rm.getPrecision(index);
precision=rm.getScale(index);
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL)
{
if (precision==0)
{
precision=-1; // precision is obviously incorrect if the type if Double/Float/Real
}
// If we're dealing with PostgreSQL and double precision types
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16)
{
precision=-1;
length=-1;
}
// MySQL: max resolution is double precision floating point (double)
// The (12,31) that is given back is not correct
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
if (precision >= length) {
precision=-1;
length=-1;
}
}
}
else
{
if (precision==0 && length<18 && length>0) // Among others Oracle is affected here.
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
}
if (length>18 || precision>18) valtype=ValueMetaInterface.TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision == 0 && length == 38 )
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
if (precision<=0 && length<=0) // undefined size: BIGNUMBER
{
valtype=ValueMetaInterface.TYPE_BIGNUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=ValueMetaInterface.TYPE_DATE;
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
valtype=ValueMetaInterface.TYPE_BOOLEAN;
break;
case java.sql.Types.BINARY:
case java.sql.Types.BLOB:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
valtype=ValueMetaInterface.TYPE_BINARY;
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 &&
(2 * rm.getPrecision(index)) == rm.getColumnDisplaySize(index))
{
// set the length for "CHAR(X) FOR BIT DATA"
length = rm.getPrecision(index);
}
else
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_ORACLE &&
( type==java.sql.Types.VARBINARY || type==java.sql.Types.LONGVARBINARY )
)
{
// set the length for Oracle "RAW" or "LONGRAW" data types
valtype = ValueMetaInterface.TYPE_STRING;
length = rm.getColumnDisplaySize(index);
}
else
{
length=-1;
}
precision=-1;
break;
default:
valtype=ValueMetaInterface.TYPE_STRING;
precision=rm.getScale(index);
break;
}
// Grab the comment as a description to the field as well.
String comments=rm.getColumnLabel(index);
ValueMetaInterface v=new ValueMeta(name, valtype);
v.setLength(length);
v.setPrecision(precision);
v.setComments(comments);
v.setLargeTextField(isClob);
// See if we need to enable lazy conversion...
if (lazyConversion && valtype==ValueMetaInterface.TYPE_STRING) {
v.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
// TODO set some encoding to go with this.
// Also set the storage metadata. a copy of the parent, set to String too.
ValueMetaInterface storageMetaData = v.clone();
storageMetaData.setType(ValueMetaInterface.TYPE_STRING);
storageMetaData.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
v.setStorageMetadata(storageMetaData);
}
return v;
}
public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs) throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset. Do not use lazy conversion
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs) throws KettleDatabaseException
{
return getRow(rs, false);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @param lazyConversion set to true if strings need to have lazy conversion enabled
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, boolean lazyConversion) throws KettleDatabaseException
{
if (rowMeta==null)
{
ResultSetMetaData rsmd = null;
try
{
rsmd = rs.getMetaData();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e);
}
rowMeta = getRowInfo(rsmd, false, lazyConversion);
}
return getRow(rs, null, rowMeta);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, ResultSetMetaData dummy, RowMetaInterface rowInfo) throws KettleDatabaseException
{
try
{
int nrcols=rowInfo.size();
Object[] data = RowDataUtil.allocateRowData(nrcols);
if (rs.next())
{
for (int i=0;i<nrcols;i++)
{
ValueMetaInterface val = rowInfo.getValueMeta(i);
switch(val.getType())
{
case ValueMetaInterface.TYPE_BOOLEAN : data[i] = Boolean.valueOf( rs.getBoolean(i+1) ); break;
case ValueMetaInterface.TYPE_NUMBER : data[i] = new Double( rs.getDouble(i+1) ); break;
case ValueMetaInterface.TYPE_BIGNUMBER : data[i] = rs.getBigDecimal(i+1); break;
case ValueMetaInterface.TYPE_INTEGER : data[i] = Long.valueOf( rs.getLong(i+1) ); break;
case ValueMetaInterface.TYPE_STRING :
{
if (val.isStorageBinaryString()) {
data[i] = rs.getBytes(i+1);
}
else {
data[i] = rs.getString(i+1);
}
}
break;
case ValueMetaInterface.TYPE_BINARY :
{
if (databaseMeta.supportsGetBlob())
{
Blob blob = rs.getBlob(i+1);
if (blob!=null)
{
data[i] = blob.getBytes(1L, (int)blob.length());
}
else
{
data[i] = null;
}
}
else
{
data[i] = rs.getBytes(i+1);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
if (databaseMeta.supportsTimeStampToDateConversion())
{
data[i] = rs.getTimestamp(i+1); break; // Timestamp extends java.util.Date
}
else
{
data[i] = rs.getDate(i+1); break;
}
default: break;
}
if (rs.wasNull()) data[i] = null; // null value, it's the default but we want it just to make sure we handle this case too.
}
}
else
{
data=null;
}
return data;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String schema, String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(schema, table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
setLookup(null, tableName, codes, condition, gets, rename, orderby, checkForMultipleResults);
}
// Lookup certain fields in a table
public void setLookup(String schemaName, String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String sql = "SELECT ";
for (int i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(gets[i]);
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+databaseMeta.quoteField(rename[i]);
}
}
sql += " FROM "+table+" WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(codes[i]);
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
if (!checkForMultipleResults && databaseMeta.supportsSetMaxRows())
{
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
return prepareUpdate(null, table, codes, condition, sets);
}
// Lookup certain fields in a table
public boolean prepareUpdate(String schemaName, String tableName, String codes[], String condition[], String sets[])
{
StringBuffer sql = new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql.append("UPDATE ").append(schemaTable).append(Const.CR).append("SET ");
for (int i=0;i<sets.length;i++)
{
if (i!=0) sql.append(", ");
sql.append(databaseMeta.quoteField(sets[i]));
sql.append(" = ?").append(Const.CR);
}
sql.append("WHERE ");
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql.append("AND ");
sql.append(databaseMeta.quoteField(codes[i]));
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql.append(" BETWEEN ? AND ? ");
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql.append(' ').append(condition[i]).append(' ');
}
else
{
sql.append(' ').append(condition[i]).append(" ? ");
}
}
try
{
String s = sql.toString();
log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param table The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String table, String codes[], String condition[])
{
return prepareDelete(null, table, codes, condition);
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param schemaName the schema-name to delete in
* @param tableName The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String schemaName, String tableName, String codes[], String condition[])
{
String sql;
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql = "DELETE FROM "+table+Const.CR;
sql+= "WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (int i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (!Const.isEmpty(returnvalue))
{
switch(returntype)
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
public Object[] getLookup() throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Object[] getLookup(boolean failOnMultipleResults) throws KettleDatabaseException
{
return getLookup(prepStatementLookup, failOnMultipleResults);
}
public Object[] getLookup(PreparedStatement ps) throws KettleDatabaseException
{
return getLookup(ps, false);
}
public Object[] getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException
{
String debug = "start";
ResultSet res = null;
try
{
debug = "pstmt.executeQuery()";
res = ps.executeQuery();
debug = "getRowInfo()";
rowMeta = getRowInfo(res.getMetaData(), false, false);
debug = "getRow(res)";
Object[] ret = getRow(res);
if (failOnMultipleResults)
{
if (ret != null && res.next())
{
// if the previous row was null, there's no reason to try res.next() again.
// on DB2 this will even cause an exception (because of the buggy DB2 JDBC driver).
throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!");
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex);
}
finally
{
try
{
debug = "res.close()";
if (res!=null) res.close(); // close resultset!
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset after looking up data", e);
}
}
}
public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, RowMetaInterface fields) throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, RowMetaInterface fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null;
if (checkTableExists(tableName))
{
retval=getAlterTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
return retval;
}
/**
* Generates SQL
* @param tableName the table name or schema/table combination: this needs to be quoted properly in advance.
* @param fields the fields
* @param tk the name of the technical key field
* @param use_autoinc true if we need to use auto-increment fields for a primary key
* @param pk the name of the primary/technical key field
* @param semicolon append semicolon to the statement
* @return the SQL needed to create the specified table and fields.
*/
public String getCreateTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+tableName+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
ValueMetaInterface v=fields.getValueMeta(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
RowMetaInterface tabFields = getTableFields(tableName);
// Don't forget to quote these as well...
databaseMeta.quoteReservedWords(tabFields);
// Find the missing fields
RowMetaInterface missing = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
// Not found?
if (tabFields.searchValueMeta( v.getName() )==null )
{
missing.addValueMeta(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
ValueMetaInterface v=missing.getValueMeta(i);
retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
RowMetaInterface surplus = new RowMeta();
for (int i=0;i<tabFields.size();i++)
{
ValueMetaInterface v = tabFields.getValueMeta(i);
// Found in table, not in input ?
if (fields.searchValueMeta( v.getName() )==null )
{
surplus.addValueMeta(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
ValueMetaInterface v=surplus.getValueMeta(i);
retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// OK, see if there are fields for wich we need to modify the type... (length, precision)
RowMetaInterface modify = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface desiredField = fields.getValueMeta(i);
ValueMetaInterface currentField = tabFields.searchValueMeta( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
// TODO: this is not an optimal way of finding out changes.
// Perhaps we should just generate the data types strings for existing and new data type and see if anything changed.
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValueMeta(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
ValueMetaInterface v=modify.getValueMeta(i);
retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(null, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.quoteField(tablename));
}
}
public void truncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return new RowMetaAndData(rowMeta, row);
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public RowMeta getMetaFromRow( Object[] row, ResultSetMetaData md ) throws SQLException {
RowMeta meta = new RowMeta();
for( int i=0; i<md.getColumnCount(); i++ ) {
String name = md.getColumnName(i+1);
ValueMetaInterface valueMeta = getValueFromSQLType( name, md, i+1, true, false );
meta.addValueMeta( valueMeta );
}
return meta;
}
public RowMetaAndData getOneRow(String sql, RowMetaInterface param, Object[] data) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param, data);
if (rs!=null)
{
Object[] row = getRow(rs); // One value: a number;
rowMeta=null;
RowMeta tmpMeta = null;
try {
ResultSetMetaData md = rs.getMetaData();
tmpMeta = getMetaFromRow( row, md );
} catch (Exception e) {
e.printStackTrace();
} finally {
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
}
return new RowMetaAndData(tmpMeta, row);
}
else
{
return null;
}
}
public RowMetaInterface getParameterMetaData(PreparedStatement ps)
{
RowMetaInterface par = new RowMeta();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<=pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
ValueMeta val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new ValueMeta(name, ValueMetaInterface.TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new ValueMeta(name, ValueMetaInterface.TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_BOOLEAN);
break;
default:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new ValueMeta(name, ValueMetaInterface.TYPE_BIGNUMBER);
}
par.addValueMeta(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public RowMetaInterface getParameterMetaData(String sql, RowMetaInterface inform, Object[] data)
{
// The database couldn't handle it: try manually!
int q=countParameters(sql);
RowMetaInterface par=new RowMeta();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
ValueMetaInterface inf=inform.getValueMeta(i);
ValueMetaInterface v = inf.clone();
par.addValueMeta(v);
}
}
else
{
for (int i=0;i<q;i++)
{
ValueMetaInterface v = new ValueMeta("name"+i, ValueMetaInterface.TYPE_NUMBER);
par.addValueMeta(v);
}
}
return par;
}
public static final RowMetaInterface getTransLogrecordFields(boolean update, boolean use_batchid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_batchid && !update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING , 50, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING , 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_batchid && update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public static final RowMetaInterface getJobLogrecordFields(boolean update, boolean use_jobid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_jobid && !update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING, 50, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING, 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_jobid && update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public void writeLogRecord( String logtable,
boolean use_id,
long id,
boolean job,
String name,
String status,
long read, long written, long updated,
long input, long output, long errors,
java.util.Date startdate, java.util.Date enddate,
java.util.Date logdate, java.util.Date depdate,
java.util.Date replayDate,
String log_string
)
throws KettleDatabaseException
{
if (use_id && log_string!=null && !status.equalsIgnoreCase("start"))
{
String sql = "UPDATE "+logtable+" SET STATUS=?, LINES_READ=?, LINES_WRITTEN=?, LINES_INPUT=?," +
" LINES_OUTPUT=?, LINES_UPDATED=?, ERRORS=?, STARTDATE=?, ENDDATE=?, LOGDATE=?, DEPDATE=?, REPLAYDATE=?, LOG_FIELD=? " +
"WHERE ";
if (job) sql+="ID_JOB=?"; else sql+="ID_BATCH=?";
RowMetaInterface rowMeta;
if (job) rowMeta = getJobLogrecordFields(true, use_id, true);
else rowMeta = getTransLogrecordFields(true, use_id, true);
Object[] data = new Object[] {
status,
Long.valueOf(read),
Long.valueOf(written),
Long.valueOf(input),
Long.valueOf(output),
Long.valueOf(updated),
Long.valueOf(errors),
startdate,
enddate,
logdate,
depdate,
replayDate,
log_string,
Long.valueOf(id),
};
execStatement(sql, rowMeta, data);
}
else
{
int parms;
String sql = "INSERT INTO "+logtable+" ( ";
if (job)
{
if (use_id)
{
sql+="ID_JOB, JOBNAME";
parms=14;
}
else
{
sql+="JOBNAME";
parms=13;
}
}
else
{
if (use_id)
{
sql+="ID_BATCH, TRANSNAME";
parms=14;
}
else
{
sql+="TRANSNAME";
parms=13;
}
}
sql+=", STATUS, LINES_READ, LINES_WRITTEN, LINES_UPDATED, LINES_INPUT, LINES_OUTPUT, ERRORS, STARTDATE, ENDDATE, LOGDATE, DEPDATE, REPLAYDATE";
if (log_string!=null && log_string.length()>0) sql+=", LOG_FIELD"; // This is possibly a CLOB!
sql+=") VALUES(";
for (int i=0;i<parms;i++) if (i==0) sql+="?"; else sql+=", ?";
if (log_string!=null && log_string.length()>0) sql+=", ?";
sql+=")";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface rowMeta = new RowMeta();
List<Object> data = new ArrayList<Object>();
if (job)
{
if (use_id)
{
rowMeta.addValueMeta( new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER));
data.add(Long.valueOf(id));
}
rowMeta.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
data.add(name);
}
else
{
if (use_id)
{
rowMeta.addValueMeta( new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER));
data.add(Long.valueOf(id));
}
rowMeta.addValueMeta( new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING));
data.add(name);
}
rowMeta.addValueMeta( new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING )); data.add(status);
rowMeta.addValueMeta( new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(read));
rowMeta.addValueMeta( new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(written));
rowMeta.addValueMeta( new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(updated));
rowMeta.addValueMeta( new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(input));
rowMeta.addValueMeta( new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(output));
rowMeta.addValueMeta( new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(errors));
rowMeta.addValueMeta( new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE )); data.add(startdate);
rowMeta.addValueMeta( new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE )); data.add(enddate);
rowMeta.addValueMeta( new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE )); data.add(logdate);
rowMeta.addValueMeta( new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE )); data.add(depdate);
rowMeta.addValueMeta( new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE )); data.add(replayDate);
if (!Const.isEmpty(log_string))
{
ValueMetaInterface large = new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING);
large.setLength(DatabaseMeta.CLOB_LENGTH);
rowMeta.addValueMeta( large );
data.add(log_string);
}
setValues(rowMeta, data.toArray(new Object[data.size()]));
pstmt.executeUpdate();
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to write log record to log table "+logtable, ex);
}
}
}
public Object[] getLastLogDate( String logtable, String name, boolean job, String status ) throws KettleDatabaseException
{
Object[] row = null;
String jobtrans = job?"JOBNAME":"TRANSNAME";
String sql = "";
sql+=" SELECT ENDDATE, DEPDATE, STARTDATE";
sql+=" FROM "+logtable;
sql+=" WHERE ERRORS = 0";
sql+=" AND STATUS = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY LOGDATE DESC, ENDDATE DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface r = new RowMeta();
r.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
setValues(r, new Object[] { name });
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rowMeta = getRowInfo(res.getMetaData(), false, false);
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String tableName, String val_key) throws KettleDatabaseException
{
return getNextValue(counters, null, tableName, val_key);
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String schemaName, String tableName, String val_key) throws KettleDatabaseException
{
Long nextValue = null;
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String lookup = schemaTable+"."+databaseMeta.quoteField(val_key);
// Try to find the previous sequence value...
Counter counter = null;
if (counters!=null) counter=counters.get(lookup);
if (counter==null)
{
RowMetaAndData rmad = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key)+") FROM "+schemaTable);
if (rmad!=null)
{
long previous;
try
{
Long tmp = rmad.getRowMeta().getInteger(rmad.getData(), 0);
// A "select max(x)" on a table with no matching rows will return null.
if ( tmp != null )
previous = tmp.longValue();
else
previous = 0L;
}
catch (KettleValueException e)
{
throw new KettleDatabaseException("Error getting the first long value from the max value returned from table : "+schemaTable);
}
counter = new Counter(previous+1, 1);
nextValue = Long.valueOf( counter.next() );
if (counters!=null) counters.put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+schemaTable);
}
}
else
{
nextValue = Long.valueOf( counter.next() );
}
return nextValue;
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
return getRows(rset, limit, monitor);
}
/** Reads the result of a ResultSet into an ArrayList
*
* @param rset the ResultSet to read out
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(ResultSet rset, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
try
{
List<Object[]> result = new ArrayList<Object[]>();
boolean stop=false;
int i=0;
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Object[] row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e);
}
}
public List<Object[]> getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
/**
* Get the first rows from a table (for preview)
* @param table_name The table name (or schema/table combination): this needs to be quoted properly
* @param limit limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException in case something goes wrong
*/
public List<Object[]> getFirstRows(String table_name, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
String sql = "SELECT * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public RowMetaInterface getReturnRowMeta()
{
return rowMeta;
}
public String[] getTableTypes() throws KettleDatabaseException
{
try
{
ArrayList<String> types = new ArrayList<String>();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames() throws KettleDatabaseException
{
return getTablenames(false);
}
public String[] getTablenames(boolean includeSchema) throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase();
List<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getViews() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getViews(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getSynonyms() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getSynonyms(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
List<Object[]> procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Object[])procs.get(i))[0].toString();
}
return str;
}
else
{
ResultSet rs = null;
try
{
DatabaseMetaData dbmd = getDatabaseMetaData();
rs = dbmd.getProcedures(null, null, null);
List<Object[]> rows = getRows(rs, 0, null);
String result[] = new String[rows.size()];
for (int i=0;i<rows.size();i++)
{
Object[] row = (Object[])rows.get(i);
String procCatalog = rowMeta.getString(row, "PROCEDURE_CAT", null);
String procSchema = rowMeta.getString(row, "PROCEDURE_SCHEMA", null);
String procName = rowMeta.getString(row, "PROCEDURE_NAME", "");
String name = "";
if (procCatalog!=null) name+=procCatalog+".";
else if (procSchema!=null) name+=procSchema+".";
name+=procName;
result[i] = name;
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e);
}
finally
{
if (rs!=null) try { rs.close(); } catch(Exception e) {}
}
}
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to lock the (quoted) tables
String sql = databaseMeta.getSQLLockTables(quotedTableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to unlock the (quoted) tables
String sql = databaseMeta.getSQLUnlockTables(quotedTableNames);
if (sql!=null)
{
execStatement(sql);
}
}
/**
* @return the opened
*/
public int getOpened()
{
return opened;
}
/**
* @param opened the opened to set
*/
public void setOpened(int opened)
{
this.opened = opened;
}
/**
* @return the connectionGroup
*/
public String getConnectionGroup()
{
return connectionGroup;
}
/**
* @param connectionGroup the connectionGroup to set
*/
public void setConnectionGroup(String connectionGroup)
{
this.connectionGroup = connectionGroup;
}
/**
* @return the partitionId
*/
public String getPartitionId()
{
return partitionId;
}
/**
* @param partitionId the partitionId to set
*/
public void setPartitionId(String partitionId)
{
this.partitionId = partitionId;
}
/**
* @return the copy
*/
public int getCopy()
{
return copy;
}
/**
* @param copy the copy to set
*/
public void setCopy(int copy)
{
this.copy = copy;
}
public void copyVariablesFrom(VariableSpace space)
{
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public void setParentVariableSpace(VariableSpace parent)
{
variables.setParentVariableSpace(parent);
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) {
if (!Const.isEmpty(variableName))
{
String value = environmentSubstitute(variableName);
if (!Const.isEmpty(value))
{
return ValueMeta.convertStringToBoolean(value);
}
}
return defaultValue;
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
// Also share the variables with the meta data object
// Make sure it's not the databaseMeta object itself. We would get an infinite loop in that case.
if (space!=databaseMeta) databaseMeta.shareVariablesWith(space);
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
public RowMetaAndData callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype) throws KettleDatabaseException {
RowMetaAndData ret;
try {
cstmt.execute();
ret = new RowMetaAndData();
int pos = 1;
if (resultname != null && resultname.length() != 0) {
ValueMeta vMeta = new ValueMeta(resultname, resulttype);
Object v =null;
switch (resulttype) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getDate(pos);
break;
}
ret.addValue(vMeta, v);
pos++;
}
for (int i = 0; i < arg.length; i++) {
if (argdir[i].equalsIgnoreCase("OUT")
|| argdir[i].equalsIgnoreCase("INOUT")) {
ValueMeta vMeta = new ValueMeta(arg[i], argtype[i]);
Object v=null;
switch (argtype[i]) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos + i));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos + i));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos + i);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos + i));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos + i);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getTimestamp(pos + i);
break;
}
ret.addValue(vMeta, v);
}
}
return ret;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
}
|
package edu.umd.cs.findbugs.gui2;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.dom4j.DocumentException;
import org.xml.sax.SAXException;
import edu.umd.cs.findbugs.BugCollection;
import edu.umd.cs.findbugs.BugCollectionBugReporter;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.DetectorFactoryCollection;
import edu.umd.cs.findbugs.FindBugs2;
import edu.umd.cs.findbugs.FindBugsProgress;
import edu.umd.cs.findbugs.IFindBugsEngine;
import edu.umd.cs.findbugs.Priorities;
import edu.umd.cs.findbugs.Project;
import edu.umd.cs.findbugs.SortedBugCollection;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.SourceFinder;
import edu.umd.cs.findbugs.config.UserPreferences;
import edu.umd.cs.findbugs.filter.Filter;
import edu.umd.cs.findbugs.filter.LastVersionMatcher;
import edu.umd.cs.findbugs.workflow.Update;
/**
* Everything having to do with loading bugs should end up here.
* @author Dan
*
*/
public class BugLoader {
/**
* Performs an analysis and returns the BugSet created
*
* @param p The Project to run the analysis on
* @param progressCallback the progressCallBack is supposed to be supplied by analyzing dialog, FindBugs supplies progress information while it runs the analysis
* @return the bugs found
* @throws InterruptedException
* @throws IOException
*/
public static BugCollection doAnalysis(@NonNull Project p, FindBugsProgress progressCallback) throws IOException, InterruptedException
{
BugCollectionBugReporter pcb=new BugCollectionBugReporter(p);
pcb.setPriorityThreshold(Priorities.NORMAL_PRIORITY);
IFindBugsEngine fb=createEngine(p, pcb);
fb.setUserPreferences(UserPreferences.getUserPreferences());
fb.setProgressCallback(progressCallback);
fb.setProjectName(p.getProjectName());
fb.execute();
List<String> possibleDirectories=p.getSourceDirList();
MainFrame instance = MainFrame.getInstance();
SourceFinder sourceFinder = new SourceFinder(p);
instance.setSourceFinder(sourceFinder);
return pcb.getBugCollection();
}
/**
* Create the IFindBugsEngine that will be used to
* analyze the application.
*
* @param p the Project
* @param pcb the PrintCallBack
* @return the IFindBugsEngine
*/
private static IFindBugsEngine createEngine(@NonNull Project p, BugReporter pcb)
{
FindBugs2 engine = new FindBugs2();
engine.setBugReporter(pcb);
engine.setProject(p);
engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance());
// Honor -effort option if one was given on the command line.
engine.setAnalysisFeatureSettings(Driver.getAnalysisSettingList());
return engine;
}
public static BugSet loadBugsHelper(BugCollection collection)
{
ArrayList<BugLeafNode> bugList=new ArrayList<BugLeafNode>();
Iterator<BugInstance> i=collection.iterator();
while (i.hasNext())
{
bugList.add(new BugLeafNode(i.next()));
}
return new BugSet(bugList);
}
public static @CheckForNull SortedBugCollection loadBugs(MainFrame mainFrame, Project project, File source) {
if (!source.isFile() || !source.canRead()) {
JOptionPane.showMessageDialog(mainFrame,"Unable to read " + source);
return null;
}
SortedBugCollection col=new SortedBugCollection(project);
col.setRequestDatabaseCloud(true);
try {
col.readXML(source);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mainFrame,"Could not read " + source+ "; " + e.getMessage());
}
addDeadBugMatcher(project);
return col;
}
public static @CheckForNull SortedBugCollection loadBugs(MainFrame mainFrame, Project project, URL url) {
SortedBugCollection col=new SortedBugCollection(project);
col.setRequestDatabaseCloud(true);
try {
col.readXML(url);
} catch (Exception e) {
String msg = SystemProperties.getOSDependentProperty("findbugs.unableToLoadViaURL");
if (msg == null)
msg = e.getMessage();
else
msg = String.format(msg);
JOptionPane.showMessageDialog(mainFrame,"Could not read " + url + "\n" + msg);
if (SystemProperties.getBoolean("findbugs.failIfUnableToLoadViaURL"))
System.exit(1);
}
addDeadBugMatcher(project);
return col;
}
static void addDeadBugMatcher(Project p) {
Filter suppressionMatcher = p.getSuppressionFilter();
if (suppressionMatcher != null) {
suppressionMatcher.softAdd(LastVersionMatcher.DEAD_BUG_MATCHER);
}
}
public static @CheckForNull Project loadProject(MainFrame mainFrame, File f)
{
try
{
Project project = Project.readXML(f);
Filter suppressionMatcher = project.getSuppressionFilter();
if (suppressionMatcher != null) {
suppressionMatcher.softAdd(LastVersionMatcher.DEAD_BUG_MATCHER);
}
project.setGuiCallback(mainFrame);
return project;
} catch (IOException e) {
JOptionPane.showMessageDialog(mainFrame,"Could not read " + f + "; " + e.getMessage());
} catch (DocumentException e) {
JOptionPane.showMessageDialog(mainFrame, "Could not read project from " + f + "; " + e.getMessage());
} catch (SAXException e) {
JOptionPane.showMessageDialog(mainFrame, "Could not read project from " + f + "; " + e.getMessage());
}
return null;
}
private BugLoader()
{
throw new UnsupportedOperationException();
}
/**
* TODO: This really needs to be rewritten such that they don't have to choose ALL xmls in one fel swoop. I'm thinking something more like new project wizard's functionality. -Dan
*
* Merges bug collection histories from xmls selected by the user. Right now all xmls must be in the same folder and he must select all of them at once
* Makes use of FindBugs's mergeCollection method in the Update class of the workflow package
* @return the merged collecction of bugs
*/
public static BugCollection combineBugHistories()
{
try
{
FBFileChooser chooser=new FBFileChooser();
chooser.setFileFilter(new FindBugsAnalysisFileFilter());
// chooser.setCurrentDirectory(GUISaveState.getInstance().getStarterDirectoryForLoadBugs()); This is done by FBFileChooser.
chooser.setMultiSelectionEnabled(true);
chooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.choose_xmls_ttl", "Choose All XML's To Combine"));
if (chooser.showOpenDialog(MainFrame.getInstance())==JFileChooser.CANCEL_OPTION)
return null;
SortedBugCollection conglomeration=new SortedBugCollection();
conglomeration.readXML(chooser.getSelectedFiles()[0]);
Update update = new Update();
for (int x=1; x<chooser.getSelectedFiles().length;x++)
{
File f=chooser.getSelectedFiles()[x];
SortedBugCollection col=new SortedBugCollection();
col.readXML(f);
conglomeration=(SortedBugCollection) update.mergeCollections(conglomeration, col, false, false);//False means dont show dead bugs
}
return conglomeration;
} catch (IOException e) {
Debug.println(e);
return null;
} catch (DocumentException e) {
Debug.println(e);
return null;
}
}
/**
* Does what it says it does, hit apple r (control r on pc) and the analysis is redone using the current project
* @param p
* @return the bugs from the reanalysis, or null if cancelled
*/
public static @CheckForNull BugCollection doAnalysis(@NonNull Project p)
{
if (p == null)
throw new NullPointerException("null project");
RedoAnalysisCallback ac= new RedoAnalysisCallback();
new AnalyzingDialog(p,ac,true);
if (ac.finished)
return ac.getBugCollection();
else
return null;
}
/**
* Does what it says it does, hit apple r (control r on pc) and the analysis is redone using the current project
* @param p
* @return the bugs from the reanalysis, or null if canceled
*/
public static @CheckForNull BugCollection redoAnalysisKeepComments(@NonNull Project p)
{
if (p == null)
throw new NullPointerException("null project");
BugSet oldSet=BugSet.getMainBugSet();
BugCollection current=MainFrame.getInstance().bugCollection;//Now we should no longer get this December 31st 1969 business.
// Sourceforge bug 1800962 indicates 'current' can be null here
if(current != null) for (BugLeafNode node: oldSet)
{
BugInstance bug=node.getBug();
current.add(bug);
}
Update update = new Update();
RedoAnalysisCallback ac= new RedoAnalysisCallback();
new AnalyzingDialog(p,ac,true);
if(current == null)
return ac.getBugCollection();
else if (ac.finished)
return update.mergeCollections(current, ac.getBugCollection(), true, false);
else
return null;
}
/** just used to know how the new analysis went*/
private static class RedoAnalysisCallback implements AnalysisCallback
{
BugCollection getBugCollection() {
return justAnalyzed;
}
BugCollection justAnalyzed;
volatile boolean finished;
public void analysisFinished(BugCollection b)
{
justAnalyzed = b;
finished = true;
}
public void analysisInterrupted()
{
finished=false;
}
}
}
|
// Totally untested, just some initla code to get started.
package guessing_game;
public class Player {
private String name;
private int lowGuess;
private int highGuess;
private int lastGuess;
private int numGuesses;
public Player(String name){
this.name = name;
this.lowGuess = 0;
this.highGuess = 1000;
this.lastGuess = (int) (Math.random() * 1000);
this.numGuesses = 0;
}
public void setName(String str) {
name = str;
}
public String getName() {
return name ;
}
public int getGuess() {
return lastGuess ;
}
public void setGuess(String highLow) {
int high;
int low;
if (highLow == "high"){
high = lastGuess;
low = lowGuess;
} else {
high = highGuess;
low = lastGuess;
}
lastGuess = (int)((high - low) / 2);
}
public int getNumGuesses() {
return numGuesses ;
}
public void setNumGuesses() {
numGuesses += 1;
}
}
|
package test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import risk.RiskBoard;
import risk.RiskBoard.Colors;
import risk.Territory;
public class BoardTest {
RiskBoard board;
@Before
public void setUp(){
board = new RiskBoard();
board.setup("TestRisk.txt");
}
@Test
public void testNewBlankBoard() {
for(Territory territory : board.getTerritories()){
assertEquals(0,territory.getTroops());
}
}
@Test
public void testBoardSetup() {
List<Territory> expected = new ArrayList<>();
expected.add(new Territory("Alaska"));
expected.add(new Territory("Alberta"));
expected.add(new Territory("Argentina"));
expected.add(new Territory("Brazil"));
assertEquals(expected.toString(), board.getTerritories().toString());
}
@Test
public void testChangeTroops(){
board.changeTroops("Argentina", 5);
assertEquals(5, board.getTroops("Argentina"));
board.changeTroops("Argentina", 2);
assertEquals(7, board.getTroops("Argentina"));
board.changeTroops("Argentina", -2);
assertEquals(5, board.getTroops("Argentina"));
board.changeTroops("Argentina", -2);
assertEquals(3, board.getTroops("Argentina"));
board.changeTroops("Argentina", -2);
assertEquals(1, board.getTroops("Argentina"));
board.changeTroops("Argentina", -20);
assertEquals(0, board.getTroops("Argentina"));
}
@Test
public void testFactions(){
assertEquals(Colors.NONE, board.getFaction("Alaska"));
board.setFaction("Alaska", Colors.BLUE);
assertEquals(Colors.BLUE, board.getFaction("Alaska"));
board.setFaction("Argentina", Colors.BLACK);
board.setFaction("Alaska", Colors.BLACK);
assertEquals(Colors.BLACK, board.getFaction("Argentina"));
assertEquals(Colors.BLACK, board.getFaction("Alaska"));
}
@Test
public void testRoutes(){
List<Territory> connections = Arrays.asList(new Territory("Alberta"), new Territory("Argentina"));
assertEquals(connections.toString(), board.getConnections("Alaska").toString());
}
@Test
public void testAttack(){
board.changeTroops("Alaska", 2);
board.changeTroops("Alberta", 2);
board.setFaction("Alaska", Colors.PINK);
board.setFaction("Alberta", Colors.BLACK);
board.attack("Alaska", "Alberta");
assertTrue(board.getTroops("Alaska")!=2 || board.getTroops("Alberta")!=2);
assertTrue(board.getTroops("Alaska")==1 || board.getTroops("Alberta")==1);
}
@Test
public void testTooFewToAttack(){
board.changeTroops("Alaska", 1);
board.changeTroops("Alberta", 10);
board.setFaction("Alaska", Colors.PINK);
board.setFaction("Alberta", Colors.BLACK);
board.attack("Alaska", "Alberta");
assertTrue(board.getTroops("Alaska")==1);
assertTrue(board.getTroops("Alberta")==10);
}
@Test
public void testTakeTerritory() {
board.changeTroops("Alaska", 1);
board.changeTroops("Alberta", 100);
board.setFaction("Alaska", Colors.PINK);
board.setFaction("Alberta", Colors.BLACK);
// WARNING: Chances of not taking the territory are very, very small,
// but there is a chance this test will fail.
for(int i=0; i<1000; i++){
board.attack("Alberta", "Alaska");
}
assertSame(Colors.BLACK, board.getFaction("Alaska"));
assertSame(3, board.getTroops("Alaska"));
}
@Test
public void testTakeTerritoryWithTwo() {
board.changeTroops("Alaska", 1);
board.changeTroops("Alberta", 100);
board.setFaction("Alaska", Colors.PINK);
board.setFaction("Alberta", Colors.BLACK);
// WARNING: Chances of not taking the territory are very, very small,
// but there is a chance this test will fail.
for(int i=0; i<1000; i++){
board.attack("Alberta", "Alaska", 2);
}
assertSame(Colors.BLACK, board.getFaction("Alaska"));
assertSame(2, board.getTroops("Alaska"));
}
@Test
public void testPlayerList() {
assertFalse(board.getPlayerList().equals(new ArrayList<Colors>()));
}
@Test
public void testAssignRandomTerritories() {
board.randomStart();
assertTrue(board.getFaction("Alaska") != Colors.NONE);
assertTrue(board.getFaction("Alberta") != Colors.NONE);
assertTrue(board.getFaction("Brazil") != Colors.NONE);
assertTrue(board.getFaction("Argentina") != Colors.NONE);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.