repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
tdefilip/opennms | integrations/opennms-jasper-extensions/src/main/java/org/opennms/netmgt/jasper/jrobin/JRobinQueryExecutor.java | 2550 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2010-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.jasper.jrobin;
import java.util.Date;
import java.util.Map;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRDataset;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.query.JRAbstractQueryExecuter;
public class JRobinQueryExecutor extends JRAbstractQueryExecuter {
protected JRobinQueryExecutor(JRDataset dataset, Map<?,?> parametersMap) {
super(dataset, parametersMap);
parseQuery();
}
@Override
public boolean cancelQuery() throws JRException {
return false;
}
@Override
public void close() {
}
@Override
public JRDataSource createDatasource() throws JRException {
try {
return new RrdXportCmd().executeCommand(getQueryString());
} catch (Throwable e) {
throw new JRException("Error creating JRobinDataSource with command: " + getQueryString(), e);
}
}
@Override
protected String getParameterReplacement(String parameterName) {
Object parameterVal = getParameterValue(parameterName);
if(parameterVal instanceof Date) {
Date date = (Date) parameterVal;
return String.valueOf(date.getTime()/1000);
}
return String.valueOf(parameterVal);
}
}
| agpl-3.0 |
ptitfred/magrit | server/sshd/src/test/java/org/kercoin/magrit/sshd/commands/GetStatusCommandTest.java | 3531 | /*
Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file.
This file is part of Magrit.
Magrit is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Magrit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public
License along with Magrit.
If not, see <http://www.gnu.org/licenses/>.
*/
package org.kercoin.magrit.sshd.commands;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import org.apache.sshd.server.ExitCallback;
import org.eclipse.jgit.lib.Repository;
import org.junit.Before;
import org.junit.Test;
import org.kercoin.magrit.core.Context;
import org.kercoin.magrit.core.build.Status;
import org.kercoin.magrit.core.build.StatusesService;
import org.kercoin.magrit.core.utils.GitUtils;
import org.kercoin.magrit.sshd.commands.GetStatusCommand;
import org.mockito.Mock;
import org.mockito.Mockito;
public class GetStatusCommandTest {
GetStatusCommand command;
private Context ctx;
@Mock StatusesService buildStatusesService;
private ByteArrayOutputStream out;
@Mock ExitCallback exitCallback;
@Before
public void setUp() {
initMocks(this);
ctx = Mockito.spy(new Context(new GitUtils()));
command = new GetStatusCommand(ctx, buildStatusesService);
out = new ByteArrayOutputStream();
command.setOutputStream(out);
command.setExitCallback(exitCallback);
given(ctx.getInjector()).willThrow(new IllegalAccessError());
}
@Test
public void testGetStatusCommand_xargs() throws Exception {
// given
given(buildStatusesService.getStatus(any(Repository.class), anyString())).willReturn(
Arrays.asList(Status.ERROR, Status.INTERRUPTED, Status.OK, Status.RUNNING)
);
// when
command.command("magrit status /r1 HEAD").run();
// then
verify(exitCallback).onExit(0);
assertThat(out.toString()).isEqualTo("EIOR\n");
}
@Test
public void testGetStatusCommand_stdin_stdout() throws Exception {
// given
given(buildStatusesService.getStatus(any(Repository.class), eq("1234567890123456789012345678901234567890"))).willReturn(
Arrays.asList(Status.ERROR, Status.OK)
);
given(buildStatusesService.getStatus(any(Repository.class), eq("abcdef7890123456789012345678901234abcdef"))).willReturn(
Arrays.asList(Status.ERROR, Status.INTERRUPTED, Status.OK, Status.RUNNING)
);
StringBuilder stdin = new StringBuilder();
stdin.append("abcdef7890123456789012345678901234abcdef").append('\n');
stdin.append("1234567890123456789012345678901234567890").append('\n');
stdin.append("--").append('\n');
command.setInputStream(new ByteArrayInputStream(stdin.toString().getBytes()));
// when
command.command("magrit status /r1 -").run();
// then
verify(exitCallback).onExit(0);
assertThat(out.toString()).isEqualTo("EIOR\n" + "EO\n");
}
}
| agpl-3.0 |
itbh-at/bev-search | server/bev-search-rest/src/main/java/at/itbh/bev/rest/JaxRsActivator.java | 1130 | /*
* JaxRsActivator.java
*
* Copyright (C) 2017 Christoph D. Hermann <christoph.hermann@itbh.at>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package at.itbh.bev.rest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
* All ReST services are provided in the root path
* <code>deyployment-url/v1/at</code>.
*
* @author Christoph D. Hermann (ITBH) <christoph.hermann@itbh.at>
*
*/
@ApplicationPath("/v1/at")
public class JaxRsActivator extends Application {
} | agpl-3.0 |
schedulix/schedulix | src/server/exception/SDMSMessage.java | 4780 | /*
Copyright (c) 2000-2013 "independIT Integrative Technologies GmbH",
Authors: Ronald Jeninga, Dieter Stubler
schedulix Enterprise Job Scheduling System
independIT Integrative Technologies GmbH [http://www.independit.de]
mailto:contact@independit.de
This file is part of schedulix
schedulix is free software:
you can redistribute it and/or modify it under the terms of the
GNU Affero General Public License as published by the
Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.independit.scheduler.server.exception;
import java.lang.*;
import java.io.*;
import java.util.*;
import de.independit.scheduler.server.*;
public class SDMSMessage
{
public final static String __version = "@(#) $Id: SDMSMessage.java,v 2.2.18.1 2013/03/14 10:24:17 ronald Exp $";
private String errId;
private String msg;
private Object o[];
private SystemEnvironment env;
private static boolean translationEnabled = true;
private static HashMap trans1 = null;
private static HashMap trans2 = null;
private void initTranslationTables(SystemEnvironment p_env)
{
trans1 = new HashMap();
trans2 = new HashMap();
try {
InputStream is = SDMSMessage.class.getResourceAsStream("/server/messages/MessageTable1.dat");
Properties prop = new Properties();
if(is != null) {
prop.load(is);
}
} catch (IOException ioe) {
translationEnabled = false;
}
}
public SDMSMessage(SystemEnvironment p_env, String p_errId, String p_msg, Object p[])
{
env = p_env;
errId = p_errId;
msg = p_msg;
o = p;
if(trans1 == null) {
initTranslationTables(p_env);
}
}
public SDMSMessage(SystemEnvironment p_env, String p_errId)
{
this(p_env, p_errId, (String) null, (Object[]) null);
}
public SDMSMessage(SystemEnvironment p_env, String p_errId, Object p1)
{
this(p_env, p_errId, (String) null, new Object[] {p1});
}
public SDMSMessage(SystemEnvironment p_env, String p_errId, Object p1, Object p2)
{
this(p_env, p_errId, (String) null, new Object[] {p1, p2});
}
public SDMSMessage(SystemEnvironment p_env, String p_errId, Object p1, Object p2, Object p3)
{
this(p_env, p_errId, (String) null, new Object[] {p1, p2, p3});
}
public SDMSMessage(SystemEnvironment p_env, String p_errId, Object p[])
{
this(p_env, p_errId, (String) null, p);
}
public SDMSMessage(SystemEnvironment p_env, String p_errId, String p_msg)
{
this(p_env, p_errId, p_msg, (Object[]) null);
}
public SDMSMessage(SystemEnvironment p_env, String p_errId, String p_msg, Object p1)
{
this(p_env, p_errId, p_msg, new Object[] {p1});
}
public SDMSMessage(SystemEnvironment p_env, String p_errId, String p_msg, Object p1, Object p2)
{
this(p_env, p_errId, p_msg, new Object[] {p1, p2});
}
public SDMSMessage(SystemEnvironment p_env, String p_errId, String p_msg, Object p1, Object p2, Object p3)
{
this(p_env, p_errId, p_msg, new Object[] {p1, p2, p3});
}
private String subst(String p_msg)
{
if(p_msg == null) return null;
int lgth = p_msg.length();
StringBuffer r = new StringBuffer(lgth + (o == null ? 0 : o.length*16));
boolean ind[] = new boolean[o == null ? 0 : o.length];
int i, j;
i = 0;
j = 0;
Arrays.fill(ind, false);
for(; i<lgth; i++) {
if(p_msg.charAt(i) != '$') continue;
if(i+1 == lgth) break;
if(!Character.isDigit(p_msg.charAt(i+1))) continue;
r.append(p_msg.substring(j,i));
i++;
j = i;
while((i < lgth) && Character.isDigit(p_msg.charAt(i))) i++;
int pnr = Integer.valueOf(p_msg.substring(j,i)).intValue();
if(pnr > o.length || pnr <= 0) {
r.append(SystemEnvironment.noneString);
} else {
r.append(o[pnr-1] != null ? o[pnr-1].toString() : SystemEnvironment.nullString);
ind[pnr-1] = true;
}
j = i;
}
if(j<lgth)
r.append(p_msg.substring(j,i));
boolean first = true;
for(i=0; i<ind.length; i++) {
if(!ind[i]) {
if(first) {
first = false;
r.append(" [");
}
r.append(o[i].toString());
}
}
if(!first) {
r.append("]");
}
return new String(r);
}
public String toString()
{
if(!translationEnabled) {
return (msg == null ? errId : subst(msg));
}
return (msg == null ? errId : subst(msg));
}
public String errNumber()
{
return errId;
}
public String getMessage()
{
return msg;
}
public void setMessage(String s)
{
msg = s;
}
}
| agpl-3.0 |
nmpgaspar/PainlessProActive | src/Examples/org/objectweb/proactive/examples/pi/PiBBP.java | 16679 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.examples.pi;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.etsi.uri.gcm.util.GCM;
import org.objectweb.fractal.adl.Factory;
import org.objectweb.fractal.api.Component;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PAGroup;
import org.objectweb.proactive.core.group.Group;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.extensions.annotation.ActiveObject;
import org.objectweb.proactive.extensions.gcmdeployment.PAGCMDeployment;
import org.objectweb.proactive.extensions.webservices.AbstractWebServicesFactory;
import org.objectweb.proactive.extensions.webservices.WebServices;
import org.objectweb.proactive.extensions.webservices.WebServicesFactory;
import org.objectweb.proactive.gcmdeployment.GCMApplication;
import org.objectweb.proactive.gcmdeployment.GCMVirtualNode;
/**
*
* This program evaluates the PI number using the Bailey-Borwein-Plouffe
* algorithm. This is the main class, which we have to execute in order to run the pi computation
*
* @author The ProActive Team
*
*/
@ActiveObject
public class PiBBP implements Serializable {
private static final long serialVersionUID = 54L;
private final static int SIMPLE = 1;
private final static int PARALLEL = 2;
private final static int PARALLEL_DISTRIBUTED = 3;
private final static int COMPONENT = 4;
private int run_ = SIMPLE;
protected int nbDecimals_;
private String deploymentDescriptorLocation_;
private GCMApplication deploymentDescriptor_;
private boolean ws_ = false;
protected PiComp piComputer;
/**
* Empty constructor
*
*/
public PiBBP() {
}
/**
* Constructor
* @param args the string array containing the arguments which will initalize the computation
*/
public PiBBP(String[] args) {
parseProgramArguments(args);
}
/**
* Sets the number of decimals to compute
* @param nbDecimals the number of decimals
*/
public void setNbDecimals(int nbDecimals) {
this.nbDecimals_ = nbDecimals;
}
/**
* Computes the value of PI on a local node, deployed on a local JVM
* @return The value of PI
*/
public String runSimple() {
System.out.println("No deployment : computation will take place on the current node.");
System.out.println("Starting computation ...");
long timeAtBeginningOfComputation = System.currentTimeMillis();
// create a PiComputer instance
piComputer = new PiComputer(Integer.valueOf(nbDecimals_));
// define the interval to calculate
Interval interval = new Interval(0, nbDecimals_);
// compute
Result result = piComputer.compute(interval);
long timeAtEndOfComputation = System.currentTimeMillis();
// display results
System.out.println("Computation finished ...");
System.out.println("Computed PI value is : " + result.getNumericalResult().toString());
System.out.println("Time waiting for result : " +
(timeAtEndOfComputation - timeAtBeginningOfComputation) + " ms");
return result.getNumericalResult().toString();
}
/**
* Computes the value of PI with a group of "pi computers", deployed on a local node
* @return the value of PI
*/
private String runParallel() {
try {
// create a group of computers on the current host
piComputer = (PiComputer) PAGroup.newGroup(PiComputer.class.getName(), new Object[][] {
new Object[] { Integer.valueOf(nbDecimals_) },
new Object[] { Integer.valueOf(nbDecimals_) } });
return computeOnGroup(piComputer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Computes the value of PI with a group of "pi computers", deployed on remote nodes
* @return the value of PI
*/
public String runParallelDistributed() {
try {
//*************************************************************
// * creation of remote nodes
// *************************************************************/
System.out.println("\nStarting deployment of virtual nodes");
// parse the descriptor file
deploymentDescriptor_ = PAGCMDeployment.loadApplicationDescriptor(new File("../descriptors/" +
deploymentDescriptorLocation_));
deploymentDescriptor_.startDeployment();
GCMVirtualNode computersVN = deploymentDescriptor_.getVirtualNode("computers-vn");
computersVN.waitReady();
// // create the remote nodes for the virtual node computersVN
// computersVN.activate();
//*************************************************************
// * creation of active objects on the remote nodes
// *************************************************************/
System.out.println("\nCreating a group of computers on the given virtual node ...");
// create a group of computers on the virtual node computersVN
List<Node> nodes = computersVN.getCurrentNodes();
piComputer = (PiComputer) PAGroup.newGroupInParallel(PiComputer.class.getName(),
new Object[] { Integer.valueOf(nbDecimals_) }, nodes.toArray(new Node[0]));
return computeOnGroup(piComputer);
} catch (Exception e) {
e.printStackTrace();
} finally {
deploymentDescriptor_.kill();
}
return "";
}
/**
* Computes PI value with the component version of the application
*
*/
public void runComponent() {
try {
String arg0 = "-fractal"; // using the fractal component model
String arg1 = "org.objectweb.proactive.examples.pi.fractal.PiBBPWrapper";
String arg2 = "r";
String arg3 = "../descriptors/" + deploymentDescriptorLocation_; // the deployment descriptor
Factory f = org.objectweb.proactive.core.component.adl.FactoryFactory.getFactory();
Map<String, GCMApplication> context = new HashMap<String, GCMApplication>();
/* Deploying runtimes */
GCMApplication deploymentDescriptor = PAGCMDeployment.loadApplicationDescriptor(new File(arg3));
context.put("deployment-descriptor", deploymentDescriptor);
deploymentDescriptor.startDeployment();
GCMVirtualNode virtualNode = deploymentDescriptor.getVirtualNode("computers-vn");
virtualNode.waitReady();
long nbNodes = virtualNode.getNbCurrentNodes();
/* Determining intervals to send for computation */
List<Interval> intervals = PiUtil.dividePIList(nbNodes, nbDecimals_);
/* Master component creation */
Component master = (Component) f.newComponent(
"org.objectweb.proactive.examples.pi.fractal.PiBBPWrapper", null);
/* Creation of worker components, depending on the number of deployed nodes */
Component worker;
List<Component> workers = new ArrayList<Component>();
for (int i = 0; i < nbNodes; i++) {
worker = (Component) f.newComponent("org.objectweb.proactive.examples.pi.fractal.PiComputer",
context);
GCM.getBindingController(master).bindFc("multicastDispatcher",
worker.getFcInterface("computation")); /*
* Master component is bound to each
* worker, with its client multicast
* interface
*/
workers.add(worker);
}
Component w;
//Starting all the workers
PiComp picomp;
for (int j = 0; j < workers.size(); j++) {
w = workers.get(j);
GCM.getGCMLifeCycleController(w).startFc();
picomp = (PiComp) w.getFcInterface("computation");
picomp.setScale(nbDecimals_); /*
* Normally, this is made when instantiating
* PiComputers, but with ADL instantiation, we have
* to make an explicit call to setScale
*/
}
GCM.getGCMLifeCycleController(master).startFc();
MasterComputation m = (MasterComputation) master.getFcInterface("s");
m.computePi(intervals); /*
* Computing and displaying the value of PI(the call is
* synchronous)
*/
/* Stopping all the components */
/* Stopping master component */
GCM.getGCMLifeCycleController(master).stopFc();
/* Stopping workers components */
for (int j = 0; j < workers.size(); j++) {
w = workers.get(j);
GCM.getGCMLifeCycleController(w).stopFc();
}
deploymentDescriptor.kill(); /* Killing deployed runtimes */
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Method called when the value of pi has to be computed with a group of "pi computers"
* @param piComputers the group of "pi computers" that will perform the computation
* @return the value of PI
*/
public String computeOnGroup(PiComp piComputers) {
int nbNodes = PAGroup.getGroup(piComputers).size();
System.out.println("\nUsing " + nbNodes + " PiComputers for the computation\n");
// distribution of the intervals to the computers is handled in
// a private method
Interval intervals = null;
try {
intervals = PiUtil.dividePI(nbNodes, nbDecimals_);
} catch (Exception e) {
e.printStackTrace();
return "";
}
// scatter group data, so that independent intervals are sent as
// parameters to each PiComputer instance
PAGroup.setScatterGroup(intervals);
//*************************************************************
// * computation
// *************************************************************/
System.out.println("Starting computation ...\n");
long timeAtBeginningOfComputation = System.currentTimeMillis();
// invocation on group, parameters are scattered, result is a
// group
Result results = piComputers.compute(intervals);
Group<Result> resultsGroup = PAGroup.getGroup(results);
// the following is displayed because the "compute" operation is
// asynchronous (non-blocking)
System.out.println("Intervals sent to the computers...\n");
Result total = PiUtil.conquerPI(results);
long timeAtEndOfComputation = System.currentTimeMillis();
//*************************************************************
// * results
// *************************************************************/
System.out.println("\nComputation finished ...");
System.out.println("Computed PI value is : " + total.getNumericalResult().toString());
System.out.println("Time waiting for result : " +
(timeAtEndOfComputation - timeAtBeginningOfComputation) + " ms");
System.out.println("Cumulated time from all computers is : " + total.getComputationTime() + " ms");
System.out
.println("Ratio for " +
resultsGroup.size() +
" processors is : " +
(((double) total.getComputationTime() / ((double) (timeAtEndOfComputation - timeAtBeginningOfComputation))) * 100) +
" %");
return total.getNumericalResult().toString();
}
/**
* This method decides which version of pi application has to be launched
*
*/
public void start() {
System.out.println("Evaluation of Pi will be performed with " + nbDecimals_ + " decimals");
switch (run_) {
case (SIMPLE):
runSimple();
break;
case (PARALLEL):
runParallel();
break;
case (PARALLEL_DISTRIBUTED):
runParallelDistributed();
try {
deploymentDescriptor_.kill();
} catch (Exception e) {
e.printStackTrace();
}
break;
case (COMPONENT):
runComponent();
break;
default:
runSimple();
}
}
public static void main(String[] args) {
try {
// PiBBP piApplication = new PiBBP(args);
// piApplication.start();
PiBBP piApplication = PAActiveObject.newActive(PiBBP.class, new Object[] { args });
if (piApplication.isWebService()) {
WebServicesFactory wsf = AbstractWebServicesFactory.getDefaultWebServicesFactory();
WebServices ws = wsf.getWebServices("http://localhost:8080/");
ws.exposeAsWebService(piApplication, "piComputation", new String[] { "runSimple",
"runParallel", "runParallelDistributed", "setNbDecimals" });
} else {
piApplication.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Tests if the computation of PI has to de deployed as a web service
* @return true if the application has to be exposed as a web service, false if not
*/
public boolean isWebService() {
return ws_;
}
/**
* Initializes the computation with the arguments found in the args array
* @param args The initialization arguments
*/
private void parseProgramArguments(String[] args) throws IllegalArgumentException {
if (args.length == 0) {
ws_ = true;
deploymentDescriptorLocation_ = "LAN.xml";
} else {
nbDecimals_ = new Integer(args[0]).intValue();
run_ = new Integer(args[1]).intValue();
int deployment = new Integer(args[2]).intValue();
switch (deployment) {
case 1:
deploymentDescriptorLocation_ = "applicationDescriptor.xml";
break;
case 2:
deploymentDescriptorLocation_ = "LAN.xml";
break;
case 3:
throw new IllegalArgumentException("P2P is no longer supported");
case 4:
deploymentDescriptorLocation_ = "sophia-cluster.xml";
break;
case 5:
deploymentDescriptorLocation_ = "custom-descriptor.xml";
break;
default:
deploymentDescriptorLocation_ = "applicationDescriptor.xml";
}
}
}
}
| agpl-3.0 |
retest/recheck | src/main/java/de/retest/recheck/image/FuzzyImageDifferenceCalculator.java | 5517 | package de.retest.recheck.image;
import static de.retest.recheck.ui.image.ImageUtils.readImage;
import static de.retest.recheck.ui.image.ImageUtils.scaleProportionallyToMaxWidthHeight;
import static de.retest.recheck.ui.image.ImageUtils.scaleToSameSize;
import static de.retest.recheck.ui.image.ImageUtils.screenshot2Image;
import static de.retest.recheck.ui.image.ImageUtils.toBufferedImage;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.IOException;
import javax.swing.GrayFilter;
import de.retest.recheck.ui.image.Screenshot;
// Inspired by http://mindmeat.blogspot.de/2008/07/java-image-comparison.html
// Alternative is using full-fledged (but native / OS-dependent):
// http://docs.opencv.org/2.4/doc/tutorials/tutorials.html
public class FuzzyImageDifferenceCalculator implements ImageDifferenceCalculator {
private static final org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger( FuzzyImageDifferenceCalculator.class );
private static final String SENSITIVITY_PROPERTY = "de.retest.recheck.image.fuzzinessSensitivity";
private static final String BLOCKSIZE_PROPERTY = "de.retest.recheck.image.fuzzinessBlockSize";
private static final int DEFAULT_BLOCKSIZE = 10;
private static final int DEFAULT_SENSITIVITY = 1;
// The pixel size of the blocks used for calculation
private final int blockSize;
// Sensitivity-higher values are less sensitive
private final int sensitivity;
private static final double STABILIZER = 25.0;
public FuzzyImageDifferenceCalculator() {
this( Integer.getInteger( BLOCKSIZE_PROPERTY, DEFAULT_BLOCKSIZE ),
Integer.getInteger( SENSITIVITY_PROPERTY, DEFAULT_SENSITIVITY ) );
}
public FuzzyImageDifferenceCalculator( final int blockSize, final int sensitivity ) {
this.blockSize = blockSize;
this.sensitivity = sensitivity;
}
public ImageDifference compare( final String file1, final String file2 ) throws IOException {
return compare( readImage( file1 ), readImage( file2 ) );
}
@Override
public ImageDifference compare( final Screenshot shot1, final Screenshot shot2 ) {
return compare( screenshot2Image( shot1 ), screenshot2Image( shot2 ) );
}
@Override
public ImageDifference compare( BufferedImage img1, BufferedImage img2 ) {
if ( img1 == null ) {
if ( img2 == null ) {
return new ImageDifference( 1.0, null, FuzzyImageDifferenceCalculator.class );
}
return new ImageDifference( 0.0, img2, FuzzyImageDifferenceCalculator.class );
}
if ( img2 == null ) {
return new ImageDifference( 0.0, img1, FuzzyImageDifferenceCalculator.class );
}
img1 = toBufferedImage( scaleProportionallyToMaxWidthHeight( img1, 800, 600 ) );
img1 = toBufferedImage( scaleToSameSize( img1, img2 ) );
img2 = toBufferedImage( scaleToSameSize( img2, img1 ) );
final BufferedImage differenceImage = toBufferedImage( img2 );
final Graphics2D gc = differenceImage.createGraphics();
gc.setColor( Color.RED );
// convert to gray images.
img1 = toBufferedImage( GrayFilter.createDisabledImage( img1 ) );
img2 = toBufferedImage( GrayFilter.createDisabledImage( img2 ) );
// set to a match by default, if a change is found then flag non-match
int numdiffs = 0;
final int numRows = (int) Math.ceil( img1.getHeight() / (float) blockSize );
final int numCols = (int) Math.ceil( img1.getWidth() / (float) blockSize );
// loop through whole image and compare individual blocks of images
StringBuilder textual = new StringBuilder();
for ( int row = 0; row < numRows; row++ ) {
textual.append( "|" );
for ( int col = 0; col < numCols; col++ ) {
final int b1 = getAverageBrightness( getSubImage( img1, col, row ) );
final int b2 = getAverageBrightness( getSubImage( img2, col, row ) );
final int diff = Math.abs( b1 - b2 );
if ( diff > sensitivity ) {
// the difference in a certain region has passed the threshold value
// draw an indicator on the change image to show where change was detected.
// TODO Merge borders of neighboring blocks
gc.drawRect( col * blockSize, row * blockSize, blockSize - 1, blockSize - 1 );
numdiffs++;
}
textual.append( diff > sensitivity ? "X" : " " );
}
textual.append( "|" );
logger.warn( textual.toString() );
textual = new StringBuilder();
}
if ( numdiffs == 0 ) {
// ensure no rounding errors...
return new ImageDifference( 1.0, differenceImage, FuzzyImageDifferenceCalculator.class );
}
final int total = numRows * numCols;
final double match = (total - numdiffs) / (double) total;
return new ImageDifference( match, differenceImage, FuzzyImageDifferenceCalculator.class );
}
// returns a value specifying some kind of average brightness in the image.
protected int getAverageBrightness( final BufferedImage img ) {
final Raster r = img.getData();
int total = 0;
for ( int y = 0; y < r.getHeight(); y++ ) {
for ( int x = 0; x < r.getWidth(); x++ ) {
total += r.getSample( r.getMinX() + x, r.getMinY() + y, 0 );
}
}
return (int) (total / (r.getWidth() / STABILIZER * (r.getHeight() / STABILIZER)));
}
private BufferedImage getSubImage( final BufferedImage img, final int col, final int row ) {
final int x = col * blockSize;
final int width = Math.abs( Math.min( img.getWidth() - x, blockSize - 1 ) );
final int y = row * blockSize;
final int height = Math.abs( Math.min( img.getHeight() - y, blockSize - 1 ) );
return img.getSubimage( x, y, width, height );
}
}
| agpl-3.0 |
StarFlight/Poker-Galore | server/poker-logic/src/main/java/com/cubeia/poker/gametypes/TexasHoldem.java | 10418 | /**
* Copyright (C) 2010 Cubeia Ltd <info@cubeia.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.cubeia.poker.gametypes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import org.apache.log4j.Logger;
import ca.ualberta.cs.poker.Card;
import ca.ualberta.cs.poker.Deck;
import ca.ualberta.cs.poker.Hand;
import com.cubeia.poker.GameType;
import com.cubeia.poker.PokerState;
import com.cubeia.poker.action.ActionRequest;
import com.cubeia.poker.action.PokerAction;
import com.cubeia.poker.action.PokerActionType;
import com.cubeia.poker.adapter.HandEndStatus;
import com.cubeia.poker.adapter.ServerAdapter;
import com.cubeia.poker.model.PlayerHands;
import com.cubeia.poker.player.PokerPlayer;
import com.cubeia.poker.result.HandResult;
import com.cubeia.poker.result.Result;
import com.cubeia.poker.rounds.BettingRound;
import com.cubeia.poker.rounds.DealCommunityCardsRound;
import com.cubeia.poker.rounds.Round;
import com.cubeia.poker.rounds.RoundVisitor;
import com.cubeia.poker.rounds.blinds.BlindsInfo;
import com.cubeia.poker.rounds.blinds.BlindsRound;
import com.cubeia.poker.timing.Periods;
import com.cubeia.poker.util.HandResultCalculator;
import com.google.inject.Inject;
public class TexasHoldem implements GameType, RoundVisitor {
private static final long serialVersionUID = -1523110440727681601L;
private static transient Logger log = Logger.getLogger(TexasHoldem.class);
private SortedMap<Integer, PokerPlayer> seatingMap;
private Round currentRound;
private Deck deck;
private List<Card> communityCards = new ArrayList<Card>();
private Map<Integer, PokerPlayer> playerMap = new HashMap<Integer, PokerPlayer>();
/**
* 0 = pre flop 1 = flop 2 = turn 3 = river
*/
private int roundId;
private BlindsInfo blindsInfo = new BlindsInfo();
@Inject
PokerState game;
private Random random = new Random();
private HandResultCalculator handResultCalculator = new HandResultCalculator();
public String toString() {
return "TexasHoldem, current round["+currentRound+"] roundId["+roundId+"] ";
}
@Override
public int getAnteLevel() {
return game.getAnteLevel();
}
public void startHand(SortedMap<Integer, PokerPlayer> seatingMap,
Map<Integer, PokerPlayer> playerMap) {
this.seatingMap = seatingMap;
this.playerMap = playerMap;
initHand();
}
private void initHand() {
deck = new Deck(getRandom().nextInt());
// FIXME: Use better seed for the shuffle
deck.shuffle();
currentRound = new BlindsRound(this, game.isTournamentTable());
roundId = 0;
}
private Random getRandom() {
return random;
}
public SortedMap<Integer, PokerPlayer> getSeatingMap() {
return seatingMap;
}
public void act(PokerAction action) {
currentRound.act(action);
checkFinishedRound();
}
private void checkFinishedRound() {
if (currentRound.isFinished()) {
handleFinishedRound();
}
}
private void dealPocketCards(PokerPlayer p, int n) {
for (int i = 0; i < n; i++) {
p.getPocketCards().addCard(deck.dealCard());
}
game.notifyPrivateCards(p.getId(), p.getPocketCards().getCards());
}
private void dealCommunityCards(int n) {
List<Card> dealt = new LinkedList<Card>();
for (int i = 0; i < n; i++) {
dealt.add(deck.dealCard());
}
communityCards.addAll(dealt);
game.notifyCommunityCards(dealt);
}
public List<Card> getCommunityCards() {
return communityCards;
}
public PokerPlayer getPlayer(int playerId) {
PokerPlayer pokerPlayer = playerMap.get(playerId);
return pokerPlayer;
}
public Iterable<PokerPlayer> getPlayers() {
return playerMap.values();
}
public void handleFinishedRound() {
currentRound.visit(this);
}
private void reportPotUpdate() {
game.updatePot();
}
/**
* Expose all pocket cards for players still in the hand
* i.e. not folded.
*/
private void exposeShowdownCards() {
if (countNonFoldedPlayers() > 1) {
for (PokerPlayer p : getSeatingMap().values()) {
if (!p.hasFolded()) {
log.debug("exposing pocket cards for player #" + p.getId());
game.exposePrivateCards(p.getId(), p.getPocketCards().getCards());
}
}
}
}
private void startBettingRound() {
log.trace("Starting new betting round. Round ID: "+(roundId+1));
currentRound = new BettingRound(this, blindsInfo.getDealerButtonSeatId());
roundId++;
}
private boolean isHandFinished() {
return (roundId >= 3 || countNonFoldedPlayers() <= 1);
}
public int countNonFoldedPlayers() {
int nonFolded = 0;
for (PokerPlayer p : getSeatingMap().values()) {
if (!p.hasFolded() && !p.isSittingOut()) {
nonFolded++;
}
}
return nonFolded;
}
public int countPlayersSittingIn() {
int sittingIn = 0;
for (PokerPlayer p : getSeatingMap().values()) {
if (!p.isSittingOut()) {
sittingIn++;
}
}
return sittingIn;
}
public void dealCommunityCards() {
if (roundId == 0) {
dealCommunityCards(3);
} else {
dealCommunityCards(1);
}
}
private void handleFinishedHand(HandResult handResult) {
log.debug("Hand over. Result: "+handResult.getPlayerHands());
game.notifyHandFinished(handResult, HandEndStatus.NORMAL);
}
private void handleCanceledHand() {
game.notifyHandFinished(new HandResult(), HandEndStatus.CANCELED_TOO_FEW_PLAYERS);
}
private HandResult createHandResult() {
HandResult result = new HandResult();
PlayerHands playerHands = createHandHolder();
result.setPlayerHands(playerHands);
log.debug("Inside createHandResult and call to set winner");
// TODO
// Add player winner flag here
Map<PokerPlayer, Result> playerResults = handResultCalculator.getPlayerResults(result.getPlayerHands(), game.getPotHolder(), playerMap);
result.setResults(playerResults);
return result;
}
private PlayerHands createHandHolder() {
PlayerHands holder = new PlayerHands();
for (PokerPlayer player : playerMap.values()) {
if (!player.hasFolded()) {
Hand h = new Hand();
h.addCards(player.getPocketCards().getCards());
h.addCards(getCommunityCards());
holder.addHand(player.getId(), h);
}
}
return holder;
}
private void moveChipsToPot() {
game.getPotHolder().moveChipsToPot(seatingMap.values());
for (PokerPlayer p : seatingMap.values()) {
p.setHasActed(false);
p.clearActionRequest();
p.commitBetStack();
}
}
public void requestAction(ActionRequest r) {
if (blindRequested(r) && game.isTournamentTable()) {
game.getServerAdapter().scheduleTimeout(game.getTimingProfile().getTime(Periods.AUTO_POST_BLIND_DELAY));
} else {
game.requestAction(r);
}
}
public void scheduleRoundTimeout() {
log.debug("scheduleRoundTimeout in: "+ game.getTimingProfile().getTime(Periods.RIVER));
game.getServerAdapter().scheduleTimeout(game.getTimingProfile().getTime(Periods.RIVER));
}
private boolean blindRequested(ActionRequest r) {
return r.isOptionEnabled(PokerActionType.SMALL_BLIND) || r.isOptionEnabled(PokerActionType.BIG_BLIND);
}
// public void requestAction(PokerPlayer player,
// PossibleAction ... possibleActions) {
// ActionRequest actionRequest = new ActionRequest();
// List<PossibleAction> options = new ArrayList<PossibleAction>();
//
// for (PossibleAction action : possibleActions) {
// options.add(action);
// }
//
// actionRequest.setOptions(options);
// actionRequest.setPlayerId(player.getId());
// player.setActionRequest(actionRequest);
// logDebug("Requesting action " + actionRequest);
// game.requestAction(actionRequest);
// }
public BlindsInfo getBlindsInfo() {
return blindsInfo;
}
public void prepareNewHand() {
communityCards.clear();
for (PokerPlayer player : playerMap.values()) {
player.clearHand();
player.setHasFolded(false);
}
}
public void notifyDealerButton(int dealerButtonSeatId) {
game.notifyDealerButton(dealerButtonSeatId);
}
public ServerAdapter getServerAdapter() {
return game.getServerAdapter();
}
public void timeout() {
log.debug("Timeout");
currentRound.timeout();
checkFinishedRound();
}
public PokerState getState() {
return game;
}
public String getStateDescription() {
return currentRound == null ? "th-round=null" : currentRound.getClass() + "_" + currentRound.getStateDescription();
}
public boolean isPlayerInHand(int playerId) {
return playerMap.get(playerId) == null ? false : playerMap.get(playerId).isInHand();
}
public void visit(BettingRound bettingRound) {
moveChipsToPot();
reportPotUpdate();
if (isHandFinished()) {
log.debug("exposeShowdownCards");
exposeShowdownCards();
handleFinishedHand(createHandResult());
game.getPotHolder().clearPots();
} else {
// dealCommunityCards();
// startBettingRound();
// Start deal community cards round
currentRound = new DealCommunityCardsRound(this);
// Schedule timeout for the community cards round
scheduleRoundTimeout();
}
}
public void visit(BlindsRound blindsRound) {
if (blindsRound.isCanceled()) {
handleCanceledHand();
} else {
updateBlindsInfo(blindsRound);
dealPocketCards();
prepareBettingRound();
}
}
public void visit(DealCommunityCardsRound round) {
startBettingRound();
}
private void prepareBettingRound() {
int bbSeatId = blindsInfo.getBigBlindSeatId();
currentRound = new BettingRound(this, bbSeatId);
}
private void updateBlindsInfo(BlindsRound blindsRound) {
this.blindsInfo = blindsRound.getBlindsInfo();
}
private void dealPocketCards() {
for (PokerPlayer p : seatingMap.values()) {
if (!p.isSittingOut()) {
dealPocketCards(p, 2);
}
}
}
}
| agpl-3.0 |
nilcy/yoyo | yoyo-actor/yoyo-actor-screen/src/main/java/yoyo/actor/screen/iface/jsf/conversation/master/package-info.java | 454 | // ========================================================================
// Copyright (C) YOYO Project Team. All rights reserved.
// GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
// http://www.gnu.org/licenses/agpl-3.0.txt
// ========================================================================
/**
* Master conversation-scoped faces module.
* @author nilcy
*/
package yoyo.actor.screen.iface.jsf.conversation.master;
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/operator/ports/quickfix/AddCompatibleOperatorQuickFix.java | 2566 | /**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.ports.quickfix;
import com.rapidminer.gui.RapidMinerGUI;
import com.rapidminer.gui.dialog.NewOperatorDialog;
import com.rapidminer.operator.ExecutionUnit;
import com.rapidminer.operator.IOObject;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorCreationException;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.metadata.CompatibilityLevel;
/**
* @author Simon Fischer
*/
public class AddCompatibleOperatorQuickFix extends AbstractQuickFix {
private final InputPort inputPort;
private final Class<? extends IOObject> neededClass;
public AddCompatibleOperatorQuickFix(InputPort inputPort, Class<? extends IOObject> clazz) {
super(MAX_RATING - 1, false, "add_compatible", clazz.getSimpleName());
this.inputPort = inputPort;
this.neededClass = clazz;
}
@Override
public void apply() {
try {
Operator oldOperator = inputPort.getPorts().getOwner().getOperator();
Operator newOperator = NewOperatorDialog.selectMatchingOperator(RapidMinerGUI.getMainFrame().getActions(), null,
neededClass, null, null);
if (newOperator != null) {
ExecutionUnit unit = inputPort.getPorts().getOwner().getConnectionContext();
int index = unit.getIndexOfOperator(oldOperator);
if (index == -1) {
unit.addOperator(newOperator);
} else {
unit.addOperator(newOperator, unit.getIndexOfOperator(oldOperator));
}
if (RapidMinerGUI.getMainFrame().VALIDATE_AUTOMATICALLY_ACTION.isSelected()) {
unit.autoWireSingle(newOperator, CompatibilityLevel.VERSION_5, true, true);
}
}
} catch (OperatorCreationException e) {
}
}
}
| agpl-3.0 |
BrunoEberhard/open-ech | src/main/model/ch/openech/model/NamedId.java | 1245 | package ch.openech.model;
import org.minimalj.model.Keys;
import org.minimalj.model.annotation.NotEmpty;
import org.minimalj.model.annotation.Size;
public class NamedId {
public static final NamedId $ = Keys.of(NamedId.class);
@NotEmpty
@Size(20)
public String namedIdCategory;
@NotEmpty
@Size(36)
public String namedId;
public String getIdCategory() {
return namedIdCategory;
}
public void setIdCategory(String idCategory) {
this.namedIdCategory = idCategory;
}
public String getId() {
return namedId;
}
public void setId(String id) {
this.namedId = id;
}
public String getPersonIdCategory() {
return namedIdCategory;
}
public void setPersonIdCategory(String personIdCategory) {
this.namedIdCategory = personIdCategory;
}
public String getPersonId() {
return namedId;
}
public void setPersonId(String personId) {
this.namedId = personId;
}
public String getOrganisationIdCategory() {
return namedIdCategory;
}
public void setOrganisationIdCategory(String organisationIdCategory) {
this.namedIdCategory = organisationIdCategory;
}
public String getOrganisationId() {
return namedId;
}
public void setOrganisationId(String organisationId) {
this.namedId = organisationId;
}
} | agpl-3.0 |
LordODG/archassistantV2.0 | Servidor/ArchAssistant/build/generated-sources/ap-source-output/Modelo/Rationaleadd_.java | 745 | package Modelo;
import Modelo.Proyecto;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2017-09-21T11:57:25")
@StaticMetamodel(Rationaleadd.class)
public class Rationaleadd_ {
public static volatile SingularAttribute<Rationaleadd, Integer> ratAddID;
public static volatile SingularAttribute<Rationaleadd, String> ratAddDescripcion;
public static volatile SingularAttribute<Rationaleadd, String> ratAddArchivo;
public static volatile SingularAttribute<Rationaleadd, String> ratAddPaso;
public static volatile SingularAttribute<Rationaleadd, Proyecto> tblProyectoProID;
} | agpl-3.0 |
SamarkandTour/Samapp-mobile | app/src/main/java/uz/samtuit/samapp/fragments/TourFeaturesDialogFragmentWindow.java | 2573 | package uz.samtuit.samapp.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import uz.samtuit.samapp.main.ItemsListActivity;
import uz.samtuit.samapp.main.R;
import uz.samtuit.samapp.util.MenuItems;
public class TourFeaturesDialogFragmentWindow extends DialogFragment{
private int currentDay;
private int indexToAssign;
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle extras = getArguments();
indexToAssign = extras.getInt("index");
currentDay = extras.getInt("current_day");
View view = inflater.inflate(R.layout.items_fragment_dialog, container);
View.OnClickListener onClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
String action = MenuItems.MainMenu.HOTEL.toString();
switch (v.getId()) {
case R.id.attraction_picker:
action = MenuItems.MainMenu.ATTRACTION.toString();
break;
case R.id.food_picker:
action = MenuItems.MainMenu.FOODNDRINK.toString();
break;
case R.id.shop_picker:
action = MenuItems.MainMenu.SHOPPING.toString();
break;
default:
action = MenuItems.MainMenu.HOTEL.toString();
break;
}
Intent intent = new Intent(getActivity(), ItemsListActivity.class);
intent.putExtra("action",action);
intent.putExtra("selected_day", currentDay);
intent.putExtra("index", indexToAssign);
intent.putExtra("from_itinerary",true);
startActivity(intent);
getDialog().cancel();
}
};
((Button)view.findViewById(R.id.hotels_picker)).setOnClickListener(onClick);
((Button)view.findViewById(R.id.attraction_picker)).setOnClickListener(onClick);
((Button)view.findViewById(R.id.shop_picker)).setOnClickListener(onClick);
((Button)view.findViewById(R.id.food_picker)).setOnClickListener(onClick);
getDialog().getWindow().setTitle(getString(R.string.title_select_category));
return view;
}
}
| agpl-3.0 |
lp0/cursus-ui | src/main/java/uk/uuid/lp0/cursus/util/DatabaseError.java | 4075 | /*
cursus - Race series management program
Copyright 2011-2014 Simon Arlott
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.uuid.lp0.cursus.util;
import java.awt.Component;
import java.io.File;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.uuid.lp0.cursus.i18n.Messages;
import uk.uuid.lp0.cursus.ui.Constants;
import uk.uuid.cursus.db.DatabaseVersion;
import uk.uuid.cursus.db.DatabaseVersionException;
import uk.uuid.cursus.db.InvalidDatabaseException;
import uk.uuid.cursus.db.InvalidFilenameException;
import uk.uuid.cursus.db.TooManyCursusRowsException;
import uk.uuid.cursus.util.CursusException;
public class DatabaseError {
private static final Logger log = LoggerFactory.getLogger(DatabaseError.class);
public static void unableToSave(Component c, String context, String message) {
JOptionPane.showMessageDialog(c, message, Constants.APP_NAME + Constants.EN_DASH + context, JOptionPane.ERROR_MESSAGE);
}
public static void errorSaving(Component c, String context, Throwable t) {
JOptionPane.showMessageDialog(c, Messages.getString("db.error-saving") + ":\n\n" + createMessage(t), Constants.APP_NAME + Constants.EN_DASH + context, //$NON-NLS-1$ //$NON-NLS-2$
JOptionPane.ERROR_MESSAGE);
}
public static void errorFileSave(Component c, String context, File file, Throwable t) {
String message;
if (t instanceof CursusException) {
message = translateMessage(t);
} else {
message = createMessage(t);
}
JOptionPane.showMessageDialog(c,
Messages.getString("err.saving-db", file.getAbsoluteFile()) + ":\n\n" + message, Constants.APP_NAME + Constants.EN_DASH + context, //$NON-NLS-1$ //$NON-NLS-2$
JOptionPane.ERROR_MESSAGE);
}
private static String createMessage(Throwable t) {
LinkedList<String> lines = new LinkedList<String>();
Throwable first = t;
do {
if (t == first || t.getCause() == null || t.getCause() == t) {
lines.addFirst(""); //$NON-NLS-1$
lines.addFirst(translateMessage(t));
lines.addFirst(t.getClass().getName() + ":"); //$NON-NLS-1$
}
t = t.getCause();
} while (t != null && t.getCause() != t);
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line).append("\n"); //$NON-NLS-1$
}
return sb.toString();
}
private static String translateMessage(Throwable t) {
if (t instanceof CursusException) {
if (t instanceof InvalidDatabaseException) {
if (t instanceof DatabaseVersionException) {
return Messages.getString("db.version-not-supported", DatabaseVersion.parseLong(((DatabaseVersionException)t).getCursus().getVersion())); //$NON-NLS-1$
} else if (t instanceof TooManyCursusRowsException) {
return Messages.getString("db.too-many-database-identifier-rows", ((TooManyCursusRowsException)t).getRows()); //$NON-NLS-1$
} else if (t instanceof InvalidFilenameException) {
if (t instanceof InvalidFilenameException.Semicolon) {
return Messages.getString("db.filename-invalid.semicolon", ((InvalidFilenameException)t).getName()); //$NON-NLS-1$
} else if (t instanceof InvalidFilenameException.Suffix) {
return Messages.getString("db.filename-invalid.suffix", ((InvalidFilenameException)t).getName(), //$NON-NLS-1$
((InvalidFilenameException.Suffix)t).getSuffix());
}
}
}
log.warn("Untranslated exception: " + t); //$NON-NLS-1$
}
return t.getLocalizedMessage();
}
} | agpl-3.0 |
tjn/relaxe | src/main/java/com/appspot/relaxe/tools/KeyInspector.java | 1294 | /*
* This file is part of Relaxe.
* Copyright (c) 2014 Topi Nieminen
* Author: Topi Nieminen <topi.nieminen@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License.
*/
package com.appspot.relaxe.tools;
public class KeyInspector
extends CatalogTool {
@Override
protected void run() throws ToolException {
// Connection c = getConnection();
// Catalog cat = getCatalog();
//
// super.run();
}
}
| agpl-3.0 |
FilotasSiskos/hopsworks | hopsworks-common/src/main/java/io/hops/hopsworks/common/dao/kafka/TopicDetailsDTO.java | 902 | package io.hops.hopsworks.common.dao.kafka;
import java.io.Serializable;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class TopicDetailsDTO implements Serializable {
private String name;
private List<PartitionDetailsDTO> parrtitionDetails;
public TopicDetailsDTO() {
}
public TopicDetailsDTO(String name) {
this.name = name;
}
public TopicDetailsDTO(String topic,
List<PartitionDetailsDTO> partitionDetails) {
this.name = topic;
this.parrtitionDetails = partitionDetails;
}
public String getName() {
return name;
}
public List<PartitionDetailsDTO> getPartition() {
return parrtitionDetails;
}
public void setName(String topic) {
this.name = topic;
}
public void setPartition(List<PartitionDetailsDTO> partitionReplicas) {
this.parrtitionDetails = partitionReplicas;
}
}
| agpl-3.0 |
jorisschellekens/pirategold | src/main/java/com/js/quickestquail/server/XSLT.java | 1925 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.js.quickestquail.server;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
/**
*
* @author joris
*/
public class XSLT {
public static void xsl(InputStream xmlIn, File htmlOut, InputStream xslIn) {
Map<String,String> empty = new HashMap<>();
xsl(xmlIn, htmlOut, xslIn, empty);
}
// This method applies the xslFilename to inFilename and writes
// the output to outFilename.
public static void xsl(InputStream xmlIn, File htmlOut, InputStream xslIn, Map<String,String> params) {
try {
// Create transformer factory
TransformerFactory factory = TransformerFactory.newInstance();
// Use the factory to create a template containing the xsl file
Templates template = factory.newTemplates(new StreamSource(xslIn));
// Use the template to create a transformer
Transformer xformer = template.newTransformer();
for(Entry<String,String> en : params.entrySet())
{
xformer.setParameter(en.getKey(), en.getValue());
}
// Prepare the input and output files
Source source = new StreamSource(xmlIn);
Result result = new StreamResult(new FileOutputStream(htmlOut));
// Apply the xsl file to the source file and write the result to the output file
xformer.transform(source, result);
} catch (FileNotFoundException e) {
} catch (TransformerConfigurationException e) {
} catch (TransformerException e) {
}
}
}
| agpl-3.0 |
malmostad/sv-contact-portlet | src/main/java/se/malmo/esb/primecase/IHandleCaseGetRegistrationDraftsAuthenticationModuleErrorFaultFaultMessage.java | 1889 |
package se.malmo.esb.primecase;
import javax.xml.ws.WebFault;
/**
* This class was generated by Apache CXF 2.2.2
* Thu Oct 15 23:14:32 CEST 2009
* Generated source version: 2.2.2
*
*/
@WebFault(name = "AuthenticationModuleError", targetNamespace = "http://schemas.datacontract.org/2004/07/PrimeSystems.PrimeCaseCore.Portal")
public class IHandleCaseGetRegistrationDraftsAuthenticationModuleErrorFaultFaultMessage extends Exception {
public static final long serialVersionUID = 20091015231432L;
private org.datacontract.schemas._2004._07.primesystems_primecasecore.AuthenticationModuleError authenticationModuleError;
public IHandleCaseGetRegistrationDraftsAuthenticationModuleErrorFaultFaultMessage() {
super();
}
public IHandleCaseGetRegistrationDraftsAuthenticationModuleErrorFaultFaultMessage(String message) {
super(message);
}
public IHandleCaseGetRegistrationDraftsAuthenticationModuleErrorFaultFaultMessage(String message, Throwable cause) {
super(message, cause);
}
public IHandleCaseGetRegistrationDraftsAuthenticationModuleErrorFaultFaultMessage(String message, org.datacontract.schemas._2004._07.primesystems_primecasecore.AuthenticationModuleError authenticationModuleError) {
super(message);
this.authenticationModuleError = authenticationModuleError;
}
public IHandleCaseGetRegistrationDraftsAuthenticationModuleErrorFaultFaultMessage(String message, org.datacontract.schemas._2004._07.primesystems_primecasecore.AuthenticationModuleError authenticationModuleError, Throwable cause) {
super(message, cause);
this.authenticationModuleError = authenticationModuleError;
}
public org.datacontract.schemas._2004._07.primesystems_primecasecore.AuthenticationModuleError getFaultInfo() {
return this.authenticationModuleError;
}
}
| agpl-3.0 |
aborg0/rapidminer-vega | src/com/rapidminer/operator/visualization/dependencies/MutualInformationMatrixOperator.java | 5879 | /*
* RapidMiner
*
* Copyright (C) 2001-2011 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.visualization.dependencies;
import java.util.List;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.OperatorCreationException;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.preprocessing.PreprocessingOperator;
import com.rapidminer.operator.preprocessing.discretization.BinDiscretization;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeInt;
import com.rapidminer.tools.OperatorService;
import com.rapidminer.tools.math.MathFunctions;
/**
* <p>This operator calculates the mutual information matrix between all attributes of the
* input example set. This operator produces a dependency matrix which can be displayed to
* the user in the result tab.</p>
*
* <p>Please note that this simple implementation
* performs a data scan for each attribute combination and might therefore take
* some time for non-memory example tables.</p>
*
* @author Ingo Mierswa
*/
public class MutualInformationMatrixOperator extends AbstractPairwiseMatrixOperator {
public MutualInformationMatrixOperator(OperatorDescription description) {
super(description);
}
/** This preprocessing discretizes the input example set by a view. */
@Override
protected ExampleSet performPreprocessing(ExampleSet eSet) throws OperatorException {
try {
PreprocessingOperator discretizationOperator = OperatorService.createOperator(BinDiscretization.class);
discretizationOperator.setParameter(BinDiscretization.PARAMETER_NUMBER_OF_BINS, getParameterAsInt(BinDiscretization.PARAMETER_NUMBER_OF_BINS) + "");
discretizationOperator.setParameter(PreprocessingOperator.PARAMETER_CREATE_VIEW, "true");
return discretizationOperator.doWork((ExampleSet)eSet.clone());
} catch (OperatorCreationException e) {
// should not happen
throw new OperatorException(getName() + ": Cannot create discretization operator (" + e + ").");
}
}
@Override
public String getMatrixName() {
return "Mutual Information";
}
/** Calculates the mutual information for both attributes. */
@Override
public double getMatrixValue(ExampleSet exampleSet, Attribute firstAttribute, Attribute secondAttribute) {
// init
double[] firstProbabilites = new double[firstAttribute.getMapping().size()];
double[] secondProbabilites = new double[secondAttribute.getMapping().size()];
double[][] jointProbabilities = new double[firstAttribute.getMapping().size()][secondAttribute.getMapping().size()];
double firstCounter = 0.0d;
double secondCounter = 0.0d;
double firstSecondCounter = 0.0d;
// count values
for (Example example : exampleSet) {
double firstValue = example.getValue(firstAttribute);
if (!Double.isNaN(firstValue)) {
firstProbabilites[(int)firstValue]++;
firstCounter++;
}
double secondValue = example.getValue(secondAttribute);
if (!Double.isNaN(secondValue)) {
secondProbabilites[(int)secondValue]++;
secondCounter++;
}
if (!Double.isNaN(firstValue) && !Double.isNaN(secondValue)) {
jointProbabilities[(int)firstValue][(int)secondValue]++;
firstSecondCounter++;
}
}
// transform to probabilities
for (int i = 0; i < firstProbabilites.length; i++) {
firstProbabilites[i] /= firstCounter;
}
for (int i = 0; i < secondProbabilites.length; i++) {
secondProbabilites[i] /= secondCounter;
}
for (int i = 0; i < jointProbabilities.length; i++) {
for (int j = 0; j < jointProbabilities[i].length; j++) {
jointProbabilities[i][j] /= firstSecondCounter;
}
}
double firstEntropy = 0.0d;
for (int i = 0; i < firstProbabilites.length; i++) {
if (firstProbabilites[i] > 0.0d)
firstEntropy += firstProbabilites[i] * MathFunctions.ld(firstProbabilites[i]);
}
firstEntropy *= -1;
double secondEntropy = 0.0d;
for (int i = 0; i < secondProbabilites.length; i++) {
if (secondProbabilites[i] > 0.0d)
secondEntropy += secondProbabilites[i] * MathFunctions.ld(secondProbabilites[i]);
}
secondEntropy *= -1;
double jointEntropy = 0.0d;
for (int i = 0; i < jointProbabilities.length; i++) {
for (int j = 0; j < jointProbabilities[i].length; j++) {
if (jointProbabilities[i][j] > 0.0d)
jointEntropy += jointProbabilities[i][j] * MathFunctions.ld(jointProbabilities[i][j]);
}
}
jointEntropy *= -1;
return firstEntropy + secondEntropy - jointEntropy;
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
types.add(new ParameterTypeInt(BinDiscretization.PARAMETER_NUMBER_OF_BINS, "Indicates the number of bins used for numerical attributes.", 2, Integer.MAX_VALUE, 10));
return types;
}
}
| agpl-3.0 |
aldocuevas/test | pos/source_code/src/com/boutique/dao/DaoPreferencias.java | 798 | package com.boutique.dao;
import java.sql.Connection;
import java.sql.SQLException;
import com.boutique.domain.Preferencias;
public class DaoPreferencias {
public static Preferencias findPreferencias() {
Connection con = DaoSource.getConnection();
Preferencias preferencias = null;
java.sql.ResultSet rs;
try {
rs = con.createStatement().executeQuery(
"SELECT * FROM preferencias;");
if (rs.next()) {
preferencias = new Preferencias();
preferencias.setDiasDevolucionProductos(rs
.getInt("devDiasPermitidos"));
preferencias.setPagarCreditoConTC(rs.getBoolean("pagarCreditoConTC"));
}
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return preferencias;
}
}
| lgpl-2.1 |
syncer/swingx | swingx-plaf/src/main/java/org/jdesktop/swingx/plaf/DefaultsList.java | 5539 | /*
* $Id: DefaultsList.java 4047 2011-07-19 18:51:12Z kschaefe $
*
* Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx.plaf;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ActionMap;
import javax.swing.Icon;
import javax.swing.InputMap;
import javax.swing.border.Border;
import javax.swing.plaf.UIResource;
import org.jdesktop.swingx.painter.Painter;
//import org.jdesktop.swingx.renderer.StringValue;
import org.jdesktop.swingx.util.Contract;
/**
* A specialty "list" for working with UI defaults. Requires adds to be done
* using key/value pairs. The purpose of this list is to enforce additions as
* pairs.
*
* @author Karl George Schaefer
*/
@SuppressWarnings("nls")
public final class DefaultsList {
private List<Object> delegate;
/**
* Creates a {@code DefaultsList}.
*/
public DefaultsList() {
delegate = new ArrayList<Object>();
}
/**
* Adds a key/value pair to the defaults list. This implementation defers to
* {@link #add(Object, Object, boolean)} with {@code enableChecking} set to
* {@code true}.
*
* @param key
* the key that will be used to query {@code UIDefaults}
* @param value
* the value associated with the key
* @throws NullPointerException
* if {@code key} is {@code null}
* @throws IllegalArgumentException
* if {@code value} is a type that should be a
* {@code UIResource} but is not. For instance, passing in a
* {@code Border} that is not a {@code UIResource} will
* cause an exception. This checking must be enabled.
*/
public void add(Object key, Object value) {
add(key, value, true);
}
/**
* Adds a key/value pair to the defaults list. A pair with a {@code null}
* value is treated specially. A {@code null}-value pair is never added to
* the list and, furthermore, if a key/value pair exists in this list with
* the same key as the newly added one, it is removed.
*
* @param key
* the key that will be used to query {@code UIDefaults}
* @param value
* the value associated with the key
* @param enableChecking
* if {@code true} then the value is checked to ensure that
* it is a {@code UIResource}, if appropriate
* @throws NullPointerException
* if {@code key} is {@code null}
* @throws IllegalArgumentException
* if {@code value} is a type that should be a
* {@code UIResource} but is not. For instance, passing in a
* {@code Border} that is not a {@code UIResource} will
* cause an exception. This checking must be enabled.
*/
public void add(Object key, Object value, boolean enableChecking) {
if (enableChecking) {
asUIResource(value, value + " must be a UIResource");
}
if (value == null && delegate.contains(key)) {
int i = delegate.indexOf(key);
delegate.remove(i + 1);
delegate.remove(i);
} else if (value != null) {
delegate.add(Contract.asNotNull(key, "key cannot be null"));
delegate.add(value);
}
}
//TODO move to Contract?
private static <T> T asUIResource(T value, String message) {
if (!(value instanceof UIResource)) {
boolean shouldThrow = false;
shouldThrow |= value instanceof ActionMap;
shouldThrow |= value instanceof Border;
shouldThrow |= value instanceof Color;
shouldThrow |= value instanceof Dimension;
shouldThrow |= value instanceof Font;
shouldThrow |= value instanceof Icon;
shouldThrow |= value instanceof InputMap;
shouldThrow |= value instanceof Insets;
shouldThrow |= value instanceof Painter<?>;
//FIXME how to handle UIResource testing
// shouldThrow |= value instanceof StringValue;
if (shouldThrow) {
throw new IllegalArgumentException(message);
}
}
return value;
}
/**
* Gets a copy of this list as an array.
*
* @return an array containing all of the key/value pairs added to this list
*/
public Object[] toArray() {
return delegate.toArray();
}
}
| lgpl-2.1 |
celements/celements-core | src/main/java/com/celements/web/utils/WebUtils.java | 19509 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.celements.web.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.model.reference.DocumentReference;
import com.celements.inheritor.InheritorFactory;
import com.celements.navigation.NavigationClasses;
import com.celements.navigation.TreeNode;
import com.celements.navigation.filter.ExternalUsageFilter;
import com.celements.navigation.filter.INavFilter;
import com.celements.navigation.filter.InternalRightsFilter;
import com.celements.navigation.service.ITreeNodeCache;
import com.celements.navigation.service.ITreeNodeService;
import com.celements.navigation.service.TreeNodeService;
import com.celements.pagetype.IPageType;
import com.celements.pagetype.PageTypeApi;
import com.celements.web.plugin.cmd.AttachmentURLCommand;
import com.celements.web.plugin.cmd.EmptyCheckCommand;
import com.celements.web.service.IWebUtilsService;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Attachment;
import com.xpn.xwiki.api.Document;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiMessageTool;
/**
* @deprecated since 2.59
*/
@Deprecated
public class WebUtils implements IWebUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(WebUtils.class);
private static IWebUtils instance;
private AttachmentURLCommand attachmentUrlCmd;
private InheritorFactory injectedInheritorFactory;
private ITreeNodeService injectedTreeNodeService;
/**
* FOR TEST ONLY!!! Please use getInstance instead.
*/
WebUtils() {}
public static IWebUtils getInstance() {
if (instance == null) {
instance = new WebUtils();
}
return instance;
}
void injectInheritorFactory(InheritorFactory injectedInheritorFactory) {
this.injectedInheritorFactory = injectedInheritorFactory;
}
InheritorFactory getInheritorFactory() {
if (injectedInheritorFactory != null) {
return injectedInheritorFactory;
}
return new InheritorFactory();
}
void injectTreeNodeService(ITreeNodeService injectedTreeNodeService) {
this.injectedTreeNodeService = injectedTreeNodeService;
}
private ITreeNodeService getTreeNodeService() {
if (injectedTreeNodeService != null) {
return injectedTreeNodeService;
}
ITreeNodeService ret = Utils.getComponent(ITreeNodeService.class);
if (injectedInheritorFactory != null) {
((TreeNodeService) ret).injectInheritorFactory(injectedInheritorFactory);
}
return ret;
}
private ITreeNodeCache getTreeNodeCache() {
return Utils.getComponent(ITreeNodeCache.class);
}
private IWebUtilsService getWebUtilsService() {
return Utils.getComponent(IWebUtilsService.class);
}
private AttachmentURLCommand getAttachmentUrlCmd() {
if (attachmentUrlCmd == null) {
attachmentUrlCmd = new AttachmentURLCommand();
}
return attachmentUrlCmd;
}
/**
* @deprecated since 2.17.0 instead use TreeNodeCache
*/
@Override
@Deprecated
public int queryCount() {
return getTreeNodeCache().queryCount();
}
/**
* @deprecated since 2.17.0 instead use TreeNodeCache
*/
@Override
@Deprecated
public void flushMenuItemCache(XWikiContext context) {
LOGGER.info("flushMenuItemCache called. Do not call flushMenuItemCache for MenuItem "
+ " changes anymore. The TreeNodeDocument change listener take care of flushing "
+ " the cache if needed.");
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public List<String> getDocumentParentsList(String fullName, boolean includeDoc,
XWikiContext context) {
ArrayList<String> docParents = new ArrayList<>();
try {
String nextParent;
if (includeDoc) {
nextParent = fullName;
} else {
nextParent = getParentFullName(fullName, context);
}
while (!"".equals(nextParent) && (context.getWiki().exists(nextParent, context))
&& !docParents.contains(nextParent)) {
docParents.add(nextParent);
nextParent = getParentFullName(nextParent, context);
}
} catch (XWikiException e) {
LOGGER.error("failed", e);
}
return docParents;
}
@Deprecated
private String getParentFullName(String fullName, XWikiContext context) throws XWikiException {
return context.getWiki().getDocument(fullName, context).getParent();
}
/**
* @deprecated since 2.17.0 instead use EmptyCheckCommand
*/
@Override
@Deprecated
public boolean isEmptyRTEDocument(XWikiDocument localdoc) {
return isEmptyRTEString(localdoc.getContent());
}
/**
* @deprecated since 2.17.0 instead use EmptyCheckCommand
*/
@Override
@Deprecated
public boolean isEmptyRTEString(String rteContent) {
return new EmptyCheckCommand().isEmptyRTEString(rteContent);
}
/**
* @deprecated since 2.17.0 instead use TreeNodeService
*/
@Override
@Deprecated
public int getActiveMenuItemPos(int menuLevel, String menuPart, XWikiContext context) {
return getTreeNodeService().getActiveMenuItemPos(menuLevel, menuPart);
}
/**
* @deprecated since 2.17.0 instead use TreeNodeService
*/
@Override
@Deprecated
public int getMenuItemPos(String fullName, String menuPart, XWikiContext context) {
return getTreeNodeService().getMenuItemPos(getRef(fullName), menuPart);
}
/**
* @deprecated since 2.17.0 instead use TreeNodeService.getSubNodesForParent
*/
@Override
@Deprecated
public List<com.xpn.xwiki.api.Object> getSubMenuItemsForParent(String parent, String menuSpace,
String menuPart, XWikiContext context) {
ExternalUsageFilter filter = new ExternalUsageFilter();
filter.setMenuPart(menuPart);
return getSubMenuItemsForParent(parent, menuSpace, filter, context);
}
/**
* @deprecated since 2.14.0 use getSubNodesForParent instead
*/
@Override
@Deprecated
public List<BaseObject> getSubMenuItemsForParent_internal(String parent, String menuSpace,
String menuPart, XWikiContext context) {
InternalRightsFilter filter = new InternalRightsFilter();
filter.setMenuPart(menuPart);
return getSubMenuItemsForParent(parent, menuSpace, filter, context);
}
/**
* @deprecated since 2.14.0 instead use TreeNodeService directly
*/
@Override
@Deprecated
public List<TreeNode> getSubNodesForParent(String parent, String menuSpace, String menuPart,
XWikiContext context) {
return getTreeNodeService().getSubNodesForParent(parent, menuSpace, menuPart);
}
/**
* @deprecated since 2.14.0 use getSubNodesForParent instead
*/
@Override
@Deprecated
public <T> List<T> getSubMenuItemsForParent(String parent, String menuSpace, INavFilter<T> filter,
XWikiContext context) {
return getTreeNodeService().getSubMenuItemsForParent(parent, menuSpace, filter);
}
/**
* @deprecated since 2.14.0 instead use TreeNodeService directly
*/
@Override
@Deprecated
public <T> List<TreeNode> getSubNodesForParent(String parent, String menuSpace,
INavFilter<T> filter, XWikiContext context) {
return getTreeNodeService().getSubNodesForParent(parent, menuSpace, filter);
}
/**
* @deprecated since 2.17.0 instead use TreeNodeService
*/
@Override
@Deprecated
public List<com.xpn.xwiki.api.Object> getMenuItemsForHierarchyLevel(int menuLevel,
String menuPart, XWikiContext context) {
String parent = getParentForLevel(menuLevel, context);
if (parent != null) {
List<com.xpn.xwiki.api.Object> submenuItems = getSubMenuItemsForParent(parent, "", menuPart,
context);
LOGGER.debug("submenuItems for parent: " + parent + " ; " + submenuItems);
return submenuItems;
}
LOGGER.debug("parent is null");
return new ArrayList<>();
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public String getParentForLevel(int menuLevel, XWikiContext context) {
String parent = null;
if (menuLevel == 1) {
parent = ""; // mainMenu
} else {
List<String> parentList = getDocumentParentsList(context.getDoc().getFullName(), true,
context);
int startAtItem = (parentList.size() - menuLevel) + 1;
if (startAtItem >= 0) {
parent = parentList.get(startAtItem);
}
}
return parent;
}
/**
* @deprecated since 2.17.0 instead use TreeNodeService
*/
@Override
@Deprecated
public BaseObject getPrevMenuItem(String fullName, XWikiContext context) throws XWikiException {
TreeNode prevTreeNode = getTreeNodeService().getPrevMenuItem(getRef(fullName));
if (prevTreeNode != null) {
DocumentReference docRef = prevTreeNode.getDocumentReference();
return context.getWiki().getDocument(docRef, context).getXObject(getRef(
"Celements2.MenuItem"));
}
return null;
}
/**
* @deprecated since 2.17.0 instead use TreeNodeService
*/
@Override
@Deprecated
public BaseObject getNextMenuItem(String fullName, XWikiContext context) throws XWikiException {
TreeNode nextTreeNode = getTreeNodeService().getNextMenuItem(getRef(fullName));
if (nextTreeNode != null) {
DocumentReference docRef = nextTreeNode.getDocumentReference();
return context.getWiki().getDocument(docRef, context).getXObject(
new NavigationClasses().getMenuItemClassRef(context.getDatabase()));
}
return null;
}
/*
* (non-Javadoc)
*
* @see com.celements.web.utils.IWebUtils#getConfigDocByInheritance(com.xpn.xwiki.doc.
* XWikiDocument, java.lang.String, com.xpn.xwiki.XWikiContext)
*/
@Override
@Deprecated
public XWikiDocument getConfigDocByInheritance(XWikiDocument doc, String className,
XWikiContext context) throws XWikiException {
XWikiDocument preferenceDoc = context.getWiki().getDocument(doc.getSpace() + ".WebPreferences",
context);
if (preferenceDoc.getObject(className, false, context) == null) {
preferenceDoc = context.getWiki().getDocument("XWiki.XWikiPreferences", context);
if (preferenceDoc.getObject(className, false, context) == null) {
String skinDocName = context.getWiki().getSpacePreference("skin", context);
if ((skinDocName != null) && (context.getWiki().exists(skinDocName, context))) {
preferenceDoc = context.getWiki().getDocument(skinDocName, context);
}
}
}
return preferenceDoc;
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public String getDocSectionAsJSON(String regex, String fullName, int section,
XWikiContext context) throws XWikiException {
return getWebUtilsService().getDocSectionAsJSON(regex, getRef(fullName), section);
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Deprecated
public String getDocSection(String regex, String fullName, int section, XWikiContext context)
throws XWikiException {
return getWebUtilsService().getDocSection(regex, getRef(fullName), section);
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public int countSections(String regex, String fullName, XWikiContext context)
throws XWikiException {
return getWebUtilsService().countSections(regex, getRef(fullName));
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public IPageType getPageTypeApi(String fullName, XWikiContext context) throws XWikiException {
return new PageTypeApi(fullName, context);
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public List<String> getAllowedLanguages(XWikiContext context) {
return getWebUtilsService().getAllowedLanguages();
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public Date parseDate(String date, String format) {
return getWebUtilsService().parseDate(date, format);
}
/**
* @deprecated since 2.14.0 instead use WebUtilsService directly
*/
@Override
@Deprecated
public XWikiMessageTool getMessageTool(String adminLanguage, XWikiContext context) {
return getWebUtilsService().getMessageTool(adminLanguage);
}
/**
* @deprecated since 2.14.0 instead use WebUtilsService directly
*/
@Override
@Deprecated
public XWikiMessageTool getAdminMessageTool(XWikiContext context) {
return getWebUtilsService().getAdminMessageTool();
}
/**
* @deprecated since 2.14.0 instead use WebUtilsService directly
*/
@Override
@Deprecated
public String getAdminLanguage(XWikiContext context) {
return getWebUtilsService().getAdminLanguage();
}
/**
* @deprecated since 2.14.0 instead use WebUtilsService directly
*/
@Override
@Deprecated
public String getAdminLanguage(String userFullName, XWikiContext context) {
return getWebUtilsService().getAdminLanguage(userFullName);
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public boolean hasParentSpace(XWikiContext context) {
return getWebUtilsService().hasParentSpace();
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public String getParentSpace(XWikiContext context) {
return getWebUtilsService().getParentSpace();
}
/**
* @deprecated since 2.17.0 instead use TreeNodeService
*/
@Override
@Deprecated
public Integer getMaxConfiguredNavigationLevel(XWikiContext context) {
return getTreeNodeService().getMaxConfiguredNavigationLevel();
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public List<Attachment> getAttachmentListSorted(Document doc, String comparator)
throws ClassNotFoundException {
return this.getWebUtilsService().getAttachmentListSorted(doc, comparator);
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService directly
*/
@Override
@Deprecated
public List<Attachment> getAttachmentListSorted(Document doc, String comparator,
boolean imagesOnly, int start, int nb) throws ClassNotFoundException {
return this.getWebUtilsService().getAttachmentListSorted(doc, comparator, imagesOnly, start,
nb);
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public String getAttachmentListSortedAsJSON(Document doc, String comparator, boolean imagesOnly) {
return this.getWebUtilsService().getAttachmentListSortedAsJSON(doc, comparator, imagesOnly);
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public String getAttachmentListSortedAsJSON(Document doc, String comparator, boolean imagesOnly,
int start, int nb) {
return this.getWebUtilsService().getAttachmentListSortedAsJSON(doc, comparator, imagesOnly,
start, nb);
}
/**
* @deprecated since 2.17.0 instead use ImageService
*/
@Override
@Deprecated
public List<Attachment> getRandomImages(String fullName, int num, XWikiContext context) {
try {
Document imgDoc = context.getWiki().getDocument(fullName, context).newDocument(context);
List<Attachment> allImagesList = getWebUtilsService().getAttachmentListSorted(imgDoc,
"AttachmentAscendingNameComparator", true);
if (allImagesList.size() > 0) {
List<Attachment> preSetImgList = prepareMaxCoverSet(num, allImagesList);
List<Attachment> imgList = new ArrayList<>(num);
Random rand = new Random();
for (int i = 1; i <= num; i++) {
int nextimg = rand.nextInt(preSetImgList.size());
imgList.add(preSetImgList.remove(nextimg));
}
return imgList;
}
} catch (XWikiException e) {
LOGGER.error("failed", e);
}
return Collections.emptyList();
}
<T> List<T> prepareMaxCoverSet(int num, List<T> allImagesList) {
List<T> preSetImgList = new Vector<>(num);
preSetImgList.addAll(allImagesList);
for (int i = 2; i <= coveredQuotient(allImagesList.size(), num); i++) {
preSetImgList.addAll(allImagesList);
}
return preSetImgList;
}
int coveredQuotient(int divisor, int dividend) {
if (dividend >= 0) {
return (((dividend + divisor) - 1) / divisor);
} else {
return (dividend / divisor);
}
}
/**
* @deprecated since 2.11.6 instead use WebUtilsService directly
*/
@Override
@Deprecated
public boolean isAdminUser(XWikiContext context) {
return getWebUtilsService().isAdminUser();
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public String getJSONContent(XWikiDocument cdoc, XWikiContext context) {
return getWebUtilsService().getJSONContent(cdoc);
}
/**
* @deprecated since 2.14.0 instead use AttachmentURLCommand directly
*/
@Override
@Deprecated
public String getAttachmentURL(String link, XWikiContext context) {
return getAttachmentUrlCmd().getAttachmentURL(link, context);
}
/**
* @deprecated since 2.14.0 instead use AttachmentURLCommand directly
*/
@Override
@Deprecated
public String getAttachmentName(String link) {
return getAttachmentUrlCmd().getAttachmentName(link);
}
/**
* @deprecated since 2.14.0 instead use AttachmentURLCommand directly
*/
@Override
@Deprecated
public String getPageFullName(String link) {
return getAttachmentUrlCmd().getPageFullName(link);
}
/**
* @deprecated since 2.14.0 instead use AttachmentURLCommand directly
*/
@Override
@Deprecated
public boolean isAttachmentLink(String link) {
return getAttachmentUrlCmd().isAttachmentLink(link);
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public String getUserNameForDocName(String authorDocName, XWikiContext context)
throws XWikiException {
return getWebUtilsService().getUserNameForDocRef(getRef(authorDocName));
}
/**
* @deprecated since 2.17.0 instead use WebUtilsService
*/
@Override
@Deprecated
public String getMajorVersion(XWikiDocument doc) {
return getWebUtilsService().getMajorVersion(doc);
}
DocumentReference getRef(String s) {
return getWebUtilsService().resolveDocumentReference(s);
}
}
| lgpl-2.1 |
WolfLeader116/OresPlus | src/main/java/wolfleader116/oresplus/StabilizedCuriumPickaxe.java | 762 | package wolfleader116.oresplus;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class StabilizedCuriumPickaxe extends ItemPickaxe
{
private final String name = "stabilizedCuriumPickaxe";
public StabilizedCuriumPickaxe(ToolMaterial material) {
super(material);
setUnlocalizedName(name);
}
public String getName()
{
return name;
}
@Override
public boolean hasEffect(ItemStack par1ItemStack){
return true;
}
@Override
@SideOnly(Side.CLIENT)
public EnumRarity getRarity(ItemStack par1ItemStack){
return EnumRarity.EPIC;
}
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | libraries/libcss/src/main/java/org/pentaho/reporting/libraries/css/resolver/values/computed/text/TextOverflowEllipsisResolveHandler.java | 3494 | /*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2006 - 2017 Hitachi Vantara and Contributors. All rights reserved.
*/
package org.pentaho.reporting.libraries.css.resolver.values.computed.text;
import org.pentaho.reporting.libraries.css.dom.DocumentContext;
import org.pentaho.reporting.libraries.css.dom.LayoutElement;
import org.pentaho.reporting.libraries.css.dom.LayoutStyle;
import org.pentaho.reporting.libraries.css.keys.text.TextStyleKeys;
import org.pentaho.reporting.libraries.css.model.StyleKey;
import org.pentaho.reporting.libraries.css.resolver.values.ResolveHandler;
import org.pentaho.reporting.libraries.css.values.CSSStringType;
import org.pentaho.reporting.libraries.css.values.CSSStringValue;
import org.pentaho.reporting.libraries.css.values.CSSValue;
import org.pentaho.reporting.libraries.css.values.CSSValueList;
/**
* Creation-Date: 21.12.2005, 16:48:23
*
* @author Thomas Morgner
*/
public class TextOverflowEllipsisResolveHandler implements ResolveHandler {
public TextOverflowEllipsisResolveHandler() {
}
/**
* This indirectly defines the resolve order. The higher the order, the more dependent is the resolver on other
* resolvers to be complete.
*
* @return
*/
public StyleKey[] getRequiredStyles() {
return new StyleKey[ 0 ];
}
/**
* Resolves a single property.
*
* @param currentNode
* @param style
*/
public void resolve( final DocumentContext process,
final LayoutElement currentNode,
final StyleKey key ) {
final LayoutStyle layoutContext = currentNode.getLayoutStyle();
final CSSValue value = layoutContext.getValue( key );
CSSStringValue lineEllipsis = null;
CSSStringValue blockEllipsis = null;
if ( value instanceof CSSValueList ) {
final CSSValueList vlist = (CSSValueList) value;
if ( vlist.getLength() == 2 ) {
lineEllipsis = filterString( vlist.getItem( 0 ) );
blockEllipsis = filterString( vlist.getItem( 1 ) );
} else if ( vlist.getLength() == 1 ) {
lineEllipsis = filterString( vlist.getItem( 0 ) );
blockEllipsis = filterString( vlist.getItem( 0 ) );
}
}
if ( lineEllipsis == null ) {
lineEllipsis = new CSSStringValue( CSSStringType.STRING, ".." );
}
if ( blockEllipsis == null ) {
blockEllipsis = new CSSStringValue( CSSStringType.STRING, ".." );
}
layoutContext.setValue( TextStyleKeys.X_BLOCK_TEXT_OVERFLOW_ELLIPSIS, blockEllipsis );
layoutContext.setValue( TextStyleKeys.X_LINE_TEXT_OVERFLOW_ELLIPSIS, lineEllipsis );
}
private CSSStringValue filterString( final CSSValue value ) {
if ( value instanceof CSSStringValue == false ) {
return null;
}
return (CSSStringValue) value;
}
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/filter/types/VerticalLineType.java | 2389 | /*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.core.filter.types;
import org.pentaho.reporting.engine.classic.core.ReportElement;
import org.pentaho.reporting.engine.classic.core.function.ExpressionRuntime;
import org.pentaho.reporting.engine.classic.core.style.ElementStyleKeys;
import java.awt.geom.Line2D;
import java.util.Locale;
public class VerticalLineType extends AbstractElementType {
public static final VerticalLineType INSTANCE = new VerticalLineType();
public VerticalLineType() {
super( "vertical-line" );
}
/**
* Returns the current value for the data source.
*
* @param runtime
* the expression runtime that is used to evaluate formulas and expressions when computing the value of this
* filter.
* @param element
* the element for which the data is computed.
* @return the value.
*/
public Object getValue( final ExpressionRuntime runtime, final ReportElement element ) {
return new Line2D.Float( 0, 0, 0, 100 );
}
public Object getDesignValue( final ExpressionRuntime runtime, final ReportElement element ) {
return new Line2D.Float( 0, 0, 0, 100 );
}
public void configureDesignTimeDefaults( final ReportElement element, final Locale locale ) {
element.getStyle().setStyleProperty( ElementStyleKeys.SCALE, Boolean.TRUE );
element.getStyle().setStyleProperty( ElementStyleKeys.DRAW_SHAPE, Boolean.TRUE );
element.getStyle().setStyleProperty( ElementStyleKeys.MIN_WIDTH, new Float( 0f ) );
}
}
| lgpl-2.1 |
windauer/exist | exist-core/src/main/java/org/exist/xmldb/LocalCollection.java | 34931 | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2015 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.exist.xmldb;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URISyntaxException;
import java.util.*;
import javax.xml.transform.OutputKeys;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.collections.IndexInfo;
import org.exist.dom.persistent.DocumentImpl;
import org.exist.dom.persistent.LockToken;
import org.exist.dom.persistent.LockedDocument;
import org.exist.security.Account;
import org.exist.security.Permission;
import org.exist.security.Subject;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.storage.lock.Lock.LockMode;
import org.exist.storage.lock.ManagedDocumentLock;
import org.exist.storage.serializers.EXistOutputKeys;
import org.exist.storage.sync.Sync;
import org.exist.storage.txn.Txn;
import org.exist.util.HtmlToXmlParser;
import com.evolvedbinary.j8fu.Either;
import com.evolvedbinary.j8fu.function.FunctionE;
import org.exist.xmldb.function.LocalXmldbCollectionFunction;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xmldb.api.base.ErrorCodes;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.Service;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.BinaryResource;
import org.xmldb.api.modules.XMLResource;
/**
* A local implementation of the Collection interface. This
* is used when the database is running in embedded mode.
*
* Extends Observable to allow status callbacks during indexing.
* Methods storeResource notifies registered observers about the
* progress of the indexer by passing an object of type ProgressIndicator
* to the observer.
*
* @author wolf
*/
public class LocalCollection extends AbstractLocal implements EXistCollection {
private static Logger LOG = LogManager.getLogger(LocalCollection.class);
/**
* Property to be passed to {@link #setProperty(String, String)}.
* When storing documents, pass HTML files through an HTML parser
* (NekoHTML) instead of the XML parser. The HTML parser will normalize
* the HTML into well-formed XML.
*/
public final static String NORMALIZE_HTML = "normalize-html";
private final static Properties defaultProperties = new Properties();
static {
defaultProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
defaultProperties.setProperty(OutputKeys.INDENT, "yes");
defaultProperties.setProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes");
defaultProperties.setProperty(EXistOutputKeys.PROCESS_XSL_PI, "no");
defaultProperties.setProperty(NORMALIZE_HTML, "no");
}
private final XmldbURI path;
private final Random random = new Random();
private Properties properties = new Properties(defaultProperties);
private boolean needsSync = false;
/**
* Create a collection with no parent (root collection).
*
* @param user the user
* @param brokerPool the broker pool
* @param collection the collection
* @throws XMLDBException if an error occurs opening the collection
*/
public LocalCollection(final Subject user, final BrokerPool brokerPool, final XmldbURI collection) throws XMLDBException {
this(user, brokerPool, null, collection);
}
/**
* Create a collection identified by its name. Load the collection from the database.
*
* @param user the user
* @param brokerPool the broker pool
* @param parent the parent collection
* @param name the name of this collection
* @throws XMLDBException if an error occurs opening the collection
*/
public LocalCollection(final Subject user, final BrokerPool brokerPool, final LocalCollection parent, final XmldbURI name) throws XMLDBException {
super(user, brokerPool, parent);
if(name == null) {
this.path = XmldbURI.ROOT_COLLECTION_URI.toCollectionPathURI();
} else {
this.path = name.toCollectionPathURI();
}
/*
no-op, used to make sure the current user can open the collection!
will throw an XMLDBException if they cannot
we are careful to throw the exception outside of the transaction operation
so that it does not immediately close the current transaction and unwind the stack,
this is because not being able to open a collection is a valid operation e.g. xmldb:collection-available
*/
final Optional<XMLDBException> openException = withDb((broker, transaction) -> {
try {
return this.<Optional<XMLDBException>>read(broker, transaction, ErrorCodes.NO_SUCH_COLLECTION).apply((collection, broker1, transaction1) -> Optional.empty());
} catch(final XMLDBException e) {
return Optional.of(e);
}
});
if(openException.isPresent()) {
throw openException.get();
}
}
protected boolean checkOwner(final Collection collection, final Account account) throws XMLDBException {
return account.equals(collection.getPermissions().getOwner());
}
protected boolean checkPermissions(final Collection collection, final int perm) throws XMLDBException {
return collection.getPermissions().validate(user, perm);
}
/**
* Close the current collection. Calling this method will flush all
* open buffers to disk.
*/
@Override
public void close() throws XMLDBException {
if (needsSync) {
withDb((broker, transaction) -> {
broker.sync(Sync.MAJOR);
return null;
});
}
}
/**
* Creates a unique name for a database resource
* Uniqueness is only guaranteed within the eXist instance
*
* The name is based on a hex encoded string of a random integer
* and will have the format xxxxxxxx.xml where x is in the range
* 0 to 9 and a to f
*
* @return the unique resource name
*/
@Override
public String createId() throws XMLDBException {
return this.<String>read().apply((collection, broker, transaction) -> {
XmldbURI id;
boolean ok;
do {
ok = true;
id = XmldbURI.create(Integer.toHexString(random.nextInt()) + ".xml");
// check if this ID does already exist
if (collection.hasDocument(broker, id)) {
ok = false;
}
if (collection.hasChildCollection(broker, id)) {
ok = false;
}
} while (!ok);
return id.toString();
});
}
@Override
public Resource createResource(String id, final String type) throws XMLDBException {
if(id == null) {
id = createId();
}
final XmldbURI idURI;
try {
idURI = XmldbURI.xmldbUriFor(id);
} catch(final URISyntaxException e) {
throw new XMLDBException(ErrorCodes.INVALID_URI,e);
}
final Resource r;
switch(type) {
case XMLResource.RESOURCE_TYPE:
r = new LocalXMLResource(user, brokerPool, this, idURI);
break;
case BinaryResource.RESOURCE_TYPE:
r = new LocalBinaryResource(user, brokerPool, this, idURI);
break;
default:
throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, "Unknown resource type: " + type);
}
((AbstractEXistResource)r).isNewResource = true;
return r;
}
@Override
public org.xmldb.api.base.Collection getChildCollection(final String name) throws XMLDBException {
final XmldbURI childURI;
try {
childURI = XmldbURI.xmldbUriFor(name);
} catch(final URISyntaxException e) {
throw new XMLDBException(ErrorCodes.INVALID_URI,e);
}
final XmldbURI nameUri = this.<XmldbURI>read().apply((collection, broker, transaction) -> {
XmldbURI childName = null;
if (collection.hasChildCollection(broker, childURI)) {
childName = getPathURI().append(childURI);
}
return childName;
});
if(nameUri != null) {
return new LocalCollection(user, brokerPool, this, nameUri);
} else {
return null;
}
}
@Override
public int getChildCollectionCount() throws XMLDBException {
return this.<Integer>read().apply((collection, broker, transaction) -> {
if(checkPermissions(collection, Permission.READ)) {
return collection.getChildCollectionCount(broker);
} else {
return 0;
}
});
}
@Override
public String getName() throws XMLDBException {
return withDb(this::getName);
}
/**
* Similar to {@link org.exist.xmldb.LocalCollection#getName()}
* but useful for operations within the XML:DB Local API
* that are already working within a transaction
*/
String getName(final DBBroker broker, final Txn transaction) throws XMLDBException {
return this.<String>read(broker, transaction).apply((collection, broker1, transaction1) -> collection.getURI().toString());
}
@Override
public org.xmldb.api.base.Collection getParentCollection() throws XMLDBException {
return withDb((broker, transaction) -> {
if (getName(broker, transaction).equals(XmldbURI.ROOT_COLLECTION)) {
return null;
}
if (collection == null) {
final XmldbURI parentUri = this.<XmldbURI>read(broker, transaction).apply((collection, broker1, transaction1) -> collection.getParentURI());
this.collection = new LocalCollection(user, brokerPool, null, parentUri);
}
return collection;
});
}
public String getPath() throws XMLDBException {
return path.toString();
}
@Override
public XmldbURI getPathURI() {
return path;
}
@Override
public Resource getResource(final String id) throws XMLDBException {
final XmldbURI idURI;
try {
idURI = XmldbURI.xmldbUriFor(id);
} catch(final URISyntaxException e) {
throw new XMLDBException(ErrorCodes.INVALID_URI, e);
}
return withDb((broker, transaction) -> getResource(broker, transaction, idURI));
}
/**
* Similar to {@link org.exist.xmldb.LocalCollection#getResource(String)}
* but useful for operations within the XML:DB Local API
* that are already working within a transaction
*/
Resource getResource(final DBBroker broker, final Txn transaction, final String id) throws XMLDBException {
final XmldbURI idURI;
try {
idURI = XmldbURI.xmldbUriFor(id);
} catch(final URISyntaxException e) {
throw new XMLDBException(ErrorCodes.INVALID_URI, e);
}
return getResource(broker, transaction, idURI);
}
Resource getResource(final DBBroker broker, final Txn transaction, final XmldbURI idURI) throws XMLDBException {
return this.<Resource>read(broker, transaction).apply((collection, broker1, transaction1) -> {
try(final LockedDocument lockedDocument = collection.getDocumentWithLock(broker1, idURI, LockMode.READ_LOCK)) {
// NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
collection.close();
final DocumentImpl document = lockedDocument == null ? null : lockedDocument.getDocument();
if (document == null) {
LOG.warn("Resource " + idURI + " not found");
return null;
}
final Resource r;
switch (document.getResourceType()) {
case DocumentImpl.XML_FILE:
r = new LocalXMLResource(user, brokerPool, this, idURI);
break;
case DocumentImpl.BINARY_FILE:
r = new LocalBinaryResource(user, brokerPool, this, idURI);
break;
default:
throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, "Unknown resource type");
}
((AbstractEXistResource) r).setMimeType(document.getMetadata().getMimeType());
return r;
}
});
}
@Override
public int getResourceCount() throws XMLDBException {
return this.<Integer>read().apply((collection, broker, transaction) -> {
if(checkPermissions(collection, Permission.READ)) {
return collection.getDocumentCount(broker);
} else {
return 0;
}
});
}
@Override
public Service getService(final String name, final String version) throws XMLDBException {
final Service service;
switch(name) {
case "XPathQueryService":
case "XQueryService":
service = new LocalXPathQueryService(user, brokerPool, this);
break;
case "CollectionManagementService":
case "CollectionManager":
service = new LocalCollectionManagementService(user, brokerPool, this);
break;
case "UserManagementService":
service = new LocalUserManagementService(user, brokerPool, this);
break;
case "DatabaseInstanceManager":
service = new LocalDatabaseInstanceManager(user, brokerPool);
break;
case "XUpdateQueryService":
service = new LocalXUpdateQueryService(user, brokerPool, this);
break;
case "IndexQueryService":
service = new LocalIndexQueryService(user, brokerPool, this);
break;
case "RestoreService":
service = new LocalRestoreService(user, brokerPool, this);
break;
default:
throw new XMLDBException(ErrorCodes.NO_SUCH_SERVICE);
}
return service;
}
@Override
public Service[] getServices() throws XMLDBException {
final Service[] services = {
new LocalXPathQueryService(user, brokerPool, this),
new LocalCollectionManagementService(user, brokerPool, this),
new LocalUserManagementService(user, brokerPool, this),
new LocalDatabaseInstanceManager(user, brokerPool),
new LocalXUpdateQueryService(user, brokerPool, this),
new LocalIndexQueryService(user, brokerPool, this)
};
return services;
}
@Override
public boolean isOpen() throws XMLDBException {
return true;
}
@Override
public String[] listChildCollections() throws XMLDBException {
return this.<String[]>read().apply((collection, broker, transaction) -> {
final String[] collections = new String[collection.getChildCollectionCount(broker)];
int j = 0;
for(final Iterator<XmldbURI> i = collection.collectionIterator(broker); i.hasNext(); j++) {
collections[j] = i.next().toString();
}
return collections;
});
}
@Override
public String[] getChildCollections() throws XMLDBException {
return listChildCollections();
}
/**
* Retrieve the list of resources in the collection.
*
* @return the list of resources.
*
* @throws XMLDBException if and invalid collection was specified, or if permission is denied
*/
@Override
public String[] listResources() throws XMLDBException {
final List<String> resources = this.<List<String>>read().apply((collection, broker, transaction) -> {
final List<String> allresources = new ArrayList<>();
for(final Iterator<DocumentImpl> i = collection.iterator(broker); i.hasNext(); ) {
final DocumentImpl doc = i.next();
try(final ManagedDocumentLock documentLock = broker.getBrokerPool().getLockManager().acquireDocumentReadLock(doc.getURI())) {
// Include only when (1) lockToken is present or (2)
// lockToken indicates that it is not a null resource
final LockToken lock = doc.getMetadata().getLockToken();
if (lock == null || (!lock.isNullResource())) {
allresources.add(doc.getFileURI().toString());
}
}
}
return allresources;
});
// Copy content of list into String array.
return resources.toArray(new String[resources.size()]);
}
@Override
public String[] getResources() throws XMLDBException {
return listResources();
}
public void registerService(final Service serv) throws XMLDBException {
throw new XMLDBException(ErrorCodes.NOT_IMPLEMENTED);
}
@Override
public void removeResource(final Resource res) throws XMLDBException {
if(res == null) {
return;
}
final XmldbURI resURI;
try {
resURI = XmldbURI.xmldbUriFor(res.getId());
} catch(final URISyntaxException e) {
throw new XMLDBException(ErrorCodes.INVALID_URI,e);
}
modify().apply((collection, broker, transaction) -> {
//Check that the document exists
try(final LockedDocument lockedDocument = collection.getDocumentWithLock(broker, resURI, LockMode.WRITE_LOCK)) {
if (lockedDocument == null) {
// NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
collection.close();
throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, "Resource " + resURI + " not found");
}
if (XMLResource.RESOURCE_TYPE.equals(res.getResourceType())) {
collection.removeXMLResource(transaction, broker, resURI);
} else {
collection.removeBinaryResource(transaction, broker, resURI);
}
// NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
collection.close();
}
return null;
});
this.needsSync = true;
}
public Properties getProperties() {
return properties;
}
@Override
public String getProperty(final String property) throws XMLDBException {
return properties.getProperty(property);
}
public String getProperty(final String property, final String defaultValue) throws XMLDBException {
return properties.getProperty(property, defaultValue);
}
public void setProperties(final Properties properties) {
if (properties == null) {
return;
}
this.properties = properties;
}
@Override
public void setProperty(final String property, final String value) throws XMLDBException {
properties.setProperty(property, value);
}
@Override
public void storeResource(final Resource resource) throws XMLDBException {
storeResource(resource, null, null);
}
@Override
public void storeResource(final Resource resource, final Date a, final Date b) throws XMLDBException {
if(resource.getResourceType().equals(XMLResource.RESOURCE_TYPE)) {
if (LOG.isDebugEnabled()) {
LOG.debug("storing document " + resource.getId());
}
((LocalXMLResource)resource).datecreated = a;
((LocalXMLResource)resource).datemodified = b;
storeXMLResource((LocalXMLResource) resource);
} else if(resource.getResourceType().equals(BinaryResource.RESOURCE_TYPE)) {
if(LOG.isDebugEnabled()) {
LOG.debug("storing binary resource " + resource.getId());
}
((LocalBinaryResource)resource).datecreated = a;
((LocalBinaryResource)resource).datemodified = b;
storeBinaryResource((LocalBinaryResource) resource);
} else {
throw new XMLDBException(ErrorCodes.UNKNOWN_RESOURCE_TYPE, "unknown resource type: " + resource.getResourceType());
}
((AbstractEXistResource)resource).isNewResource = false;
this.needsSync = true;
}
private void storeBinaryResource(final LocalBinaryResource res) throws XMLDBException {
final XmldbURI resURI;
try {
resURI = XmldbURI.xmldbUriFor(res.getId());
} catch(final URISyntaxException e) {
throw new XMLDBException(ErrorCodes.INVALID_URI,e);
}
modify().apply((collection, broker, transaction) -> {
try {
final long conLength = res.getStreamLength();
if (conLength != -1) {
try (InputStream is = res.getStreamContent(broker, transaction)) {
collection.addBinaryResource(transaction, broker, resURI, is, res.getMimeType(broker, transaction), conLength, res.datecreated, res.datemodified);
}
} else {
collection.addBinaryResource(transaction, broker, resURI, (byte[]) res.getContent(broker, transaction), res.getMimeType(broker, transaction), res.datecreated, res.datemodified);
}
} catch(final EXistException e) {
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e.getMessage(), e);
}
return null;
});
}
private void storeXMLResource(final LocalXMLResource res) throws XMLDBException {
final XmldbURI resURI;
try {
resURI = XmldbURI.xmldbUriFor(res.getId());
} catch(final URISyntaxException e) {
throw new XMLDBException(ErrorCodes.INVALID_URI,e);
}
modify().apply((collection, broker, transaction) -> {
String uri = null;
if(res.file != null) {
uri = res.file.toUri().toASCIIString();
}
// for(final Observer observer : observers) {
// collection.addObserver(observer);
// }
try(final ManagedDocumentLock documentLock = broker.getBrokerPool().getLockManager().acquireDocumentWriteLock(collection.getURI().append(resURI))) {
XMLReader reader = null;
/* validate */
final IndexInfo info;
if (res.root != null) {
info = collection.validateXMLResource(transaction, broker, resURI, res.root);
} else {
final InputSource source;
if (uri != null) {
source = new InputSource(uri);
} else if (res.inputSource != null) {
source = res.inputSource;
} else {
source = new InputSource(new StringReader(res.content));
}
if (useHtmlReader(broker, transaction, res)) {
reader = getHtmlReader();
info = collection.validateXMLResource(transaction, broker, resURI, source, reader);
} else {
info = collection.validateXMLResource(transaction, broker, resURI, source);
}
}
//Notice : the document should now have a LockMode.WRITE_LOCK update lock
//TODO : check that no exception occurs in order to allow it to be released
info.getDocument().getMetadata().setMimeType(res.getMimeType(broker, transaction));
if (res.datecreated != null) {
info.getDocument().getMetadata().setCreated(res.datecreated.getTime());
}
if (res.datemodified != null) {
info.getDocument().getMetadata().setLastModified(res.datemodified.getTime());
}
/* store */
if (res.root != null) {
collection.store(transaction, broker, info, res.root);
} else {
final InputSource source;
if (uri != null) {
source = new InputSource(uri);
} else if (res.inputSource != null) {
source = res.inputSource;
} else {
source = new InputSource(new StringReader(res.content));
}
if (reader != null) {
collection.store(transaction, broker, info, source, reader);
} else {
collection.store(transaction, broker, info, source);
}
}
// NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
collection.close();
return null;
// collection.deleteObservers();
} catch(final EXistException | SAXException e) {
// NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
collection.close();
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e.getMessage(), e);
}
});
}
/**
* Determines if a HTML reader should be used for the resource.
*
* @param broker the database broker
* @param transaction the current transaction
* @param res the html resource
*
* @return true if a HTML reader should be used.
*
* @throws XMLDBException if the HTML Reader cannot be configured.
*/
private boolean useHtmlReader(final DBBroker broker, final Txn transaction, final LocalXMLResource res) throws XMLDBException {
final String normalize = properties.getProperty(NORMALIZE_HTML, "no");
return ((normalize.equalsIgnoreCase("yes") || normalize.equalsIgnoreCase("true")) &&
("text/html".equals(res.getMimeType(broker, transaction)) || res.getId().endsWith(".htm") ||
res.getId().endsWith(".html")));
}
/**
* Get's the HTML Reader
*
* @return the HTML reader configured in conf.xml
*
* @throws XMLDBException if the HTML reader cannot be retrieved.
*/
private XMLReader getHtmlReader() throws XMLDBException {
final Optional<Either<Throwable, XMLReader>> maybeReaderInst = HtmlToXmlParser.getHtmlToXmlParser(brokerPool.getConfiguration());
if (maybeReaderInst.isPresent()) {
final Either<Throwable, XMLReader> readerInst = maybeReaderInst.get();
if (readerInst.isLeft()) {
final String msg = "Unable to parse HTML to XML please ensure the parser is configured in conf.xml and is present on the classpath";
final Throwable t = readerInst.left().get();
LOG.error(msg, t);
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, msg, t);
} else {
final XMLReader htmlReader = readerInst.right().get();
if(LOG.isDebugEnabled()) {
LOG.debug("Converting HTML to XML using: " + htmlReader.getClass().getName());
}
return htmlReader;
}
} else {
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "There is no HTML to XML parser configured in conf.xml");
}
}
@Override
public Date getCreationTime() throws XMLDBException {
return this.<Date>read().apply((collection, broker, transaction) -> new Date(collection.getCreationTime()));
}
@Override
public boolean isRemoteCollection() throws XMLDBException {
return false;
}
public XmldbURI getURI() {
final StringBuilder accessor = new StringBuilder(XmldbURI.XMLDB_URI_PREFIX);
//TODO : get the name from client
accessor.append("exist");
accessor.append("://");
//No host ;-)
accessor.append("");
//No port ;-)
//No context ;-)
//accessor.append(getContext());
try {
//TODO : cache it when constructed
return XmldbURI.create(accessor.toString(), getPath());
} catch(final XMLDBException e) {
//TODO : should never happen
return null;
}
}
/**
* Higher-order-function for performing read-only operations against this collection
*
* NOTE this read will occur using the database user set on the collection
*
* @param <R> the return type.
*
* @return A function to receive a read-only operation to perform against the collection
*
* @throws XMLDBException if the collection could not be read
*/
protected <R> FunctionE<LocalXmldbCollectionFunction<R>, R, XMLDBException> read() throws XMLDBException {
return readOp -> this.<R>read(path).apply(readOp::apply);
}
/**
* Higher-order-function for performing read-only operations against this collection
*
* NOTE this read will occur using the database user set on the collection
*
* @param <R> the return type.
* @param errorCode The error code to use in the XMLDBException if the collection does not exist, see {@link ErrorCodes}
* @return A function to receive a read-only operation to perform against the collection
*
* @throws XMLDBException if the collection could not be read
*/
private <R> FunctionE<LocalXmldbCollectionFunction<R>, R, XMLDBException> read(final int errorCode) throws XMLDBException {
return readOp -> this.<R>read(path, errorCode).apply(readOp::apply);
}
/**
* Higher-order-function for performing read-only operations against this collection
*
* NOTE this read will occur using the database user set on the collection
*
* @param <R> the return type.
* @param broker The broker to use for the operation
* @param transaction The transaction to use for the operation
* @return A function to receive a read-only operation to perform against the collection
*/
private <R> FunctionE<LocalXmldbCollectionFunction<R>, R, XMLDBException> read(final DBBroker broker, final Txn transaction) throws XMLDBException {
return readOp -> this.<R>read(broker, transaction, path).apply(readOp::apply);
}
/**
* Higher-order-function for performing read-only operations against this collection
*
* NOTE this read will occur using the database user set on the collection
*
* @param <R> the return type.
* @param broker The broker to use for the operation
* @param transaction The transaction to use for the operation
* @param errorCode The error code to use in the XMLDBException if the collection does not exist, see {@link ErrorCodes}
* @return A function to receive a read-only operation to perform against the collection
*
* @throws XMLDBException if the collection could not be read
*/
private <R> FunctionE<LocalXmldbCollectionFunction<R>, R, XMLDBException> read(final DBBroker broker, final Txn transaction, final int errorCode) throws XMLDBException {
return readOp -> this.<R>read(broker, transaction, path, errorCode).apply(readOp::apply);
}
/**
* Higher-order-function for performing read/write operations against this collection
*
* NOTE this read/write will occur using the database user set on the collection
*
* @param <R> the return type.
*
* @return A function to receive a read/write operation to perform against the collection
*
* @throws XMLDBException if the collection could not be modified
*/
private <R> FunctionE<LocalXmldbCollectionFunction<R>, R, XMLDBException> modify() throws XMLDBException {
return modifyOp -> this.<R>modify(path).apply(modifyOp::apply);
}
/**
* Higher-order-function for performing read/write operations against this collection
*
* NOTE this read/write will occur using the database user set on the collection
*
* @param <R> the return type.
* @param broker The database broker to use when accessing the collection
* @param transaction The transaction to use when accessing the collection
*
* @return A function to receive a read/write operation to perform against the collection
*
* @throws XMLDBException if the collection could not be modified
*/
private <R> FunctionE<LocalXmldbCollectionFunction<R>, R, XMLDBException> modify(final DBBroker broker, final Txn transaction) throws XMLDBException {
return modifyOp -> this.<R>modify(broker, transaction, path).apply(modifyOp::apply);
}
/**
* Higher-order function for performing lockable operations on this collection
*
* @param <R> the return type.
* @param lockMode the lock mode
* @param broker The broker to use for the operation
* @param transaction The transaction to use for the operation
*
* @return A function to receive an operation to perform on the locked database collection
*
* @throws XMLDBException if the the operation raises an error
*/
protected <R> FunctionE<LocalXmldbCollectionFunction<R>, R, XMLDBException> with(final LockMode lockMode, final DBBroker broker, final Txn transaction) throws XMLDBException {
return op -> this.<R>with(lockMode, broker, transaction, path).apply(op::apply);
}
}
| lgpl-2.1 |
joansmith/orbeon-forms | src/main/java/org/orbeon/oxf/xforms/control/controls/XFormsRangeControl.java | 3351 | /**
* Copyright (C) 2010 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.xforms.control.controls;
import org.dom4j.Element;
import org.orbeon.oxf.xforms.XFormsConstants;
import org.orbeon.oxf.xforms.control.XFormsControl;
import org.orbeon.oxf.xforms.control.XFormsValueControlBase;
import org.orbeon.oxf.xforms.xbl.XBLContainer;
import org.orbeon.oxf.xml.XMLConstants;
import scala.Tuple3;
/**
* Represents an xf:range control.
*/
public class XFormsRangeControl extends XFormsValueControlBase {
private String start;
private String end;
private String step;
public XFormsRangeControl(XBLContainer container, XFormsControl parent, Element element, String id) {
super(container, parent, element, id);
this.start = element.attributeValue("start");
this.end = element.attributeValue("end");
this.step = element.attributeValue("step");
}
@Override
public Tuple3<String, String, String> getJavaScriptInitialization() {
return getCommonJavaScriptInitialization();
}
public String getStart() {
return start;
}
public String getEnd() {
return end;
}
public String getStep() {
return step;
}
@Override
public scala.Option<String> translateExternalValue(String externalValue) {
return scala.Option.apply(convertFromExternalValue(externalValue));
}
private String convertFromExternalValue(String externalValue) {
final String typeName = getBuiltinTypeName();
if (getStart() != null && getEnd() != null && "integer".equals(typeName)) {
final int start = Integer.parseInt(getStart());
final int end = Integer.parseInt(getEnd());
final int value = start + ((int) (Double.parseDouble(externalValue) * (double) (end - start)));
return Integer.toString(value);
} else {
return externalValue;
}
}
@Override
public void evaluateExternalValue() {
final String internalValue = getValue();
final String updatedValue;
if (internalValue == null) {// can it be really?
updatedValue = null;
} else if (getStart() != null && getEnd() != null
&& (XMLConstants.XS_INTEGER_QNAME.equals(valueType()) || XFormsConstants.XFORMS_INTEGER_QNAME.equals(valueType()))) {
final int start = Integer.parseInt(getStart());
final int end = Integer.parseInt(getEnd());
final double value = ((double) (Integer.parseInt(internalValue) - start)) / ((double) end - start);
updatedValue = Double.toString(value);
} else {
updatedValue = internalValue;
}
setExternalValue(updatedValue);
}
}
| lgpl-2.1 |
karlmutch/WebAlgo-Java-Class | apFloat/source/org/apfloat/calc/ParseException.java | 6174 | /* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */
/* JavaCCOptions:KEEP_LINE_COL=null */
package org.apfloat.calc;
/**
* This exception is thrown when parse errors are encountered.
* You can explicitly create objects of this exception type by
* calling the method generateParseException in the generated
* parser.
*
* You can modify this class to customize your error reporting
* mechanisms so long as you retain the public fields.
*/
public class ParseException extends Exception {
/**
* The version identifier for this Serializable class.
* Increment only if the <i>serialized</i> form of the
* class changes.
*/
private static final long serialVersionUID = 1L;
/**
* This constructor is used by the method "generateParseException"
* in the generated parser. Calling this constructor generates
* a new object of this type with the fields "currentToken",
* "expectedTokenSequences", and "tokenImage" set.
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
)
{
super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever
* purpose you can think of. Constructing the exception in this
* manner makes the exception behave in the normal way - i.e., as
* documented in the class "Throwable". The fields "errorToken",
* "expectedTokenSequences", and "tokenImage" do not contain
* relevant information. The JavaCC generated code does not use
* these constructors.
*/
public ParseException() {
super();
}
/** Constructor with message. */
public ParseException(String message) {
super(message);
}
/**
* This is the last token that has been consumed successfully. If
* this object has been created due to a parse error, the token
* followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array
* of integers represents a sequence of tokens (by their ordinal
* values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated
* parser within which the parse error occurred. This array is
* defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* It uses "currentToken" and "expectedTokenSequences" to generate a parse
* error message and returns it. If this object has been created
* due to a parse error, and you do not catch it (it gets thrown
* from the parser) the correct error message
* gets displayed.
*/
private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
}
/**
* The end of line string for this machine.
*/
protected String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version
* when these raw version cannot be used as part of an ASCII
* string literal.
*/
static String add_escapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
}
/* JavaCC - OriginalChecksum=e4a6dd4ecae948eb058051851c36d831 (do not edit this line) */
| lgpl-2.1 |
concord-consortium/datagraph | src/main/java/org/concord/datagraph/ui/DataGraphTable.java | 12450 | /*
* Copyright (C) 2004 The Concord Consortium, Inc.,
* 10 Concord Crossing, Concord, MA 01742
*
* Web Site: http://www.concord.org
* Email: info@concord.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* END LICENSE */
/* Author: Edward Burke
* Based on work by Eric Brown-Munoz
$Revision: 1.3 $
*/
package org.concord.datagraph.ui;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import org.concord.datagraph.engine.DataGraphable;
import org.concord.graph.engine.*;
import org.concord.graph.event.*;
public class DataGraphTable extends JTable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private SelectableList graphablesList = null;
private TableModel extraModel;
ListSelectionListener listSelectionListener = new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
//System.out.println(" @@ ListSelection.valueChanged event " + e.getValueIsAdjusting());
if (e.getValueIsAdjusting()) return;
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
if ( graphablesList != null) {
int index;
int fIndex;
if (getSelectionModel().getSelectionMode()==ListSelectionModel.SINGLE_SELECTION){
index = lsm.getMinSelectionIndex();
fIndex = graphablesList.getFirstSelectedIndex();
if (index >= 0 && fIndex!=index) {
//The table has something selected but it is different from the selection on the list
graphablesList.select(index);
}
else if (fIndex!=index && fIndex >= 0){
//The table doesn't have anything selected and
//it is different from the selection on the list
// setSelectionIndexInternal(lsm, fIndex);
}
}
else{
index = lsm.getLeadSelectionIndex();
if (index >= 0) {
//The table has something selected
graphablesList.select(index);
}
}
}
setupColWidth();
}
};
public DataGraphTable()
{
super();
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setSelectionBackground(Color.white);
setPreferredSize(new Dimension(200, 200));
}
private void setupColWidth()
{
TableColumn column = getColumnModel().getColumn(0);
column.setPreferredWidth(80);
column = getColumnModel().getColumn(1);
column.setPreferredWidth(200);
}
public void setExtraModel(TableModel model)
{
extraModel = model;
}
public void setSelectableList( SelectableList list )
{
if (graphablesList!=null){
graphablesList.removeGraphableListListener(graphableListListener);
}
this.graphablesList = list;
Renderer cellRenderer = new Renderer();
cellRenderer.setSelectableList(graphablesList);
setDefaultRenderer(String.class, cellRenderer);
Model tableModel = new Model(graphablesList);
setTableModel(tableModel);
setupColWidth();
if (graphablesList!=null){
ListSelectionModel lsm = getSelectionModel();
int newIndex = graphablesList.getFirstSelectedIndex();
int index = lsm.getMinSelectionIndex();
if (newIndex >= 0 && newIndex!=index) {
addSelectionIndexInternal(lsm, newIndex);
}
graphablesList.addGraphableListListener(graphableListListener);
}
}
GraphableListListener graphableListListener = new GraphableListAdapter()
{
public void listGraphableSelected(EventObject e)
{
//System.out.println(" T Table receives selected event");
int newIndex = graphablesList.indexOf((Graphable)e.getSource());
if (newIndex!=-1){
ListSelectionModel lsm = getSelectionModel();
//int index = lsm.getMinSelectionIndex();
//if (index!=newIndex){
addSelectionIndexInternal(lsm, newIndex);
//}
}
}
public void listGraphableDeselected(EventObject e)
{
//System.out.println(" T Table receives deselected event");
int newIndex = graphablesList.indexOf((Graphable)e.getSource());
if (newIndex!=-1){
ListSelectionModel lsm = getSelectionModel();
//int index = lsm.getMinSelectionIndex();
//if (index!=newIndex){
removeSelectionIndexInternal(lsm, newIndex);
//}
}
}
};
private void addSelectionIndexInternal(ListSelectionModel lsm, int newIndex)
{
lsm.removeListSelectionListener(listSelectionListener);
//lsm.setLeadSelectionIndex(newIndex);
lsm.addSelectionInterval(newIndex,newIndex);
lsm.addListSelectionListener(listSelectionListener);
}
private void removeSelectionIndexInternal(ListSelectionModel lsm, int newIndex)
{
lsm.removeListSelectionListener(listSelectionListener);
lsm.removeSelectionInterval(newIndex,newIndex);
lsm.addListSelectionListener(listSelectionListener);
}
public void setTableModel(TableModel model)
{
setModel(model);
getSelectionModel().addListSelectionListener(listSelectionListener);
}
public TableModel getTableModel()
{
return getModel();
}
public class Renderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
SelectableList graphableList;
public void setSelectableList( SelectableList list )
{
graphableList = list;
}
/**
*
* Returns the default table cell renderer.
*
* This method is overriden to use the specific colors for each row
* @see javax.swing.table.DefaultTableCellRenderer
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Color rowColor=null;
Color foreColor=null;
Color backColor=null;
// TODO: figure out how to get this color
if (graphableList != null && row < graphableList.size()){
Graphable g = (Graphable) graphableList.elementAt(row);
if (g instanceof DataGraphable)
rowColor = ((DataGraphable) g).getColor();
}
if (isSelected) {
foreColor = rowColor;
if(foreColor == null){
foreColor = (table.getSelectionForeground() != null) ? table.getSelectionForeground() : table.getForeground();
}
if (backColor == null){
backColor = (table.getSelectionBackground() != null) ? table.getSelectionBackground() : table.getBackground();
}
super.setBackground(backColor);
super.setForeground(foreColor);
setFont(table.getFont().deriveFont(Font.BOLD));
super.setBorder(BorderFactory.createLineBorder(rowColor));
}
else {
foreColor = rowColor;
if(foreColor == null){
foreColor = table.getForeground();
}
if(backColor == null){
backColor = table.getBackground();
}
super.setForeground(foreColor);
super.setBackground(backColor);
setFont(table.getFont());
super.setBorder(noFocusBorder);
}
if (hasFocus) {
}
setValue(value);
// ---- begin optimization to avoid painting background ----
Color back = getBackground();
boolean colorMatch = (back != null) && ( back.equals(table.getBackground()) ) && table.isOpaque();
setOpaque(!colorMatch);
// ---- end optimization to aviod painting background ----
return this;
}
}
public class Model extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
SelectableList graphables;
TableCellRenderer cellRenderer;
private String colNames[] = {"Visible","Function"};
public Model()
{
}
public Model(SelectableList list )
{
setSelectableList(list);
}
public void setSelectableList( SelectableList list )
{
graphables = list;
if (list==null) return;
list.addGraphableListListener(new GraphableListAdapter()
{
int index;
public void listGraphableAdded(EventObject e)
{
index = graphables.indexOf((Graphable)e.getSource());
fireTableRowsInserted(index,index);
}
public void listGraphableRemoved(EventObject e)
{
//The following two lines cause the columns to change size,
//so I took them out
//index = graphables.indexOf((Graphable)e.getSource());
//fireTableRowsDeleted(index,index);
fireTableDataChanged();
}
public void listGraphableChanged(EventObject e)
{
//This is necessary to update the table with the info of the graphable
//But if also fires a valueChanged(ListSelectionEvent) event on the table
//even if the selection is the same.
//The handler of this event is in GraphableTable, and it doesn't
//do anything if the selected index is the same
index = graphables.indexOf((Graphable)e.getSource());
fireTableRowsUpdated(index,index);
}
public void listGraphableSelected(EventObject e)
{
//This is not necessary because the Table is listening to selections
//fireTableDataChanged();
}
public void listGraphableDeselected(EventObject e)
{
//This is not necessary because the Table is listening to selections
//fireTableDataChanged();
}
});
}
public int getColumnCount()
{
int count = colNames.length;
if (extraModel != null)
count += extraModel.getColumnCount();
return count;
}
public int getRowCount()
{
return graphables.size();
}
public String getColumnName(int column)
{
if (column >= colNames.length && extraModel != null)
return extraModel.getColumnName(column - colNames.length);
return colNames[column];
}
public void setColumnName(int column, String name)
{
if (column < colNames.length)
{
colNames[column] = name;
fireTableStructureChanged();
}
}
public Object getValueAt(int rowIndex, int columnIndex)
{
Object retval = null;
DefaultGraphable graphable = (DefaultGraphable)graphables.elementAt(rowIndex);
if (graphable==null) return null;
switch (columnIndex) {
case 0:
retval = new Boolean(graphable.isVisible());
break;
case 1:
retval = " " + graphable.getLabel();
break;
default:
if (extraModel != null)
{
retval = extraModel.getValueAt(rowIndex, columnIndex - colNames.length);
}
}
return retval;
}
public Class getColumnClass( int columnIndex)
{
Class retval = String.class;
if (columnIndex == 0 ) {
retval = Boolean.class;
}
if (columnIndex > colNames.length && extraModel != null)
{
retval = extraModel.getColumnClass(columnIndex - colNames.length);
}
return retval;
}
public boolean isCellEditable(int rowIndex, int columnIndex)
{
boolean retval = false;
if (columnIndex == 0) retval = true;
if (columnIndex > colNames.length && extraModel != null)
{
retval = extraModel.isCellEditable(rowIndex, columnIndex - colNames.length);
}
return retval;
}
public void setValueAt( Object aValue, int rowIndex, int columnIndex)
{
if (columnIndex == 0)
{
Graphable theOne = (Graphable)graphables.elementAt(rowIndex);
theOne.setVisible(((Boolean)aValue).booleanValue());
}
else if (extraModel != null)
{
extraModel.setValueAt(aValue, rowIndex, columnIndex - colNames.length);
}
}
}
}
| lgpl-2.1 |
Fosstrak/fosstrak-capturingapp | src/main/java/org/fosstrak/capturingapp/util/SimpleEPCISDocument.java | 5195 | /*
* Copyright (C) 2007 ETH Zurich
*
* This file is part of Fosstrak (www.fosstrak.org).
*
* Fosstrak is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* Fosstrak is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Fosstrak; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.fosstrak.capturingapp.util;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.fosstrak.ale.xsd.epcglobal.EPC;
import org.fosstrak.epcis.model.ActionType;
import org.fosstrak.epcis.model.BusinessLocationType;
import org.fosstrak.epcis.model.EPCISBodyType;
import org.fosstrak.epcis.model.EPCISDocumentType;
import org.fosstrak.epcis.model.EPCListType;
import org.fosstrak.epcis.model.EventListType;
import org.fosstrak.epcis.model.ObjectEventType;
import org.fosstrak.epcis.model.ReadPointType;
/**
* Helper class to assemble an EPCIS document. you can add object events and
* when you have all the events together, you can compile the final
* EPCIS document for further processing.
* @author sawielan
*
*/
public class SimpleEPCISDocument {
/** a list of all the object events in the EPCIS document. */
protected LinkedList<ObjectEventType> objectEvents =
new LinkedList<ObjectEventType> ();
/**
* add a new object event to the EPCIS document.
* @param epcs a list of EPCs to put into the report.
* @param action the kind of action triggered by this object even.
* @param bizSteps the <code>bizsteps</code> to set in the event.
* @param disposition the disposition.
* @param readPointId the id of the read point.
* @param bizLocationId the id of the location.
*/
public void addObjectEvent(List<Object> epcs,
ActionType action, String bizSteps, String disposition,
String readPointId, String bizLocationId) {
EPCListType epcList = new EPCListType();
// add the epcs
for (Object o : epcs) {
if (o instanceof EPC) {
EPC epc = (EPC) o;
org.fosstrak.epcis.model.EPC nepc =
new org.fosstrak.epcis.model.EPC();
nepc.setValue(epc.getValue());
epcList.getEpc().add(nepc);
}
}
ObjectEventType objEvent = new ObjectEventType();
objEvent.setEpcList(epcList);
objEvent.setEventTime(getNow());
objEvent.setEventTimeZoneOffset(getTimeOffset(objEvent.getEventTime()));
// set action
objEvent.setAction(action);
// set bizStep
objEvent.setBizStep(bizSteps);
// set disposition
objEvent.setDisposition(disposition);
// set readPoint
ReadPointType readPoint = new ReadPointType();
readPoint.setId(readPointId);
objEvent.setReadPoint(readPoint);
// set bizLocation
BusinessLocationType bizLocation = new BusinessLocationType();
bizLocation.setId(bizLocationId);
objEvent.setBizLocation(bizLocation);
objectEvents.add(objEvent);
}
/**
* returns a string that describes the time offset.
* @param eventTime a gregorian calendar holding a time.
* @return a time offset string.
*/
protected String getTimeOffset(XMLGregorianCalendar eventTime) {
String offset = "";
// get the current time zone and set the eventTimeZoneOffset
if (null != eventTime) {
int timezone = eventTime.getTimezone();
int h = Math.abs(timezone / 60);
int m = Math.abs(timezone % 60);
DecimalFormat format = new DecimalFormat("00");
String sign = (timezone < 0) ? "-" : "+";
offset = sign + format.format(h) + ":" + format.format(m);
}
return offset;
}
/**
* @return a gregorian calendar describing the current time.
*/
protected XMLGregorianCalendar getNow() {
// get the current time and set the eventTime
XMLGregorianCalendar now = null;
try {
DatatypeFactory dataFactory = DatatypeFactory.newInstance();
now = dataFactory.newXMLGregorianCalendar(new GregorianCalendar());
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
return now;
}
/**
* @return the assembled EPCIS document.
*/
public EPCISDocumentType getDocument() {
// create the EPCISDocument
EPCISDocumentType epcisDoc = new EPCISDocumentType();
EPCISBodyType epcisBody = new EPCISBodyType();
EventListType eventList = new EventListType();
for (ObjectEventType objEvent : objectEvents) {
eventList.getObjectEventOrAggregationEventOrQuantityEvent().
add(objEvent);
}
epcisBody.setEventList(eventList);
epcisDoc.setEPCISBody(epcisBody);
epcisDoc.setSchemaVersion(new BigDecimal("1.0"));
epcisDoc.setCreationDate(getNow());
return epcisDoc;
}
}
| lgpl-2.1 |
esig/dss | dss-xades/src/main/java/eu/europa/esig/dss/xades/validation/scope/XPointerSignatureScope.java | 2486 | /**
* DSS - Digital Signature Services
* Copyright (C) 2015 European Commission, provided under the CEF programme
*
* This file is part of the "DSS - Digital Signature Services" project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package eu.europa.esig.dss.xades.validation.scope;
import eu.europa.esig.dss.DomUtils;
import eu.europa.esig.dss.enumerations.SignatureScopeType;
import eu.europa.esig.dss.model.Digest;
import eu.europa.esig.dss.validation.scope.SignatureScopeWithTransformations;
import java.util.List;
/**
* XPointer signature scope
*/
public class XPointerSignatureScope extends SignatureScopeWithTransformations {
private static final long serialVersionUID = 203530674533107438L;
/**
* XPointer query
*/
private final String uri;
/**
* Default constructor
*
* @param uri {@link String}
* @param transformations a list of {@link String} transform descriptions
* @param digest {@link Digest}
*/
protected XPointerSignatureScope(final String uri, final List<String> transformations, final Digest digest) {
super(getDocumentNameFromXPointer(uri), digest, transformations);
this.uri = uri;
}
private static String getDocumentNameFromXPointer(String uri) {
return DomUtils.isRootXPointer(uri) ? "Full XML file" : DomUtils.getXPointerId(uri);
}
@Override
public String getDescription() {
StringBuilder sb = new StringBuilder("XPointer query to ");
if (DomUtils.isRootXPointer(uri)) {
sb.append("root XML element");
} else {
sb.append("element with Id '");
sb.append(getName());
sb.append("'");
}
return addTransformationIfNeeded(sb.toString());
}
@Override
public SignatureScopeType getType() {
return DomUtils.isRootXPointer(uri) ? SignatureScopeType.FULL : SignatureScopeType.PARTIAL;
}
}
| lgpl-2.1 |
attatrol/checkstyle | src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/TypeParameterNameTest.java | 6924 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.naming;
import static com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck.MSG_INVALID_PATTERN;
import static org.junit.Assert.assertArrayEquals;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
public class TypeParameterNameTest
extends BaseCheckTestSupport {
@Override
protected String getPath(String filename) throws IOException {
return super.getPath("checks" + File.separator
+ "naming" + File.separator + filename);
}
@Test
public void testGetInterfaceRequiredTokens() {
final InterfaceTypeParameterNameCheck checkObj =
new InterfaceTypeParameterNameCheck();
final int[] expected = {TokenTypes.TYPE_PARAMETER};
assertArrayEquals(expected, checkObj.getRequiredTokens());
}
@Test
public void testGetMethodRequiredTokens() {
final MethodTypeParameterNameCheck checkObj =
new MethodTypeParameterNameCheck();
final int[] expected = {TokenTypes.TYPE_PARAMETER};
assertArrayEquals(expected, checkObj.getRequiredTokens());
}
@Test
public void testGetClassRequiredTokens() {
final ClassTypeParameterNameCheck checkObj =
new ClassTypeParameterNameCheck();
final int[] expected = {TokenTypes.TYPE_PARAMETER};
assertArrayEquals(expected, checkObj.getRequiredTokens());
}
@Test
public void testClassDefault()
throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(ClassTypeParameterNameCheck.class);
final String pattern = "^[A-Z]$";
final String[] expected = {
"5:38: " + getCheckMessage(MSG_INVALID_PATTERN, "t", pattern),
"13:14: " + getCheckMessage(MSG_INVALID_PATTERN, "foo", pattern),
"27:24: " + getCheckMessage(MSG_INVALID_PATTERN, "foo", pattern),
};
verify(checkConfig, getPath("InputTypeParameterName.java"), expected);
}
@Test
public void testMethodDefault()
throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(MethodTypeParameterNameCheck.class);
final String pattern = "^[A-Z]$";
final String[] expected = {
"7:13: " + getCheckMessage(MSG_INVALID_PATTERN, "TT", pattern),
"9:6: " + getCheckMessage(MSG_INVALID_PATTERN, "e_e", pattern),
"19:6: " + getCheckMessage(MSG_INVALID_PATTERN, "Tfo$o2T", pattern),
"23:6: " + getCheckMessage(MSG_INVALID_PATTERN, "foo", pattern),
"28:10: " + getCheckMessage(MSG_INVALID_PATTERN, "_fo", pattern),
};
verify(checkConfig, getPath("InputTypeParameterName.java"), expected);
}
@Test
public void testInterfaceDefault()
throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(InterfaceTypeParameterNameCheck.class);
final String pattern = "^[A-Z]$";
final String[] expected = {
"48:15: " + getCheckMessage(MSG_INVALID_PATTERN, "Input", pattern),
};
verify(checkConfig, getPath("InputTypeParameterName.java"), expected);
}
@Test
public void testClassFooName()
throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(ClassTypeParameterNameCheck.class);
checkConfig.addAttribute("format", "^foo$");
final String pattern = "^foo$";
final String[] expected = {
"5:38: " + getCheckMessage(MSG_INVALID_PATTERN, "t", pattern),
"33:18: " + getCheckMessage(MSG_INVALID_PATTERN, "T", pattern),
};
verify(checkConfig, getPath("InputTypeParameterName.java"), expected);
}
@Test
public void testMethodFooName()
throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(MethodTypeParameterNameCheck.class);
checkConfig.addAttribute("format", "^foo$");
final String pattern = "^foo$";
final String[] expected = {
"7:13: " + getCheckMessage(MSG_INVALID_PATTERN, "TT", pattern),
"9:6: " + getCheckMessage(MSG_INVALID_PATTERN, "e_e", pattern),
"19:6: " + getCheckMessage(MSG_INVALID_PATTERN, "Tfo$o2T", pattern),
"28:10: " + getCheckMessage(MSG_INVALID_PATTERN, "_fo", pattern),
"35:6: " + getCheckMessage(MSG_INVALID_PATTERN, "E", pattern),
"37:14: " + getCheckMessage(MSG_INVALID_PATTERN, "T", pattern),
//"40:14: Name 'EE' must match pattern '^foo$'.",
};
verify(checkConfig, getPath("InputTypeParameterName.java"), expected);
}
@Test
public void testInterfaceFooName()
throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(InterfaceTypeParameterNameCheck.class);
checkConfig.addAttribute("format", "^foo$");
final String pattern = "^foo$";
final String[] expected = {
"48:15: " + getCheckMessage(MSG_INVALID_PATTERN, "Input", pattern),
"52:24: " + getCheckMessage(MSG_INVALID_PATTERN, "T", pattern),
};
verify(checkConfig, getPath("InputTypeParameterName.java"), expected);
}
@Test
public void testGetAcceptableTokens() {
final AbstractTypeParameterNameCheck typeParameterNameCheckObj =
new ClassTypeParameterNameCheck();
final int[] actual = typeParameterNameCheckObj.getAcceptableTokens();
final int[] expected = {
TokenTypes.TYPE_PARAMETER,
};
assertArrayEquals(expected, actual);
}
}
| lgpl-2.1 |
lucee/Lucee | core/src/main/java/lucee/runtime/functions/string/StringEach.java | 1085 | package lucee.runtime.functions.string;
import lucee.runtime.PageContext;
import lucee.runtime.exp.FunctionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.ext.function.BIF;
import lucee.runtime.ext.function.Function;
import lucee.runtime.functions.closure.Each;
import lucee.runtime.op.Caster;
import lucee.runtime.type.UDF;
import lucee.runtime.type.util.StringListData;
public class StringEach extends BIF implements Function {
private static final long serialVersionUID = 2207105205243253849L;
@Override
public Object invoke(PageContext pc, Object[] args) throws PageException {
if (args.length < 2) {
throw new FunctionException(pc, "StringEach", 2, 2, args.length);
}
return call(pc, Caster.toString(args[0]), Caster.toFunction(args[1]));
}
public static String call(PageContext pc, String str, UDF udf) throws PageException {
StringListData stringList = new StringListData(str, "", false, false);
return Each.call(pc, stringList, udf);
}
// call(Llucee/runtime/PageContext;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;
} | lgpl-2.1 |
R3d-Dragon/jMovieManager | jMMCore/src/jmm/interfaces/OSConstantsInterface.java | 1928 | /**
* Copyright (c) 2010-2015 Bryan Beck.
* All rights reserved.
*
* This project is licensed under LGPL v2.1.
* See jMovieManager-license.txt for details.
*
*/
package jmm.interfaces;
/**
*
* @author Bryan Beck
* @since 25.04.2011
*/
public interface OSConstantsInterface {
/** Windows **/
//Notwendig fuer die Plattform Idendifikation
public static final String WIN_ID = "windows";
//Der Standardbrowser
public static final String WIN_PATH = "rundll32";
//Das Flag zum aufrufen der URL
public static final String WIN_FLAG = "url.dll,FileProtocolHandler";
//Name der MediaInfo Library
public static final String WIN_X64_MEDIAINFO = "MediaInfo.dll";
public static final String WIN_X86_MEDIAINFO = "MediaInfo_i386.dll";
/** LINUX **/
//Notwendig fuer die Plattform Idendifikation
public static final String UNIX_ID = "linux";
// The default browser under unix.
public static final String UNIX_PATH = "netscape";
// The flag to display a url.
public static final String UNIX_FLAG = "-remote openURL";
//Name der MediaInfo Library
public static final String UNIX_UBUNTU_LIBZEN = "/usr/lib/libzen.so.0";
//public static final String UNIX_UBUNTU_LIBZEN2 = "/usr/lib/libzen.so.0.0.0";
public static final String UNIX_UBUNTU_MEDIAINFO = "/usr/lib/libmediainfo.so.0";
//public static final String UNIX_UBUNTU_MEDIAINFO2 = "/usr/lib/libmediainfo.so.0.0.0";
/** MAC OS **/
//Notwendig fuer die Plattform Idendifikation
public static final String MAC_ID = "mac";
//Der Standardbrowser
public static final String MAC_PATH = "netscape";
//Das Flag zum aufrufen der URL
public static final String MAC_FLAG = "-remote openURL";
//Name der MediaInfo Library
//Rename libmediainfo.0.0.0.dylib to libmediainfo.dylib
public static final String MAC_MEDIAINFO = "libmediainfo.dylib";
}
| lgpl-2.1 |
alkacon/opencms-core | src/org/opencms/jsp/CmsJspTagSearch.java | 18394 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.jsp;
import org.opencms.ade.publish.CmsPublishListHelper;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.collectors.I_CmsCollectorPublishListProvider;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.shared.I_CmsContentLoadCollectorInfo;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.jsp.search.config.CmsSearchConfiguration;
import org.opencms.jsp.search.config.I_CmsSearchConfiguration;
import org.opencms.jsp.search.config.parser.CmsJSONSearchConfigurationParser;
import org.opencms.jsp.search.config.parser.CmsPlainQuerySearchConfigurationParser;
import org.opencms.jsp.search.config.parser.CmsXMLSearchConfigurationParser;
import org.opencms.jsp.search.controller.CmsSearchController;
import org.opencms.jsp.search.controller.I_CmsSearchControllerCommon;
import org.opencms.jsp.search.controller.I_CmsSearchControllerMain;
import org.opencms.jsp.search.result.CmsSearchResultWrapper;
import org.opencms.jsp.search.result.I_CmsSearchResultWrapper;
import org.opencms.jsp.util.CmsJspElFunctions;
import org.opencms.main.CmsException;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.search.CmsSearchException;
import org.opencms.search.CmsSearchResource;
import org.opencms.search.fields.CmsSearchField;
import org.opencms.search.solr.CmsSolrIndex;
import org.opencms.search.solr.CmsSolrQuery;
import org.opencms.search.solr.CmsSolrResultList;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsUUID;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.jsp.JspException;
import org.apache.commons.logging.Log;
/**
* This tag is used to easily create a search form for a Solr search within a JSP.
*/
public class CmsJspTagSearch extends CmsJspScopedVarBodyTagSuport implements I_CmsCollectorPublishListProvider {
/**
* Type for the file formats that can be parsed.
* The format is given via the tag's attribute "fileFormat".
*/
private static enum FileFormat {
/**
* XML file (of type jsp-search-form).
*/
XML,
/**
* json file in respective format.
*/
JSON
}
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsJspTagSearch.class);
/** Serial version UID required for safe serialization. */
private static final long serialVersionUID = 6048771777971251L;
/** Default number of items which are checked for change for the "This page" publish dialog. */
public static final int DEFAULT_CONTENTINFO_ROWS = 600;
/** The CmsObject for the current user. */
protected transient CmsObject m_cms;
/** The FlexController for the current request. */
protected CmsFlexController m_controller;
/** Number of entries for which content info should be added to allow correct relations in "This page" publish dialog. */
private Integer m_addContentInfoForEntries;
/** The "configFile" tag attribute. */
private Object m_configFile;
/** The "configString" tag attribute. */
private String m_configString;
/** The "fileFormat" tag attribute converted to type FileFormat. */
private FileFormat m_fileFormat;
/** Search controller keeping all the config and state from the search. */
private I_CmsSearchControllerMain m_searchController;
/** The search index that should be used .
* It will either be the configured index, or "Solr Offline" / "Solr Online" depending on the project.
* */
private CmsSolrIndex m_index;
/**
* Empty constructor, required for JSP tags.
*
*/
public CmsJspTagSearch() {
super();
m_fileFormat = FileFormat.XML;
}
/**
* @see org.opencms.file.collectors.I_CmsCollectorPublishListProvider#getPublishResources(org.opencms.file.CmsObject, org.opencms.gwt.shared.I_CmsContentLoadCollectorInfo)
*/
@SuppressWarnings("javadoc")
public static Set<CmsResource> getPublishResourcesInternal(CmsObject cms, I_CmsContentLoadCollectorInfo info)
throws CmsException {
CmsSolrIndex solrOnline = OpenCms.getSearchManager().getIndexSolr(CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE);
CmsSolrIndex solrOffline = OpenCms.getSearchManager().getIndexSolr(CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE);
Set<CmsResource> result = new HashSet<CmsResource>();
try {
Map<String, String[]> searchParams = CmsRequestUtil.createParameterMap(
info.getCollectorParams(),
true,
null);
// use "complicated" constructor to allow more than 50 results -> set ignoreMaxResults to true
// adjust the CmsObject to prevent unintended filtering of resources
CmsSolrResultList offlineResults = solrOffline.search(
CmsPublishListHelper.adjustCmsObject(cms, false),
new CmsSolrQuery(null, searchParams),
true);
Set<String> offlineIds = new HashSet<String>(offlineResults.size());
for (CmsSearchResource offlineResult : offlineResults) {
offlineIds.add(offlineResult.getField(CmsSearchField.FIELD_ID));
}
for (String id : offlineIds) {
CmsResource resource = cms.readResource(new CmsUUID(id));
if (!(resource.getState().isUnchanged())) {
result.add(resource);
}
}
CmsSolrResultList onlineResults = solrOnline.search(
CmsPublishListHelper.adjustCmsObject(cms, true),
new CmsSolrQuery(null, searchParams),
true);
Set<String> deletedIds = new HashSet<String>(onlineResults.size());
for (CmsSearchResource onlineResult : onlineResults) {
String uuid = onlineResult.getField(CmsSearchField.FIELD_ID);
if (!offlineIds.contains(uuid)) {
deletedIds.add(uuid);
}
}
for (String uuid : deletedIds) {
CmsResource resource = cms.readResource(new CmsUUID(uuid), CmsResourceFilter.ALL);
if (!(resource.getState().isUnchanged())) {
result.add(resource);
}
}
} catch (CmsSearchException e) {
LOG.warn(Messages.get().getBundle().key(Messages.LOG_TAG_SEARCH_SEARCH_FAILED_0), e);
}
return result;
}
/**
* @see javax.servlet.jsp.tagext.BodyTagSupport#doEndTag()
*/
@Override
public int doEndTag() throws JspException {
release();
return super.doEndTag();
}
/**
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/
@Override
public int doStartTag() throws JspException, CmsIllegalArgumentException {
// initialize the content load tag
init();
addContentInfo();
return EVAL_BODY_INCLUDE;
}
/** Get the value of the specified configuration file (given via the tag's "configFile" attribute).
* @return The config file.
*/
public Object getConfigFile() {
return m_configFile;
}
/** Getter for the "configString".
* @return The "configString".
*/
public String getConfigString() {
return m_configString;
}
/** Get the value of the specified format of the configuration file (given via the tag's "fileFormat" attribute).
* @return The file format.
*/
public String getFileFormat() {
return m_fileFormat.toString();
}
/**
* @see org.opencms.file.collectors.I_CmsCollectorPublishListProvider#getPublishResources(org.opencms.file.CmsObject, org.opencms.gwt.shared.I_CmsContentLoadCollectorInfo)
*/
public Set<CmsResource> getPublishResources(CmsObject cms, I_CmsContentLoadCollectorInfo info) throws CmsException {
return getPublishResourcesInternal(cms, info);
}
/**
* @see javax.servlet.jsp.tagext.Tag#release()
*/
@Override
public void release() {
m_cms = null;
m_configFile = null;
setConfigString(null);
m_searchController = null;
m_index = null;
m_controller = null;
m_addContentInfoForEntries = null;
super.release();
}
/** Setter for "addContentInfo", indicating if content information should be added.
* @param doAddInfo The value of the "addContentInfo" attribute of the tag
*/
public void setAddContentInfo(final Boolean doAddInfo) {
if ((null != doAddInfo) && doAddInfo.booleanValue() && (null == m_addContentInfoForEntries)) {
m_addContentInfoForEntries = Integer.valueOf(DEFAULT_CONTENTINFO_ROWS);
}
}
/** Setter for the configuration file.
* @param fileName Name of the configuration file to use for the search.
*/
public void setConfigFile(Object fileName) {
m_configFile = fileName;
}
/** Setter for the "configString".
* @param configString The "configString".
*/
public void setConfigString(final String configString) {
m_configString = configString;
}
/** Setter for "contentInfoMaxItems".
* @param maxItems number of items to maximally check for alterations.
*/
public void setContentInfoMaxItems(Integer maxItems) {
if (null != maxItems) {
m_addContentInfoForEntries = maxItems;
}
}
/** Setter for the file format.
* @param fileFormat File format the configuration file is in.
*/
public void setFileFormat(String fileFormat) {
if (fileFormat.toUpperCase().equals(FileFormat.JSON.toString())) {
m_fileFormat = FileFormat.JSON;
}
}
/**
* Initializes this formatter tag.
* <p>
*
* @throws JspException
* in case something goes wrong
*/
protected void init() throws JspException {
// initialize OpenCms access objects
m_controller = CmsFlexController.getController(pageContext.getRequest());
m_cms = m_controller.getCmsObject();
try {
I_CmsSearchConfiguration config = null;
if (m_configFile != null) {
CmsFile configFile = m_cms.readFile(CmsJspElFunctions.convertRawResource(m_cms, m_configFile));
if (m_fileFormat == FileFormat.JSON) {
// read the JSON config file
OpenCms.getLocaleManager();
String configString = new String(
configFile.getContents(),
CmsLocaleManager.getResourceEncoding(m_cms, configFile));
config = new CmsSearchConfiguration(new CmsJSONSearchConfigurationParser(configString), m_cms);
} else { // assume XML
CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(m_cms, configFile);
config = new CmsSearchConfiguration(
new CmsXMLSearchConfigurationParser(xmlContent, m_cms.getRequestContext().getLocale()),
m_cms);
}
}
if (m_configString != null) {
if (m_configString.trim().startsWith("{")) {
config = new CmsSearchConfiguration(
new CmsJSONSearchConfigurationParser(m_configString, config),
m_cms);
} else {
config = new CmsSearchConfiguration(
new CmsPlainQuerySearchConfigurationParser(m_configString, config),
m_cms);
}
}
m_searchController = new CmsSearchController(config);
String indexName = m_searchController.getCommon().getConfig().getSolrIndex();
m_index = OpenCms.getSearchManager().getIndexSolr(indexName);
storeAttribute(getVar(), getSearchResults());
} catch (Exception e) { // CmsException | UnsupportedEncodingException | JSONException
LOG.error(e.getLocalizedMessage(), e);
m_controller.setThrowable(e, m_cms.getRequestContext().getUri());
throw new JspException(e);
}
}
/**
* Adds the content info for the collected resources used in the "This page" publish dialog.
*/
private void addContentInfo() {
if (!m_cms.getRequestContext().getCurrentProject().isOnlineProject()
&& CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE.equals(m_searchController.getCommon().getConfig().getSolrIndex())
&& (null != m_addContentInfoForEntries)) {
CmsSolrQuery query = new CmsSolrQuery();
m_searchController.addQueryParts(query, m_cms);
query.setStart(Integer.valueOf(0));
query.setRows(m_addContentInfoForEntries);
query.setFields(CmsSearchField.FIELD_ID);
query.setFacet(false);
CmsContentLoadCollectorInfo info = new CmsContentLoadCollectorInfo();
info.setCollectorClass(this.getClass().getName());
// Somehow the normal toString() does add '+' for spaces, but keeps "real" '+'
// so we cannot reconstruct the correct query again.
// Using toQueryString() puts '+' for spaces as well, but escapes the "real" '+'
// so we can "repair" the query.
// The method adds '?' as first character, what we do not need.
String queryString = query.toQueryString();
if (queryString.length() > 0) {
// Cut the leading '?' and put correct spaces in place
queryString = queryString.substring(1).replace('+', ' ');
}
info.setCollectorParams(queryString);
info.setId((new CmsUUID()).getStringValue());
if (CmsJspTagEditable.getDirectEditProvider(pageContext) != null) {
try {
CmsJspTagEditable.getDirectEditProvider(pageContext).insertDirectEditListMetadata(
pageContext,
info);
} catch (JspException e) {
LOG.error("Could not write content info.", e);
}
}
}
}
/** Here the search query is composed and executed.
* The result is wrapped in an easily usable form.
* It is exposed to the JSP via the tag's "var" attribute.
* @return The result object exposed via the tag's attribute "var".
*/
private I_CmsSearchResultWrapper getSearchResults() {
// The second parameter is just ignored - so it does not matter
m_searchController.updateFromRequestParameters(pageContext.getRequest().getParameterMap(), false);
I_CmsSearchControllerCommon common = m_searchController.getCommon();
// Do not search for empty query, if configured
if (common.getState().getQuery().isEmpty()
&& (!common.getConfig().getIgnoreQueryParam() && !common.getConfig().getSearchForEmptyQueryParam())) {
return new CmsSearchResultWrapper(m_searchController, null, null, m_cms, null);
}
Map<String, String[]> queryParams = null;
boolean isEditMode = CmsJspTagEditable.isEditableRequest(pageContext.getRequest());
if (isEditMode) {
String params = "";
if (common.getConfig().getIgnoreReleaseDate()) {
params += "&fq=released:[* TO *]";
}
if (common.getConfig().getIgnoreExpirationDate()) {
params += "&fq=expired:[* TO *]";
}
if (!params.isEmpty()) {
queryParams = CmsRequestUtil.createParameterMap(params.substring(1));
}
}
CmsSolrQuery query = new CmsSolrQuery(null, queryParams);
m_searchController.addQueryParts(query, m_cms);
try {
// use "complicated" constructor to allow more than 50 results -> set ignoreMaxResults to true
// also set resource filter to allow for returning unreleased/expired resources if necessary.
CmsSolrResultList solrResultList = m_index.search(
m_cms,
query.clone(), // use a clone of the query, since the search function manipulates the query (removes highlighting parts), but we want to keep the original one.
true,
null,
false,
isEditMode ? CmsResourceFilter.IGNORE_EXPIRATION : null,
m_searchController.getCommon().getConfig().getMaxReturnedResults());
return new CmsSearchResultWrapper(m_searchController, solrResultList, query, m_cms, null);
} catch (CmsSearchException e) {
LOG.warn(Messages.get().getBundle().key(Messages.LOG_TAG_SEARCH_SEARCH_FAILED_0), e);
return new CmsSearchResultWrapper(m_searchController, null, query, m_cms, e);
}
}
}
| lgpl-2.1 |
deegree/deegree3 | deegree-core/deegree-core-remoteows/deegree-remoteows-wms/src/main/java/org/deegree/remoteows/wms/RemoteWmsBuilder.java | 3263 | /*----------------------------------------------------------------------------
This file is part of deegree
Copyright (C) 2001-2013 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
and
- Occam Labs UG (haftungsbeschränkt) -
and others
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
e-mail: info@deegree.org
website: http://www.deegree.org/
----------------------------------------------------------------------------*/
package org.deegree.remoteows.wms;
import java.net.URL;
import org.deegree.protocol.wms.client.WMSClient;
import org.deegree.remoteows.RemoteOWS;
import org.deegree.remoteows.wms_new.jaxb.AuthenticationType;
import org.deegree.remoteows.wms_new.jaxb.HTTPBasicAuthenticationType;
import org.deegree.remoteows.wms_new.jaxb.RemoteWMS;
import org.deegree.workspace.ResourceBuilder;
import org.deegree.workspace.ResourceInitException;
import org.deegree.workspace.ResourceMetadata;
/**
* This class is responsible for building remote WMS.
*
* @author <a href="mailto:schmitz@occamlabs.de">Andreas Schmitz</a>
*
* @since 3.4
*/
public class RemoteWmsBuilder implements ResourceBuilder<RemoteOWS> {
private RemoteWMS cfg;
private ResourceMetadata<RemoteOWS> metadata;
public RemoteWmsBuilder( org.deegree.remoteows.wms_new.jaxb.RemoteWMS cfg, ResourceMetadata<RemoteOWS> metadata ) {
this.cfg = cfg;
this.metadata = metadata;
}
@Override
public RemoteOWS build() {
try {
URL capas = metadata.getLocation().resolveToUrl( cfg.getCapabilitiesDocumentLocation().getLocation() );
int connTimeout = cfg.getConnectionTimeout() == null ? 5 : cfg.getConnectionTimeout();
int reqTimeout = cfg.getRequestTimeout() == null ? 60 : cfg.getRequestTimeout();
WMSClient client;
AuthenticationType type = cfg.getAuthentication() == null ? null : cfg.getAuthentication().getValue();
String user = null;
String pass = null;
if ( type instanceof HTTPBasicAuthenticationType ) {
HTTPBasicAuthenticationType basic = (HTTPBasicAuthenticationType) type;
user = basic.getUsername();
pass = basic.getPassword();
}
client = new WMSClient( capas, connTimeout, reqTimeout, user, pass );
return new org.deegree.remoteows.wms.RemoteWMS( client, metadata );
} catch ( Exception e ) {
throw new ResourceInitException( "Unable to build remote WMS: " + e.getLocalizedMessage(), e );
}
}
}
| lgpl-2.1 |
geotools/geotools | modules/library/main/src/main/java/org/geotools/data/store/FilteringFeatureIterator.java | 2098 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2016, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.data.store;
import java.util.NoSuchElementException;
import org.geotools.feature.FeatureIterator;
import org.opengis.feature.Feature;
import org.opengis.filter.Filter;
/**
* Decorates a FeatureIterator with one that filters content.
*
* @author Justin Deoliveira, The Open Planning Project
*/
public class FilteringFeatureIterator<F extends Feature> implements FeatureIterator<F> {
/** delegate iterator */
protected FeatureIterator<F> delegate;
/** The Filter */
protected Filter filter;
/** Next feature */
protected F next;
public FilteringFeatureIterator(FeatureIterator<F> delegate, Filter filter) {
this.delegate = delegate;
this.filter = filter;
}
@Override
public boolean hasNext() {
if (next != null) {
return true;
}
while (delegate.hasNext()) {
F peek = delegate.next();
if (filter.evaluate(peek)) {
next = peek;
break;
}
}
return next != null;
}
@Override
public F next() throws NoSuchElementException {
if (next == null && !this.hasNext()) {
throw new NoSuchElementException();
}
F f = next;
next = null;
return f;
}
@Override
public void close() {
delegate.close();
delegate = null;
next = null;
filter = null;
}
}
| lgpl-2.1 |
yersan/wildfly-core | controller/src/test/java/org/jboss/as/controller/transform/description/BasicResourceTestCase.java | 37737 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.controller.transform.description;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS;
import java.util.Collections;
import java.util.NoSuchElementException;
import org.jboss.as.controller.ExpressionResolver;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ProcessType;
import org.jboss.as.controller.ResourceDefinition;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.NonResolvingResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.transform.OperationResultTransformer;
import org.jboss.as.controller.transform.OperationTransformer;
import org.jboss.as.controller.transform.PathAddressTransformer;
import org.jboss.as.controller.transform.ResourceTransformationContext;
import org.jboss.as.controller.transform.ResourceTransformer;
import org.jboss.as.controller.transform.TransformationContext;
import org.jboss.as.controller.transform.TransformationTarget;
import org.jboss.as.controller.transform.TransformationTargetImpl;
import org.jboss.as.controller.transform.TransformerRegistry;
import org.jboss.as.controller.transform.Transformers;
import org.jboss.as.controller.transform.TransformersSubRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* @author Emanuel Muckenhuber
*/
public class BasicResourceTestCase {
private static PathElement PATH = PathElement.pathElement("toto", "testSubsystem");
private static PathElement DISCARD = PathElement.pathElement("discard");
private static PathElement DYNAMIC = PathElement.pathElement("dynamic");
private static PathElement DYNAMIC_REDIRECT_ORIGINAL = PathElement.pathElement("dynamic-redirect-original");
private static PathElement DYNAMIC_REDIRECT_NEW = PathElement.pathElement("dynamic-redirect-new");
private static PathElement CONFIGURATION_TEST = PathElement.pathElement("configuration", "test");
private static PathElement TEST_CONFIGURATION = PathElement.pathElement("test", "configuration");
private static PathElement SETTING_DIRECTORY = PathElement.pathElement("setting", "directory");
private static PathElement DIRECTORY_SETTING = PathElement.pathElement("directory", "setting");
private Resource resourceRoot = Resource.Factory.create();
private TransformerRegistry registry = TransformerRegistry.Factory.create();
private ManagementResourceRegistration resourceRegistration = ManagementResourceRegistration.Factory.forProcessType(ProcessType.EMBEDDED_SERVER).createRegistration(ROOT);
private static final TransformationDescription description;
static {
// Build
final ResourceTransformationDescriptionBuilder builder = TransformationDescriptionBuilder.Factory.createInstance(PATH);
builder.getAttributeBuilder()
.addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, "test")
.setValueConverter(AttributeConverter.Factory.createHardCoded(ModelNode.TRUE), "othertest")
.end();
// Create a child resource based on an attribute
final ResourceTransformationDescriptionBuilder attrResourceBuilder = builder.addChildResource(PathElement.pathElement("attribute-resource"))
.getAttributeBuilder().addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, "test-resource")
.end()
.setCustomResourceTransformer(new ResourceTransformer() {
@Override
public void transformResource(final ResourceTransformationContext context, final PathAddress address, final Resource resource) throws OperationFailedException {
// Remote the test-resource attribute
final ModelNode model = resource.getModel();
final ModelNode testResource = model.remove("test-resource");
// Add the current resource
context.addTransformedResource(PathAddress.EMPTY_ADDRESS, resource);
// Use the test-resource attribute to create a child
final Resource child = Resource.Factory.create();
child.getModel().get("attribute").set(testResource);
context.addTransformedResource(PathAddress.EMPTY_ADDRESS.append(PathElement.pathElement("resource", "test")), child);
context.processChildren(resource);
}
});
attrResourceBuilder.addChildRedirection(PathElement.pathElement("resource-attribute"), new PathAddressTransformer() {
@Override
public PathAddress transform(PathElement current, Builder builder) {
return builder.next(); // skip the current element
}
})
.getAttributeBuilder().addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, "test-attribute").end()
.setCustomResourceTransformer(new ResourceTransformer() {
@Override
public void transformResource(ResourceTransformationContext context, PathAddress address, Resource resource) throws OperationFailedException {
// Get the current attribute
final ModelNode attribute = resource.getModel().get("test-attribute");
// Add it to the existing resource
final Resource existing = context.readTransformedResource(PathAddress.EMPTY_ADDRESS); //
final ModelNode model = existing.getModel();
model.get("test-attribute").set(attribute);
}
});
builder.addOperationTransformationOverride("test-operation")
.setValueConverter(AttributeConverter.Factory.createHardCoded(ModelNode.TRUE), "operation-test")
.inheritResourceAttributeDefinitions()
.end();
builder.addOperationTransformationOverride("rename-operation")
.rename("new-name-op")
.setValueConverter(AttributeConverter.Factory.createHardCoded(ModelNode.TRUE), "operation-test")
.end();
builder.addOperationTransformationOverride("operation-with-transformer")
.setCustomOperationTransformer(new OperationTransformer() {
@Override
public TransformedOperation transformOperation(TransformationContext context, PathAddress address,
ModelNode operation) throws OperationFailedException {
ModelNode remove = operation.clone();
remove.get(OP).set(REMOVE);
remove.remove("test");
ModelNode add = operation.clone();
add.get(OP).set(ADD);
add.get("new").set("shiny");
ModelNode composite = new ModelNode();
composite.get(OP).set(COMPOSITE);
composite.get(OP_ADDR).setEmptyList();
composite.get(STEPS).add(remove);
composite.get(STEPS).add(add);
return new TransformedOperation(composite, OperationResultTransformer.ORIGINAL_RESULT);
}
});
// Discard all
builder.discardChildResource(DISCARD);
builder.addChildResource(DYNAMIC, new TestDynamicDiscardPolicy())
.getAttributeBuilder()
.setValueConverter(new AttributeConverter.DefaultAttributeConverter() {
@Override
protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) {
attributeValue.set(attributeValue.asString().toUpperCase());
}
}, "attribute");
builder.addChildRedirection(DYNAMIC_REDIRECT_ORIGINAL, DYNAMIC_REDIRECT_NEW, new TestDynamicDiscardPolicy())
.getAttributeBuilder()
.setValueConverter(new AttributeConverter.DefaultAttributeConverter() {
@Override
protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) {
attributeValue.set(attributeValue.asString().toUpperCase());
}
}, "attribute");
// configuration=test/setting=directory > test=configuration/directory=setting
builder.addChildRedirection(CONFIGURATION_TEST, TEST_CONFIGURATION)
.getAttributeBuilder().addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, "test-config").end()
.addChildRedirection(SETTING_DIRECTORY, DIRECTORY_SETTING);
// Register at the server root
description = builder.build();
}
@Before
public void setUp() {
// Cleanup
resourceRoot = Resource.Factory.create();
registry = TransformerRegistry.Factory.create();
resourceRegistration = ManagementResourceRegistration.Factory.forProcessType(ProcessType.EMBEDDED_SERVER).createRegistration(ROOT);
// test
final Resource toto = Resource.Factory.create();
toto.getModel().get("test").set("onetwothree");
// discard
final Resource discard = Resource.Factory.create();
discard.getModel().get("attribute").set("two");
toto.registerChild(PathElement.pathElement("discard", "one"), discard);
//dynamic discard
final Resource dynamicKeep = Resource.Factory.create();
dynamicKeep.getModel().get("attribute").set("keep");
toto.registerChild(PathElement.pathElement("dynamic", "keep"), dynamicKeep);
final Resource dynamicReject = Resource.Factory.create();
dynamicReject.getModel().get("attribute").set("reject");
toto.registerChild(PathElement.pathElement("dynamic", "reject"), dynamicReject);
final Resource dynamicDiscard = Resource.Factory.create();
dynamicDiscard.getModel().get("attribute").set("discard");
toto.registerChild(PathElement.pathElement("dynamic", "discard"), dynamicDiscard);
//dynamic discard and child redirection
final Resource dynamicRedirectKeep = Resource.Factory.create();
dynamicRedirectKeep.getModel().get("attribute").set("keep");
toto.registerChild(PathElement.pathElement("dynamic-redirect-original", "keep"), dynamicRedirectKeep);
final Resource dynamicRedirectReject = Resource.Factory.create();
dynamicRedirectReject.getModel().get("attribute").set("reject");
toto.registerChild(PathElement.pathElement("dynamic-redirect-original", "reject"), dynamicRedirectReject);
final Resource dynamicRedirectDiscard = Resource.Factory.create();
dynamicRedirectDiscard.getModel().get("attribute").set("discard");
toto.registerChild(PathElement.pathElement("dynamic-redirect-original", "discard"), dynamicRedirectDiscard);
// configuration
final Resource configuration = Resource.Factory.create();
final Resource setting = Resource.Factory.create();
configuration.registerChild(SETTING_DIRECTORY, setting);
toto.registerChild(CONFIGURATION_TEST, configuration);
// attribute-resource
final Resource attrResource = Resource.Factory.create();
attrResource.getModel().get("test-resource").set("abc");
toto.registerChild(PathElement.pathElement("attribute-resource", "test"), attrResource);
// resource-attribute
final Resource resourceAttr = Resource.Factory.create();
resourceAttr.getModel().get("test-attribute").set("test");
attrResource.registerChild(PathElement.pathElement("resource-attribute", "test"), resourceAttr);
//
resourceRoot.registerChild(PATH, toto);
// Register the description
final TransformersSubRegistration reg = registry.getServerRegistration(ModelVersion.create(1));
TransformationDescription.Tools.register(description, reg);
}
@Test
public void testResourceTransformation() throws Exception {
final ModelNode address = new ModelNode();
address.add("toto", "testSubsystem");
final ModelNode node = new ModelNode();
node.get(ModelDescriptionConstants.OP).set("add");
node.get(ModelDescriptionConstants.OP_ADDR).set(address);
final OperationTransformer.TransformedOperation op = transformOperation(ModelVersion.create(1), node);
Assert.assertNotNull(op);
final Resource resource = transformResource(ModelVersion.create(1));
Assert.assertNotNull(resource);
final Resource toto = resource.getChild(PATH);
final ModelNode model = toto.getModel();
Assert.assertNotNull(toto);
Assert.assertFalse(toto.hasChild(PathElement.pathElement("discard", "one")));
Assert.assertFalse(toto.hasChild(CONFIGURATION_TEST));
Assert.assertFalse(toto.hasChild(PathElement.pathElement("dynamic", "discard")));
Assert.assertFalse(toto.hasChild(PathElement.pathElement("dynamic", "reject")));
Resource dynamicKeep = toto.getChild(PathElement.pathElement("dynamic", "keep"));
Assert.assertEquals("KEEP", dynamicKeep.getModel().get("attribute").asString());
Assert.assertFalse(toto.hasChildren("dynamic-redirect-original")); //Make sure that we didn't keep the originals
Assert.assertFalse(toto.hasChild(PathElement.pathElement("dynamic-redirect-new", "discard")));
Assert.assertFalse(toto.hasChild(PathElement.pathElement("dynamic-redirect-new", "reject")));
Resource dynamicRedirectKeep = toto.getChild(PathElement.pathElement("dynamic-redirect-new", "keep"));
Assert.assertEquals("KEEP", dynamicRedirectKeep.getModel().get("attribute").asString());
final Resource attResource = toto.getChild(PathElement.pathElement("attribute-resource", "test"));
Assert.assertNotNull(attResource);
final ModelNode attResourceModel = attResource.getModel();
Assert.assertFalse(attResourceModel.get("test-resource").isDefined()); // check that the resource got removed
Assert.assertTrue(attResourceModel.hasDefined("test-attribute"));
Assert.assertTrue(attResource.hasChild(PathElement.pathElement("resource", "test")));
}
@Test
public void testAddOperation() throws Exception {
final ModelNode address = new ModelNode();
address.add("toto", "testSubsystem");
final ModelNode node = new ModelNode();
node.get(ModelDescriptionConstants.OP).set("add");
node.get(ModelDescriptionConstants.OP_ADDR).set(address);
node.get("test").set("${one:two}");
OperationTransformer.TransformedOperation op = transformOperation(ModelVersion.create(1), node);
Assert.assertTrue(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 1), node);
Assert.assertTrue(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 5), node);
Assert.assertTrue(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 1), node);
Assert.assertFalse(op.rejectOperation(success()));
node.get("test").set("concrete");
op = transformOperation(ModelVersion.create(1), node);
Assert.assertFalse(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 1), node);
Assert.assertFalse(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 5), node);
Assert.assertFalse(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 1), node);
Assert.assertFalse(op.rejectOperation(success()));
}
@Test
public void testWriteAttribute() throws Exception {
final ModelNode address = new ModelNode();
address.add("toto", "testSubsystem");
final ModelNode node = new ModelNode();
node.get(ModelDescriptionConstants.OP).set("write-attribute");
node.get(ModelDescriptionConstants.OP_ADDR).set(address);
node.get("name").set("test");
node.get("value").set("${one:two}");
OperationTransformer.TransformedOperation op = transformOperation(ModelVersion.create(1), node);
Assert.assertTrue(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 1), node);
Assert.assertTrue(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 5), node);
Assert.assertTrue(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 1), node);
Assert.assertFalse(op.rejectOperation(success()));
node.get("value").set("test");
op = transformOperation(ModelVersion.create(1), node);
Assert.assertFalse(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 1), node);
Assert.assertFalse(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 5), node);
Assert.assertFalse(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 1), node);
Assert.assertFalse(op.rejectOperation(success()));
}
@Test
public void testAlias() throws Exception {
final ModelNode address = new ModelNode();
address.add("toto", "testSubsystem");
address.add("configuration", "test");
final ModelNode node = new ModelNode();
node.get(ModelDescriptionConstants.OP).set("add");
node.get(ModelDescriptionConstants.OP_ADDR).set(address);
node.get("test-config").set("${one:two}");
validateAliasTransformation(node.clone(), ModelVersion.create(1));
validateAliasTransformation(node.clone(), ModelVersion.create(1, 0, 1));
validateAliasTransformation(node.clone(), ModelVersion.create(1, 0, 5));
OperationTransformer.TransformedOperation op = transformOperation(ModelVersion.create(1, 1), node.clone());
Assert.assertFalse(op.rejectOperation(success()));
node.get("test-config").set("concrete");
op = transformOperation(ModelVersion.create(1), node);
Assert.assertFalse(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 1), node);
Assert.assertFalse(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 0, 5), node);
Assert.assertFalse(op.rejectOperation(success()));
op = transformOperation(ModelVersion.create(1, 1), node);
Assert.assertFalse(op.rejectOperation(success()));
}
private void validateAliasTransformation(final ModelNode node, final ModelVersion version) throws OperationFailedException, NoSuchElementException {
OperationTransformer.TransformedOperation op = transformOperation(version, node);
Assert.assertTrue(op.rejectOperation(success()));
PathAddress transformed = PathAddress.pathAddress(op.getTransformedOperation().require(OP_ADDR));
Assert.assertEquals("test", transformed.getLastElement().getKey());
Assert.assertEquals("configuration", transformed.getLastElement().getValue());
}
@Test
public void testOperationOverride() throws Exception {
final ModelNode address = new ModelNode();
address.add("toto", "testSubsystem");
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set("test-operation");
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
operation.get("test").set("${one:two}");
validateOperationOverride(operation, ModelVersion.create(1));
validateOperationOverride(operation, ModelVersion.create(1, 0, 1));
validateOperationOverride(operation, ModelVersion.create(1, 0, 5));
OperationTransformer.TransformedOperation op = transformOperation(ModelVersion.create(1, 1), operation);
Assert.assertFalse(op.rejectOperation(success())); // inherited
}
private void validateOperationOverride(final ModelNode operation, final ModelVersion version) throws IllegalArgumentException, OperationFailedException {
OperationTransformer.TransformedOperation op = transformOperation(version, operation);
ModelNode transformed = op.getTransformedOperation();
Assert.assertTrue(transformed.get("operation-test").asBoolean()); // explicit
Assert.assertTrue(transformed.get("othertest").asBoolean()); // inherited
Assert.assertTrue(op.rejectOperation(success())); // inherited
}
@Test
public void testOperationTransformer() throws Exception {
final ModelNode address = new ModelNode();
address.add("toto", "testSubsystem");
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set("operation-with-transformer");
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
operation.get("test").set("a");
validateCompositeOperationTransformation(operation, ModelVersion.create(1));
validateCompositeOperationTransformation(operation, ModelVersion.create(1, 0 , 1));
validateCompositeOperationTransformation(operation, ModelVersion.create(1, 0 , 5));
}
private void validateCompositeOperationTransformation(final ModelNode operation, final ModelVersion version) throws OperationFailedException {
OperationTransformer.TransformedOperation op = transformOperation(version, operation);
final ModelNode transformed = op.getTransformedOperation();
System.out.println(transformed);
Assert.assertEquals(COMPOSITE, transformed.get(OP).asString());
Assert.assertEquals(new ModelNode().setEmptyList(), transformed.get(OP_ADDR));
Assert.assertEquals(ModelType.LIST, transformed.get(STEPS).getType());
Assert.assertEquals(2, transformed.get(STEPS).asList().size());
ModelNode remove = transformed.get(STEPS).asList().get(0);
Assert.assertEquals(2, remove.keys().size());
Assert.assertEquals(REMOVE, remove.get(OP).asString());
Assert.assertEquals(PATH, PathAddress.pathAddress(remove.get(OP_ADDR)).iterator().next());
ModelNode add = transformed.get(STEPS).asList().get(1);
Assert.assertEquals(4, add.keys().size());
Assert.assertEquals(ADD, add.get(OP).asString());
Assert.assertEquals(PATH, PathAddress.pathAddress(add.get(OP_ADDR)).iterator().next());
Assert.assertEquals("a", add.get("test").asString());
Assert.assertEquals("shiny", add.get("new").asString());
}
@Test
public void testRenameOperation() throws Exception {
final ModelNode address = new ModelNode();
address.add("toto", "testSubsystem");
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set("rename-operation");
operation.get(ModelDescriptionConstants.OP_ADDR).set(address);
operation.get("param").set("test");
validateRenamedOperation(operation, ModelVersion.create(1));
validateRenamedOperation(operation, ModelVersion.create(1, 0, 1));
validateRenamedOperation(operation, ModelVersion.create(1, 0, 5));
OperationTransformer.TransformedOperation op = transformOperation(ModelVersion.create(1, 1), operation);
final ModelNode notTransformed = op.getTransformedOperation();
Assert.assertEquals("rename-operation", notTransformed.get(OP).asString());
}
private void validateRenamedOperation(final ModelNode operation, final ModelVersion version) throws IllegalArgumentException, OperationFailedException {
OperationTransformer.TransformedOperation op = transformOperation(version, operation);
final ModelNode transformed = op.getTransformedOperation();
Assert.assertEquals("new-name-op", transformed.get(OP).asString());
Assert.assertEquals("test", transformed.get("param").asString());
Assert.assertTrue(transformed.get("operation-test").asBoolean()); // explicit
Assert.assertFalse(transformed.hasDefined("othertest")); // not inherited
Assert.assertFalse(op.rejectOperation(success())); // inherited
}
@Test
public void testDynamicDiscardOperations() throws Exception {
PathAddress subsystem = PathAddress.pathAddress("toto", "testSubsystem");
final PathAddress keepAddress = subsystem.append("dynamic", "keep");
final ModelNode opKeep = Util.createAddOperation(keepAddress);
opKeep.get("attribute").set("keep");
OperationTransformer.TransformedOperation txKeep = transformOperation(ModelVersion.create(1), opKeep.clone());
Assert.assertFalse(txKeep.rejectOperation(success()));
Assert.assertNotNull(txKeep.getTransformedOperation());
Assert.assertEquals("KEEP", txKeep.getTransformedOperation().get("attribute").asString());
Assert.assertEquals(keepAddress, PathAddress.pathAddress(txKeep.getTransformedOperation().get(OP_ADDR)));
txKeep = transformOperation(ModelVersion.create(1, 0, 1), opKeep.clone());
Assert.assertFalse(txKeep.rejectOperation(success()));
Assert.assertNotNull(txKeep.getTransformedOperation());
Assert.assertEquals("KEEP", txKeep.getTransformedOperation().get("attribute").asString());
Assert.assertEquals(keepAddress, PathAddress.pathAddress(txKeep.getTransformedOperation().get(OP_ADDR)));
txKeep = transformOperation(ModelVersion.create(1, 0, 5), opKeep.clone());
Assert.assertFalse(txKeep.rejectOperation(success()));
Assert.assertNotNull(txKeep.getTransformedOperation());
Assert.assertEquals("KEEP", txKeep.getTransformedOperation().get("attribute").asString());
Assert.assertEquals(keepAddress, PathAddress.pathAddress(txKeep.getTransformedOperation().get(OP_ADDR)));
txKeep = transformOperation(ModelVersion.create(1, 1), opKeep.clone());
Assert.assertFalse(txKeep.rejectOperation(success()));
Assert.assertNotNull(txKeep.getTransformedOperation());
Assert.assertEquals("keep", txKeep.getTransformedOperation().get("attribute").asString());
Assert.assertEquals(keepAddress, PathAddress.pathAddress(txKeep.getTransformedOperation().get(OP_ADDR)));
final ModelNode opDiscard = Util.createAddOperation(subsystem.append("dynamic", "discard"));
OperationTransformer.TransformedOperation txDiscard = transformOperation(ModelVersion.create(1), opDiscard.clone());
Assert.assertFalse(txDiscard.rejectOperation(success()));
Assert.assertNull(txDiscard.getTransformedOperation());
txDiscard = transformOperation(ModelVersion.create(1, 0, 1), opDiscard.clone());
Assert.assertFalse(txDiscard.rejectOperation(success()));
Assert.assertNull(txDiscard.getTransformedOperation());
txDiscard = transformOperation(ModelVersion.create(1, 0, 5), opDiscard.clone());
Assert.assertFalse(txDiscard.rejectOperation(success()));
Assert.assertNull(txDiscard.getTransformedOperation());
txDiscard = transformOperation(ModelVersion.create(1, 1), opDiscard.clone());
Assert.assertFalse(txDiscard.rejectOperation(success()));
Assert.assertNotNull(txDiscard.getTransformedOperation());
final ModelNode opReject = Util.createAddOperation(subsystem.append("dynamic", "reject"));
OperationTransformer.TransformedOperation txReject = transformOperation(ModelVersion.create(1), opReject.clone());
Assert.assertTrue(txReject.rejectOperation(success()));
Assert.assertNotNull(txReject.getTransformedOperation());
txReject = transformOperation(ModelVersion.create(1, 0, 1), opReject.clone());
Assert.assertTrue(txReject.rejectOperation(success()));
Assert.assertNotNull(txReject.getTransformedOperation());
txReject = transformOperation(ModelVersion.create(1, 0, 5), opReject.clone());
Assert.assertTrue(txReject.rejectOperation(success()));
Assert.assertNotNull(txReject.getTransformedOperation());
txReject = transformOperation(ModelVersion.create(1, 1), opReject.clone());
Assert.assertFalse(txReject.rejectOperation(success()));
Assert.assertNotNull(txReject.getTransformedOperation());
}
@Test
public void testDynamicDiscardRedirectOperations() throws Exception {
PathAddress subsystem = PathAddress.pathAddress("toto", "testSubsystem");
final PathAddress keepNewAddress = subsystem.append("dynamic-redirect-new", "keep");
final PathAddress keepOriginalAddress = subsystem.append("dynamic-redirect-original", "keep");
final ModelNode opKeep = Util.createAddOperation(keepOriginalAddress);
opKeep.get("attribute").set("keep");
OperationTransformer.TransformedOperation txKeep = transformOperation(ModelVersion.create(1), opKeep.clone());
Assert.assertFalse(txKeep.rejectOperation(success()));
Assert.assertNotNull(txKeep.getTransformedOperation());
Assert.assertEquals("KEEP", txKeep.getTransformedOperation().get("attribute").asString());
Assert.assertEquals(keepNewAddress, PathAddress.pathAddress(txKeep.getTransformedOperation().get(OP_ADDR)));
txKeep = transformOperation(ModelVersion.create(1, 0, 1), opKeep.clone());
Assert.assertFalse(txKeep.rejectOperation(success()));
Assert.assertNotNull(txKeep.getTransformedOperation());
Assert.assertEquals("KEEP", txKeep.getTransformedOperation().get("attribute").asString());
Assert.assertEquals(keepNewAddress, PathAddress.pathAddress(txKeep.getTransformedOperation().get(OP_ADDR)));
txKeep = transformOperation(ModelVersion.create(1, 0, 5), opKeep.clone());
Assert.assertFalse(txKeep.rejectOperation(success()));
Assert.assertNotNull(txKeep.getTransformedOperation());
Assert.assertEquals("KEEP", txKeep.getTransformedOperation().get("attribute").asString());
Assert.assertEquals(keepNewAddress, PathAddress.pathAddress(txKeep.getTransformedOperation().get(OP_ADDR)));
txKeep = transformOperation(ModelVersion.create(1, 1), opKeep.clone());
Assert.assertFalse(txKeep.rejectOperation(success()));
Assert.assertNotNull(txKeep.getTransformedOperation());
Assert.assertEquals("keep", txKeep.getTransformedOperation().get("attribute").asString());
Assert.assertEquals(keepOriginalAddress, PathAddress.pathAddress(txKeep.getTransformedOperation().get(OP_ADDR)));
final ModelNode opDiscard = Util.createAddOperation(subsystem.append("dynamic-redirect-original", "discard"));
OperationTransformer.TransformedOperation txDiscard = transformOperation(ModelVersion.create(1), opDiscard.clone());
Assert.assertFalse(txDiscard.rejectOperation(success()));
Assert.assertNull(txDiscard.getTransformedOperation());
txDiscard = transformOperation(ModelVersion.create(1, 0, 1), opDiscard.clone());
Assert.assertFalse(txDiscard.rejectOperation(success()));
Assert.assertNull(txDiscard.getTransformedOperation());
txDiscard = transformOperation(ModelVersion.create(1, 0, 5), opDiscard.clone());
Assert.assertFalse(txDiscard.rejectOperation(success()));
Assert.assertNull(txDiscard.getTransformedOperation());
txDiscard = transformOperation(ModelVersion.create(1, 1), opDiscard.clone());
Assert.assertFalse(txDiscard.rejectOperation(success()));
Assert.assertNotNull(txDiscard.getTransformedOperation());
final ModelNode opReject = Util.createAddOperation(subsystem.append("dynamic-redirect-original", "reject"));
OperationTransformer.TransformedOperation txReject = transformOperation(ModelVersion.create(1), opReject.clone());
Assert.assertTrue(txReject.rejectOperation(success()));
Assert.assertNotNull(txReject.getTransformedOperation());
txReject = transformOperation(ModelVersion.create(1, 0, 1), opReject.clone());
Assert.assertTrue(txReject.rejectOperation(success()));
Assert.assertNotNull(txReject.getTransformedOperation());
txReject = transformOperation(ModelVersion.create(1, 0, 5), opReject.clone());
Assert.assertTrue(txReject.rejectOperation(success()));
Assert.assertNotNull(txReject.getTransformedOperation());
txReject = transformOperation(ModelVersion.create(1, 1), opReject.clone());
Assert.assertFalse(txReject.rejectOperation(success()));
Assert.assertNotNull(txReject.getTransformedOperation());
}
private Resource transformResource(final ModelVersion version) throws OperationFailedException {
final TransformationTarget target = create(registry, version);
final ResourceTransformationContext context = createContext(target);
return getTransfomers(target).transformResource(context, resourceRoot);
}
private OperationTransformer.TransformedOperation transformOperation(final ModelVersion version, final ModelNode operation) throws OperationFailedException {
final TransformationTarget target = create(registry, version);
final TransformationContext context = createContext(target);
return getTransfomers(target).transformOperation(context, operation);
}
private ResourceTransformationContext createContext(final TransformationTarget target) {
return Transformers.Factory.create(target, resourceRoot, resourceRegistration,
ExpressionResolver.TEST_RESOLVER, RunningMode.NORMAL, ProcessType.STANDALONE_SERVER, null);
}
private Transformers getTransfomers(final TransformationTarget target) {
return Transformers.Factory.create(target);
}
protected TransformationTarget create(final TransformerRegistry registry, ModelVersion version) {
return create(registry, version, TransformationTarget.TransformationTargetType.SERVER);
}
protected TransformationTarget create(final TransformerRegistry registry, ModelVersion version, TransformationTarget.TransformationTargetType type) {
return TransformationTargetImpl.create(null, registry, version, Collections.<PathAddress, ModelVersion>emptyMap(), type);
}
private static final ResourceDefinition ROOT = new SimpleResourceDefinition(PathElement.pathElement("test"), NonResolvingResourceDescriptionResolver.INSTANCE);
private static ModelNode success() {
final ModelNode result = new ModelNode();
result.get(ModelDescriptionConstants.OUTCOME).set(ModelDescriptionConstants.SUCCESS);
result.get(ModelDescriptionConstants.RESULT);
return result;
}
private static class TestDynamicDiscardPolicy implements DynamicDiscardPolicy {
@Override
public DiscardPolicy checkResource(TransformationContext context, PathAddress address) {
String action = address.getLastElement().getValue();
switch (action) {
case "keep":
return DiscardPolicy.NEVER;
case "discard":
return DiscardPolicy.DISCARD_AND_WARN;
case "reject":
return DiscardPolicy.REJECT_AND_WARN;
}
throw new IllegalArgumentException("Unknown address");
}
}
}
| lgpl-2.1 |
raffy1982/spine-project | Spine_serverApp/src/spine/datamodel/functions/StepCounterSpineFunctionReq.java | 2145 | /*****************************************************************
SPINE - Signal Processing In-Node Environment is a framework that
allows dynamic configuration of feature extraction capabilities
of WSN nodes via an OtA protocol
Copyright (C) 2007 Telecom Italia S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
/**
*
* Objects of this class are used for expressing at high level function requests
* (both activation and deactivation) of type 'StepCounter'.
* An application that needs to do a StepCounter request, must create a new StepCounterSpineFunctionReq
* object for alarm activation, or deactivation.
*
* This class also implements the encode method of the abstract class SpineFunctionReq that is used internally
* to convert the high level request into an actual SPINE Ota message.
*
*
* @author Raffaele Gravina
*
* @version 1.3
*/
package spine.datamodel.functions;
public class StepCounterSpineFunctionReq extends SpineFunctionReq {
private static final long serialVersionUID = 1L;
/**
*
* Returns a string representation of the StepCounterSpineFunctionReq object.
*
* @return a string representation of this StepCounterSpineFunctionReq
*
*/
public String toString() {
String s = "Steps-Counter Function Req {";
s += (this.isActivationRequest)? "activate" : "deactivate";
s += "}";
return s;
}
}
| lgpl-2.1 |
skyvers/skyve | skyve-core/src/main/java/org/skyve/metadata/view/fluent/FluentFormItem.java | 10057 | package org.skyve.metadata.view.fluent;
import org.skyve.impl.metadata.view.HorizontalAlignment;
import org.skyve.impl.metadata.view.Inject;
import org.skyve.impl.metadata.view.container.form.FormItem;
import org.skyve.impl.metadata.view.widget.Blurb;
import org.skyve.impl.metadata.view.widget.Button;
import org.skyve.impl.metadata.view.widget.DialogButton;
import org.skyve.impl.metadata.view.widget.Link;
import org.skyve.impl.metadata.view.widget.Spacer;
import org.skyve.impl.metadata.view.widget.StaticImage;
import org.skyve.impl.metadata.view.widget.bound.Label;
import org.skyve.impl.metadata.view.widget.bound.ProgressBar;
import org.skyve.impl.metadata.view.widget.bound.ZoomIn;
import org.skyve.impl.metadata.view.widget.bound.input.CheckBox;
import org.skyve.impl.metadata.view.widget.bound.input.ColourPicker;
import org.skyve.impl.metadata.view.widget.bound.input.Combo;
import org.skyve.impl.metadata.view.widget.bound.input.ContentImage;
import org.skyve.impl.metadata.view.widget.bound.input.ContentLink;
import org.skyve.impl.metadata.view.widget.bound.input.ContentSignature;
import org.skyve.impl.metadata.view.widget.bound.input.DefaultWidget;
import org.skyve.impl.metadata.view.widget.bound.input.Geometry;
import org.skyve.impl.metadata.view.widget.bound.input.GeometryMap;
import org.skyve.impl.metadata.view.widget.bound.input.HTML;
import org.skyve.impl.metadata.view.widget.bound.input.LookupDescription;
import org.skyve.impl.metadata.view.widget.bound.input.Password;
import org.skyve.impl.metadata.view.widget.bound.input.Radio;
import org.skyve.impl.metadata.view.widget.bound.input.RichText;
import org.skyve.impl.metadata.view.widget.bound.input.Slider;
import org.skyve.impl.metadata.view.widget.bound.input.Spinner;
import org.skyve.impl.metadata.view.widget.bound.input.TextArea;
import org.skyve.impl.metadata.view.widget.bound.input.TextField;
import org.skyve.metadata.MetaData;
public class FluentFormItem {
private FormItem item = null;
public FluentFormItem() {
item = new FormItem();
}
public FluentFormItem(FormItem item) {
this.item = item;
}
public FluentFormItem from(@SuppressWarnings("hiding") FormItem item) {
Integer i = item.getColspan();
if (i != null) {
colspan(i.intValue());
}
i = item.getRowspan();
if (i != null) {
rowspan(i.intValue());
}
horizontalAlignment(item.getHorizontalAlignment());
label(item.getLabel());
Boolean b = item.getShowLabel();
if (b != null) {
showLabel(b.booleanValue());
}
labelHorizontalAlignment(item.getLabelHorizontalAlignment());
if (b != null) {
showHelp(b.booleanValue());
}
help(item.getHelp());
b = item.getRequired();
if (b != null) {
required(b.booleanValue());
}
MetaData widget = item.getWidget();
if (widget instanceof DefaultWidget) {
defaultWidget(new FluentDefaultWidget().from((DefaultWidget) widget));
}
else if (widget instanceof ContentImage) {
contentImage(new FluentContentImage().from((ContentImage) widget));
}
else if (widget instanceof ContentLink) {
contentLink(new FluentContentLink().from((ContentLink) widget));
}
else if (widget instanceof ContentSignature) {
contentSignature(new FluentContentSignature().from((ContentSignature) widget));
}
else if (widget instanceof Button) {
button(new FluentButton().from((Button) widget));
}
else if (widget instanceof ZoomIn) {
zoomIn(new FluentZoomIn().from((ZoomIn) widget));
}
else if (widget instanceof DialogButton) {
dialogButton(new FluentDialogButton().from((DialogButton) widget));
}
else if (widget instanceof Geometry) {
geometry(new FluentGeometry().from((Geometry) widget));
}
else if (widget instanceof GeometryMap) {
geometryMap(new FluentGeometryMap().from((GeometryMap) widget));
}
else if (widget instanceof HTML) {
html(new FluentHTML().from((HTML) widget));
}
else if (widget instanceof Label) {
label(new FluentLabel().from((Label) widget));
}
else if (widget instanceof Blurb) {
blurb(new FluentBlurb().from((Blurb) widget));
}
else if (widget instanceof ProgressBar) {
progressBar(new FluentProgressBar().from((ProgressBar) widget));
}
else if (widget instanceof CheckBox) {
checkBox(new FluentCheckBox().from((CheckBox) widget));
}
else if (widget instanceof ColourPicker) {
colourPicker(new FluentColourPicker().from((ColourPicker) widget));
}
else if (widget instanceof Combo) {
combo(new FluentCombo().from((Combo) widget));
}
else if (widget instanceof Radio) {
radio(new FluentRadio().from((Radio) widget));
}
else if (widget instanceof LookupDescription) {
lookupDescription(new FluentLookupDescription().from((LookupDescription) widget));
}
else if (widget instanceof Password) {
password(new FluentPassword().from((Password) widget));
}
else if (widget instanceof RichText) {
richText(new FluentRichText().from((RichText) widget));
}
else if (widget instanceof Slider) {
slider(new FluentSlider().from((Slider) widget));
}
else if (widget instanceof Spacer) {
spacer(new FluentSpacer().from((Spacer) widget));
}
else if (widget instanceof Spinner) {
spinner(new FluentSpinner().from((Spinner) widget));
}
else if (widget instanceof StaticImage) {
staticImage(new FluentStaticImage().from((StaticImage) widget));
}
else if (widget instanceof Link) {
link(new FluentLink().from((Link) widget));
}
else if (widget instanceof TextArea) {
textArea(new FluentTextArea().from((TextArea) widget));
}
else if (widget instanceof TextField) {
textField(new FluentTextField().from((TextField) widget));
}
else if (widget instanceof Inject) {
inject(new FluentInject().from((Inject) widget));
}
else {
throw new IllegalStateException(widget + " is not catered for");
}
return this;
}
public FluentFormItem colspan(int colspan) {
item.setColspan(Integer.valueOf(colspan));
return this;
}
public FluentFormItem rowspan(int rowspan) {
item.setRowspan(Integer.valueOf(rowspan));
return this;
}
public FluentFormItem horizontalAlignment(HorizontalAlignment horizontalAlignment) {
item.setHorizontalAlignment(horizontalAlignment);
return this;
}
public FluentFormItem label(String label) {
item.setLabel(label);
return this;
}
public FluentFormItem showLabel(boolean showLabel) {
item.setShowLabel(showLabel ? Boolean.TRUE : Boolean.FALSE);
return this;
}
public FluentFormItem labelHorizontalAlignment(HorizontalAlignment labelHorizontalAlignment) {
item.setLabelHorizontalAlignment(labelHorizontalAlignment);
return this;
}
public FluentFormItem showHelp(boolean showHelp) {
item.setShowHelp(showHelp ? Boolean.TRUE : Boolean.FALSE);
return this;
}
public FluentFormItem help(String help) {
item.setHelp(help);
return this;
}
public FluentFormItem required(boolean required) {
item.setRequired(required ? Boolean.TRUE : Boolean.FALSE);
return this;
}
public FluentFormItem defaultWidget(FluentDefaultWidget widget) {
item.setWidget(widget.get());
return this;
}
public FluentFormItem contentImage(FluentContentImage image) {
item.setWidget(image.get());
return this;
}
public FluentFormItem contentLink(FluentContentLink link) {
item.setWidget(link.get());
return this;
}
public FluentFormItem contentSignature(FluentContentSignature signature) {
item.setWidget(signature.get());
return this;
}
public FluentFormItem button(FluentButton button) {
item.setWidget(button.get());
return this;
}
public FluentFormItem zoomIn(FluentZoomIn zoomIn) {
item.setWidget(zoomIn.get());
return this;
}
public FluentFormItem dialogButton(FluentDialogButton button) {
item.setWidget(button.get());
return this;
}
public FluentFormItem geometry(FluentGeometry geometry) {
item.setWidget(geometry.get());
return this;
}
public FluentFormItem geometryMap(FluentGeometryMap map) {
item.setWidget(map.get());
return this;
}
public FluentFormItem html(FluentHTML html) {
item.setWidget(html.get());
return this;
}
public FluentFormItem label(FluentLabel label) {
item.setWidget(label.get());
return this;
}
public FluentFormItem blurb(FluentBlurb blurb) {
item.setWidget(blurb.get());
return this;
}
public FluentFormItem progressBar(FluentProgressBar bar) {
item.setWidget(bar.get());
return this;
}
public FluentFormItem checkBox(FluentCheckBox check) {
item.setWidget(check.get());
return this;
}
public FluentFormItem colourPicker(FluentColourPicker colour) {
item.setWidget(colour.get());
return this;
}
public FluentFormItem combo(FluentCombo combo) {
item.setWidget(combo.get());
return this;
}
public FluentFormItem radio(FluentRadio radio) {
item.setWidget(radio.get());
return this;
}
public FluentFormItem lookupDescription(FluentLookupDescription lookup) {
item.setWidget(lookup.get());
return this;
}
public FluentFormItem password(FluentPassword password) {
item.setWidget(password.get());
return this;
}
public FluentFormItem richText(FluentRichText text) {
item.setWidget(text.get());
return this;
}
public FluentFormItem slider(FluentSlider slider) {
item.setWidget(slider.get());
return this;
}
public FluentFormItem spacer(FluentSpacer spacer) {
item.setWidget(spacer.get());
return this;
}
public FluentFormItem spinner(FluentSpinner spinner) {
item.setWidget(spinner.get());
return this;
}
public FluentFormItem staticImage(FluentStaticImage image) {
item.setWidget(image.get());
return this;
}
public FluentFormItem link(FluentLink link) {
item.setWidget(link.get());
return this;
}
public FluentFormItem textArea(FluentTextArea text) {
item.setWidget(text.get());
return this;
}
public FluentFormItem textField(FluentTextField text) {
item.setWidget(text.get());
return this;
}
public FluentFormItem inject(FluentInject inject) {
item.setWidget(inject.get());
return this;
}
public FormItem get() {
return item;
}
}
| lgpl-2.1 |
hal/core | dmr/src/main/java/org/jboss/dmr/client/GreetingService.java | 1330 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.dmr.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* The client side stub for the RPC service.
*/
@RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
String greetServer(String name) throws IllegalArgumentException;
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/legacy/Eye.java | 1236 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id: Eye.java 4599 2004-09-26 05:18:27Z oneovthafew $
package org.hibernate.test.legacy;
import java.util.HashSet;
import java.util.Set;
/**
* @author Gavin King
*/
public class Eye {
private long id;
private String name;
private Jay jay;
private Set jays = new HashSet();
/**
* @return Returns the id.
*/
public long getId() {
return id;
}
/**
* @param id The id to set.
*/
public void setId(long id) {
this.id = id;
}
/**
* @return Returns the jay.
*/
public Jay getJay() {
return jay;
}
/**
* @param jay The jay to set.
*/
public void setJay(Jay jay) {
this.jay = jay;
}
/**
* @return Returns the jays.
*/
public Set getJays() {
return jays;
}
/**
* @param jays The jays to set.
*/
public void setJays(Set jays) {
this.jays = jays;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
}
| lgpl-2.1 |
geotools/geotools | modules/plugin/coverage-multidim/netcdf/src/main/java/org/geotools/imageio/netcdf/NetCDFGeoreferenceManager.java | 26670 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2015 - 2016, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.imageio.netcdf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.geotools.coverage.io.netcdf.crs.NetCDFProjection;
import org.geotools.coverage.io.netcdf.crs.ProjectionBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.imageio.netcdf.cv.CoordinateVariable;
import org.geotools.imageio.netcdf.utilities.NetCDFCRSUtilities;
import org.geotools.imageio.netcdf.utilities.NetCDFUtilities;
import org.geotools.util.Utilities;
import org.geotools.util.logging.Logging;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import ucar.nc2.Attribute;
import ucar.nc2.Variable;
import ucar.nc2.constants.AxisType;
import ucar.nc2.dataset.CoordinateAxis;
import ucar.nc2.dataset.NetcdfDataset;
/**
* Store information about the underlying NetCDF georeferencing, such as Coordinate Variables (i.e.
* Latitude, Longitude, Time variables, with values), Coordinate Reference Systems (i.e.
* GridMappings), NetCDF dimensions to NetCDF coordinates relations.
*/
class NetCDFGeoreferenceManager {
/** Base class for BBOX initialization and retrieval. */
class BBoxGetter {
/**
* BoundingBoxes available for the underlying dataset. Most common case is that the whole
* dataset has a single boundingbox/grid-mapping, resulting into a map made by a single
* element. In that case, the only one envelope will be referred through the "DEFAULT" key
*/
protected Map<String, ReferencedEnvelope> boundingBoxes;
public BBoxGetter() throws FactoryException, IOException {
boundingBoxes = new HashMap<>();
init();
}
protected void init() throws FactoryException, IOException {
double[] xLon = new double[2];
double[] yLat = new double[2];
byte set = 0;
isLonLat = false;
Map<String, Object> crsProperties = new HashMap<>();
String axisUnit = null;
// Scan over coordinateVariables
for (CoordinateVariable<?> cv : getCoordinatesVariables()) {
if (cv.isNumeric()) {
// is it lat or lon (or geoY or geoX)?
AxisType type = cv.getAxisType();
switch (type) {
case GeoY:
case Lat:
getCoordinate(cv, yLat);
if (yLat[1] > yLat[0]) {
setNeedsFlipping(true);
} else {
setNeedsFlipping(false);
}
set++;
break;
case GeoX:
case Lon:
getCoordinate(cv, xLon);
set++;
break;
default:
break;
}
switch (type) {
case Lat:
case Lon:
isLonLat = true;
break;
case GeoY:
case GeoX:
axisUnit = cv.getUnit();
break;
default:
break;
}
}
if (set == 2) {
break;
}
}
if (set != 2) {
throw new IllegalStateException("Unable to create envelope for this dataset");
}
// The previous code was able to automatically convert km coordinates to meter.
// Let's check if we still want this automatically conversion occur or we
// want the actual axisUnit to be used.
if (!NetCDFCRSUtilities.isConvertAxisKm() && axisUnit != null) {
// We assume that unit will be the same for Lon/GeoX
crsProperties.put(ProjectionBuilder.AXIS_UNIT, axisUnit);
}
// create the envelope
CoordinateReferenceSystem crs = NetCDFCRSUtilities.WGS84;
// Looks for Projection definition
if (!isLonLat) {
// First, looks for a global crs (it may have been defined
// as a NetCDF output write operation) to be used as fallback
CoordinateReferenceSystem defaultCrs = NetCDFProjection.lookForDatasetCRS(dataset);
// Then, look for a per variable CRS
CoordinateReferenceSystem localCrs =
NetCDFProjection.lookForVariableCRS(dataset, defaultCrs, crsProperties);
if (localCrs != null) {
// lookup for a custom EPSG if any
crs = NetCDFProjection.lookupForCustomEpsg(localCrs);
}
}
ReferencedEnvelope boundingBox =
new ReferencedEnvelope(xLon[0], xLon[1], yLat[0], yLat[1], crs);
boundingBoxes.put(NetCDFGeoreferenceManager.DEFAULT, boundingBox);
}
public void dispose() {
if (boundingBoxes != null) {
boundingBoxes.clear();
}
}
public ReferencedEnvelope getBBox(String bboxName) {
return boundingBoxes.get(bboxName);
}
}
/**
* BBoxGetter Implementation for multiple bounding boxes management. Use it for NetCDF datasets
* defining multiple bounding boxes.
*/
class MultipleBBoxGetter extends BBoxGetter {
/**
* Class delegated to retrieve and compute the coordinates from the available coordinate
* variables.
*/
class CoordinatesManager {
// Map for longitude/easting coordinates
private Map<String, double[]> xLonCoords = new HashMap<>();
// Map for latitude/northing coordinates
private Map<String, double[]> yLatCoords = new HashMap<>();
/** Set latitude/northing coordinates */
public void setYLat(CoordinateVariable<?> cv) throws IOException {
double[] yLat = new double[2];
getCoordinate(cv, yLat);
if (yLat[1] > yLat[0]) {
setNeedsFlipping(true);
} else {
setNeedsFlipping(false);
}
yLatCoords.put(cv.getName(), yLat);
}
/** Set longitude/easting coordinates */
public void setXlon(CoordinateVariable<?> cv) throws IOException {
double[] xLon = new double[2];
getCoordinate(cv, xLon);
xLonCoords.put(cv.getName(), xLon);
}
/**
* Compute a {@link ReferencedEnvelope} instance, from the specified coordinate names
*/
public ReferencedEnvelope computeEnvelope(
String coordinates, CoordinateReferenceSystem crs) {
Utilities.ensureNonNull("coordinates", coordinates);
String[] coords = coordinates.split(" ");
double[] xLon = null;
double[] yLat = null;
// Get the previously computed coordinates
for (String coord : coords) {
if (xLonCoords.containsKey(coord)) {
xLon = xLonCoords.get(coord);
} else if (yLatCoords.containsKey(coord)) {
yLat = yLatCoords.get(coord);
}
}
if (xLon == null || yLat == null) {
throw new IllegalArgumentException(
"Unable to initialize the boundingBox due to missing coordinates ");
}
return new ReferencedEnvelope(xLon[0], xLon[1], yLat[0], yLat[1], crs);
}
/**
* Get the coordinates available for this variable. They are retrieved from the
* {@linkplain NetCDFUtilities#COORDINATES} coordinates attribute. If missing, they will
* be retrieved from the dimension names
*/
public String getCoordinateNames(Variable var) {
String coordinates = null;
Attribute coordinatesAttribute = var.findAttribute(NetCDFUtilities.COORDINATES);
boolean hasXLon = false;
boolean hasYLat = false;
if (coordinatesAttribute != null) {
// Look for coordinates attribute first
coordinates = coordinatesAttribute.getStringValue();
} else if (!(var instanceof CoordinateAxis)) {
// fallback on dimensions to coordinates mapping
String dimensions = var.getDimensionsString();
if (dimensions != null && !dimensions.isEmpty()) {
coordinates = dimensions;
}
}
if (coordinates != null) {
for (String coord : coordinates.split(" ")) {
if (xLonCoords.containsKey(coord)) {
hasXLon = true;
} else if (yLatCoords.containsKey(coord)) {
hasYLat = true;
}
}
}
return (hasXLon && hasYLat) ? coordinates : null;
}
public void dispose() {
// release resources.
if (xLonCoords != null) {
xLonCoords.clear();
xLonCoords = null;
}
if (yLatCoords != null) {
yLatCoords.clear();
yLatCoords = null;
}
}
}
public MultipleBBoxGetter() throws FactoryException, IOException {
super();
}
@Override
protected void init() throws FactoryException, IOException {
isLonLat = false;
CoordinatesManager manager = new CoordinatesManager();
for (CoordinateVariable<?> cv : getCoordinatesVariables()) {
if (cv.isNumeric()) {
// is it lat or lon (or geoY or geoX)?
AxisType type = cv.getAxisType();
switch (type) {
case GeoY:
case Lat:
manager.setYLat(cv);
break;
case GeoX:
case Lon:
manager.setXlon(cv);
break;
default:
break;
}
}
}
// create the envelope
CoordinateReferenceSystem crs = NetCDFCRSUtilities.WGS84;
// Looking for all coordinates pairs
List<Variable> variables = dataset.getVariables();
for (Variable var : variables) {
Attribute gridMappingAttribute = var.findAttribute(NetCDFUtilities.GRID_MAPPING);
String coordinates = manager.getCoordinateNames(var);
if (coordinates != null && !boundingBoxes.containsKey(coordinates)) {
// Computing the bbox
crs = lookForCrs(crs, gridMappingAttribute, var);
ReferencedEnvelope boundingBox = manager.computeEnvelope(coordinates, crs);
boundingBoxes.put(coordinates, boundingBox);
}
}
manager.dispose();
}
@Override
public ReferencedEnvelope getBBox(String shortName) {
// find auxiliary coordinateVariable
String coordinates = getCoordinatesForVariable(shortName);
if (coordinates != null) {
return boundingBoxes.get(coordinates);
}
throw new IllegalArgumentException(
"Unable to find an envelope for the provided variable: " + shortName);
}
/** Look for a Coordinate Reference System */
private CoordinateReferenceSystem lookForCrs(
CoordinateReferenceSystem crs, Attribute gridMappingAttribute, Variable var)
throws FactoryException {
if (gridMappingAttribute != null) {
String gridMappingName = gridMappingAttribute.getStringValue();
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("The variable refers to gridMapping: " + gridMappingName);
}
Variable mapping = dataset.findVariable(null, gridMappingName);
if (mapping != null) {
CoordinateReferenceSystem localCrs = NetCDFProjection.parseProjection(mapping);
if (localCrs != null) {
// lookup for a custom EPSG if any
crs = NetCDFProjection.lookupForCustomEpsg(localCrs);
}
} else if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.warning(
"The specified variable "
+ var.getFullName()
+ " declares a gridMapping = "
+ gridMappingName
+ " but that mapping doesn't exist.");
}
}
return crs;
}
}
private static final Logger LOGGER = Logging.getLogger(NetCDFGeoreferenceManager.class);
/**
* Set it to {@code true} in case the dataset has a single bbox. Set it to {@code false} in case
* the dataset has multiple 2D coordinates definitions and bboxes. Used to quickly access the
* bbox in case there is only a single one.
*/
private boolean hasSingleBBox = true;
/** The underlying BoundingBox getter instance */
private BBoxGetter bbox;
/**
* Class mapping the NetCDF dimensions to related coordinate variables/axis names. Typical
* example is a "time" coordinate variable containing the time instants for the "time"
* dimensions.
*/
class DimensionMapper {
/**
* Mapping containing the relation between a dimension and the related coordinate variable
*/
private Map<String, String> dimensions;
/** Return the whole dimension to coordinates mapping */
public Map<String, String> getDimensions() {
return dimensions;
}
/** Return the dimension names handled by this mapper */
public Set<String> getDimensionNames() {
return dimensions.keySet();
}
/** Return the dimension name associated to the specified coordinateVariable. */
public String getDimension(String coordinateVariableName) {
return dimensions.get(coordinateVariableName);
}
/** Mapper parsing the coordinateVariables. */
public DimensionMapper(Map<String, CoordinateVariable<?>> coordinates) {
// check other dimensions
int coordinates2Dx = 0;
int coordinates2Dy = 0;
dimensions = new HashMap<>();
Set<String> coordinateKeys = new TreeSet<>(coordinates.keySet());
for (String key : coordinateKeys) {
// get from coordinate vars
final CoordinateVariable<?> cv = getCoordinateVariable(key);
if (cv != null) {
final String name = cv.getName();
AxisType axisType = cv.getAxisType();
switch (axisType) {
case GeoX:
case Lon:
coordinates2Dx++;
continue;
case GeoY:
case Lat:
coordinates2Dy++;
continue;
case Height:
case Pressure:
case RadialElevation:
case RadialDistance:
case GeoZ:
if (NetCDFCRSUtilities.VERTICAL_AXIS_NAMES.contains(name)
&& !dimensions.containsKey(NetCDFUtilities.ELEVATION_DIM)) {
// Main elevation dimension
dimensions.put(NetCDFUtilities.ELEVATION_DIM, name);
} else {
// additional elevation dimension
dimensions.put(name.toUpperCase(), name);
}
break;
case Time:
if (!dimensions.containsKey(NetCDFUtilities.TIME_DIM)) {
// Main time dimension
dimensions.put(NetCDFUtilities.TIME_DIM, name);
} else {
// additional time dimension
dimensions.put(name.toUpperCase(), name);
}
break;
default:
// additional dimension
dimensions.put(name.toUpperCase(), name);
break;
}
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine(
"Null coordinate variable: '"
+ key
+ "' while processing input: "
+ dataset.getLocation());
}
}
}
if (coordinates2Dx + coordinates2Dy > 2) {
if (coordinates2Dx != coordinates2Dy) {
throw new IllegalArgumentException(
"number of x/lon coordinates must match number of y/lat coordinates");
}
// More than 2D coordinates have been found, as an instance lon1, lat1, lon2, lat2
// Report that by unsetting the singleBbox flag.
setHasSingleBBox(false);
}
}
/** Update the dimensions mapping */
public void remap(String dimension, String name) {
dimensions.put(dimension, name);
}
}
/** Map containing coordinates being wrapped by variables */
private Map<String, CoordinateVariable<?>> coordinatesVariables;
static final String DEFAULT = "Default";
/** Flag reporting if the input file needs flipping or not */
private boolean needsFlipping = false;
/** The underlying NetCDF dataset */
private NetcdfDataset dataset;
/** The DimensionMapper instance */
private DimensionMapper dimensionMapper;
/** Flag reporting if the dataset is lonLat to avoid projections checks */
private boolean isLonLat;
public boolean isNeedsFlipping() {
return needsFlipping;
}
public void setNeedsFlipping(boolean needsFlipping) {
this.needsFlipping = needsFlipping;
}
public boolean isLonLat() {
return isLonLat;
}
public boolean isHasSingleBBox() {
return hasSingleBBox;
}
public void setHasSingleBBox(boolean hasSingleBBox) {
this.hasSingleBBox = hasSingleBBox;
}
public CoordinateVariable<?> getCoordinateVariable(String name) {
return coordinatesVariables.get(name);
}
public Collection<CoordinateVariable<?>> getCoordinatesVariables() {
return coordinatesVariables.values();
}
public void dispose() {
if (coordinatesVariables != null) {
coordinatesVariables.clear();
}
bbox.dispose();
}
public ReferencedEnvelope getBoundingBox(String shortName) {
return bbox.getBBox(hasSingleBBox ? DEFAULT : shortName);
}
public CoordinateReferenceSystem getCoordinateReferenceSystem(String shortName) {
ReferencedEnvelope envelope = getBoundingBox(shortName);
if (envelope != null) {
return envelope.getCoordinateReferenceSystem();
}
throw new IllegalArgumentException(
"Unable to find a CRS for the provided variable: " + shortName);
}
private String getCoordinatesForVariable(String shortName) {
Variable var = dataset.findVariable(null, shortName);
if (var != null) {
// Getting the coordinates attribute
Attribute attribute = var.findAttribute(NetCDFUtilities.COORDINATES);
if (attribute != null) {
return attribute.getStringValue();
} else {
return var.getDimensionsString();
}
}
return null;
}
public Collection<CoordinateVariable<?>> getCoordinatesVariables(String shortName) {
if (hasSingleBBox) {
return coordinatesVariables.values();
} else {
String coordinates = getCoordinatesForVariable(shortName);
String[] coords = coordinates.split(" ");
List<CoordinateVariable<?>> coordVar = new ArrayList<>();
for (String coord : coords) {
coordVar.add(coordinatesVariables.get(coord));
}
return coordVar;
}
}
public DimensionMapper getDimensionMapper() {
return dimensionMapper;
}
/**
* Main constructor to setup the NetCDF Georeferencing based on the available information stored
* within the NetCDF dataset.
*/
public NetCDFGeoreferenceManager(NetcdfDataset dataset) {
this.dataset = dataset;
initCoordinates();
try {
initBBox();
} catch (IOException | FactoryException ioe) {
throw new RuntimeException(ioe);
}
}
/**
* Parse the CoordinateAxes of the dataset and setup proper {@link CoordinateVariable} instances
* on top of it and proper mapping between NetCDF dimensions and related coordinate variables.
*/
private void initCoordinates() {
// get the coordinate variables
Map<String, CoordinateVariable<?>> coordinates = new HashMap<>();
Set<String> unsupported = NetCDFUtilities.getUnsupportedDimensions();
Set<String> ignored = NetCDFUtilities.getIgnoredDimensions();
for (CoordinateAxis axis : dataset.getCoordinateAxes()) {
final int axisDimensions = axis.getDimensions().size();
if (axisDimensions > 0 && axisDimensions < 3) {
String axisName = axis.getFullName();
if (axis.getAxisType() != null) {
coordinates.put(axisName, CoordinateVariable.create(axis));
} else {
// Workaround for Unsupported Axes
if (unsupported.contains(axisName)) {
axis.setAxisType(AxisType.GeoZ);
coordinates.put(axisName, CoordinateVariable.create(axis));
// Workaround for files that have a time dimension, but in a format that
// could not be parsed
} else if ("time".equals(axisName)) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine(
"Detected unparseable unit string in time axis: '"
+ axis.getUnitsString()
+ "'.");
}
axis.setAxisType(AxisType.Time);
coordinates.put(axisName, CoordinateVariable.create(axis));
} else if (!ignored.contains(axisName)) {
LOGGER.warning(
"Unsupported axis: "
+ axis
+ " in input: "
+ dataset.getLocation()
+ " has been found");
}
}
}
}
coordinatesVariables = coordinates;
dimensionMapper = new DimensionMapper(coordinates);
}
/** Initialize the bbox getter */
private void initBBox() throws IOException, FactoryException {
bbox = hasSingleBBox ? new BBoxGetter() : new MultipleBBoxGetter();
}
/**
* Get the bounding box coordinates from the provided coordinateVariable. The resulting
* coordinates will be stored in the provided array. The convention is that the stored
* coordinates represent the center of the cell so we apply a half pixel offset to go to the
* corner.
*/
private void getCoordinate(CoordinateVariable<?> cv, double[] coordinate) throws IOException {
if (cv.isRegular()) {
coordinate[0] = cv.getStart() - (cv.getIncrement() / 2d);
coordinate[1] = coordinate[0] + cv.getIncrement() * (cv.getSize());
} else {
double min = ((Number) cv.getMinimum()).doubleValue();
double max = ((Number) cv.getMaximum()).doubleValue();
double incr = (max - min) / (cv.getSize() - 1);
coordinate[0] = min - (incr / 2d);
coordinate[1] = max + (incr / 2d);
}
}
}
| lgpl-2.1 |
yyhpys/ccnx-trace-interest | android/CCNx-Android-Lib/src/org/ccnx/android/ccnlib/CCNxWrapper.java | 7952 | /*
* CCNx Android Helper Library.
*
* Copyright (C) 2010, 2011 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.android.ccnlib;
import java.util.List;
import java.util.Properties;
import java.util.Map.Entry;
import org.ccnx.android.ccnlib.CCNxServiceStatus.SERVICE_STATUS;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
/**
* Wrap up the AIDL calls to a CCNxService. Hide all the ugly RPC from
* the user of the services.
*/
public abstract class CCNxWrapper {
public String TAG = "CCNxWrapper";
private static final int DEFAULT_WAIT_FOR_READY = 60000;
private Object _lock = new Object();
// Timeout to wait for ready in ms
private int waitForReadyTimeout = DEFAULT_WAIT_FOR_READY;
protected String serviceClassName = "";
protected String serviceName = "";
protected String serviceType = TAG;
protected ServiceConnection sConn;
protected Object iServiceLock = new Object();
protected ICCNxService iService = null;
protected String OPTION_LOG_LEVEL = "0";
protected Properties options = new Properties();
CCNxServiceCallback _scb;
SERVICE_STATUS status = SERVICE_STATUS.SERVICE_OFF;
Context _ctx;
private IStatusCallback _cb = new IStatusCallback.Stub() {
public void status(int st){
Log.d(TAG,"Received a status update.. " + status.name());
synchronized(_lock) {
setStatus(SERVICE_STATUS.fromOrdinal(st));
if(SERVICE_STATUS.SERVICE_FINISHED.equals(status)){
setStatus(SERVICE_STATUS.SERVICE_OFF);
}
}
issueCallback();
}
};
public CCNxWrapper(Context ctx){
_ctx = ctx;
}
public void setCallback(CCNxServiceCallback scb){
_scb = scb;
}
protected void issueCallback(){
_scb.newCCNxStatus(status);
}
/**
* Start the service. If the service is running we will not try to start it
* we will only try to bind to it
* @return true if we are bound, false if we are not, some error occurred
*/
public boolean startService(){
Log.d(TAG,"startService()");
if(!isRunning()){
_ctx.startService(getStartIntent());
} else {
setStatus(SERVICE_STATUS.SERVICE_RUNNING);
issueCallback();
}
bindService();
return isBound();
}
public void bindIfRunning(){
Log.d(TAG,"If Running, Bind");
if(isRunning()){
bindService();
}
}
/**
* Check whether we are bound to the running service
* @return true if we are bound, false if we are not
*/
public boolean isBound(){
synchronized(iServiceLock) {
return(iService != null);
}
}
protected void bindService(){
sConn = new ServiceConnection(){
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(TAG, " Service Connected");
synchronized(iServiceLock) {
iService = ICCNxService.Stub.asInterface(binder);
try {
iService.registerStatusCallback(_cb);
SERVICE_STATUS st = SERVICE_STATUS.fromOrdinal(iService.getStatus());
Log.i(TAG,"bindService sets status: " + st);
setStatus(st);
} catch (RemoteException e) {
// Did the service crash?
e.printStackTrace();
}
}
issueCallback();
}
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG, " Service Disconnected");
synchronized(iServiceLock) {
iService = null;
}
}
};
_ctx.bindService(getBindIntent(), sConn, Context.BIND_AUTO_CREATE);
}
protected void unbindService(){
synchronized(iServiceLock) {
if(isBound()){
_ctx.unbindService(sConn);
}
iService = null;
}
}
public void stopService(){
synchronized(iServiceLock) {
try {
if( null != iService)
iService.stop();
} catch (RemoteException e) {
e.printStackTrace();
}
unbindService();
}
_ctx.stopService(new Intent(serviceName));
}
public boolean isRunning(){
ActivityManager am = (ActivityManager) _ctx.getSystemService(Activity.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(50);
for(ActivityManager.RunningServiceInfo s : services){
if(s.service.getClassName().equalsIgnoreCase(serviceClassName)){
Log.d(TAG,"Found " + serviceClassName + " Service Running");
return true;
}
}
Log.d(TAG,serviceClassName + " Not Running");
return false;
}
/**
* Sets the default timeout to be used for the waitForReady() call.
* Set it to 0 to not use a timeout.
*
* @param timeout timeout to be used in waitForReady()
*/
public void setWaitForReadyTimeout(int timeout){
waitForReadyTimeout = timeout;
}
/**
* waits until this service is in state RUNNING. (blocking call)
* There is a timeout associated with this wait. It can be changed
* using the setWaitForReadyTimeout() function. If set to 0 it will wait forever.
*
* Alternatively, you can call waitForReady() and give it the timeout parameter as the argument.
*
* @return true if we are ready, false if we timed out
*/
public boolean waitForReady(){
return waitForReady(waitForReadyTimeout);
}
/**
* waits until the service is in state RUNNING. (blocking call)
* This function takes a timeout as a parameter. If the timeout is triggered it will
* return false. If timeout is set to 0 it won't be used and wait will block indefinitely.
*
* This function does not use the default value ser by setWaitForReadyTimeout().
*
* @param timeout timeout passed to the wait() call.
* @return true if we are ready, false otherwise
*/
public boolean waitForReady(int timeout){
synchronized(_lock){
while(!SERVICE_STATUS.SERVICE_RUNNING.equals(status)){
try {
if(timeout == 0){
_lock.wait();
} else {
_lock.wait(waitForReadyTimeout);
}
} catch (InterruptedException e) {
// Our timeout expired
return false;
}
}
}
return true;
}
public boolean isReady(){
return (SERVICE_STATUS.SERVICE_RUNNING.equals(status));
}
public void setOption(String key, String value) {
options.setProperty(key, value);
}
public void clearOptions() {
options.clear();
}
protected void fillIntentOptions(Intent i) {
for(Entry<Object, Object> entry : options.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
i.putExtra(key, value);
Log.i(TAG, "Adding option " + key + " = " + value);
}
}
/**
* Create an Intent to be issued to bind to the Service. It will be used as the parameter to bindService()
* This function is useful for adding "extras" to the intent
*
* @return Intent to start this service
*/
protected abstract Intent getBindIntent();
/**
* Create an Intent to be issued to start the Service. It will be used as the parameter to startService()
* This function is useful for adding "extras" to the intent
*
* @return Intent to start this service
*/
protected abstract Intent getStartIntent();
public SERVICE_STATUS getStatus(){
return status;
}
protected void setStatus(SERVICE_STATUS st) {
Log.i(TAG,"setStatus = " + st);
synchronized(_lock) {
status = st;
_lock.notifyAll();
}
}
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/metadata/AttributeRegistry.java | 1762 | /*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.core.metadata;
/**
* The attribute registry allows to update the available attributes for an element. The update should happen during the
* boot-process or reports may behave inconsistently.
*/
public interface AttributeRegistry {
/**
* Adds a new or updates the metadata for an existing attribute of a report-element.
*
* @param metaData
* the new metadata object.
*/
public void putAttributeDescription( AttributeMetaData metaData );
/**
* Retrieves the metadata for an attribute by namespace and name.
*
* @param namespace
* the namespace for the attribute.
* @param name
* the attribute name.
* @return the attribute definition or null, if the attribute is not defined.
*/
public AttributeMetaData getAttributeDescription( String namespace, String name );
}
| lgpl-2.1 |
attunetc/ehr | src/com/wdeanmedical/ehr/entity/ICD10AM.java | 4146 | /*
* WDean Medical is distributed under the
* GNU Lesser General Public License (GNU LGPL).
* For details see: http://www.wdeanmedical.com
* copyright 2013-2014 WDean Medical
*/
package com.wdeanmedical.ehr.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "icd_10am")
public class ICD10AM extends BaseEntity implements Serializable {
private static final long serialVersionUID = -6643559192047668494L;
private Integer level;
private String code;
private String description;
private Boolean dagger;
private Boolean asterisk;
private Boolean valid;
private Boolean austCode;
private String longDesc;
private Date effectiveFrom;
private Date inactive;
private Date reactivated;
private Integer sex;
private Integer sType;
private Integer ageL;
private Integer ageH;
private Integer aType;
private Boolean rDiag;
private Integer morphCode;
private Date conceptChange;
private Boolean unacceptPdx;
public ICD10AM() {
}
@Column(name = "description")
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
@Column(name = "code")
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
@Column(name = "level")
public Integer getLevel() { return level; }
public void setLevel(Integer level) { this.level = level; }
@Column(name = "dagger")
public Boolean getDagger() { return dagger; }
public void setDagger(Boolean dagger) { this.dagger = dagger; }
@Column(name = "asterisk")
public Boolean getAsterisk() { return asterisk; }
public void setAsterisk(Boolean asterisk) { this.asterisk = asterisk; }
@Column(name = "valid")
public Boolean getValid() { return valid; }
public void setValid(Boolean valid) { this.valid = valid; }
@Column(name = "aust_code")
public Boolean getAustCode() { return austCode; }
public void setAustCode(Boolean austCode) { this.austCode = austCode; }
@Column(name = "long_desc")
public String getLongDesc() { return longDesc; }
public void setLongDesc(String longDesc) { this.longDesc = longDesc; }
@Column(name = "effective_from")
public Date getEffectiveFrom() { return effectiveFrom; }
public void setEffectiveFrom(Date effectiveFrom) { this.effectiveFrom = effectiveFrom; }
@Column(name = "inactive")
public Date getInactive() { return inactive; }
public void setInactive(Date inactive) { this.inactive = inactive; }
@Column(name = "reactivated")
public Date getReactivated() { return reactivated; }
public void setReactivated(Date reactivated) { this.reactivated = reactivated; }
@Column(name = "sex")
public Integer getSex() { return sex; }
public void setSex(Integer sex) { this.sex = sex; }
@Column(name = "s_type")
public Integer getsType() { return sType; }
public void setsType(Integer sType) { this.sType = sType; }
@Column(name = "age_l")
public Integer getAgeL() { return ageL; }
public void setAgeL(Integer ageL) { this.ageL = ageL; }
@Column(name = "age_h")
public Integer getAgeH() { return ageH; }
public void setAgeH(Integer ageH) { this.ageH = ageH; }
@Column(name = "a_type")
public Integer getaType() { return aType; }
public void setaType(Integer aType) { this.aType = aType; }
@Column(name = "r_diag")
public Boolean getrDiag() { return rDiag; }
public void setrDiag(Boolean rDiag) { this.rDiag = rDiag; }
@Column(name = "morph_code")
public Integer getMorphCode() { return morphCode; }
public void setMorphCode(Integer morphCode) { this.morphCode = morphCode; }
@Column(name = "concept_change")
public Date getConceptChange() { return conceptChange; }
public void setConceptChange(Date conceptChange) { this.conceptChange = conceptChange; }
@Column(name = "unaccept_pdx")
public Boolean getUnacceptPdx() { return unacceptPdx; }
public void setUnacceptPdx(Boolean unacceptPdx) { this.unacceptPdx = unacceptPdx; }
}
| lgpl-2.1 |
syncer/swingx | swingx-beaninfo/src/main/java/org/jdesktop/swingx/JXListBeanInfo.java | 1400 | /*
* $Id: JXListBeanInfo.java 3846 2010-10-21 15:49:30Z kschaefe $
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx;
import org.jdesktop.beans.BeanInfoSupport;
/**
*
* @author rbair
*/
public class JXListBeanInfo extends BeanInfoSupport {
/** Creates a new instance of JXListBeanInfo */
public JXListBeanInfo() {
super(JXList.class);
}
@Override
protected void initialize() {
setPreferred(true, "highlighters");
// setPropertyEditor(HighlighterPropertyEditor.class, "highlighters");
}
}
| lgpl-2.1 |
jbossws/jbossws-cxf | modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/samples/exception/server/JBWS3945Servlet.java | 2130 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.ws.jaxws.samples.exception.server;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JBWS3945Servlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setStatus(400);
res.setContentType("application/soap+xml");
res.getOutputStream().println("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"><soap:Body>" +
"<soap:Fault><soap:Code><soap:Value>soap:Sender</soap:Value><soap:Subcode><soap:Value xmlns:ns1=\"http://ws.gss.redhat.com/\">ns1:AnException</soap:Value></soap:Subcode>" +
"</soap:Code><soap:Reason><soap:Text xml:lang=\"it\">this is a fault string!</soap:Text></soap:Reason><soap:Role>mr.actor</soap:Role><soap:Detail><test/></soap:Detail>" +
"</soap:Fault></soap:Body></soap:Envelope>");
}
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | engine/extensions-kettle/src/main/java/org/pentaho/reporting/engine/classic/extensions/datasources/kettle/parser/KettleTransFromRepositoryReadHandler.java | 2814 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.extensions.datasources.kettle.parser;
import org.pentaho.reporting.engine.classic.extensions.datasources.kettle.KettleTransFromRepositoryProducer;
import org.pentaho.reporting.engine.classic.extensions.datasources.kettle.KettleTransformationProducer;
import org.pentaho.reporting.libraries.xmlns.parser.ParseException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
public class KettleTransFromRepositoryReadHandler extends AbstractKettleTransformationProducerReadHandler {
private String transformation;
private String directory;
public KettleTransFromRepositoryReadHandler() {
}
/**
* Starts parsing.
*
* @param attrs the attributes.
* @throws SAXException if there is a parsing error.
*/
protected void startParsing( final Attributes attrs ) throws SAXException {
super.startParsing( attrs );
transformation = attrs.getValue( getUri(), "transformation" );
if ( transformation == null ) {
throw new ParseException( "Required attribute 'transformation' is not defined" );
}
directory = attrs.getValue( getUri(), "directory" );
if ( directory == null ) {
throw new ParseException( "Required attribute 'directory' is not defined" );
}
}
public String getTransformation() {
return transformation;
}
public String getDirectory() {
return directory;
}
/**
* Returns the object for this element or null, if this element does not create an object.
*
* @return the object.
*/
public KettleTransformationProducer getObject() {
KettleTransFromRepositoryProducer kettleTransFromRepositoryProducer = new KettleTransFromRepositoryProducer
( getRepositoryName(), directory, transformation, getStepName(), getUsername(), getPassword(),
getDefinedArgumentNames(), getDefinedVariableNames() );
kettleTransFromRepositoryProducer.setStopOnError( isStopOnError() );
return kettleTransFromRepositoryProducer;
}
}
| lgpl-2.1 |
RemiKoutcherawy/exist | exist-core/src/main/java/org/exist/protocolhandler/embedded/InMemoryOutputStream.java | 4452 | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2017 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.protocolhandler.embedded;
import java.io.IOException;
import java.io.InputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.collections.IndexInfo;
import org.exist.dom.persistent.DocumentImpl;
import org.exist.protocolhandler.xmldb.XmldbURL;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.storage.lock.Lock;
import org.exist.storage.lock.Lock.LockMode;
import org.exist.storage.txn.TransactionManager;
import org.exist.storage.txn.Txn;
import org.exist.util.MimeTable;
import org.exist.util.MimeType;
import org.exist.util.io.FastByteArrayInputStream;
import org.exist.util.io.FastByteArrayOutputStream;
import org.exist.xmldb.XmldbURI;
import org.xml.sax.InputSource;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*/
public class InMemoryOutputStream extends FastByteArrayOutputStream {
private final static Logger LOG = LogManager.getLogger(InMemoryOutputStream.class);
XmldbURL xmldbURL;
public InMemoryOutputStream(XmldbURL xmldbURL) {
this.xmldbURL = xmldbURL;
}
@Override
public void close() throws IOException {
super.close();
stream(xmldbURL, toByteArray());
}
public void stream(XmldbURL xmldbURL, byte[] data) throws IOException {
BrokerPool db;
try {
db = BrokerPool.getInstance();
} catch (EXistException e) {
throw new IOException(e);
}
try (DBBroker broker = db.getBroker()) {
final XmldbURI collectionUri = XmldbURI.create(xmldbURL.getCollection());
final XmldbURI documentUri = XmldbURI.create(xmldbURL.getDocumentName());
final TransactionManager transact = db.getTransactionManager();
try (final Txn txn = transact.beginTransaction()) {
// Collection collection = broker.openCollection(collectionUri, LockMode.WRITE_LOCK);
Collection collection = broker.getOrCreateCollection(txn, collectionUri);
if (collection == null) {
throw new IOException("Resource " + collectionUri.toString() + " is not a collection.");
}
Lock lock = collection.getLock();
if (!lock.isLockedForWrite()) {
txn.acquireLock(lock, LockMode.WRITE_LOCK);
}
if (collection.hasChildCollection(broker, documentUri)) {
throw new IOException("Resource " + documentUri.toString() + " is a collection.");
}
MimeType mime = MimeTable.getInstance().getContentTypeFor(documentUri);
String contentType = null;
if (mime != null) {
contentType = mime.getName();
} else {
mime = MimeType.BINARY_TYPE;
}
if (mime.isXMLType()) {
final InputSource inputsource = new InputSource(new FastByteArrayInputStream(data));
final IndexInfo info = collection.validateXMLResource(txn, broker, documentUri, inputsource);
final DocumentImpl doc = info.getDocument();
doc.getMetadata().setMimeType(contentType);
collection.store(txn, broker, info, inputsource);
} else {
try (final InputStream is = new FastByteArrayInputStream(data)) {
collection.addBinaryResource(txn, broker, documentUri, is, contentType, data.length);
}
}
txn.commit();
}
} catch (final IOException ex) {
LOG.debug(ex);
throw ex;
} catch (final Exception ex) {
LOG.debug(ex);
throw new IOException(ex.getMessage(), ex);
}
}
}
| lgpl-2.1 |
windauer/exist | extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/RestXqServiceRegistryPersistence.java | 10453 | /*
Copyright (c) 2012, Adam Retter
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adam Retter Consulting nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Adam Retter BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.exist.extensions.exquery.restxq.impl;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.Map.Entry;
import javax.xml.namespace.QName;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.EXistException;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.util.Configuration;
import org.exist.util.FileUtils;
import org.exist.util.io.TemporaryFileManager;
import org.exist.xquery.CompiledXQuery;
import org.exquery.ExQueryException;
import org.exquery.restxq.RestXqService;
import org.exquery.restxq.RestXqServiceRegistry;
import org.exquery.restxq.RestXqServiceRegistryListener;
import org.exquery.xquery3.FunctionSignature;
/**
*
* @author <a href="mailto:adam.retter@googlemail.com">Adam Retter</a>
*/
public class RestXqServiceRegistryPersistence implements RestXqServiceRegistryListener {
public final static int REGISTRY_FILE_VERSION = 0x1;
private final static String VERSION_LABEL = "version";
private final static String LABEL_SEP = ": ";
public final static String FIELD_SEP = ",";
public final static String ARITY_SEP = "#";
public final static String REGISTRY_FILENAME = "restxq.registry";
private final Logger log = LogManager.getLogger(getClass());
private final BrokerPool pool;
private final RestXqServiceRegistry registry;
public RestXqServiceRegistryPersistence(final BrokerPool pool, final RestXqServiceRegistry registry) {
this.pool = pool;
this.registry = registry;
}
private BrokerPool getBrokerPool() {
return pool;
}
private RestXqServiceRegistry getRegistry() {
return registry;
}
public void loadRegistry() {
//only load the registry if a serialized registry exists on disk
getRegistryFile(false)
.filter(r -> Files.exists(r))
.filter(r -> Files.isRegularFile(r))
.ifPresent(this::loadRegistry);
}
private void loadRegistry(final Path fRegistry) {
log.info("Loading RESTXQ registry from: " + fRegistry.toAbsolutePath().toString());
try(final LineNumberReader reader = new LineNumberReader(Files.newBufferedReader(fRegistry));
final DBBroker broker = getBrokerPool().getBroker()) {
//read version line first
String line = reader.readLine();
final String versionStr = line.substring(line.indexOf(VERSION_LABEL) + VERSION_LABEL.length() + LABEL_SEP.length());
if(REGISTRY_FILE_VERSION != Integer.parseInt(versionStr)) {
log.error("Unable to load RESTXQ registry file: " + fRegistry.toAbsolutePath().toString() + ". Expected version: " + REGISTRY_FILE_VERSION + " but saw version: " + versionStr);
} else {
while((line = reader.readLine()) != null) {
final String xqueryLocation = line.substring(0, line.indexOf(FIELD_SEP));
final CompiledXQuery xquery = XQueryCompiler.compile(broker, new URI(xqueryLocation));
final List<RestXqService> services = XQueryInspector.findServices(xquery);
getRegistry().register(services);
}
}
} catch(final ExQueryException | IOException | EXistException | URISyntaxException eqe) {
log.error(eqe.getMessage(), eqe);
}
log.info("RESTXQ registry loaded.");
}
@Override
public void registered(final RestXqService service) {
//TODO consider a pause before writing to disk of maybe 1 second or so
//to allow updates to batched together i.e. when one xquery has many resource functions
updateRegistryOnDisk(service, UpdateAction.ADD);
}
@Override
public void deregistered(final RestXqService service) {
//TODO consider a pause before writing to disk of maybe 1 second or so
//to allow updates to batched together i.e. when one xquery has many resource functions
updateRegistryOnDisk(service, UpdateAction.REMOVE);
}
private synchronized void updateRegistryOnDisk(final RestXqService restXqService, final UpdateAction updateAction) {
//we can ignore the change in service provided to this function as args, as we just write the details of all
//services to disk, overwriting the old registry
final Optional<Path> optTmpNewRegistry = getRegistryFile(true);
if(!optTmpNewRegistry.isPresent()) {
log.error("Could not save RESTXQ Registry to disk!");
} else {
final Path tmpNewRegistry = optTmpNewRegistry.get();
log.info("Preparing new RESTXQ registry on disk: " + tmpNewRegistry.toAbsolutePath().toString());
try {
try (final PrintWriter writer = new PrintWriter(Files.newBufferedWriter(tmpNewRegistry, StandardOpenOption.TRUNCATE_EXISTING))) {
writer.println(VERSION_LABEL + LABEL_SEP + REGISTRY_FILE_VERSION);
//get details of RESTXQ functions in XQuery modules
final Map<URI, List<FunctionSignature>> xqueryServices = new HashMap<>();
for (final RestXqService service : getRegistry()) {
List<FunctionSignature> fnNames = xqueryServices.get(service.getResourceFunction().getXQueryLocation());
if (fnNames == null) {
fnNames = new ArrayList<>();
}
fnNames.add(service.getResourceFunction().getFunctionSignature());
xqueryServices.put(service.getResourceFunction().getXQueryLocation(), fnNames);
}
//iterate and save to disk
for (final Entry<URI, List<FunctionSignature>> xqueryServiceFunctions : xqueryServices.entrySet()) {
writer.print(xqueryServiceFunctions.getKey() + FIELD_SEP);
final List<FunctionSignature> fnSigs = xqueryServiceFunctions.getValue();
for (final FunctionSignature fnSig : fnSigs) {
writer.print(qnameToClarkNotation(fnSig.getName()) + ARITY_SEP + fnSig.getArgumentCount());
}
writer.println();
}
}
final Optional<Path> optRegistry = getRegistryFile(false);
if (optRegistry.isPresent()) {
final Path registry = optRegistry.get();
//replace the original registry with the new registry
final Path localTmpNewRegistry = Files.copy(tmpNewRegistry, registry.getParent().resolve(tmpNewRegistry.getFileName()));
Files.move(localTmpNewRegistry, registry, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
log.info("Replaced RESTXQ registry: " + FileUtils.fileName(tmpNewRegistry) + " -> " + FileUtils.fileName(registry));
} else {
throw new IOException("Unable to retrieve existing RESTXQ registry");
}
} catch(final IOException ioe) {
log.error(ioe.getMessage(), ioe);
} finally {
TemporaryFileManager.getInstance().returnTemporaryFile(tmpNewRegistry);
}
}
}
public static String qnameToClarkNotation(final QName qname) {
if(qname.getNamespaceURI() == null) {
return qname.getLocalPart();
} else {
return "{" + qname.getNamespaceURI() + "}" + qname.getLocalPart();
}
}
private enum UpdateAction {
ADD,
REMOVE
}
private Optional<Path> getRegistryFile(final boolean temp) {
try(final DBBroker broker = getBrokerPool().getBroker()) {
final Configuration configuration = broker.getConfiguration();
final Path dataDir = (Path)configuration.getProperty(BrokerPool.PROPERTY_DATA_DIR);
final Path registryFile;
if(temp) {
final TemporaryFileManager temporaryFileManager = TemporaryFileManager.getInstance();
registryFile = temporaryFileManager.getTemporaryFile();
} else {
registryFile = dataDir.resolve(REGISTRY_FILENAME);
}
return Optional.of(registryFile);
} catch(final EXistException | IOException e) {
log.error(e.getMessage(), e);
return Optional.empty();
}
}
} | lgpl-2.1 |
serrapos/opencms-core | src/org/opencms/workplace/CmsLogin.java | 62319 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.workplace;
import org.opencms.db.CmsLoginMessage;
import org.opencms.db.CmsUserSettings;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.i18n.CmsAcceptLanguageHeaderParser;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsMessageContainer;
import org.opencms.json.JSONArray;
import org.opencms.json.JSONException;
import org.opencms.json.JSONObject;
import org.opencms.jsp.CmsJspLoginBean;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.security.CmsOrganizationalUnit;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUriSplitter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;
import org.apache.commons.logging.Log;
/**
* Handles the login of Users to the OpenCms workplace.<p>
*
* @since 6.0.0
*/
public class CmsLogin extends CmsJspLoginBean {
/** Action constant: Default action, display the dialog. */
public static final int ACTION_DISPLAY = 0;
/** Action constant: Login successful. */
public static final int ACTION_LOGIN = 1;
/** Action constant: Logout. */
public static final int ACTION_LOGOUT = 2;
/** The parameter name for the "getoulist" action. */
public static final String PARAM_ACTION_GETOULIST = "getoulist";
/** The parameter name for the "login" action. */
public static final String PARAM_ACTION_LOGIN = "login";
/** The parameter name for the "logout" action. */
public static final String PARAM_ACTION_LOGOUT = "logout";
/** The html id for the login form. */
public static final String PARAM_FORM = "ocLoginForm";
/** The parameter name for the organizational unit. */
public static final String PARAM_OUFQN = "ocOuFqn";
/** The parameter name for the search organizational unit. */
public static final String PARAM_OUSEARCH = "ocOuSearch";
/** The parameter name for the password. */
public static final String PARAM_PASSWORD = "ocPword";
/** The parameter name for the PC type. */
public static final String PARAM_PCTYPE = "ocPcType";
/** The parameter name for the organizational unit. */
public static final String PARAM_PREDEF_OUFQN = "ocPredefOuFqn";
/** The parameter name for the user name. */
public static final String PARAM_USERNAME = "ocUname";
/** The parameter name for the workplace data. */
public static final String PARAM_WPDATA = "ocWpData";
/** PC type constant: private PC. */
public static final String PCTYPE_PRIVATE = "private";
/** PC type constant: public PC. */
public static final String PCTYPE_PUBLIC = "public";
/** The oufqn cookie name. */
private static final String COOKIE_OUFQN = "OpenCmsOuFqn";
/** The PC type cookie name. */
private static final String COOKIE_PCTYPE = "OpenCmsPcType";
/** The username cookie name. */
private static final String COOKIE_USERNAME = "OpenCmsUserName";
/** The workplace data cookie name, value stores following information: ${left},${top},${width},${height}. */
private static final String COOKIE_WP_DATA = "OpenCmsWpData";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsLogin.class);
/** The action to perform. */
private int m_action;
/** The value of the "login" action parameter. */
private String m_actionLogin;
/** The value of the "logout" action parameter. */
private String m_actionLogout;
/** The path to open if direct edit is selected as start view. */
private String m_directEditPath;
/** The locale to use for display, this will not be the workplace locale, but the browser locale. */
private Locale m_locale;
/** The message to display with the dialog in a JavaScrip alert. */
private CmsMessageContainer m_message;
/** The selected organizational unit. */
private CmsOrganizationalUnit m_ou;
/** The value of the organizational unit parameter. */
private String m_oufqn;
/** The list of all organizational units. */
private List<CmsOrganizationalUnit> m_ous;
/** The value of the password parameter. */
private String m_password;
/** The value of the PC type parameter. */
private String m_pcType;
/** The redirect URL after a successful login. */
private String m_requestedResource;
/** The value of the user name parameter. */
private String m_username;
/**
* Public constructor for login page.<p>
*
* @param context the JSP page context object
* @param req the JSP request
* @param res the JSP response
*/
public CmsLogin(PageContext context, HttpServletRequest req, HttpServletResponse res) {
super(context, req, res);
// this page must never be cached
res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
CmsRequestUtil.setNoCacheHeaders(res);
// divine the best locale from the users browser settings
CmsAcceptLanguageHeaderParser parser = new CmsAcceptLanguageHeaderParser(
req,
OpenCms.getWorkplaceManager().getDefaultLocale());
List<Locale> acceptedLocales = parser.getAcceptedLocales();
List<Locale> workplaceLocales = OpenCms.getWorkplaceManager().getLocales();
m_locale = OpenCms.getLocaleManager().getFirstMatchingLocale(acceptedLocales, workplaceLocales);
if (m_locale == null) {
// no match found - use OpenCms default locale
m_locale = OpenCms.getWorkplaceManager().getDefaultLocale();
}
}
/**
* Returns the HTML code for selecting an organizational unit.<p>
*
* @return the HTML code for selecting an organizational unit
*/
public String buildOrgUnitSelector() {
StringBuffer html = new StringBuffer();
html.append("<select style='width: 100%;' size='1' ");
appendId(html, PARAM_OUFQN);
html.append(">\n");
for (CmsOrganizationalUnit ou : getOus()) {
String selected = "";
if (ou.getName().equals(m_oufqn)
|| (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_oufqn) && ou.getName().equals(m_oufqn.substring(1)))) {
selected = " selected='selected'";
}
html.append("<option value='").append(ou.getName()).append("'").append(selected).append(">");
html.append(ou.getDisplayName(m_locale));
html.append("</option>\n");
}
html.append("</select>\n");
return html.toString();
}
/**
* Returns the HTML for the login dialog in it's current state.<p>
*
* @return the HTML for the login dialog
*
* @throws IOException in case a redirect fails
*/
public String displayDialog() throws IOException {
if ((OpenCms.getSiteManager().getSites().size() > 1)
&& !OpenCms.getSiteManager().isWorkplaceRequest(getRequest())) {
// this is a multi site-configuration, but not a request to the configured Workplace site
StringBuffer loginLink = new StringBuffer(256);
loginLink.append(OpenCms.getSiteManager().getWorkplaceSiteMatcher().toString());
loginLink.append(getFormLink());
// send a redirect to the workplace site
getResponse().sendRedirect(loginLink.toString());
return null;
}
CmsObject cms = getCmsObject();
m_message = null;
if (cms.getRequestContext().getCurrentUser().isGuestUser()) {
// user is not currently logged in
m_action = ACTION_DISPLAY;
m_username = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_USERNAME);
if (m_username != null) {
// remove white spaces, can only lead to confusion on user name
m_username = m_username.trim();
}
m_password = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_PASSWORD);
m_actionLogin = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_ACTION_LOGIN);
m_oufqn = getRequest().getParameter(PARAM_OUFQN);
if (m_oufqn == null) {
m_oufqn = getPreDefOuFqn();
}
if (OpenCms.getLoginManager().isEnableSecurity()) {
// security option is enabled, try to get PC type from request parameter
m_pcType = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_PCTYPE);
} else {
// if security option is disabled, just set PC type to "private" to get common login dialog
m_pcType = PCTYPE_PRIVATE;
}
// try to get some info from a cookie
getCookieData();
// set PC type to "public" as default if not already set by cookie, request or if security option is disabled
if (m_pcType == null) {
m_pcType = PCTYPE_PUBLIC;
}
} else {
// user is already logged in
m_oufqn = cms.getRequestContext().getOuFqn();
m_action = ACTION_LOGIN;
m_actionLogout = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_ACTION_LOGOUT);
}
if (m_oufqn == null) {
m_oufqn = CmsOrganizationalUnit.SEPARATOR;
}
String actionGetOus = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_ACTION_GETOULIST);
if (Boolean.TRUE.toString().equals(actionGetOus)) {
return getJsonOrgUnitList();
}
// initialize the right ou
m_ou = null;
try {
m_ou = OpenCms.getOrgUnitManager().readOrganizationalUnit(getCmsObject(), m_oufqn);
} catch (CmsException e) {
m_oufqn = CmsOrganizationalUnit.SEPARATOR;
try {
m_ou = OpenCms.getOrgUnitManager().readOrganizationalUnit(getCmsObject(), m_oufqn);
} catch (CmsException exc) {
LOG.error(exc.getLocalizedMessage(), exc);
}
}
// initialize the requested resource
m_requestedResource = CmsRequestUtil.getNotEmptyParameter(
getRequest(),
CmsWorkplaceManager.PARAM_LOGIN_REQUESTED_RESOURCE);
if (m_requestedResource == null) {
// no resource was requested, use default workplace URI
m_requestedResource = CmsFrameset.JSP_WORKPLACE_URI;
}
if (Boolean.valueOf(m_actionLogin).booleanValue()) {
// login was requested
if ((m_username == null) && (m_password == null)) {
m_message = Messages.get().container(Messages.GUI_LOGIN_NO_DATA_0);
} else if (m_username == null) {
m_message = Messages.get().container(Messages.GUI_LOGIN_NO_NAME_0);
} else if (m_password == null) {
m_message = Messages.get().container(Messages.GUI_LOGIN_NO_PASSWORD_0);
} else if ((m_username != null) && (m_password != null)) {
// try to login with the given user information
login((m_oufqn == null ? CmsOrganizationalUnit.SEPARATOR : m_oufqn) + m_username, m_password);
if (getLoginException() == null) {
// the login was successful
m_action = ACTION_LOGIN;
// set the default project of the user
CmsUserSettings settings = new CmsUserSettings(cms);
// get the direct edit path
m_directEditPath = getDirectEditPath(settings);
try {
CmsProject project = cms.readProject(settings.getStartProject());
if (OpenCms.getOrgUnitManager().getAllAccessibleProjects(cms, project.getOuFqn(), false).contains(
project)) {
// user has access to the project, set this as current project
cms.getRequestContext().setCurrentProject(project);
}
} catch (CmsException e) {
// unable to set the startup project, bad but not critical
LOG.warn(
Messages.get().getBundle().key(
Messages.LOG_LOGIN_NO_STARTUP_PROJECT_2,
m_username,
settings.getStartProject()),
e);
}
} else {
// there was an error during login
if (org.opencms.security.Messages.ERR_LOGIN_FAILED_DISABLED_2 == getLoginException().getMessageContainer().getKey()) {
// the user account is disabled
m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_DISABLED_0);
} else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_TEMP_DISABLED_4 == getLoginException().getMessageContainer().getKey()) {
// the user account is temporarily disabled because of too many login failures
m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_TEMP_DISABLED_0);
} else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_WITH_MESSAGE_1 == getLoginException().getMessageContainer().getKey()) {
// all logins have been disabled be the Administration
CmsLoginMessage loginMessage = OpenCms.getLoginManager().getLoginMessage();
if (loginMessage != null) {
m_message = Messages.get().container(
Messages.GUI_LOGIN_FAILED_WITH_MESSAGE_1,
loginMessage.getMessage());
}
}
if (m_message == null) {
// any other error - display default message
m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_0);
}
}
}
} else if (Boolean.valueOf(m_actionLogout).booleanValue()) {
m_action = ACTION_LOGOUT;
// store the workplace window data
Cookie wpDataCookie = getCookie(COOKIE_WP_DATA);
String wpData = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_WPDATA);
if (wpData != null) {
wpData = CmsEncoder.escapeXml(wpData);
wpDataCookie.setValue(wpData);
setCookie(wpDataCookie, false);
}
// after logout this will automatically redirect to the login form again
logout();
return null;
}
if (m_action == ACTION_LOGIN) {
// clear message
m_message = null;
// login is successful, check if the requested resource can be read
CmsUriSplitter splitter = new CmsUriSplitter(m_requestedResource, true);
String resource = splitter.getPrefix();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(resource)) {
// bad resource name, use workplace as default
resource = CmsFrameset.JSP_WORKPLACE_URI;
}
if (!getCmsObject().existsResource(resource, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
// requested resource does either not exist or is not readable by user
if (CmsFrameset.JSP_WORKPLACE_URI.equals(resource)) {
// we know the Workplace exists, so the user does not have access to the Workplace
// probably this is a "Guest" user in a default setup where "Guest" has no access to the Workplace
m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_NO_WORKPLACE_PERMISSIONS_0);
m_action = ACTION_DISPLAY;
} else if (getCmsObject().existsResource(CmsFrameset.JSP_WORKPLACE_URI)) {
// resource does either not exist or is not readable, but general workplace permissions are granted
m_message = Messages.get().container(Messages.GUI_LOGIN_UNKNOWN_RESOURCE_1, m_requestedResource);
m_requestedResource = CmsFrameset.JSP_WORKPLACE_URI;
} else {
// resource does not exist and no general workplace permissions granted
m_message = Messages.get().container(
Messages.GUI_LOGIN_FAILED_NO_TARGET_PERMISSIONS_1,
m_requestedResource);
m_action = ACTION_DISPLAY;
}
}
if (m_action == ACTION_DISPLAY) {
// the login was invalid
m_requestedResource = null;
// destroy the generated session
HttpSession session = getRequest().getSession(false);
if (session != null) {
session.invalidate();
}
} else {
// successfully logged in, so set the cookie
setCookieData();
}
}
return displayLoginForm();
}
/**
* Gets the login info from the cookies.<p>
*/
public void getCookieData() {
// get the PC type cookie
Cookie pcTypeCookie = getCookie(COOKIE_PCTYPE);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(pcTypeCookie.getValue())) {
// only set the data if needed
if (m_pcType == null) {
m_pcType = pcTypeCookie.getValue();
}
}
if ("null".equals(m_pcType)) {
m_pcType = null;
}
// get other cookies only on private PC types (or if security option is disabled)
if ((m_pcType == null) || PCTYPE_PRIVATE.equals(m_pcType)) {
// get the user name cookie
Cookie userNameCookie = getCookie(COOKIE_USERNAME);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(userNameCookie.getValue())) {
// only set the data if needed
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_username)) {
m_username = userNameCookie.getValue();
}
if (m_pcType == null) {
// set PC type to private PC if the user cookie is found
m_pcType = PCTYPE_PRIVATE;
}
}
if ("null".equals(m_username)) {
m_username = null;
}
// get the organizational unit cookie
Cookie ouFqnCookie = getCookie(COOKIE_OUFQN);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(ouFqnCookie.getValue())) {
// only set the data if needed
if (m_oufqn == null) {
m_oufqn = ouFqnCookie.getValue();
}
}
if ("null".equals(m_oufqn)) {
m_oufqn = null;
}
}
}
/**
* @see org.opencms.jsp.CmsJspLoginBean#getFormLink()
*/
@Override
public String getFormLink() {
if (getPreDefOuFqn() == null) {
return super.getFormLink();
}
String preDefOuFqn = (String)getRequest().getAttribute(PARAM_PREDEF_OUFQN);
try {
OpenCms.getOrgUnitManager().readOrganizationalUnit(getCmsObject(), preDefOuFqn);
} catch (CmsException e) {
// organizational unit does not exist
return super.getFormLink();
}
return link("/system/login" + CmsEncoder.escapeXml(preDefOuFqn));
}
/**
* Returns the available organizational units as JSON array string.<p>
*
* @return the available organizational units as JSON array string
*/
public String getJsonOrgUnitList() {
List<CmsOrganizationalUnit> allOus = getOus();
List<JSONObject> jsonOus = new ArrayList<JSONObject>(allOus.size());
int index = 0;
for (CmsOrganizationalUnit ou : allOus) {
JSONObject jsonObj = new JSONObject();
try {
// 1: OU fully qualified name
jsonObj.put("name", ou.getName());
// 2: OU display name
jsonObj.put("displayname", ou.getDisplayName(m_locale));
// 3: OU simple name
jsonObj.put("simplename", ou.getSimpleName());
// 4: OU description
jsonObj.put("description", ou.getDescription(m_locale));
// 5: selection flag
boolean isSelected = false;
if (ou.getName().equals(m_oufqn)
|| (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_oufqn) && ou.getName().equals(m_oufqn.substring(1)))) {
isSelected = true;
}
jsonObj.put("active", isSelected);
// 6: level of the OU
jsonObj.put("level", CmsResource.getPathLevel(ou.getName()));
// 7: OU index
jsonObj.put("index", index);
// add the generated JSON object to the result list
jsonOus.add(jsonObj);
index++;
} catch (JSONException e) {
// error creating JSON object, skip this OU
}
}
// generate a JSON array from the JSON object list
JSONArray jsonArr = new JSONArray(jsonOus);
return jsonArr.toString();
}
/**
* Sets the login cookies.<p>
*/
public void setCookieData() {
// set the PC type cookie only if security dialog is enabled
if (OpenCms.getLoginManager().isEnableSecurity() && CmsStringUtil.isNotEmpty(m_pcType)) {
Cookie pcTypeCookie = getCookie(COOKIE_PCTYPE);
pcTypeCookie.setValue(m_pcType);
setCookie(pcTypeCookie, false);
}
// only store user name and OU cookies on private PC types
if (PCTYPE_PRIVATE.equals(m_pcType)) {
// set the user name cookie
Cookie userNameCookie = getCookie(COOKIE_USERNAME);
userNameCookie.setValue(m_username);
setCookie(userNameCookie, false);
// set the organizational unit cookie
Cookie ouFqnCookie = getCookie(COOKIE_OUFQN);
ouFqnCookie.setValue(m_oufqn);
setCookie(ouFqnCookie, false);
} else if (OpenCms.getLoginManager().isEnableSecurity() && PCTYPE_PUBLIC.equals(m_pcType)) {
// delete user name and organizational unit cookies
Cookie userNameCookie = getCookie(COOKIE_USERNAME);
setCookie(userNameCookie, true);
Cookie ouFqnCookie = getCookie(COOKIE_OUFQN);
setCookie(ouFqnCookie, true);
}
}
/**
* Appends the JavaScript for the login screen to the given HTML buffer.<p>
*
* @param html the HTML buffer to append the script to
* @param message the message to display after an unsuccessful login
*/
protected void appendDefaultLoginScript(StringBuffer html, CmsMessageContainer message) {
html.append("<script type=\"text/javascript\" src=\"");
html.append(CmsWorkplace.getSkinUri()).append("jquery/packed/jquery.js");
html.append("\"></script>\n");
html.append("<script type=\"text/javascript\">\n");
if (message != null) {
html.append("function showAlert() {\n");
html.append("\talert(\"");
html.append(CmsStringUtil.escapeJavaScript(message.key(m_locale)));
html.append("\");\n");
html.append("}\n");
}
html.append("var orgUnitShow = false;\n");
html.append("var orgUnits = null;\n");
html.append("var activeOu = -1;\n");
html.append("var searchTimeout;\n");
html.append("var searchDefaultValue = \"");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_ORGUNIT_SEARCH_0));
html.append("\";\n");
// triggers the options to select the OU to login to
html.append("function orgUnitSelection() {\n");
html.append("\tif (!orgUnitShow) {\n");
html.append("\t\tif (orgUnits == null) {\n");
html.append("\t\t\t$.post(\"");
html.append(getFormLink());
html.append("\", { ");
html.append(PARAM_ACTION_GETOULIST);
html.append(": \"true\" }");
html.append(", function(data){ fillOrgUnits(data); });\n");
html.append("\t\t}\n");
html.append("\t\tdocument.getElementById('ouSelId').style.display = 'block';\n");
html.append("\t\tdocument.getElementById('ouLabelId').style.display = 'block';\n");
html.append("\t\tdocument.getElementById('ouSearchId').style.display = 'block';\n");
html.append("\t\tdocument.getElementById('ouBtnId').value = '");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_ORGUNIT_SELECT_OFF_0));
html.append("';\n");
html.append("\t} else {\n");
html.append("\t\tdocument.getElementById('ouSelId').style.display = 'none';\n");
html.append("\t\tdocument.getElementById('ouLabelId').style.display = 'none';\n");
html.append("\t\tdocument.getElementById('ouSearchId').style.display = 'none';\n");
html.append("\t\tdocument.getElementById('ouBtnId').value = '");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_ORGUNIT_SELECT_ON_0));
html.append("';\n");
html.append("\t}\n");
html.append("\torgUnitShow = !orgUnitShow;\n");
html.append("\tdocument.getElementById('titleId').style.display = 'block';\n");
html.append("\tdocument.getElementById('titleIdOu').style.display = 'none';\n");
html.append("}\n");
// creates the HTML for the OUs to login to
html.append("function fillOrgUnits(data) {\n");
html.append("\torgUnits = eval(data);\n");
html.append("\tvar html = \"\";\n");
html.append("\tvar foundOu = false;\n");
html.append("\tvar activeIndex = -1;\n");
html.append("\tfor (var i = 0; i < orgUnits.length; i++) {\n");
html.append("\t\tvar currOu = orgUnits[i];\n");
html.append("\t\tvar actClass = \"\";\n");
html.append("\t\tif (currOu.active == true) {\n");
html.append("\t\t\t// this is the active OU\n");
html.append("\t\t\tactiveOu = currOu.index;\n");
html.append("\t\t\tactClass = \" class=\\\"active\\\"\";\n");
html.append("\t\t}\n");
html.append("\t\tvar actStyle = \"\";\n");
html.append("\t\tif (currOu.level > 0) {\n");
html.append("\t\t\tactStyle = \" style=\\\"margin-left: \" + (currOu.level * 20) + \"px;\\\"\";\n");
html.append("\t\t}\n");
html.append("\t\thtml += \"<div\";\n");
html.append("\t\thtml += actClass;\n");
html.append("\t\thtml += actStyle;\n");
html.append("\t\thtml += \" id=\\\"ou\" + currOu.index;\n");
html.append("\t\thtml += \"\\\" onclick=\\\"selectOu('\";\n");
html.append("\t\thtml += currOu.name;\n");
html.append("\t\thtml += \"', \" + currOu.index;\n");
html.append("\t\thtml += \");\\\"><span class=\\\"name\\\">\";\n");
html.append("\t\thtml += currOu.description;\n");
html.append("\t\thtml += \"</span>\";\n");
html.append("\t\tif (currOu.name != \"\") {\n");
html.append("\t\t\thtml += \"<span class=\\\"path\\\"\";\n");
html.append("\t\t\thtml += \" title=\\\"\";\n");
html.append("\t\t\thtml += currOu.name;\n");
html.append("\t\t\thtml += \"\\\">\";\n");
html.append("\t\t\thtml += currOu.simplename;\n");
html.append("\t\t\thtml += \"</span>\";\n");
html.append("\t\t}\n");
html.append("\t\thtml += \"</div>\";\n");
html.append("\t}\n");
html.append("\thtml += \"<div id=\\\"nooufound\\\" style=\\\"display: none;\\\"><span class=\\\"name\\\">\";\n");
html.append("\thtml += \"");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_ORGUNIT_SEARCH_NORESULTS_0));
html.append("\";\n");
html.append("\thtml += \"</span></div>\";\n");
html.append("\t$(\"#ouSelId\").append(html);\n");
html.append("\t$(\"#ouSelId\").slideDown();\n");
html.append("\tscrollToActiveOu();\n");
html.append("}\n");
// shows the list of OUs matching the search term or all OUs if the search term is empty
html.append("function showOrgUnits(searchTerm) {\n");
html.append("\tvar html = \"\";\n");
html.append("\tvar foundOu = false;\n");
html.append("\tfor (var i = 0; i < orgUnits.length; i++) {\n");
html.append("\t\tvar currOu = orgUnits[i];\n");
html.append("\t\tif (searchTerm != \"\") {\n");
html.append("\t\t\tvar stLower = searchTerm.toLowerCase();\n");
html.append("\t\t\tif (currOu.name.toLowerCase().indexOf(stLower )== -1 && currOu.description.toLowerCase().indexOf(stLower) == -1) {\n");
html.append("\t\t\t\t$(\"#ou\" + i + \":visible\").slideUp();\n");
html.append("\t\t\t} else {\n");
html.append("\t\t\t\t$(\"#ou\" + i + \":hidden\").slideDown();\n");
html.append("\t\t\t\t$(\"#ou\" + i).removeAttr(\"style\");\n");
html.append("\t\t\t\tfoundOu = true;\n");
html.append("\t\t\t}\n");
html.append("\t\t} else {\n");
html.append("\t\t\tfoundOu = true;\n");
html.append("\t\t\tvar actStyle = \"\";\n");
html.append("\t\t\tif (currOu.level > 0) {\n");
html.append("\t\t\t\tactStyle = \"margin-left: \" + (currOu.level * 20) + \"px;\";\n");
html.append("\t\t\t}\n");
html.append("\t\t\t$(\"#ou\" + i).attr(\"style\", actStyle);\n");
html.append("\t\t\t$(\"#ou\" + i + \":hidden\").slideDown();\n");
html.append("\t\t}\n");
html.append("\t}\n");
html.append("\tif (searchTerm != \"\" && foundOu == false) {\n");
html.append("\t\t$(\"#nooufound:hidden\").slideDown();\n");
html.append("\t} else {\n");
html.append("\t\t$(\"#nooufound:visible\").slideUp();\n");
html.append("\t}\n");
html.append("\tif (searchTerm == \"\") {\n");
html.append("\t\tscrollToActiveOu();\n");
html.append("\t}\n");
html.append("}\n");
// selects the OU to login to
html.append("function selectOu(ouPath, ouIndex) {\n");
html.append("\tif (ouIndex != -1 && ouIndex != activeOu) {\n");
html.append("\t\t$(\"#ou\" + ouIndex).addClass(\"active\");\n");
html.append("\t\torgUnits[ouIndex].active = true;\n");
html.append("\t\t$(\"#");
html.append(PARAM_OUFQN);
html.append("\").val(ouPath);\n");
html.append("\t\tif (activeOu != -1) {\n");
html.append("\t\t\torgUnits[activeOu].active = false;\n");
html.append("\t\t\t$(\"#ou\" + activeOu).removeClass();\n");
html.append("\t\t}\n");
html.append("\t\tactiveOu = ouIndex;\n");
html.append("\t}\n");
html.append("}\n");
// filters the OUs by the provided search term using a timeout, called by the onkeyup event of the search input field
html.append("function searchOu() {\n");
html.append("\tvar searchElem = $(\"#");
html.append(PARAM_OUSEARCH);
html.append("\");\n");
html.append("\tvar searchTerm = searchElem.val();\n");
html.append("\tif (searchTerm == searchDefaultValue) {");
html.append("\t\tsearchTerm = \"\";");
html.append("\t}");
html.append("\tclearTimeout(searchTimeout);\n");
html.append("\tsearchTimeout = setTimeout(\"showOrgUnits(\\\"\" + trim(searchTerm) + \"\\\");\", 750);\n");
html.append("}\n");
// sets the value of the OU search input field, called by the onfocus and onblur event of the field
html.append("function checkOuValue() {\n");
html.append("\tvar searchElem = $(\"#");
html.append(PARAM_OUSEARCH);
html.append("\");\n");
html.append("\tif (searchElem.val() == searchDefaultValue) {");
html.append("\t\tsearchElem.val(\"\");");
html.append("\t\tsearchElem.removeAttr(\"class\");");
html.append("\t} else if (searchElem.val() == \"\") {");
html.append("\t\tsearchElem.val(searchDefaultValue);");
html.append("\t\tsearchElem.attr(\"class\", \"inactive\");");
html.append("\t}");
html.append("}\n");
// scrolls to the currently selected OU if it is out of visible range
html.append("function scrollToActiveOu() {\n");
html.append("\tif (activeOu != -1) {\n");
html.append("\t\tvar activeOffset = $(\"#ou\" + activeOu).offset().top;\n");
html.append("\t\tvar parentOffset = $(\"#ouSelId\").offset().top;\n");
html.append("\t\tactiveOffset = activeOffset - parentOffset;\n");
html.append("\t\tif (activeOffset > $(\"#ouSelId\").height()) {;\n");
html.append("\t\t\t$(\"#ouSelId\").animate({scrollTop: activeOffset}, 500);\n");
html.append("\t\t};\n");
html.append("\t}\n");
html.append("}\n");
// called when the login form page is loaded
html.append("function doOnload() {\n");
html.append("\tdocument.");
html.append(PARAM_FORM);
html.append(".");
html.append(PARAM_USERNAME);
html.append(".select();\n");
html.append("\tdocument.");
html.append(PARAM_FORM);
html.append(".");
html.append(PARAM_USERNAME);
html.append(".focus();\n");
if (message != null) {
html.append("\tshowAlert();\n");
}
html.append("}\n");
// helper function to trim a given string
html.append("function trim (myStr) {\n");
html.append("\treturn myStr.replace(/^\\s+/, '').replace (/\\s+$/, '');\n");
html.append("}\n");
html.append("</script>\n");
}
/**
* Appends the JavaScript that opens the Direct Edit window after a successful login
* to the given HTML buffer.<p>
*
* @param html the html buffer to append the script to
*/
protected void appendDirectEditOpenerScript(StringBuffer html) {
html.append("<script type=\"text/javascript\">\n");
html.append("function doOnload() {\n");
// the window's name must be the same as in:
// system/workplace/resources/commons/explorer.js
html.append("window.name='preview';");
html.append("window.location.replace('");
html.append(link(m_directEditPath));
html.append("');");
html.append("}\n");
html.append("</script>\n");
}
/**
* Appends the HTML form name/id code for the given id to the given html.<p>
*
* @param html the html where to append the id to
* @param id the id to append
*/
protected void appendId(StringBuffer html, String id) {
html.append(" name=\"");
html.append(id);
html.append("\" id=\"");
html.append(id);
html.append("\" ");
}
/**
* Appends the JavaScript that opens the Workplace window after a successful login
* to the given HTML buffer.<p>
*
* @param html the html buffer to append the script to
* @param requestedResource the requested resource to open in a new window
* @param message the message to display if the originally requested resource is not available
*/
protected void appendWorkplaceOpenerScript(StringBuffer html, String requestedResource, CmsMessageContainer message) {
String winId = "OpenCms" + System.currentTimeMillis();
html.append("<script type=\"text/javascript\">\n");
html.append("function doOnload() {\n");
// display missing resource warning if required
if (message != null) {
html.append("\talert(\"");
html.append(CmsStringUtil.escapeJavaScript(message.key(m_locale)));
html.append("\");\n");
}
// display login message if required
CmsLoginMessage loginMessage = OpenCms.getLoginManager().getLoginMessage();
if ((loginMessage != null) && (loginMessage.isActive())) {
String msg;
if (loginMessage.isLoginForbidden()) {
// login forbidden for normal users, current user must be Administrator
msg = Messages.get().container(
Messages.GUI_LOGIN_SUCCESS_WITH_MESSAGE_2,
loginMessage.getMessage(),
new Date(loginMessage.getTimeEnd())).key(m_locale);
} else {
// just display the message
msg = loginMessage.getMessage();
}
html.append("\talert(\"");
html.append(CmsStringUtil.escapeJavaScript(msg));
html.append("\");\n");
}
String openResource = requestedResource;
// check if user agreement should be shown
CmsLoginUserAgreement agreementInfo = new CmsLoginUserAgreement(this);
if (agreementInfo.isShowUserAgreement()) {
openResource = agreementInfo.getConfigurationVfsPath()
+ "?"
+ CmsLoginUserAgreement.PARAM_WPRES
+ "="
+ requestedResource;
}
html.append("\tvar openUri = \"");
html.append(link(openResource));
html.append("\";\n");
html.append("\tvar workplaceWin = openWorkplace(openUri, \"");
html.append(winId);
html.append("\");\n");
html.append("\tif (window.name != \"");
html.append(winId);
html.append("\") {\n");
html.append("\t\twindow.opener = workplaceWin;\n");
html.append("\t\tif (workplaceWin != null) {\n");
html.append("\t\t\twindow.close();\n");
html.append("\t\t}\n");
html.append("\t}\n");
html.append("}\n");
html.append("function openWorkplace(url, name) {\n");
Cookie wpDataCookie = getCookie(COOKIE_WP_DATA);
boolean useCookieData = false;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(wpDataCookie.getValue())) {
String[] winValues = CmsStringUtil.splitAsArray(wpDataCookie.getValue(), '|');
if (winValues.length == 4) {
useCookieData = true;
html.append("\tvar winLeft = ").append(winValues[0]).append(";\n");
html.append("\tvar winTop = ").append(winValues[1]).append(";\n");
html.append("\tvar winWidth = ").append(winValues[2]).append(";\n");
html.append("\tvar winHeight = ").append(winValues[3]).append(";\n");
}
}
if (!useCookieData) {
html.append("\tvar isInWin = (window.name.match(/^OpenCms\\d+$/) != null);\n");
html.append("\tvar winHeight = 0, winWidth = 0, winTop = 0, winLeft = 0;\n");
html.append("\tif (window.innerHeight) {\n");
// Mozilla
html.append("\t\twinHeight = window.innerHeight;\n");
html.append("\t\twinWidth = window.innerWidth;\n");
html.append("\t} else if (document.documentElement && document.documentElement.clientHeight) {\n");
// IE 6 "strict" mode
html.append("\t\twinHeight = document.documentElement.clientHeight;\n");
html.append("\t\twinWidth = document.documentElement.clientWidth;\n");
html.append("\t} else if (document.body && document.body.clientHeight) {\n");
// IE 5, IE 6 "relaxed" mode
html.append("\t\twinHeight = document.body.clientWidth;\n");
html.append("\t\twinWidth = document.body.clientHeight;\n");
html.append("\t}\n");
html.append("\tif (window.screenY) {\n");
// Mozilla
html.append("\t\twinTop = window.screenY;\n");
html.append("\t\twinLeft = window.screenX;\n");
html.append("\t\tif (! isInWin) {\n");
html.append("\t\t\twinTop += 25;\n");
html.append("\t\t\twinLeft += 25;\n");
html.append("\t\t}\n");
html.append("\t} else if (window.screenTop) {\n");
// IE
html.append("\t\twinTop = window.screenTop;\n");
html.append("\t\twinLeft = window.screenLeft;\n");
html.append("\t}\n");
html.append("\n");
}
if (requestedResource.startsWith(CmsWorkplace.VFS_PATH_WORKPLACE)) {
html.append("\tvar openerStr = \"width=\" + winWidth + \",height=\" + winHeight + \",left=\" + winLeft + \",top=\" + winTop + \",scrollbars=no,location=no,toolbar=no,menubar=no,directories=no,status=yes,resizable=yes\";\n");
} else {
html.append("\tvar openerStr = \"width=\" + winWidth + \",height=\" + winHeight + \",left=\" + winLeft + \",top=\" + winTop + \",scrollbars=yes,location=yes,toolbar=yes,menubar=yes,directories=no,status=yes,resizable=yes\";\n");
}
html.append("\tvar OpenCmsWin = window.open(url, name, openerStr);\n");
html.append("\n");
html.append("\ttry{\n");
html.append("\t\tif (! OpenCmsWin.opener) {\n");
html.append("\t\t\tOpenCmsWin.opener = self;\n");
html.append("\t\t}\n");
html.append("\t\tif (OpenCmsWin.focus) {\n");
html.append("\t\t\tOpenCmsWin.focus();\n");
html.append("\t\t}\n");
html.append("\t} catch (e) {}\n");
html.append("\n");
html.append("\treturn OpenCmsWin;\n");
html.append("}\n");
html.append("</script>\n");
}
/**
* Returns the HTML for the login form.<p>
*
* @return the HTML for the login form
*/
protected String displayLoginForm() {
StringBuffer html = new StringBuffer(8192);
html.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n");
html.append("<html><head>\n");
html.append("<title>");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_TITLE_0));
html.append("OpenCms " + OpenCms.getSystemInfo().getVersionNumber());
html.append("</title>\n");
String encoding = getRequestContext().getEncoding();
html.append("<meta HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=");
html.append(encoding);
html.append("\">\n");
// append workplace CSS
html.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
html.append(CmsWorkplace.getStyleUri(this, "workplace.css"));
html.append("\">\n");
// append favicon relation
html.append("<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"");
html.append(CmsWorkplace.getSkinUri()).append("commons/favicon.ico");
html.append("\">\n");
if (m_action == ACTION_DISPLAY) {
// append default script
appendDefaultLoginScript(html, m_message);
} else if (m_action == ACTION_LOGIN) {
// append window opener script
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_directEditPath)) {
appendDirectEditOpenerScript(html);
} else {
appendWorkplaceOpenerScript(html, m_requestedResource, m_message);
}
}
html.append("</head>\n");
html.append("<body class=\"dialog\" onload=\"doOnload();\">\n");
html.append("<div style=\"text-align: center; padding-top: 50px;\">");
html.append("<img src=\"");
html.append(CmsWorkplace.getResourceUri("commons/login_logo.png"));
html.append("\" alt=\"OpenCms Logo\">");
html.append("</div>\n");
html.append("<table class=\"logindialog\" cellpadding=\"0\" cellspacing=\"0\"><tr><td>\n");
html.append("<table class=\"dialogbox\" cellpadding=\"0\" cellspacing=\"0\"><tr><td>\n");
html.append("<div class=\"dialoghead\">");
if (m_oufqn == null) {
m_oufqn = CmsOrganizationalUnit.SEPARATOR;
}
if (m_action == ACTION_DISPLAY) {
html.append("<div id='titleId'");
if (!m_oufqn.equals(CmsOrganizationalUnit.SEPARATOR)) {
html.append(" style='display: none;'");
}
html.append(">\n");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_HEADLINE_0));
html.append("</div>\n");
html.append("<div id='titleIdOu'");
if (m_oufqn.equals(CmsOrganizationalUnit.SEPARATOR)) {
html.append(" style='display: none;'");
}
html.append(">\n");
html.append(Messages.get().getBundle(m_locale).key(
Messages.GUI_LOGIN_HEADLINE_SELECTED_ORGUNIT_1,
m_ou.getDescription(getCmsObject().getRequestContext().getLocale())));
html.append("</div>\n");
} else if (m_action == ACTION_LOGIN) {
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_HEADLINE_ALREADY_IN_0));
}
html.append("</div>\n");
if (m_action == ACTION_DISPLAY) {
// start form
html.append("<form style=\"margin: 0px; padding: 0px;\" action=\"");
html.append(getFormLink());
html.append("\"");
if (PCTYPE_PUBLIC.equals(m_pcType)) {
html.append(" autocomplete=\"off\"");
}
appendId(html, PARAM_FORM);
html.append("method=\"POST\">\n");
}
html.append("<div class=\"dialogcontent\">\n");
html.append("<table border=\"0\">\n");
// show security option box if enabled in configuration
if ((m_action == ACTION_DISPLAY) && OpenCms.getLoginManager().isEnableSecurity()) {
html.append("<tr>\n");
html.append("<td rowspan=\"2\">\n");
// security image should not be shown any more
//html.append("<img src=\"");
//html.append(CmsWorkplace.getResourceUri("commons/login_security.png"));
//html.append("\" height=\"48\" width=\"48\" alt=\"\">");
html.append("</td>\n");
html.append("<td colspan=\"2\" style=\"white-space: nowrap;\">\n");
html.append("<div style=\"padding-bottom: 5px;\"><b>");
html.append(CmsStringUtil.escapeHtml(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_SECURITY_0)));
html.append("</b></div>\n");
html.append("</td>\n");
html.append("</tr>\n");
html.append("<tr>\n");
html.append("<td colspan=\"2\" style=\"white-space: nowrap;\">");
html.append("<div class=\"loginsecurity\">");
html.append("<input type=\"radio\" value=\"");
html.append(PCTYPE_PUBLIC);
html.append("\" name=\"");
html.append(PARAM_PCTYPE);
html.append("\"");
if (PCTYPE_PUBLIC.equals(m_pcType)) {
html.append(" checked=\"checked\"");
}
html.append("> ");
html.append(CmsStringUtil.escapeHtml(Messages.get().getBundle(m_locale).key(
Messages.GUI_LOGIN_PCTYPE_PUBLIC_0)));
html.append("<br/>");
html.append("<input type=\"radio\" value=\"");
html.append(PCTYPE_PRIVATE);
html.append("\" name=\"");
html.append(PARAM_PCTYPE);
html.append("\"");
if (PCTYPE_PRIVATE.equals(m_pcType)) {
html.append(" checked=\"checked\"");
}
html.append("> ");
html.append(CmsStringUtil.escapeHtml(Messages.get().getBundle(m_locale).key(
Messages.GUI_LOGIN_PCTYPE_PRIVATE_0)));
html.append("</div></td>\n");
html.append("</tr>\n");
}
html.append("<tr>\n");
html.append("<td></td>\n<td colspan=\"2\" style=\"white-space: nowrap;\">\n");
html.append("<div style=\"padding-bottom: 10px;\">");
if (m_action == ACTION_DISPLAY) {
html.append(CmsStringUtil.escapeHtml(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_MESSAGE_0)));
} else if (m_action == ACTION_LOGIN) {
html.append(CmsStringUtil.escapeHtml(Messages.get().getBundle(m_locale).key(
Messages.GUI_LOGIN_MESSAGE_ALREADY_IN_0)));
}
html.append("</div>\n");
html.append("</td>\n");
html.append("</tr>\n");
html.append("<tr>\n");
html.append("<td style=\"width: 60px; text-align: center; vertical-align: top\" rowspan=\"5\">");
html.append("<img src=\"");
html.append(CmsWorkplace.getResourceUri("commons/login.png"));
html.append("\" height=\"48\" width=\"48\" alt=\"\">");
html.append("</td>\n");
html.append("<td style=\"white-space: nowrap;\"><b>");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_USERNAME_0));
html.append("</b> </td>\n");
html.append("<td style=\"width: 300px; white-space: nowrap;\">");
if (m_action == ACTION_DISPLAY) {
// append input for user name
html.append("<input style=\"width: 300px;\" type=\"text\"");
if (PCTYPE_PUBLIC.equals(m_pcType)) {
html.append(" autocomplete=\"off\"");
}
appendId(html, PARAM_USERNAME);
html.append("value=\"");
html.append((CmsStringUtil.isEmpty(m_username) || PCTYPE_PUBLIC.equals(m_pcType))
? ""
: CmsEncoder.escapeXml(m_username));
html.append("\">");
} else if (m_action == ACTION_LOGIN) {
// append name of user that has been logged in
html.append(getRequestContext().getCurrentUser().getFullName());
}
html.append("</td>\n");
html.append("</tr>\n");
if (m_action == ACTION_DISPLAY) {
// append 2 rows: input for user name and login button
html.append("<tr>\n");
html.append("<td style=\"white-space: nowrap;\"><b>");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_PASSWORD_0));
html.append("</b> </td>\n");
html.append("<td style=\"width: 300px; white-space: nowrap;\">");
html.append("<input style=\"width: 300px;\" type=\"password\"");
if (PCTYPE_PUBLIC.equals(m_pcType)) {
html.append(" autocomplete=\"off\"");
}
appendId(html, PARAM_PASSWORD);
html.append(">");
html.append("</td>\n");
html.append("</tr>\n");
html.append("<tr>\n");
html.append("<td style=\"white-space: nowrap;\"><div id='ouLabelId' style='display: none;'><b>");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_ORGUNIT_0)).append(
"</b> \n");
html.append("</div></td>\n");
html.append("<td style=\"width: 300px; white-space: nowrap;\"><div id='ouSearchId' style='display: none;'><input class=\"inactive\" style=\"width: 300px;\" type=\"text\" value=\"");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_ORGUNIT_SEARCH_0));
html.append("\"");
appendId(html, PARAM_OUSEARCH);
html.append(" onfocus=\"checkOuValue();\"");
html.append(" onblur=\"checkOuValue();\"");
html.append(" onkeyup=\"searchOu();\"");
html.append("/>");
html.append("<input type=\"hidden\" value=\"");
html.append(m_oufqn == null ? "" : m_oufqn);
html.append("\"");
appendId(html, PARAM_OUFQN);
html.append("/>");
html.append("</div></td>\n");
html.append("</tr>\n");
html.append("<tr>\n");
html.append("<td colspan=\"2\"><div id='ouSelId' style='display: none;'>");
html.append("</div></td>\n");
html.append("</tr>\n");
html.append("<tr>\n");
html.append("<td>\n");
html.append("</td>\n");
html.append("<td style=\"white-space: nowrap;\">\n");
html.append("<input type=\"hidden\"");
appendId(html, PARAM_ACTION_LOGIN);
html.append("value=\"true\">\n");
if (m_requestedResource != null) {
html.append("<input type=\"hidden\"");
appendId(html, CmsWorkplaceManager.PARAM_LOGIN_REQUESTED_RESOURCE);
html.append("value=\"");
html.append(CmsEncoder.escapeXml(m_requestedResource));
html.append("\">\n");
}
html.append("<input class=\"loginbutton\" type=\"submit\" value=\"");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_BUTTON_0));
html.append("\">\n");
if ((getOus().size() > 1)
&& ((getPreDefOuFqn() == null) || getPreDefOuFqn().equals(CmsOrganizationalUnit.SEPARATOR))) {
// options
html.append(" <input id='ouBtnId' class='loginbutton' type='button' value='");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_ORGUNIT_SELECT_ON_0));
html.append("' onclick='javascript:orgUnitSelection();'>\n");
}
html.append("</td>\n");
html.append("</tr>\n");
} else if (m_action == ACTION_LOGIN) {
// append 2 rows: one empty, other for button with re-open window script
html.append("<tr><td></td><td></td></tr>\n");
html.append("<tr>\n");
html.append("<td></td>\n");
html.append("<td style=\"width:100%; white-space: nowrap;\">\n");
html.append("<input class=\"loginbutton\" type=\"button\" value=\"");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_BUTTON_ALREADY_IN_0));
html.append("\" onclick=\"doOnload()\">\n");
html.append("</td>\n");
html.append("</tr>\n");
}
html.append("</table>\n");
html.append("</div>");
if (m_action == ACTION_DISPLAY) {
// end form
html.append("</form>\n");
}
html.append("</td></tr></table>\n");
html.append("</td></tr></table>\n");
html.append("<div style=\"text-align: center; font-size: 10px; white-space: nowrap;\">");
html.append("<a href=\"http://www.opencms.org\" target=\"_blank\">OpenCms</a> ");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_OPENCMS_IS_FREE_SOFTWARE_0));
html.append("</div>\n");
html.append("<div style=\"text-align: center; font-size: 10px; white-space: nowrap;\">");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_TRADEMARKS_0));
html.append("</div>\n");
html.append("<div style=\"text-align: center; font-size: 10px; white-space: nowrap;\">");
html.append("© 2002 - 2012 Alkacon Software GmbH. ");
html.append(Messages.get().getBundle(m_locale).key(Messages.GUI_LOGIN_RIGHTS_RESERVED_0));
html.append("</div>\n");
html.append("<noscript>\n");
html.append("<div style=\"text-align: center; font-size: 14px; border: 2px solid black; margin: 50px; padding: 20px; background-color: red; color: white; white-space: nowrap;\"><b>");
html.append(CmsStringUtil.escapeHtml(Messages.get().getBundle(m_locale).key(
Messages.GUI_LOGIN_NOSCRIPT_1,
OpenCms.getSiteManager().getWorkplaceSiteMatcher())));
html.append("</b></div>\n");
html.append("</noscript>\n");
html.append("</body></html>");
return html.toString();
}
/**
* Returns the cookie with the given name, if not cookie is found a new one is created.<p>
*
* @param name the name of the cookie
*
* @return the cookie
*/
protected Cookie getCookie(String name) {
Cookie[] cookies = getRequest().getCookies();
for (int i = 0; (cookies != null) && (i < cookies.length); i++) {
if (name.equalsIgnoreCase(cookies[i].getName())) {
return cookies[i];
}
}
return new Cookie(name, "");
}
/**
* Returns all organizational units in the system.<p>
*
* @return a list of {@link CmsOrganizationalUnit} objects
*/
protected List<CmsOrganizationalUnit> getOus() {
if (m_ous == null) {
m_ous = new ArrayList<CmsOrganizationalUnit>();
try {
if (getPreDefOuFqn() == null) {
m_ous.add(OpenCms.getOrgUnitManager().readOrganizationalUnit(getCmsObject(), ""));
m_ous.addAll(OpenCms.getOrgUnitManager().getOrganizationalUnits(getCmsObject(), "", true));
Iterator<CmsOrganizationalUnit> itOus = m_ous.iterator();
while (itOus.hasNext()) {
CmsOrganizationalUnit ou = itOus.next();
if (ou.hasFlagHideLogin() || ou.hasFlagWebuser()) {
itOus.remove();
}
}
} else {
m_ous.add(OpenCms.getOrgUnitManager().readOrganizationalUnit(getCmsObject(), m_oufqn));
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
return m_ous;
}
/**
* Returns the predefined organizational unit fqn.<p>
*
* This is normally selected by url, and set by the {@link CmsWorkplaceLoginHandler}.<p>
*
* @return the predefined organizational unit fqn
*/
protected String getPreDefOuFqn() {
if (Boolean.valueOf(m_actionLogout).booleanValue() && (getRequest().getAttribute(PARAM_PREDEF_OUFQN) == null)) {
String oufqn = getCmsObject().getRequestContext().getOuFqn();
if (!oufqn.startsWith(CmsOrganizationalUnit.SEPARATOR)) {
oufqn = CmsOrganizationalUnit.SEPARATOR + oufqn;
}
getRequest().setAttribute(CmsLogin.PARAM_PREDEF_OUFQN, oufqn);
}
return (String)getRequest().getAttribute(PARAM_PREDEF_OUFQN);
}
/**
* Sets the cookie in the response.<p>
*
* @param cookie the cookie to set
* @param delete flag to determine if the cookir should be deleted
*/
protected void setCookie(Cookie cookie, boolean delete) {
if (getRequest().getAttribute(PARAM_PREDEF_OUFQN) != null) {
// prevent the use of cookies if using a direct ou login url
return;
}
int maxAge = 0;
if (!delete) {
// set the expiration date of the cookie to six months from today
GregorianCalendar cal = new GregorianCalendar();
cal.add(Calendar.MONTH, 6);
maxAge = (int)((cal.getTimeInMillis() - System.currentTimeMillis()) / 1000);
}
cookie.setMaxAge(maxAge);
// set the path
cookie.setPath(link("/system/login"));
// set the cookie
getResponse().addCookie(cookie);
}
/**
* Returns the direct edit path from the user settings, or <code>null</code> if not set.<p>
*
* @param userSettings the user settings
*
* @return the direct edit path
*/
private String getDirectEditPath(CmsUserSettings userSettings) {
if (userSettings.getStartView().equals(CmsWorkplace.VIEW_DIRECT_EDIT)) {
String folder = userSettings.getStartFolder();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(getCmsObject().getRequestContext().getSiteRoot())
|| getCmsObject().getRequestContext().getSiteRoot().equals("/")) {
folder = CmsStringUtil.joinPaths(userSettings.getStartSite(), folder);
}
try {
CmsResource targetRes = getCmsObject().readDefaultFile(folder);
if (targetRes != null) {
return targetRes.getRootPath();
}
} catch (Exception e) {
LOG.debug(e);
}
}
return null;
}
} | lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/MultiTenancyTest.java | 4307 | package org.hibernate.test.cache.infinispan.functional;
import org.hibernate.MultiTenancyStrategy;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.infinispan.entity.EntityRegionImpl;
import org.hibernate.cache.infinispan.util.Caches;
import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.hibernate.test.cache.infinispan.functional.entities.Item;
import org.hibernate.test.cache.infinispan.tm.XaConnectionProvider;
import org.hibernate.testing.env.ConnectionProviderBuilder;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.util.CloseableIterable;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.context.Flag;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public class MultiTenancyTest extends SingleNodeTest {
private static final String DB1 = "db1";
private static final String DB2 = "db2";
private final ConnectionProvider db1
= new XaConnectionProvider(ConnectionProviderBuilder.buildConnectionProvider(DB1));
private final ConnectionProvider db2
= new XaConnectionProvider(ConnectionProviderBuilder.buildConnectionProvider(DB2));
@Override
public List<Object[]> getParameters() {
return Collections.singletonList(READ_ONLY_INVALIDATION);
}
@Override
protected void configureStandardServiceRegistryBuilder(StandardServiceRegistryBuilder ssrb) {
super.configureStandardServiceRegistryBuilder(ssrb);
ssrb.addService(MultiTenantConnectionProvider.class, new AbstractMultiTenantConnectionProvider() {
@Override
protected ConnectionProvider getAnyConnectionProvider() {
return db1;
}
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
if (DB1.equals(tenantIdentifier)) return db1;
if (DB2.equals(tenantIdentifier)) return db2;
throw new IllegalArgumentException();
}
});
}
@Override
protected void configureSessionFactoryBuilder(SessionFactoryBuilder sfb) {
super.configureSessionFactoryBuilder(sfb);
sfb.applyMultiTenancyStrategy(MultiTenancyStrategy.DATABASE);
}
@Override
protected void cleanupTest() throws Exception {
db1.getConnection().close();
db2.getConnection().close();
}
@Test
public void testMultiTenancy() throws Exception {
final Item item = new Item("my item", "description" );
withTxSession(sessionFactory().withOptions().tenantIdentifier(DB1), s -> s.persist(item));
for (int i = 0; i < 5; ++i) { // make sure we get something cached
withTxSession(sessionFactory().withOptions().tenantIdentifier(DB1), s -> {
Item item2 = s.get(Item.class, item.getId());
assertNotNull(item2);
assertEquals(item.getName(), item2.getName());
});
}
// The table ITEMS is not created in DB2 - we would get just an exception
// for (int i = 0; i < 5; ++i) { // make sure we get something cached
// withTx(tm, new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// Session s = sessionFactory().withOptions().tenantIdentifier(DB2).openSession();
// s.getTransaction().begin();
// Item item2 = s.get(Item.class, id);
// s.getTransaction().commit();
// s.close();
// assertNull(item2);
// return null;
// }
// });
// }
EntityRegionImpl region = (EntityRegionImpl) sessionFactory().getSecondLevelCacheRegion(Item.class.getName());
AdvancedCache localCache = region.getCache().withFlags(Flag.CACHE_MODE_LOCAL);
assertEquals(1, localCache.size());
try (CloseableIterator iterator = localCache.keySet().iterator()) {
assertEquals("OldCacheKeyImplementation", iterator.next().getClass().getSimpleName());
}
}
}
| lgpl-2.1 |
geotools/geotools | modules/extension/xsd/xsd-wfs/src/main/java/org/geotools/wfs/v2_0/bindings/FeatureTypeTypeBinding.java | 4119 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2014, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.wfs.v2_0.bindings;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import net.opengis.ows11.KeywordsType;
import net.opengis.ows11.Ows11Factory;
import net.opengis.wfs20.FeatureTypeType;
import net.opengis.wfs20.OutputFormatListType;
import net.opengis.wfs20.Wfs20Factory;
import org.eclipse.emf.ecore.EObject;
import org.geotools.wfs.v2_0.WFS;
import org.geotools.xsd.AbstractComplexEMFBinding;
public class FeatureTypeTypeBinding extends AbstractComplexEMFBinding {
private Wfs20Factory factory;
public FeatureTypeTypeBinding(Wfs20Factory factory) {
super(factory);
this.factory = factory;
}
@Override
public QName getTarget() {
return WFS.FeatureTypeType;
}
@Override
public Class getType() {
return FeatureTypeType.class;
}
@SuppressWarnings("unchecked")
@Override
protected void setProperty(EObject object, String property, Object value, boolean lax) {
if ("OtherCRS".equals(property)) {
String stringValue = null;
if (value instanceof String) {
stringValue = (String) value;
} else if (value instanceof URI) {
stringValue = value.toString();
}
if (stringValue != null) {
// GEOT-6620-Do not added Other SRS again if it already exists
if (!((FeatureTypeType) object).getOtherCRS().contains(stringValue)) {
((FeatureTypeType) object).getOtherCRS().add(stringValue);
}
return;
}
} else if ("OtherSRS".equals(property)) {
if (value instanceof Collection) {
Collection<URI> formatListAsUris = (Collection<URI>) value;
List<String> formatListAsString = new ArrayList<>();
for (URI uri : formatListAsUris) {
formatListAsString.add(uri.toString());
}
value = formatListAsString;
} else {
if (value instanceof URI) {
value = value.toString();
}
}
} else if ("Keywords".equals(property)) {
if (value instanceof String) {
String[] split = ((String) value).split(",");
KeywordsType kwd = Ows11Factory.eINSTANCE.createKeywordsType();
for (String s : split) {
String kw = s.trim();
kwd.getKeyword().add(kw);
}
((FeatureTypeType) object).getKeywords().add(kwd);
return;
}
} else if ("OutputFormats".equals(property)) {
if (value != null) {
OutputFormatListType oflt = ((FeatureTypeType) object).getOutputFormats();
if (oflt == null) {
oflt = factory.createOutputFormatListType();
}
if (value instanceof Map<?, ?>) {
oflt.getFormat().addAll(((Map<String, ArrayList<String>>) value).get("Format"));
} else {
oflt.getFormat().add(value.toString());
}
((FeatureTypeType) object).setOutputFormats(oflt);
return;
}
}
super.setProperty(object, property, value, lax);
}
}
| lgpl-2.1 |
jezhiggins/mango | src/test/java/uk/co/jezuk/mango/ArrayIteratorTest.java | 1092 | package uk.co.jezuk.mango;
import junit.framework.*;
import java.util.NoSuchElementException;
import java.util.Iterator;
public class ArrayIteratorTest extends TestCase
{
public ArrayIteratorTest(String name) { super(name); }
public static Test suite() { return new TestSuite(ArrayIteratorTest.class); }
public void test1()
{
Iterator<String> i = Iterators.ArrayIterator(new String[]{ "one", "two", "three" } );
assertEquals(true, i.hasNext());
assertEquals("one", i.next());
assertEquals(true, i.hasNext());
assertEquals("two", i.next());
assertEquals(true, i.hasNext());
assertEquals("three", i.next());
assertEquals(false, i.hasNext());
try {
i.next();
fail();
}
catch(NoSuchElementException e)
{
}
} // test1
public void test2()
{
Iterator<Void> i = Iterators.ArrayIterator(null);
assertEquals(false, i.hasNext());
try {
i.next();
fail();
}
catch(NoSuchElementException e)
{
} // catch
} // test2
} // ArrayIteratorTest
| lgpl-2.1 |
JiriOndrusek/wildfly-core | elytron/src/main/java/org/wildfly/extension/elytron/DirContextParser.java | 3278 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.extension.elytron;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static org.jboss.as.controller.PersistentResourceXMLDescription.builder;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.wildfly.extension.elytron.ElytronDescriptionConstants.DIR_CONTEXT;
import static org.wildfly.extension.elytron.ElytronDescriptionConstants.DIR_CONTEXTS;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
/**
* A parser for the DirContext definition.
*
* <a href="mailto:jkalina@redhat.com">Jan Kalina</a>
*/
class DirContextParser {
private final PersistentResourceXMLDescription dirContextParser = builder(PathElement.pathElement(ElytronDescriptionConstants.DIR_CONTEXT), null)
.addAttributes(DirContextDefinition.ATTRIBUTES)
.build();
private final ElytronSubsystemParser elytronSubsystemParser;
DirContextParser(ElytronSubsystemParser elytronSubsystemParser) {
this.elytronSubsystemParser = elytronSubsystemParser;
}
private void verifyNamespace(XMLExtendedStreamReader reader) throws XMLStreamException {
elytronSubsystemParser.verifyNamespace(reader);
}
void readDirContexts(ModelNode parentAddressNode, XMLExtendedStreamReader reader, List<ModelNode> operations) throws XMLStreamException {
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
verifyNamespace(reader);
String localName = reader.getLocalName();
PathAddress parentAddress = PathAddress.pathAddress(parentAddressNode);
if (DIR_CONTEXT.equals(localName)) {
dirContextParser.parse(reader, parentAddress, operations);
} else {
throw unexpectedElement(reader);
}
}
}
void writeDirContexts(ModelNode subsystem, XMLExtendedStreamWriter writer) throws XMLStreamException {
if (subsystem.hasDefined(DIR_CONTEXT)) {
writer.writeStartElement(DIR_CONTEXTS);
dirContextParser.persist(writer, subsystem);
writer.writeEndElement();
}
}
}
| lgpl-2.1 |
MUNDO-platform/srccode | mundo-java-backend/src/main/java/pl/orange/labs/mundo/plugins/wfs/entity/XmlWfsSpatialOperators.java | 2012 | /*
* Platforma MUNDO – Dane po Warszawsku http://danepowarszawsku.pl/
*
* @authors Jarosław Legierski, Tomasz Janisiewicz, Henryk Rosa Centrum Badawczo – Rozwojowe/ Orange Labs
* copyright (c) 2014-2015 Orange Polska S.A. niniejszy kod jest otwarty i dystrybuowany
* na licencji: Lesser General Public License v2.1 (LGPLv2.1), której pełny tekst można
* znaleźć pod adresem: https://www.gnu.org/licenses/lgpl-2.1.html
*
* oprogramowanie stworzone w ramach Projektu : MUNDO Miejskie Usługi Na Danych Oparte
* Beneficjenci: Fundacja Techsoup, Orange Polska S.A., Politechnika Warszawska,
* Fundacja Pracownia Badań i Innowacji Społecznych „Stocznia”, Fundacja Projekt Polska
* Wartość projektu: 1 108 978
* Wartość dofinansowania: 847 000
* Okres realizacji 01.04.2014 – 31.12.2015
* Projekt współfinansowany przez Narodowe Centrum Badań i Rozwoju w ramach
* Programu Innowacje Społeczne
*
*/
package pl.orange.labs.mundo.plugins.wfs.entity;
import pl.orange.labs.mundo.plugins.wfs.entity.XmlWfsSpatialOperator;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
*
* @author Tomasz Janisiewicz <tomasz.janisiewicz@orange.com>
*/
@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
@XmlAccessorType(XmlAccessType.FIELD)
public class XmlWfsSpatialOperators
{
@XmlElement(name="SpatialOperator", namespace="http://www.opengis.net/ogc")
private List<XmlWfsSpatialOperator> spatialOperatorsList;
@XmlTransient
public List<XmlWfsSpatialOperator> getSpatialOperatorsList() {
return spatialOperatorsList;
}
public void setSpatialOperatorsList(List<XmlWfsSpatialOperator> spatialOperatorsList) {
this.spatialOperatorsList = spatialOperatorsList;
}
}
| lgpl-2.1 |
phoenixctms/ctsms | web/src/main/java/org/phoenixctms/ctsms/web/model/PaymentMethodSelectorListener.java | 352 | package org.phoenixctms.ctsms.web.model;
import org.phoenixctms.ctsms.enumeration.PaymentMethod;
public interface PaymentMethodSelectorListener {
public final static PaymentMethod NO_SELECTION_PAYMENT_METHOD = null;
public PaymentMethod getPaymentMethod(int property);
public void setPaymentMethod(int property, PaymentMethod paymentMethod);
}
| lgpl-2.1 |
phoenixctms/ctsms | core/src/exec/java/org/phoenixctms/ctsms/util/ChunkedDaoOperationAdapter.java | 3425 | package org.phoenixctms.ctsms.util;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.andromda.spring.PaginationResult;
import org.phoenixctms.ctsms.Search;
public abstract class ChunkedDaoOperationAdapter<DAO, ENTITY> {
public enum PageSizes {
TINY(100), DEFAULT(1000), BIG(10000), HUGE(100000);
public final int value;
/**
* @param text
*/
private PageSizes(final int value) {
this.value = value;
}
}
protected DAO dao;
private Method loadAllSorted;
private Method search;
private Search searchArg;
private final static Search EMPTY_SEARCH = new Search();
static {
EMPTY_SEARCH.setUseSqlLimiting(true);
}
public ChunkedDaoOperationAdapter(DAO dao) throws Exception {
this.dao = dao;
defineLoadMethods(dao);
}
public ChunkedDaoOperationAdapter(DAO dao, Search search) throws Exception {
this.dao = dao;
defineLoadMethods(dao);
searchArg = search;
searchArg.setUseSqlLimiting(true);
}
private void defineLoadMethods(DAO dao) throws Exception {
loadAllSorted = dao.getClass().getMethod("loadAllSorted", int.class, int.class);
search = dao.getClass().getMethod("search", int.class, int.class, Search.class);
}
public final long getTotalCount() throws Exception {
PaginationResult result;
if (searchArg != null) {
result = (PaginationResult) search.invoke(dao, 1, 1, searchArg);
} else {
result = (PaginationResult) search.invoke(dao, 1, 1, EMPTY_SEARCH);
}
return result.getTotalSize();
}
protected boolean isIncrementPageNumber() {
return true;
}
protected Collection<ENTITY> load(int pageNumber, int pageSize) throws Exception {
if (searchArg != null) {
PaginationResult result = (PaginationResult) search.invoke(dao, pageNumber, pageSize, searchArg);
return Arrays.<ENTITY> asList((ENTITY[]) result.getData());
} else {
return (Collection<ENTITY>) loadAllSorted.invoke(dao, pageNumber, pageSize);
}
}
protected abstract boolean process(Collection<ENTITY> page, Object passThrough) throws Exception;
protected abstract boolean process(ENTITY entity, Object passThrough) throws Exception;
public final void processEach(int pageSize, Object passThrough) throws Exception {
Collection<ENTITY> entities;
int pageNumber = 1;
while ((entities = load(pageNumber, pageSize)).size() > 0) {
Iterator<ENTITY> it = entities.iterator();
while (it.hasNext()) {
if (!process(it.next(), passThrough)) {
return;
}
}
if (isIncrementPageNumber()) {
pageNumber++;
}
}
}
public final void processEach(Object passThrough) throws Exception {
processEach(PageSizes.DEFAULT, passThrough);
}
public final void processEach(PageSizes pageSize, Object passThrough) throws Exception {
processEach(pageSize.value, passThrough);
}
public final void processPages(int pageSize, Object passThrough) throws Exception {
Collection<ENTITY> entities;
int pageNumber = 1;
while ((entities = load(pageNumber, pageSize)).size() > 0) {
if (!process(entities, passThrough)) {
return;
}
if (isIncrementPageNumber()) {
pageNumber++;
}
}
}
public final void processPages(Object passThrough) throws Exception {
processPages(PageSizes.DEFAULT, passThrough);
}
public final void processPages(PageSizes pageSize, Object passThrough) throws Exception {
processPages(pageSize.value, passThrough);
}
}
| lgpl-2.1 |
dianhu/Kettle-Research | src-ui/org/pentaho/di/ui/trans/steps/exceloutput/ExcelOutputDialog.java | 54291 | /* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
/**
* Allows you to edit the Excel Output meta-data
* @author Matt
* @since 7-sep-2006
*
*/
package org.pentaho.di.ui.trans.steps.exceloutput;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleException;
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.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.exceloutput.ExcelField;
import org.pentaho.di.trans.steps.exceloutput.ExcelOutputMeta;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.di.ui.trans.step.TableItemInsertListener;
public class ExcelOutputDialog extends BaseStepDialog implements StepDialogInterface
{
private static Class<?> PKG = ExcelOutputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wFileTab, wContentTab, wFieldsTab;
private FormData fdFileComp, fdContentComp, fdFieldsComp;
private Label wlFilename;
private Button wbFilename;
private TextVar wFilename;
private FormData fdlFilename, fdbFilename, fdFilename;
private Label wlExtension;
private TextVar wExtension;
private FormData fdlExtension, fdExtension;
private Label wlAddStepnr;
private Button wAddStepnr;
private FormData fdlAddStepnr, fdAddStepnr;
private Label wlAddDate;
private Button wAddDate;
private FormData fdlAddDate, fdAddDate;
private Label wlAddTime;
private Button wAddTime;
private FormData fdlAddTime, fdAddTime;
private Label wlProtectSheet;
private Button wProtectSheet;
private FormData fdlProtectSheet, fdProtectSheet;
private Button wbShowFiles;
private FormData fdbShowFiles;
private Label wlHeader;
private Button wHeader;
private FormData fdlHeader, fdHeader;
private Label wlFooter;
private Button wFooter;
private FormData fdlFooter, fdFooter;
private Label wlEncoding;
private CCombo wEncoding;
private FormData fdlEncoding, fdEncoding;
private Label wlSplitEvery;
private Text wSplitEvery;
private FormData fdlSplitEvery, fdSplitEvery;
private Label wlTemplate;
private Button wTemplate;
private FormData fdlTemplate, fdTemplate;
private Label wlTemplateAppend;
private Button wTemplateAppend;
private FormData fdlTemplateAppend, fdTemplateAppend;
private Label wlTemplateFilename;
private Button wbTemplateFilename;
private TextVar wTemplateFilename;
private FormData fdlTemplateFilename, fdbTemplateFilename, fdTemplateFilename;
private Label wlPassword;
private TextVar wPassword;
private FormData fdlPassword, fdPassword;
private Label wlSheetname;
private TextVar wSheetname;
private FormData fdlSheetname, fdSheetname;
private TableView wFields;
private FormData fdFields;
private ExcelOutputMeta input;
private Button wMinWidth;
private Listener lsMinWidth;
private boolean gotEncodings = false;
private Label wlAddToResult;
private Button wAddToResult;
private FormData fdlAddToResult, fdAddToResult;
private Label wlAppend;
private Button wAppend;
private FormData fdlAppend, fdAppend;
private Label wlDoNotOpenNewFileInit;
private Button wDoNotOpenNewFileInit;
private FormData fdlDoNotOpenNewFileInit, fdDoNotOpenNewFileInit;
private Label wlSpecifyFormat;
private Button wSpecifyFormat;
private FormData fdlSpecifyFormat, fdSpecifyFormat;
private Label wlDateTimeFormat;
private CCombo wDateTimeFormat;
private FormData fdlDateTimeFormat, fdDateTimeFormat;
private Label wlAutoSize;
private Button wAutoSize;
private FormData fdlAutoSize, fdAutoSize;
private Label wlNullIsBlank;
private Button wNullIsBlank;
private FormData fdlNullIsBlank, fdNullIsBlank;
private Group wTemplateGroup;
private FormData fdTemplateGroup;
private ColumnInfo[] colinf;
private Map<String, Integer> inputFields;
public ExcelOutputDialog(Shell parent, Object in, TransMeta transMeta, String sname)
{
super(parent, (BaseStepMeta)in, transMeta, sname);
input=(ExcelOutputMeta)in;
inputFields =new HashMap<String, Integer>();
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
setShellImage(shell, input);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.DialogTitle"));
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "System.Label.StepName"));
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.top = new FormAttachment(0, margin);
fdlStepname.right = new FormAttachment(middle, -margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
//////////////////////////
// START OF FILE TAB///
///
wFileTab=new CTabItem(wTabFolder, SWT.NONE);
wFileTab.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.FileTab.TabTitle"));
Composite wFileComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wFileComp);
FormLayout fileLayout = new FormLayout();
fileLayout.marginWidth = 3;
fileLayout.marginHeight = 3;
wFileComp.setLayout(fileLayout);
// Filename line
wlFilename=new Label(wFileComp, SWT.RIGHT);
wlFilename.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.Filename.Label"));
props.setLook(wlFilename);
fdlFilename=new FormData();
fdlFilename.left = new FormAttachment(0, 0);
fdlFilename.top = new FormAttachment(0, margin);
fdlFilename.right= new FormAttachment(middle, -margin);
wlFilename.setLayoutData(fdlFilename);
wbFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbFilename);
wbFilename.setText(BaseMessages.getString(PKG, "System.Button.Browse"));
fdbFilename=new FormData();
fdbFilename.right= new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(0, 0);
wbFilename.setLayoutData(fdbFilename);
wFilename=new TextVar(transMeta, wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
fdFilename=new FormData();
fdFilename.left = new FormAttachment(middle, 0);
fdFilename.top = new FormAttachment(0, margin);
fdFilename.right= new FormAttachment(wbFilename, -margin);
wFilename.setLayoutData(fdFilename);
// Open new File at Init
wlDoNotOpenNewFileInit=new Label(wFileComp, SWT.RIGHT);
wlDoNotOpenNewFileInit.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.DoNotOpenNewFileInit.Label"));
props.setLook(wlDoNotOpenNewFileInit);
fdlDoNotOpenNewFileInit=new FormData();
fdlDoNotOpenNewFileInit.left = new FormAttachment(0, 0);
fdlDoNotOpenNewFileInit.top = new FormAttachment(wFilename, margin);
fdlDoNotOpenNewFileInit.right= new FormAttachment(middle, -margin);
wlDoNotOpenNewFileInit.setLayoutData(fdlDoNotOpenNewFileInit);
wDoNotOpenNewFileInit=new Button(wFileComp, SWT.CHECK );
wDoNotOpenNewFileInit.setToolTipText(BaseMessages.getString(PKG, "ExcelOutputDialog.DoNotOpenNewFileInit.Tooltip"));
props.setLook(wDoNotOpenNewFileInit);
fdDoNotOpenNewFileInit=new FormData();
fdDoNotOpenNewFileInit.left = new FormAttachment(middle, 0);
fdDoNotOpenNewFileInit.top = new FormAttachment(wFilename, margin);
fdDoNotOpenNewFileInit.right= new FormAttachment(100, 0);
wDoNotOpenNewFileInit.setLayoutData(fdDoNotOpenNewFileInit);
wDoNotOpenNewFileInit.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Extension line
wlExtension=new Label(wFileComp, SWT.RIGHT);
wlExtension.setText(BaseMessages.getString(PKG, "System.Label.Extension"));
props.setLook(wlExtension);
fdlExtension=new FormData();
fdlExtension.left = new FormAttachment(0, 0);
fdlExtension.top = new FormAttachment(wDoNotOpenNewFileInit, margin);
fdlExtension.right= new FormAttachment(middle, -margin);
wlExtension.setLayoutData(fdlExtension);
wExtension=new TextVar(transMeta,wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wExtension.setText("");
props.setLook(wExtension);
wExtension.addModifyListener(lsMod);
fdExtension=new FormData();
fdExtension.left = new FormAttachment(middle, 0);
fdExtension.top = new FormAttachment(wDoNotOpenNewFileInit, margin);
fdExtension.right= new FormAttachment(wbFilename, -margin);
wExtension.setLayoutData(fdExtension);
// Create multi-part file?
wlAddStepnr=new Label(wFileComp, SWT.RIGHT);
wlAddStepnr.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.AddStepnr.Label"));
props.setLook(wlAddStepnr);
fdlAddStepnr=new FormData();
fdlAddStepnr.left = new FormAttachment(0, 0);
fdlAddStepnr.top = new FormAttachment(wExtension, margin);
fdlAddStepnr.right= new FormAttachment(middle, -margin);
wlAddStepnr.setLayoutData(fdlAddStepnr);
wAddStepnr=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddStepnr);
fdAddStepnr=new FormData();
fdAddStepnr.left = new FormAttachment(middle, 0);
fdAddStepnr.top = new FormAttachment(wExtension, margin);
fdAddStepnr.right= new FormAttachment(100, 0);
wAddStepnr.setLayoutData(fdAddStepnr);
wAddStepnr.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Create multi-part file?
wlAddDate=new Label(wFileComp, SWT.RIGHT);
wlAddDate.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.AddDate.Label"));
props.setLook(wlAddDate);
fdlAddDate=new FormData();
fdlAddDate.left = new FormAttachment(0, 0);
fdlAddDate.top = new FormAttachment(wAddStepnr, margin);
fdlAddDate.right= new FormAttachment(middle, -margin);
wlAddDate.setLayoutData(fdlAddDate);
wAddDate=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddDate);
fdAddDate=new FormData();
fdAddDate.left = new FormAttachment(middle, 0);
fdAddDate.top = new FormAttachment(wAddStepnr, margin);
fdAddDate.right= new FormAttachment(100, 0);
wAddDate.setLayoutData(fdAddDate);
wAddDate.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
// System.out.println("wAddDate.getSelection()="+wAddDate.getSelection());
}
}
);
// Create multi-part file?
wlAddTime=new Label(wFileComp, SWT.RIGHT);
wlAddTime.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.AddTime.Label"));
props.setLook(wlAddTime);
fdlAddTime=new FormData();
fdlAddTime.left = new FormAttachment(0, 0);
fdlAddTime.top = new FormAttachment(wAddDate, margin);
fdlAddTime.right= new FormAttachment(middle, -margin);
wlAddTime.setLayoutData(fdlAddTime);
wAddTime=new Button(wFileComp, SWT.CHECK);
props.setLook(wAddTime);
fdAddTime=new FormData();
fdAddTime.left = new FormAttachment(middle, 0);
fdAddTime.top = new FormAttachment(wAddDate, margin);
fdAddTime.right= new FormAttachment(100, 0);
wAddTime.setLayoutData(fdAddTime);
wAddTime.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
// Specify date time format?
wlSpecifyFormat=new Label(wFileComp, SWT.RIGHT);
wlSpecifyFormat.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.SpecifyFormat.Label"));
props.setLook(wlSpecifyFormat);
fdlSpecifyFormat=new FormData();
fdlSpecifyFormat.left = new FormAttachment(0, 0);
fdlSpecifyFormat.top = new FormAttachment(wAddTime, margin);
fdlSpecifyFormat.right= new FormAttachment(middle, -margin);
wlSpecifyFormat.setLayoutData(fdlSpecifyFormat);
wSpecifyFormat=new Button(wFileComp, SWT.CHECK);
props.setLook(wSpecifyFormat);
wSpecifyFormat.setToolTipText(BaseMessages.getString(PKG, "ExcelOutputDialog.SpecifyFormat.Tooltip"));
fdSpecifyFormat=new FormData();
fdSpecifyFormat.left = new FormAttachment(middle, 0);
fdSpecifyFormat.top = new FormAttachment(wAddTime, margin);
fdSpecifyFormat.right= new FormAttachment(100, 0);
wSpecifyFormat.setLayoutData(fdSpecifyFormat);
wSpecifyFormat.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
setDateTimeFormat();
}
}
);
// Prepare a list of possible DateTimeFormats...
String dats[] = Const.getDateFormats();
// DateTimeFormat
wlDateTimeFormat=new Label(wFileComp, SWT.RIGHT);
wlDateTimeFormat.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.DateTimeFormat.Label"));
props.setLook(wlDateTimeFormat);
fdlDateTimeFormat=new FormData();
fdlDateTimeFormat.left = new FormAttachment(0, 0);
fdlDateTimeFormat.top = new FormAttachment(wSpecifyFormat, margin);
fdlDateTimeFormat.right= new FormAttachment(middle, -margin);
wlDateTimeFormat.setLayoutData(fdlDateTimeFormat);
wDateTimeFormat=new CCombo(wFileComp, SWT.BORDER | SWT.READ_ONLY);
wDateTimeFormat.setEditable(true);
props.setLook(wDateTimeFormat);
wDateTimeFormat.addModifyListener(lsMod);
fdDateTimeFormat=new FormData();
fdDateTimeFormat.left = new FormAttachment(middle, 0);
fdDateTimeFormat.top = new FormAttachment(wSpecifyFormat, margin);
fdDateTimeFormat.right= new FormAttachment(100, 0);
wDateTimeFormat.setLayoutData(fdDateTimeFormat);
for (int x=0;x<dats.length;x++) wDateTimeFormat.add(dats[x]);
wbShowFiles=new Button(wFileComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbShowFiles);
wbShowFiles.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.ShowFiles.Button"));
fdbShowFiles=new FormData();
fdbShowFiles.left = new FormAttachment(middle, 0);
fdbShowFiles.top = new FormAttachment(wDateTimeFormat, margin*3);
wbShowFiles.setLayoutData(fdbShowFiles);
wbShowFiles.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
ExcelOutputMeta tfoi = new ExcelOutputMeta();
getInfo(tfoi);
String files[] = tfoi.getFiles(transMeta);
if (files!=null && files.length>0)
{
EnterSelectionDialog esd = new EnterSelectionDialog(shell, files, BaseMessages.getString(PKG, "ExcelOutputDialog.SelectOutputFiles.DialogTitle"), BaseMessages.getString(PKG, "ExcelOutputDialog.SelectOutputFiles.DialogMessage"));
esd.setViewOnly();
esd.open();
}
else
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage(BaseMessages.getString(PKG, "ExcelOutputDialog.NoFilesFound.DialogMessage"));
mb.setText(BaseMessages.getString(PKG, "System.Dialog.Error.Title"));
mb.open();
}
}
}
);
// Add File to the result files name
wlAddToResult=new Label(wFileComp, SWT.RIGHT);
wlAddToResult.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.AddFileToResult.Label"));
props.setLook(wlAddToResult);
fdlAddToResult=new FormData();
fdlAddToResult.left = new FormAttachment(0, 0);
fdlAddToResult.top = new FormAttachment(wbShowFiles, 2*margin);
fdlAddToResult.right = new FormAttachment(middle, -margin);
wlAddToResult.setLayoutData(fdlAddToResult);
wAddToResult=new Button(wFileComp, SWT.CHECK);
wAddToResult.setToolTipText(BaseMessages.getString(PKG, "ExcelOutputDialog.AddFileToResult.Tooltip"));
props.setLook(wAddToResult);
fdAddToResult=new FormData();
fdAddToResult.left = new FormAttachment(middle, 0);
fdAddToResult.top = new FormAttachment(wbShowFiles, 2*margin);
fdAddToResult.right = new FormAttachment(100, 0);
wAddToResult.setLayoutData(fdAddToResult);
SelectionAdapter lsSelR = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
input.setChanged();
}
};
wAddToResult.addSelectionListener(lsSelR);
fdFileComp=new FormData();
fdFileComp.left = new FormAttachment(0, 0);
fdFileComp.top = new FormAttachment(0, 0);
fdFileComp.right = new FormAttachment(100, 0);
fdFileComp.bottom= new FormAttachment(100, 0);
wFileComp.setLayoutData(fdFileComp);
wFileComp.layout();
wFileTab.setControl(wFileComp);
/////////////////////////////////////////////////////////////
/// END OF FILE TAB
/////////////////////////////////////////////////////////////
//////////////////////////
// START OF CONTENT TAB///
///
wContentTab=new CTabItem(wTabFolder, SWT.NONE);
wContentTab.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.ContentTab.TabTitle"));
FormLayout contentLayout = new FormLayout ();
contentLayout.marginWidth = 3;
contentLayout.marginHeight = 3;
Composite wContentComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wContentComp);
wContentComp.setLayout(contentLayout);
// Append checkbox
wlAppend=new Label(wContentComp, SWT.RIGHT);
wlAppend.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.Append.Label"));
props.setLook(wlAppend);
fdlAppend=new FormData();
fdlAppend.left = new FormAttachment(0, 0);
fdlAppend.top = new FormAttachment(0, 0);
fdlAppend.right= new FormAttachment(middle, -margin);
wlAppend.setLayoutData(fdlAppend);
wAppend=new Button(wContentComp, SWT.CHECK);
props.setLook(wAppend);
wAppend.setToolTipText(BaseMessages.getString(PKG, "ExcelOutputDialog.Append.Tooltip"));
fdAppend=new FormData();
fdAppend.left = new FormAttachment(middle, 0);
fdAppend.top = new FormAttachment(0, 0);
fdAppend.right= new FormAttachment(100, 0);
wAppend.setLayoutData(fdAppend);
wAppend.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
input.setChanged();
}
});
wlHeader=new Label(wContentComp, SWT.RIGHT);
wlHeader.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.Header.Label"));
props.setLook(wlHeader);
fdlHeader=new FormData();
fdlHeader.left = new FormAttachment(0, 0);
fdlHeader.top = new FormAttachment(wAppend, margin);
fdlHeader.right= new FormAttachment(middle, -margin);
wlHeader.setLayoutData(fdlHeader);
wHeader=new Button(wContentComp, SWT.CHECK );
props.setLook(wHeader);
fdHeader=new FormData();
fdHeader.left = new FormAttachment(middle, 0);
fdHeader.top = new FormAttachment(wAppend, margin);
fdHeader.right= new FormAttachment(100, 0);
wHeader.setLayoutData(fdHeader);
wHeader.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
wlFooter=new Label(wContentComp, SWT.RIGHT);
wlFooter.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.Footer.Label"));
props.setLook(wlFooter);
fdlFooter=new FormData();
fdlFooter.left = new FormAttachment(0, 0);
fdlFooter.top = new FormAttachment(wHeader, margin);
fdlFooter.right= new FormAttachment(middle, -margin);
wlFooter.setLayoutData(fdlFooter);
wFooter=new Button(wContentComp, SWT.CHECK );
props.setLook(wFooter);
fdFooter=new FormData();
fdFooter.left = new FormAttachment(middle, 0);
fdFooter.top = new FormAttachment(wHeader, margin);
fdFooter.right= new FormAttachment(100, 0);
wFooter.setLayoutData(fdFooter);
wFooter.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
wlEncoding=new Label(wContentComp, SWT.RIGHT);
wlEncoding.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.Encoding.Label"));
props.setLook(wlEncoding);
fdlEncoding=new FormData();
fdlEncoding.left = new FormAttachment(0, 0);
fdlEncoding.top = new FormAttachment(wFooter, margin);
fdlEncoding.right= new FormAttachment(middle, -margin);
wlEncoding.setLayoutData(fdlEncoding);
wEncoding=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY);
wEncoding.setEditable(true);
props.setLook(wEncoding);
wEncoding.addModifyListener(lsMod);
fdEncoding=new FormData();
fdEncoding.left = new FormAttachment(middle, 0);
fdEncoding.top = new FormAttachment(wFooter, margin);
fdEncoding.right= new FormAttachment(100, 0);
wEncoding.setLayoutData(fdEncoding);
wEncoding.addFocusListener(new FocusListener()
{
public void focusLost(org.eclipse.swt.events.FocusEvent e)
{
}
public void focusGained(org.eclipse.swt.events.FocusEvent e)
{
Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(busy);
setEncodings();
shell.setCursor(null);
busy.dispose();
}
}
);
wlSplitEvery=new Label(wContentComp, SWT.RIGHT);
wlSplitEvery.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.SplitEvery.Label"));
props.setLook(wlSplitEvery);
fdlSplitEvery=new FormData();
fdlSplitEvery.left = new FormAttachment(0, 0);
fdlSplitEvery.top = new FormAttachment(wEncoding, margin);
fdlSplitEvery.right= new FormAttachment(middle, -margin);
wlSplitEvery.setLayoutData(fdlSplitEvery);
wSplitEvery=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSplitEvery);
wSplitEvery.addModifyListener(lsMod);
fdSplitEvery=new FormData();
fdSplitEvery.left = new FormAttachment(middle, 0);
fdSplitEvery.top = new FormAttachment(wEncoding, margin);
fdSplitEvery.right= new FormAttachment(100, 0);
wSplitEvery.setLayoutData(fdSplitEvery);
// Sheet name line
wlSheetname=new Label(wContentComp, SWT.RIGHT);
wlSheetname.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.Sheetname.Label"));
props.setLook(wlSheetname);
fdlSheetname=new FormData();
fdlSheetname.left = new FormAttachment(0, 0);
fdlSheetname.top = new FormAttachment(wSplitEvery, margin);
fdlSheetname.right= new FormAttachment(middle, -margin);
wlSheetname.setLayoutData(fdlSheetname);
wSheetname=new TextVar(transMeta, wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wSheetname.setToolTipText(BaseMessages.getString(PKG, "ExcelOutputDialog.Sheetname.Tooltip"));
props.setLook(wSheetname);
wSheetname.addModifyListener(lsMod);
fdSheetname=new FormData();
fdSheetname.left = new FormAttachment(middle, 0);
fdSheetname.top = new FormAttachment(wSplitEvery, margin);
fdSheetname.right= new FormAttachment(100, 0);
wSheetname.setLayoutData(fdSheetname);
// Protect Sheet?
wlProtectSheet=new Label(wContentComp, SWT.RIGHT);
wlProtectSheet.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.ProtectSheet.Label"));
props.setLook(wlProtectSheet);
fdlProtectSheet=new FormData();
fdlProtectSheet.left = new FormAttachment(0, 0);
fdlProtectSheet.top = new FormAttachment(wSheetname, margin);
fdlProtectSheet.right= new FormAttachment(middle, -margin);
wlProtectSheet.setLayoutData(fdlProtectSheet);
wProtectSheet=new Button(wContentComp, SWT.CHECK);
props.setLook(wProtectSheet);
fdProtectSheet=new FormData();
fdProtectSheet.left = new FormAttachment(middle, 0);
fdProtectSheet.top = new FormAttachment(wSheetname, margin);
fdProtectSheet.right= new FormAttachment(100, 0);
wProtectSheet.setLayoutData(fdProtectSheet);
wProtectSheet.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
EnablePassword();
}
}
);
// Password line
wlPassword=new Label(wContentComp, SWT.RIGHT);
wlPassword.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.Password.Label"));
props.setLook(wlPassword);
fdlPassword=new FormData();
fdlPassword.left = new FormAttachment(0, 0);
fdlPassword.top = new FormAttachment(wProtectSheet, margin);
fdlPassword.right= new FormAttachment(middle, -margin);
wlPassword.setLayoutData(fdlPassword);
wPassword=new TextVar(transMeta, wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER | SWT.PASSWORD);
wPassword.setToolTipText(BaseMessages.getString(PKG, "ExcelOutputDialog.Password.Tooltip"));
props.setLook(wPassword);
wPassword.setEchoChar('*');
wPassword.addModifyListener(lsMod);
fdPassword=new FormData();
fdPassword.left = new FormAttachment(middle, 0);
fdPassword.top = new FormAttachment(wProtectSheet, margin);
fdPassword.right= new FormAttachment(100, 0);
wPassword.setLayoutData(fdPassword);
// auto size columns?
wlAutoSize=new Label(wContentComp, SWT.RIGHT);
wlAutoSize.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.AutoSize.Label"));
props.setLook(wlAutoSize);
fdlAutoSize=new FormData();
fdlAutoSize.left = new FormAttachment(0, 0);
fdlAutoSize.top = new FormAttachment(wPassword, margin);
fdlAutoSize.right= new FormAttachment(middle, -margin);
wlAutoSize.setLayoutData(fdlAutoSize);
wAutoSize=new Button(wContentComp, SWT.CHECK);
props.setLook(wAutoSize);
wAutoSize.setToolTipText(BaseMessages.getString(PKG, "ExcelOutputDialog.AutoSize.Tooltip"));
fdAutoSize=new FormData();
fdAutoSize.left = new FormAttachment(middle, 0);
fdAutoSize.top = new FormAttachment(wPassword, margin);
fdAutoSize.right= new FormAttachment(100, 0);
wAutoSize.setLayoutData(fdAutoSize);
wAutoSize.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
EnableAutoSize();
}
}
);
// write null values as blank cells ?
wlNullIsBlank=new Label(wContentComp, SWT.RIGHT);
wlNullIsBlank.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.NullIsBlank.Label"));
props.setLook(wlNullIsBlank);
fdlNullIsBlank=new FormData();
fdlNullIsBlank.left = new FormAttachment(0, 0);
fdlNullIsBlank.top = new FormAttachment(wAutoSize, margin);
fdlNullIsBlank.right= new FormAttachment(middle, -margin);
wlNullIsBlank.setLayoutData(fdlNullIsBlank);
wNullIsBlank=new Button(wContentComp, SWT.CHECK);
props.setLook(wNullIsBlank);
wNullIsBlank.setToolTipText(BaseMessages.getString(PKG, "ExcelOutputDialog.NullIsBlank.Tooltip"));
fdNullIsBlank=new FormData();
fdNullIsBlank.left = new FormAttachment(middle, 0);
fdNullIsBlank.top = new FormAttachment(wAutoSize, margin);
fdNullIsBlank.right= new FormAttachment(100, 0);
wNullIsBlank.setLayoutData(fdNullIsBlank);
// ///////////////////////////////
// START OF Template Group GROUP //
/////////////////////////////////
wTemplateGroup= new Group(wContentComp, SWT.SHADOW_NONE);
props.setLook(wTemplateGroup);
wTemplateGroup.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.TemplateGroup.Label"));
FormLayout TemplateGroupgroupLayout = new FormLayout();
TemplateGroupgroupLayout.marginWidth = 10;
TemplateGroupgroupLayout.marginHeight = 10;
wTemplateGroup.setLayout(TemplateGroupgroupLayout);
// Use template
wlTemplate=new Label(wTemplateGroup, SWT.RIGHT);
wlTemplate.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.Template.Label"));
props.setLook(wlTemplate);
fdlTemplate=new FormData();
fdlTemplate.left = new FormAttachment(0, 0);
fdlTemplate.top = new FormAttachment(wNullIsBlank, margin);
fdlTemplate.right= new FormAttachment(middle, -margin);
wlTemplate.setLayoutData(fdlTemplate);
wTemplate=new Button(wTemplateGroup, SWT.CHECK );
props.setLook(wTemplate);
fdTemplate=new FormData();
fdTemplate.left = new FormAttachment(middle, 0);
fdTemplate.top = new FormAttachment(wNullIsBlank, margin);
fdTemplate.right= new FormAttachment(100, 0);
wTemplate.setLayoutData(fdTemplate);
wTemplate.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
EnableTemplate();
}
}
);
// TemplateFilename line
wlTemplateFilename=new Label(wTemplateGroup, SWT.RIGHT);
wlTemplateFilename.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.TemplateFilename.Label"));
props.setLook(wlTemplateFilename);
fdlTemplateFilename=new FormData();
fdlTemplateFilename.left = new FormAttachment(0, 0);
fdlTemplateFilename.top = new FormAttachment(wTemplate, margin);
fdlTemplateFilename.right= new FormAttachment(middle, -margin);
wlTemplateFilename.setLayoutData(fdlTemplateFilename);
wbTemplateFilename=new Button(wTemplateGroup, SWT.PUSH| SWT.CENTER);
props.setLook(wbTemplateFilename);
wbTemplateFilename.setText(BaseMessages.getString(PKG, "System.Button.Browse"));
fdbTemplateFilename=new FormData();
fdbTemplateFilename.right= new FormAttachment(100, 0);
fdbTemplateFilename.top = new FormAttachment(wTemplate, 0);
wbTemplateFilename.setLayoutData(fdbTemplateFilename);
wTemplateFilename=new TextVar(transMeta, wTemplateGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTemplateFilename);
wTemplateFilename.addModifyListener(lsMod);
fdTemplateFilename=new FormData();
fdTemplateFilename.left = new FormAttachment(middle, 0);
fdTemplateFilename.top = new FormAttachment(wTemplate, margin);
fdTemplateFilename.right= new FormAttachment(wbTemplateFilename, -margin);
wTemplateFilename.setLayoutData(fdTemplateFilename);
// Template Append
wlTemplateAppend=new Label(wTemplateGroup, SWT.RIGHT);
wlTemplateAppend.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.TemplateAppend.Label"));
props.setLook(wlTemplateAppend);
fdlTemplateAppend=new FormData();
fdlTemplateAppend.left = new FormAttachment(0, 0);
fdlTemplateAppend.top = new FormAttachment(wTemplateFilename, margin);
fdlTemplateAppend.right= new FormAttachment(middle, -margin);
wlTemplateAppend.setLayoutData(fdlTemplateAppend);
wTemplateAppend=new Button(wTemplateGroup, SWT.CHECK );
props.setLook(wTemplateAppend);
fdTemplateAppend=new FormData();
fdTemplateAppend.left = new FormAttachment(middle, 0);
fdTemplateAppend.top = new FormAttachment(wTemplateFilename, margin);
fdTemplateAppend.right= new FormAttachment(100, 0);
wTemplateAppend.setLayoutData(fdTemplateAppend);
wTemplateAppend.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
fdTemplateGroup= new FormData();
fdTemplateGroup.left = new FormAttachment(0, margin);
fdTemplateGroup.top = new FormAttachment(wNullIsBlank, margin);
fdTemplateGroup.right = new FormAttachment(100, -margin);
wTemplateGroup.setLayoutData(fdTemplateGroup);
// ///////////////////////////////////////////////////////////
// / END OF Template Group GROUP
// ///////////////////////////////////////////////////////////
fdContentComp = new FormData();
fdContentComp.left = new FormAttachment(0, 0);
fdContentComp.top = new FormAttachment(0, 0);
fdContentComp.right = new FormAttachment(100, 0);
fdContentComp.bottom= new FormAttachment(100, 0);
wContentComp.setLayoutData(fdContentComp);
wContentComp.layout();
wContentTab.setControl(wContentComp);
/////////////////////////////////////////////////////////////
/// END OF CONTENT TAB
/////////////////////////////////////////////////////////////
// Fields tab...
//
wFieldsTab = new CTabItem(wTabFolder, SWT.NONE);
wFieldsTab.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.FieldsTab.TabTitle"));
FormLayout fieldsLayout = new FormLayout ();
fieldsLayout.marginWidth = Const.FORM_MARGIN;
fieldsLayout.marginHeight = Const.FORM_MARGIN;
Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE);
wFieldsComp.setLayout(fieldsLayout);
props.setLook(wFieldsComp);
wGet=new Button(wFieldsComp, SWT.PUSH);
wGet.setText(BaseMessages.getString(PKG, "System.Button.GetFields"));
wGet.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.GetFields"));
wMinWidth =new Button(wFieldsComp, SWT.PUSH);
wMinWidth.setText(BaseMessages.getString(PKG, "ExcelOutputDialog.MinWidth.Button"));
wMinWidth.setToolTipText(BaseMessages.getString(PKG, "ExcelOutputDialog.MinWidth.Tooltip"));
setButtonPositions(new Button[] { wGet, wMinWidth}, margin, null);
final int FieldsRows=input.getOutputFields().length;
// Prepare a list of possible formats...
String[] formats = new String[]
{
// Numbers
"#",
"0",
"0.00",
"#,##0",
"#,##0.00",
"$#,##0;($#,##0)",
"$#,##0;($#,##0)",
"$#,##0;($#,##0)",
"$#,##0;($#,##0)",
"0%",
"0.00%",
"0.00E00",
"#,##0;(#,##0)",
"#,##0;(#,##0)",
"#,##0.00;(#,##0.00)",
"#,##0.00;(#,##0.00)",
"#,##0;(#,##0)",
"#,##0;(#,##0)",
"#,##0.00;(#,##0.00)",
"#,##0.00;(#,##0.00)",
"#,##0.00;(#,##0.00)",
"##0.0E0",
// Forces text
"@",
// Dates
"M/d/yy",
"d-MMM-yy",
"d-MMM",
"MMM-yy",
"h:mm a",
"h:mm:ss a",
"H:mm",
"H:mm:ss",
"M/d/yy H:mm",
"mm:ss",
"H:mm:ss",
"H:mm:ss",
};
colinf=new ColumnInfo[]
{
new ColumnInfo(BaseMessages.getString(PKG, "ExcelOutputDialog.NameColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false),
new ColumnInfo(BaseMessages.getString(PKG, "ExcelOutputDialog.TypeColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes() ),
new ColumnInfo(BaseMessages.getString(PKG, "ExcelOutputDialog.FormatColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, formats),
};
wFields=new TableView(transMeta, wFieldsComp,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(0, 0);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(wGet, -margin);
wFields.setLayoutData(fdFields);
//
// Search the fields in the background
final Runnable runnable = new Runnable()
{
public void run()
{
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta!=null)
{
try
{
RowMetaInterface row = transMeta.getPrevStepFields(stepMeta);
// Remember these fields...
for (int i=0;i<row.size();i++)
{
inputFields.put(row.getValueMeta(i).getName(), Integer.valueOf(i));
}
setComboBoxes();
}
catch(KettleException e)
{
logError(BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message"));
}
}
}
};
new Thread(runnable).start();
fdFieldsComp=new FormData();
fdFieldsComp.left = new FormAttachment(0, 0);
fdFieldsComp.top = new FormAttachment(0, 0);
fdFieldsComp.right = new FormAttachment(100, 0);
fdFieldsComp.bottom= new FormAttachment(100, 0);
wFieldsComp.setLayoutData(fdFieldsComp);
wFieldsComp.layout();
wFieldsTab.setControl(wFieldsComp);
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(wStepname, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
setButtonPositions(new Button[] { wOK, wCancel }, margin, wTabFolder);
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsMinWidth = new Listener() { public void handleEvent(Event e) { setMinimalWidth(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
wOK.addListener (SWT.Selection, lsOK );
wGet.addListener (SWT.Selection, lsGet );
wMinWidth.addListener (SWT.Selection, lsMinWidth );
wCancel.addListener(SWT.Selection, lsCancel);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
wFilename.addSelectionListener( lsDef );
wTemplateFilename.addSelectionListener( lsDef );
// Whenever something changes, set the tooltip to the expanded version:
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFilename.setToolTipText(transMeta.environmentSubstitute( wFilename.getText() ) );
}
}
);
wTemplateFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wTemplateFilename.setToolTipText(transMeta.environmentSubstitute( wTemplateFilename.getText() ) );
}
}
);
wbFilename.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(new String[] {"*.xls", "*.*"});
if (wFilename.getText()!=null)
{
dialog.setFileName(transMeta.environmentSubstitute(wFilename.getText()));
}
dialog.setFilterNames(new String[] {BaseMessages.getString(PKG, "System.FileType.ExcelFiles"), BaseMessages.getString(PKG, "System.FileType.AllFiles")});
if (dialog.open()!=null)
{
wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName());
}
}
}
);
wbTemplateFilename.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] {"*.xls", "*.*"});
if (wTemplateFilename.getText()!=null)
{
dialog.setFileName(transMeta.environmentSubstitute(wTemplateFilename.getText()));
}
dialog.setFilterNames(new String[] {BaseMessages.getString(PKG, "System.FileType.ExcelFiles"), BaseMessages.getString(PKG, "System.FileType.AllFiles")});
if (dialog.open()!=null)
{
wTemplateFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName());
}
}
}
);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
lsResize = new Listener()
{
public void handleEvent(Event event)
{
Point size = shell.getSize();
wFields.setSize(size.x-10, size.y-50);
wFields.table.setSize(size.x-10, size.y-50);
wFields.redraw();
}
};
shell.addListener(SWT.Resize, lsResize);
wTabFolder.setSelection(0);
// Set the shell size, based upon previous time...
setSize();
getData();
setDateTimeFormat();
EnableAutoSize();
input.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
private void EnableAutoSize()
{
wMinWidth.setEnabled(!wAutoSize.getSelection());
}
private void setDateTimeFormat()
{
if(wSpecifyFormat.getSelection())
{
wAddDate.setSelection(false);
wAddTime.setSelection(false);
}
wDateTimeFormat.setEnabled(wSpecifyFormat.getSelection());
wlDateTimeFormat.setEnabled(wSpecifyFormat.getSelection());
wAddDate.setEnabled(!wSpecifyFormat.getSelection());
wlAddDate.setEnabled(!wSpecifyFormat.getSelection());
wAddTime.setEnabled(!wSpecifyFormat.getSelection());
wlAddTime.setEnabled(!wSpecifyFormat.getSelection());
}
protected void setComboBoxes()
{
// Something was changed in the row.
//
final Map<String, Integer> fields = new HashMap<String, Integer>();
// Add the currentMeta fields...
fields.putAll(inputFields);
Set<String> keySet = fields.keySet();
List<String> entries = new ArrayList<String>(keySet);
String fieldNames[] = (String[]) entries.toArray(new String[entries.size()]);
Const.sortStrings(fieldNames);
colinf[0].setComboValues(fieldNames);
}
private void setEncodings()
{
// Encoding of the text file:
if (!gotEncodings)
{
gotEncodings = true;
wEncoding.removeAll();
List<Charset> values = new ArrayList<Charset>(Charset.availableCharsets().values());
for (int i=0;i<values.size();i++)
{
Charset charSet = (Charset)values.get(i);
wEncoding.add( charSet.displayName() );
}
// Now select the default!
String defEncoding = Const.getEnvironmentVariable("file.encoding", "UTF-8");
int idx = Const.indexOfString(defEncoding, wEncoding.getItems() );
if (idx>=0) wEncoding.select( idx );
}
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
if (input.getFileName() != null) wFilename.setText(input.getFileName());
wDoNotOpenNewFileInit.setSelection(input.isDoNotOpenNewFileInit());
if (input.getExtension() != null) wExtension.setText(input.getExtension());
if (input.getEncoding() !=null) wEncoding.setText(input.getEncoding());
if (input.getTemplateFileName() != null) wTemplateFilename.setText(input.getTemplateFileName());
wSplitEvery.setText(""+input.getSplitEvery());
wAppend.setSelection(input.isAppend());
wHeader.setSelection(input.isHeaderEnabled());
wFooter.setSelection(input.isFooterEnabled());
wAddDate.setSelection(input.isDateInFilename());
wAddTime.setSelection(input.isTimeInFilename());
if (input.getDateTimeFormat()!= null) wDateTimeFormat.setText( input.getDateTimeFormat() );
wSpecifyFormat.setSelection(input.isSpecifyFormat());
wAddToResult.setSelection(input.isAddToResultFiles());
wAutoSize.setSelection(input.isAutoSizeColums());
wNullIsBlank.setSelection(input.isNullBlank());
wAddStepnr.setSelection(input.isStepNrInFilename());
wTemplate.setSelection(input.isTemplateEnabled());
wTemplateAppend.setSelection(input.isTemplateAppend());
if (input.getSheetname() != null)
{
wSheetname.setText(input.getSheetname());
}
else
{
wSheetname.setText("Sheet1");
}
wProtectSheet.setSelection(input.isSheetProtected());
EnablePassword();
EnableTemplate();
if (input.getPassword() != null) wPassword.setText(input.getPassword());
logDebug("getting fields info...");
for (int i=0;i<input.getOutputFields().length;i++)
{
ExcelField field = input.getOutputFields()[i];
TableItem item = wFields.table.getItem(i);
if (field.getName()!=null) item.setText(1, field.getName());
item.setText(2, field.getTypeDesc());
if (field.getFormat()!=null) item.setText(3, field.getFormat());
}
wFields.optWidth(true);
wStepname.selectAll();
}
private void cancel()
{
stepname=null;
input.setChanged(backupChanged);
dispose();
}
private void getInfo(ExcelOutputMeta tfoi)
{
tfoi.setFileName( wFilename.getText() );
tfoi.setEncoding( wEncoding.getText() );
tfoi.setDoNotOpenNewFileInit(wDoNotOpenNewFileInit.getSelection() );
tfoi.setExtension( wExtension.getText() );
tfoi.setTemplateFileName( wTemplateFilename.getText() );
tfoi.setSplitEvery( Const.toInt(wSplitEvery.getText(), 0) );
tfoi.setAppend( wAppend.getSelection() );
tfoi.setHeaderEnabled( wHeader.getSelection() );
tfoi.setFooterEnabled( wFooter.getSelection() );
tfoi.setStepNrInFilename( wAddStepnr.getSelection() );
tfoi.setDateInFilename( wAddDate.getSelection() );
tfoi.setTimeInFilename( wAddTime.getSelection() );
tfoi.setDateTimeFormat(wDateTimeFormat.getText());
tfoi.setSpecifyFormat(wSpecifyFormat.getSelection());
tfoi.setAutoSizeColums(wAutoSize.getSelection());
tfoi.setNullIsBlank(wNullIsBlank.getSelection());
tfoi.setAddToResultFiles( wAddToResult.getSelection() );
tfoi.setProtectSheet( wProtectSheet.getSelection() );
tfoi.setPassword( wPassword.getText() );
tfoi.setTemplateEnabled( wTemplate.getSelection() );
tfoi.setTemplateAppend( wTemplateAppend.getSelection() );
if (wSheetname.getText()!=null)
{
tfoi.setSheetname( wSheetname.getText() );
}
else
{
tfoi.setSheetname( "Sheet 1" );
}
int i;
//Table table = wFields.table;
int nrfields = wFields.nrNonEmpty();
tfoi.allocate(nrfields);
for (i=0;i<nrfields;i++)
{
ExcelField field = new ExcelField();
TableItem item = wFields.getNonEmpty(i);
field.setName( item.getText(1) );
field.setType( item.getText(2) );
field.setFormat( item.getText(3) );
tfoi.getOutputFields()[i] = field;
}
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
stepname = wStepname.getText(); // return value
getInfo(input);
dispose();
}
private void EnablePassword()
{
input.setChanged();
wPassword.setEnabled(wProtectSheet.getSelection());
wlPassword.setEnabled(wProtectSheet.getSelection());
}
private void EnableTemplate()
{
input.setChanged();
wTemplateFilename.setEnabled(wTemplate.getSelection());
wTemplateAppend.setEnabled(wTemplate.getSelection());
}
private void get()
{
try
{
RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if (r!=null)
{
TableItemInsertListener listener = new TableItemInsertListener()
{
public boolean tableItemInserted(TableItem tableItem, ValueMetaInterface v)
{
if (v.isNumber())
{
if (v.getLength()>0)
{
int le=v.getLength();
int pr=v.getPrecision();
if (v.getPrecision()<=0)
{
pr=0;
}
String mask="";
for (int m=0;m<le-pr;m++)
{
mask+="0";
}
if (pr>0) mask+=".";
for (int m=0;m<pr;m++)
{
mask+="0";
}
tableItem.setText(3, mask);
}
}
return true;
}
};
BaseStepDialog.getFieldsFromPrevious(r, wFields, 1, new int[] { 1 }, new int[] { 2 }, 4, 5, listener);
}
}
catch(KettleException ke)
{
new ErrorDialog(shell, BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Title"), BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message"), ke);
}
}
/**
* Sets the output width to minimal width...
*
*/
public void setMinimalWidth()
{
int nrNonEmptyFields = wFields.nrNonEmpty();
for (int i=0;i<nrNonEmptyFields;i++)
{
TableItem item = wFields.getNonEmpty(i);
item.setText(4, "");
item.setText(5, "");
int type = ValueMeta.getType(item.getText(2));
switch(type)
{
case ValueMetaInterface.TYPE_STRING: item.setText(3, ""); break;
case ValueMetaInterface.TYPE_INTEGER: item.setText(3, "0"); break;
case ValueMetaInterface.TYPE_NUMBER: item.setText(3, "0.#####"); break;
case ValueMetaInterface.TYPE_DATE: break;
default: break;
}
}
wFields.optWidth(true);
}
public String toString()
{
return this.getClass().getName();
}
}
| lgpl-2.1 |
jzuijlek/Lucee | core/src/main/java/lucee/runtime/ComponentSpecificAccess.java | 14204 | /**
* Copyright (c) 2014, the Railo Company Ltd.
* Copyright (c) 2015, Lucee Assosication Switzerland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
package lucee.runtime;
import java.util.Iterator;
import java.util.Set;
import lucee.commons.lang.types.RefBoolean;
import lucee.runtime.component.Member;
import lucee.runtime.component.Property;
import lucee.runtime.dump.DumpData;
import lucee.runtime.dump.DumpProperties;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.type.Collection;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Objects;
import lucee.runtime.type.Struct;
import lucee.runtime.type.UDF;
import lucee.runtime.type.UDFProperties;
import lucee.runtime.type.dt.DateTime;
import lucee.runtime.type.scope.Scope;
import lucee.runtime.type.scope.Variables;
import lucee.runtime.type.util.StructSupport;
public final class ComponentSpecificAccess extends StructSupport implements Component, Objects {
private int access;
private Component component;
/**
* constructor of the class
*
* @param access
* @param component
* @throws ExpressionException
*/
public ComponentSpecificAccess(int access, Component component) {
this.access = access;
this.component = component;
}
public static ComponentSpecificAccess toComponentSpecificAccess(int access, Component component) {
if (component instanceof ComponentSpecificAccess) {
ComponentSpecificAccess csa = (ComponentSpecificAccess) component;
if (access == csa.getAccess()) return csa;
component = csa.getComponent();
}
return new ComponentSpecificAccess(access, component);
}
@Override
public PageSource getPageSource() {
return component.getPageSource();
}
@Override
public Set keySet() {
return component.keySet(access);
}
@Override
public String getDisplayName() {
return component.getDisplayName();
}
@Override
public String getExtends() {
return component.getExtends();
}
@Override
public String getHint() {
return component.getHint();
}
@Override
public String getName() {
return component.getName();
}
@Override
public String getCallName() {
return component.getCallName();
}
@Override
public String getAbsName() {
return component.getAbsName();
}
@Override
public String getBaseAbsName() {
return component.getBaseAbsName();
}
@Override
public boolean isBasePeristent() {
return component.isPersistent();
}
@Override
public boolean getOutput() {
return component.getOutput();
}
@Override
public boolean instanceOf(String type) {
return component.instanceOf(type);
}
@Override
public boolean isValidAccess(int access) {
return component.isValidAccess(access);
}
@Override
public Struct getMetaData(PageContext pc) throws PageException {
return component.getMetaData(pc);
}
@Override
public Object call(PageContext pc, String key, Object[] args) throws PageException {
return call(pc, KeyImpl.init(key), args);
}
@Override
public Object call(PageContext pc, Collection.Key key, Object[] args) throws PageException {
return component.call(pc, access, key, args);
}
@Override
public Object callWithNamedValues(PageContext pc, String key, Struct args) throws PageException {
return callWithNamedValues(pc, KeyImpl.init(key), args);
}
@Override
public Object callWithNamedValues(PageContext pc, Collection.Key key, Struct args) throws PageException {
return component.callWithNamedValues(pc, access, key, args);
}
@Override
public int size() {
return component.size(access);
}
@Override
public Collection.Key[] keys() {
return component.keys(access);
}
@Override
public Object remove(Collection.Key key) throws PageException {
return component.remove(key);
}
@Override
public Object removeEL(Collection.Key key) {
return component.removeEL(key);
}
@Override
public void clear() {
component.clear();
}
@Override
public Object get(Collection.Key key) throws PageException {
return component.get(access, key);
}
@Override
public Object get(Collection.Key key, Object defaultValue) {
return component.get(access, key, defaultValue);
}
@Override
public Object set(Collection.Key key, Object value) throws PageException {
return component.set(key, value);
}
@Override
public Object setEL(Collection.Key key, Object value) {
return component.setEL(key, value);
}
@Override
public Iterator<Collection.Key> keyIterator() {
return component.keyIterator(access);
}
@Override
public Iterator<String> keysAsStringIterator() {
return component.keysAsStringIterator(access);
}
@Override
public Iterator<Entry<Key, Object>> entryIterator() {
return component.entryIterator(access);
}
@Override
public Iterator<Object> valueIterator() {
return component.valueIterator(access);
}
@Override
public boolean containsKey(Collection.Key key) {
return component.get(access, key, null) != null;
}
@Override
public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) {
return component.toDumpData(pageContext, maxlevel, dp, access);
}
@Override
public String castToString() throws PageException {
return component.castToString();
}
@Override
public String castToString(String defaultValue) {
return component.castToString(defaultValue);
}
@Override
public boolean castToBooleanValue() throws PageException {
return component.castToBooleanValue();
}
@Override
public Boolean castToBoolean(Boolean defaultValue) {
return component.castToBoolean(defaultValue);
}
@Override
public double castToDoubleValue() throws PageException {
return component.castToDoubleValue();
}
@Override
public double castToDoubleValue(double defaultValue) {
return component.castToDoubleValue(defaultValue);
}
@Override
public DateTime castToDateTime() throws PageException {
return component.castToDateTime();
}
@Override
public DateTime castToDateTime(DateTime defaultValue) {
return component.castToDateTime(defaultValue);
}
@Override
public int compareTo(boolean b) throws PageException {
return component.compareTo(b);
}
@Override
public int compareTo(DateTime dt) throws PageException {
return component.compareTo(dt);
}
@Override
public int compareTo(String str) throws PageException {
return component.compareTo(str);
}
@Override
public int compareTo(double d) throws PageException {
return component.compareTo(d);
}
/*
* public Object get(PageContext pc, String key, Object defaultValue) { return
* get(pc,KeyImpl.init(key),defaultValue); }
*/
@Override
public Object get(PageContext pc, Collection.Key key, Object defaultValue) {
return component.get(access, key, defaultValue);
}
/*
* public Object get(PageContext pc, String key) throws PageException { return
* get(pc,KeyImpl.init(key)); }
*/
@Override
public Object get(PageContext pc, Collection.Key key) throws PageException {
return component.get(access, key);
}
@Override
public Collection duplicate(boolean deepCopy) {
return new ComponentSpecificAccess(access, (Component) component.duplicate(deepCopy));
}
/*
* public Object set(PageContext pc, String propertyName, Object value) throws PageException {
* return component.set(propertyName,value); }
*/
@Override
public Object set(PageContext pc, Collection.Key propertyName, Object value) throws PageException {
return component.set(propertyName, value);
}
/*
* public Object setEL(PageContext pc, String propertyName, Object value) { return
* component.setEL(propertyName,value); }
*/
@Override
public Object setEL(PageContext pc, Key propertyName, Object value) {
return component.setEL(propertyName, value);
}
public int getAccess() {
return access;
}
@Override
public Class getJavaAccessClass(RefBoolean isNew) throws PageException {
return component.getJavaAccessClass(isNew);
}
@Override
public String getWSDLFile() {
return component.getWSDLFile();
}
@Override
public Property[] getProperties(boolean onlyPeristent) {
return component.getProperties(onlyPeristent);
}
@Override
public Property[] getProperties(boolean onlyPeristent, boolean includeBaseProperties, boolean overrideProperties, boolean inheritedMappedSuperClassOnly) {
return component.getProperties(onlyPeristent, includeBaseProperties, overrideProperties, inheritedMappedSuperClassOnly);
}
@Override
public ComponentScope getComponentScope() {
return component.getComponentScope();
}
public Component getComponent() {
return component;
}
@Override
public boolean contains(PageContext pc, Key key) {
return component.contains(access, key);
}
@Override
public Member getMember(int access, Key key, boolean dataMember, boolean superAccess) {
return component.getMember(access, key, dataMember, superAccess);
}
@Override
public void setProperty(Property property) throws PageException {
component.setProperty(property);
}
@Override
public boolean equalTo(String type) {
return component.equalTo(type);
}
@Override
public void registerUDF(Collection.Key key, UDF udf) throws PageException {
component.registerUDF(key, udf);
}
@Override
public void registerUDF(Collection.Key key, UDFProperties props) throws PageException {
component.registerUDF(key, props);
}
@Override
public boolean isPersistent() {
return component.isPersistent();
}
@Override
public boolean isAccessors() {
return component.isAccessors();
}
@Override
public void setEntity(boolean entity) {
component.setEntity(entity);
}
@Override
public boolean isEntity() {
return component.isEntity();
}
@Override
public Component getBaseComponent() {
return component.getBaseComponent();
}
@Override
public Set<Key> keySet(int access) {
return component.keySet(access);
}
@Override
public Object getMetaStructItem(Key name) {
return component.getMetaStructItem(name);
}
@Override
public Object call(PageContext pc, int access, Key name, Object[] args) throws PageException {
return component.call(pc, access, name, args);
}
@Override
public Object callWithNamedValues(PageContext pc, int access, Key name, Struct args) throws PageException {
return component.callWithNamedValues(pc, access, name, args);
}
@Override
public int size(int access) {
return component.size();
}
@Override
public Key[] keys(int access) {
return component.keys(access);
}
@Override
public Iterator<Key> keyIterator(int access) {
return component.keyIterator(access);
}
@Override
public Iterator<String> keysAsStringIterator(int access) {
return component.keysAsStringIterator(access);
}
@Override
public Iterator<Entry<Key, Object>> entryIterator(int access) {
return component.entryIterator(access);
}
@Override
public Iterator<Object> valueIterator(int access) {
return component.valueIterator(access);
}
@Override
public Object get(int access, Key key) throws PageException {
return component.get(access, key);
}
@Override
public Object get(int access, Key key, Object defaultValue) {
return component.get(access, key, defaultValue);
}
@Override
public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp, int access) {
return toDumpData(pageContext, maxlevel, dp, access);
}
@Override
public boolean contains(int access, Key name) {
return component.contains(access, name);
}
@Override
public Class getJavaAccessClass(PageContext pc, RefBoolean isNew, boolean writeLog, boolean takeTop, boolean create, boolean supressWSbeforeArg) throws PageException {
return component.getJavaAccessClass(pc, isNew, writeLog, takeTop, create, supressWSbeforeArg);
}
@Override
public Class getJavaAccessClass(PageContext pc, RefBoolean isNew, boolean writeLog, boolean takeTop, boolean create, boolean supressWSbeforeArg, boolean output,
boolean returnValue) throws PageException {
return component.getJavaAccessClass(pc, isNew, writeLog, takeTop, create, supressWSbeforeArg, output, returnValue);
}
@Override
public int getModifier() {
return component.getModifier();
}
@Override
public String id() {
return component.id();
}
@Override
public Scope staticScope() {
return component.staticScope();
}
@Override
public Variables beforeStaticConstructor(PageContext pc) {
return component.beforeStaticConstructor(pc);
}
@Override
public void afterStaticConstructor(PageContext pc, Variables var) {
component.afterStaticConstructor(pc, var);
}
@Override
public Interface[] getInterfaces() {
return component.getInterfaces();
}
@Override
public int getType() {
if (component instanceof ComponentImpl) {
return ((ComponentImpl) component).getType();
}
return Struct.TYPE_REGULAR;
}
} | lgpl-2.1 |
foodisgoodyesiam/Joushou-Tweaks | src/main/java/foodisgood/mods/joushou_tweaks/JTPath2.java | 10614 | package foodisgood.mods.joushou_tweaks;
import java.util.List;
import java.util.Random;
import cpw.mods.fml.common.registry.VillagerRegistry.IVillageCreationHandler;
import net.minecraft.util.MathHelper;
import net.minecraft.world.gen.structure.MapGenVillage;
import net.minecraft.world.gen.structure.StructureBoundingBox;
import net.minecraft.world.gen.structure.StructureComponent;
import net.minecraft.world.gen.structure.StructureVillagePieces;
import net.minecraft.world.gen.structure.StructureVillagePieces.PieceWeight;
import net.minecraft.world.gen.structure.StructureVillagePieces.Start;
@SuppressWarnings("rawtypes")
public class JTPath2 extends JTPath {
JTPath parent;
int tier;
public static JTPath2 construct(JTPath parentPath, int tier, StructureVillagePieces.Start start, List pieces, Random rand, int p1, int p2, int p3, int p4, int p5) {
StructureBoundingBox bounds = StructureBoundingBox.getComponentToAddBoundingBox(p1, p2, p3, 0, 0, 0, 16, 26, 16, p4);
return (StructureComponent.findIntersecting(pieces, bounds) == null) ? new JTPath2(parentPath, tier, start, p5, rand, bounds, p4) : null;
}
public JTPath2(JTPath parentPath, int tier, StructureVillagePieces.Start start, int int2, Random rand, StructureBoundingBox box, int terrainType) {
super(start, int2, rand, box, terrainType);
parent = parentPath;
this.tier = tier;
}
public static StructureBoundingBox func_74933_a(StructureVillagePieces.Start startPiece, List p_74933_1_, Random p_74933_2_, int xCoord, int p_74933_4_, int zCoord, int terrainType) {
for (int i1 = 7 * MathHelper.getRandomIntegerInRange(p_74933_2_, 3, 7); i1 >= 7; i1 -= 7) {
switch (terrainType) {//Actually direction, not terrain type...
case 2://-Z
if (Math.abs(startPiece.getBoundingBox().minZ-zCoord+i1)>=villageSize)
continue;
break;
case 0://+Z
if (Math.abs(startPiece.getBoundingBox().minZ-zCoord-i1)>=villageSize)
continue;
break;
case 1://-X
if (Math.abs(startPiece.getBoundingBox().minX-xCoord+i1)>=villageSize)
continue;
break;
default:
case 3://+X
if (Math.abs(startPiece.getBoundingBox().minX-xCoord-i1)>=villageSize)
continue;
break;
}
StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(xCoord, p_74933_4_, zCoord, 0, 0, 0, 3, 3, i1, terrainType);
if (StructureComponent.findIntersecting(p_74933_1_, structureboundingbox) == null)
return structureboundingbox;
}
return null;
}
@Override
protected void tryEndRoads(StructureComponent p_74861_1_, List p_74861_2_, Random rand) {
if (tier>7 || totalMade>maxBuildings)
return;
if (rand.nextInt(6) != 0 && parent.totalMade<maxBuildings) {//TODO: Replace this with a configurable number
switch (this.coordBaseMode) {
case 0:
getNextComponentVillagePath2((StructureVillagePieces.Start)p_74861_1_, p_74861_2_, rand, this.getBoundingBox().minX - 1, this.getBoundingBox().minY, this.getBoundingBox().maxZ - 2, 1, this.getComponentType());
break;
case 1:
getNextComponentVillagePath2((StructureVillagePieces.Start)p_74861_1_, p_74861_2_, rand, this.getBoundingBox().minX, this.getBoundingBox().minY, this.getBoundingBox().minZ - 1, 2, this.getComponentType());
break;
case 2:
getNextComponentVillagePath2((StructureVillagePieces.Start)p_74861_1_, p_74861_2_, rand, this.getBoundingBox().minX - 1, this.getBoundingBox().minY, this.getBoundingBox().minZ, 1, this.getComponentType());
break;
case 3:
getNextComponentVillagePath2((StructureVillagePieces.Start)p_74861_1_, p_74861_2_, rand, this.getBoundingBox().maxX - 2, this.getBoundingBox().minY, this.getBoundingBox().minZ - 1, 2, this.getComponentType());
}
}
if (rand.nextInt(6) != 0 && parent.totalMade<maxBuildings) {//TODO: Don't forget this one too!
switch (this.coordBaseMode) {
case 0:
getNextComponentVillagePath2((StructureVillagePieces.Start)p_74861_1_, p_74861_2_, rand, this.getBoundingBox().maxX + 1, this.getBoundingBox().minY, this.getBoundingBox().maxZ - 2, 3, this.getComponentType());
break;
case 1:
getNextComponentVillagePath2((StructureVillagePieces.Start)p_74861_1_, p_74861_2_, rand, this.getBoundingBox().minX, this.getBoundingBox().minY, this.getBoundingBox().maxZ + 1, 0, this.getComponentType());
break;
case 2:
getNextComponentVillagePath2((StructureVillagePieces.Start)p_74861_1_, p_74861_2_, rand, this.getBoundingBox().maxX + 1, this.getBoundingBox().minY, this.getBoundingBox().minZ, 3, this.getComponentType());
break;
case 3:
getNextComponentVillagePath2((StructureVillagePieces.Start)p_74861_1_, p_74861_2_, rand, this.getBoundingBox().maxX - 2, this.getBoundingBox().minY, this.getBoundingBox().maxZ + 1, 0, this.getComponentType());
}
}
}
@SuppressWarnings("unchecked")
@Override
protected StructureComponent getNextComponentVillagePath2(StructureVillagePieces.Start p_75080_0_, List p_75080_1_, Random p_75080_2_, int xCoord, int p_75080_4_, int zCoord, int p_75080_6_, int p_75080_7_) {
if (totalMade>maxBuildings || p_75080_7_ > 3 + p_75080_0_.terrainType)
return null;
else if (Math.abs(xCoord - p_75080_0_.getBoundingBox().minX) <= villageSize && Math.abs(zCoord - p_75080_0_.getBoundingBox().minZ) <= villageSize) {
StructureBoundingBox structureboundingbox = JTPath2.func_74933_a(p_75080_0_, p_75080_1_, p_75080_2_, xCoord, p_75080_4_, zCoord, p_75080_6_);
if (structureboundingbox != null && structureboundingbox.minY > 10) {
JTPath2 path = new JTPath2(parent, tier+1, p_75080_0_, p_75080_7_, p_75080_2_, structureboundingbox, p_75080_6_);
int j1 = (path.getBoundingBox().minX + path.getBoundingBox().maxX) / 2;
int k1 = (path.getBoundingBox().minZ + path.getBoundingBox().maxZ) / 2;
int l1 = path.getBoundingBox().maxX - path.getBoundingBox().minX;
int i2 = path.getBoundingBox().maxZ - path.getBoundingBox().minZ;
int j2 = l1 > i2 ? l1 : i2;
if (!recheckBiomes || p_75080_0_.getWorldChunkManager().areBiomesViable(j1, k1, j2 / 2 + 4, MapGenVillage.villageSpawnBiomes)) {
p_75080_1_.add(path);
p_75080_0_.field_74930_j.add(path);
return path;
}
}
return null;
} else
return null;
}
/**
* Gets the next village component, with the bounding box shifted -1 in the X and Z direction.
*/
@Override
protected StructureComponent getNextComponentNN(StructureVillagePieces.Start p_74891_1_, List p_74891_2_, Random p_74891_3_, int p_74891_4_, int p_74891_5_) {
parent.totalMade++;
switch (this.coordBaseMode) {
case 0:
return getNextVillageStructureComponent(p_74891_1_, p_74891_2_, p_74891_3_, this.getBoundingBox().minX - 1, this.getBoundingBox().minY + p_74891_4_, this.getBoundingBox().minZ + p_74891_5_, 1, this.getComponentType());
case 1:
return getNextVillageStructureComponent(p_74891_1_, p_74891_2_, p_74891_3_, this.getBoundingBox().minX + p_74891_5_, this.getBoundingBox().minY + p_74891_4_, this.getBoundingBox().minZ - 1, 2, this.getComponentType());
case 2:
return getNextVillageStructureComponent(p_74891_1_, p_74891_2_, p_74891_3_, this.getBoundingBox().minX - 1, this.getBoundingBox().minY + p_74891_4_, this.getBoundingBox().minZ + p_74891_5_, 1, this.getComponentType());
case 3:
return getNextVillageStructureComponent(p_74891_1_, p_74891_2_, p_74891_3_, this.getBoundingBox().minX + p_74891_5_, this.getBoundingBox().minY + p_74891_4_, this.getBoundingBox().minZ - 1, 2, this.getComponentType());
default:
return null;
}
}
/**
* Gets the next village component, with the bounding box shifted +1 in the X and Z direction.
*/
@Override
protected StructureComponent getNextComponentPP(StructureVillagePieces.Start p_74894_1_, List p_74894_2_, Random p_74894_3_, int p_74894_4_, int p_74894_5_) {
parent.totalMade++;
switch (coordBaseMode) {
case 0:
return getNextVillageStructureComponent(p_74894_1_, p_74894_2_, p_74894_3_, this.getBoundingBox().maxX + 1, this.getBoundingBox().minY + p_74894_4_, this.getBoundingBox().minZ + p_74894_5_, 3, this.getComponentType());
case 1:
return getNextVillageStructureComponent(p_74894_1_, p_74894_2_, p_74894_3_, this.getBoundingBox().minX + p_74894_5_, this.getBoundingBox().minY + p_74894_4_, this.getBoundingBox().maxZ + 1, 0, this.getComponentType());
case 2:
return getNextVillageStructureComponent(p_74894_1_, p_74894_2_, p_74894_3_, this.getBoundingBox().maxX + 1, this.getBoundingBox().minY + p_74894_4_, this.getBoundingBox().minZ + p_74894_5_, 3, this.getComponentType());
case 3:
return getNextVillageStructureComponent(p_74894_1_, p_74894_2_, p_74894_3_, this.getBoundingBox().minX + p_74894_5_, this.getBoundingBox().minY + p_74894_4_, this.getBoundingBox().maxZ + 1, 0, this.getComponentType());
default:
return null;
}
}
public static class JTPath2Handler implements IVillageCreationHandler {//TODO: Do I need this?\
public JTPath2Handler() {}
@Override
public Object buildComponent(PieceWeight arg0, Start arg1, List arg2,
Random arg3, int arg4, int arg5, int arg6, int arg7, int arg8) {
return JTPath2.construct(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);//TODO: Can't add parent here, I don't think I should have villages generating this on their own...
}
@Override
public Class<?> getComponentClass() {
return JTPath2.class;
}
@Override
public PieceWeight getVillagePieceWeight(Random arg0, int arg1) {
return new StructureVillagePieces.PieceWeight(JTPath2.class, 10, 0);
}
}
}
| lgpl-2.1 |
plast-lab/soot | src/main/java/soot/jimple/toolkits/annotation/purity/PurityNode.java | 1312 | package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Interface shared by all kinds of nodes in a PurityGraph. Such nodes are immutables. They are hashable and two nodes are
* equal only if they have the same kind and were constructed using the same arguments (structural equality).
*
*/
public interface PurityNode {
/** Is it an inside node ? */
public boolean isInside();
/** Is it a load node ? */
public boolean isLoad();
/** Is it a parameter or this node ? */
public boolean isParam();
}
| lgpl-2.1 |
jhalliday/hibernate-ogm | core/src/main/java/org/hibernate/ogm/transaction/impl/ForwardingTransactionImplementor.java | 2756 | /*
* Hibernate OGM, Domain model persistence for NoSQL datastores
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.ogm.transaction.impl;
import javax.transaction.Synchronization;
import org.hibernate.HibernateException;
import org.hibernate.engine.transaction.spi.IsolationDelegate;
import org.hibernate.engine.transaction.spi.JoinStatus;
import org.hibernate.engine.transaction.spi.LocalStatus;
import org.hibernate.engine.transaction.spi.TransactionImplementor;
/**
* A {@link TransactionImplementor} delegating all methods to another {@code TransactionImplementor} instance. Useful as
* a base class for implementations which need to customize/amend the behavior of the underlying implementation.
*
* @author Gunnar Morling
*/
public class ForwardingTransactionImplementor implements TransactionImplementor {
private final TransactionImplementor delegate;
public ForwardingTransactionImplementor(TransactionImplementor delegate) {
this.delegate = delegate;
}
@Override
public IsolationDelegate createIsolationDelegate() {
return delegate.createIsolationDelegate();
}
@Override
public JoinStatus getJoinStatus() {
return delegate.getJoinStatus();
}
@Override
public void markForJoin() {
delegate.markForJoin();
}
@Override
public void join() {
delegate.join();
}
@Override
public void resetJoinStatus() {
delegate.resetJoinStatus();
}
@Override
public void markRollbackOnly() {
delegate.markRollbackOnly();
}
@Override
public void invalidate() {
delegate.invalidate();
}
@Override
public boolean isInitiator() {
return delegate.isInitiator();
}
@Override
public void begin() {
delegate.begin();
}
@Override
public void commit() {
delegate.commit();
}
@Override
public void rollback() {
delegate.rollback();
}
@Override
public LocalStatus getLocalStatus() {
return delegate.getLocalStatus();
}
@Override
public boolean isActive() {
return delegate.isActive();
}
@Override
public boolean isParticipating() {
return delegate.isParticipating();
}
@Override
public boolean wasCommitted() {
return delegate.wasCommitted();
}
@Override
public boolean wasRolledBack() {
return delegate.wasRolledBack();
}
@Override
public void registerSynchronization(Synchronization synchronization) throws HibernateException {
delegate.registerSynchronization( synchronization );
}
@Override
public void setTimeout(int seconds) {
delegate.setTimeout( seconds );
}
@Override
public int getTimeout() {
return delegate.getTimeout();
}
TransactionImplementor getDelegate() {
return delegate;
}
}
| lgpl-2.1 |
yyhpys/ccnx-trace-interest | javasrc/src/org/ccnx/ccn/test/protocol/InterestTest.java | 6771 | /*
* A CCNx library test.
*
* Copyright (C) 2008, 2009, 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
package org.ccnx.ccn.test.protocol;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.impl.security.crypto.CCNDigestHelper;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.protocol.BloomFilter;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Exclude;
import org.ccnx.ccn.protocol.ExcludeComponent;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
import org.ccnx.ccn.protocol.PublisherID;
import org.ccnx.ccn.test.CCNTestBase;
import org.ccnx.ccn.test.impl.encoding.XMLEncodableTester;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test the generation and matching functionality of Interests.
*/
public class InterestTest extends CCNTestBase {
public static String testName = "/test/parc/home/smetters/interestingData.txt/v/5";
public static ContentName tcn = null;
public static PublisherID pubID = null;
private byte [] bloomSeed = "burp".getBytes();
private Exclude ef = null;
private String [] bloomTestValues = {
"one", "two", "three", "four",
"five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve",
"thirteen"
};
@BeforeClass
public static void setUpBeforeClass() throws Exception {
CCNTestBase.setUpBeforeClass();
byte [] testID = CCNDigestHelper.digest(testName.getBytes());
tcn = ContentName.fromURI(testName);
pubID = new PublisherID(testID,PublisherID.PublisherType.ISSUER_KEY);
}
@Before
public void setUp() throws Exception {
}
private void excludeSetup() {
BloomFilter bf1 = new BloomFilter(13, bloomSeed);
ExcludeComponent e1 = new ExcludeComponent("aaa".getBytes());
ExcludeComponent e2 = new ExcludeComponent("zzzzzzzz".getBytes());
try {
ArrayList<Exclude.Element>te = new ArrayList<Exclude.Element>(2);
te.add(e2);
te.add(e1);
new Exclude(te);
Assert.fail("Out of order exclude filter succeeded");
} catch (InvalidParameterException ipe) {}
for (String value : bloomTestValues) {
bf1.insert(value.getBytes());
}
ArrayList<Exclude.Element>excludes = new ArrayList<Exclude.Element>(2);
excludes.add(e1);
excludes.add(bf1);
excludes.add(e2);
ef = new Exclude(excludes);
}
@Test
public void testSimpleInterest() {
Interest plain = new Interest(tcn);
Interest plainDec = new Interest();
Interest plainBDec = new Interest();
XMLEncodableTester.encodeDecodeTest("PlainInterest", plain, plainDec, plainBDec);
Interest nplain = new Interest(tcn,pubID);
Interest nplainDec = new Interest();
Interest nplainBDec = new Interest();
XMLEncodableTester.encodeDecodeTest("FancyInterest", nplain, nplainDec, nplainBDec);
Interest opPlain = new Interest(tcn);
opPlain.childSelector(Interest.CHILD_SELECTOR_RIGHT);
Interest opPlainDec = new Interest();
Interest opPlainBDec = new Interest();
XMLEncodableTester.encodeDecodeTest("PreferenceInterest", opPlain, opPlainDec, opPlainBDec);
Interest opMSC = new Interest(tcn);
opMSC.maxSuffixComponents(3);
Interest opMSCDec = new Interest();
Interest opMSCBDec = new Interest();
XMLEncodableTester.encodeDecodeTest("MaxSuffixComponentsInterest", opMSC, opMSCDec, opMSCBDec);
Interest opMinSC = new Interest(tcn);
opMinSC.minSuffixComponents(3);
Interest opMinSCDec = new Interest();
Interest opMinSCBDec = new Interest();
XMLEncodableTester.encodeDecodeTest("MinSuffixComponentsInterest", opMinSC, opMinSCDec, opMinSCBDec);
}
@Test
public void testProfileInterests() throws Exception {
// Should test the interests used for segments (getLower) as well.
Interest lv =
VersioningProfile.latestVersionInterest(
ContentName.fromNative("/test/InterestTest/testProfileInterests"),
null, KeyManager.getDefaultKeyManager().getDefaultKeyID());
Interest lvDec = new Interest();
Interest lvBDec = new Interest();
XMLEncodableTester.encodeDecodeTest("LatestVersionInterest", lv, lvDec, lvBDec);
Interest lvs =
VersioningProfile.latestVersionInterest(
ContentName.fromNative("/test/InterestTest/testProfileInterests"),
2, KeyManager.getDefaultKeyManager().getDefaultKeyID());
Interest lvsDec = new Interest();
Interest lvsBDec = new Interest();
XMLEncodableTester.encodeDecodeTest("LatestVersionInterest - Short", lvs, lvsDec, lvsBDec);
}
@Test
public void testExclude() {
excludeSetup();
Interest exPlain = new Interest(tcn);
exPlain.exclude(ef);
Interest exPlainDec = new Interest();
Interest exPlainBDec = new Interest();
XMLEncodableTester.encodeDecodeTest("ExcludeInterest", exPlain, exPlainDec, exPlainBDec);
}
@Test
public void testMatch() {
// paul r Comment - should really test more comprehensively
// For now just do this to test the exclude matching
excludeSetup();
try {
Interest interest = new Interest("/paul");
interest.exclude(ef);
Assert.assertTrue(interest.matches(ContentName.fromNative("/paul/car"), null));
Assert.assertFalse(interest.matches(ContentName.fromNative("/paul/zzzzzzzz"), null));
for (String value : bloomTestValues) {
String completeName = "/paul/" + value;
Assert.assertFalse(interest.matches(ContentName.fromNative(completeName), null));
}
} catch (MalformedContentNameStringException e) {
Assert.fail(e.getMessage());
}
}
@Test
public void testMatchDigest() throws MalformedContentNameStringException {
ContentName name = ContentName.fromNative("/paul");
byte [] content = "hello".getBytes();
ContentObject co = ContentObject.buildContentObject(name, content);
byte [] digest = co.digest();
Interest interest = new Interest(ContentName.fromNative(name, digest));
Assert.assertTrue(interest.matches(co));
interest = new Interest(ContentName.fromNative(name, "simon"));
Assert.assertFalse(interest.matches(co));
}
}
| lgpl-2.1 |
lucee/unoffical-Lucee-no-jre | source/java/loader/src/lucee/runtime/Mapping.java | 3719 | /**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import lucee.commons.io.res.Resource;
import lucee.runtime.config.Config;
/**
* interface of the mapping definition
*/
public interface Mapping extends Serializable {
public Class<?> getArchiveClass(String className) throws ClassNotFoundException;
public Class<?> getArchiveClass(String className, Class<?> defaultValue);
public InputStream getArchiveResourceAsStream(String string);
public Class<?> getPhysicalClass(String className) throws ClassNotFoundException,IOException;
public Class<?> getPhysicalClass(String className, byte[] code) throws IOException;
/**
* @return Returns the physical.
*/
public abstract Resource getPhysical();
/**
* @return Returns the virtual lower case.
*/
public abstract String getVirtualLowerCase();
/**
* @return Returns the virtual lower case with slash at the end.
*/
public abstract String getVirtualLowerCaseWithSlash();
/**
* @return return the archive file
*/
public abstract Resource getArchive();
/**
* @return returns if mapping has a archive
*/
public abstract boolean hasArchive();
/**
* @return return if mapping has a physical path
*/
public abstract boolean hasPhysical();
/**
* @return class root directory
*/
public abstract Resource getClassRootDirectory();
/**
* pagesoucre matching given realpath
*
* @param realPath
* @return matching pagesource
*/
public abstract PageSource getPageSource(String realPath);
/**
* @param path
* @param isOut
* @return matching pagesoucre
*/
public abstract PageSource getPageSource(String path, boolean isOut);
/**
* checks the mapping
*/
public abstract void check();
/**
* @return Returns the hidden.
*/
public abstract boolean isHidden();
/**
* @return Returns the physicalFirst.
*/
public abstract boolean isPhysicalFirst();
/**
* @return Returns the readonly.
*/
public abstract boolean isReadonly();
/**
* @return Returns the strArchive.
*/
public abstract String getStrArchive();
/**
* @return Returns the strPhysical.
*/
public abstract String getStrPhysical();
/**
* @return Returns the trusted.
* @deprecated use instead <code>public short getInspectTemplate();</code>
*/
public abstract boolean isTrusted();
public short getInspectTemplate();
public abstract boolean isTopLevel();
/**
* @return Returns the virtual.
*/
public abstract String getVirtual();
/**
* returns config of the mapping
*
* @return config
*/
public Config getConfig();
/**
* mapping can have a specific listener mode to overwrite the listener mode coming from the Application Context
* @return
*/
public int getListenerMode();
/**
* mapping can have a specific listener type to overwrite the listener mode coming from the Application Context
* @return
*/
public int getListenerType();
} | lgpl-2.1 |
johnscancella/spotbugs | spotbugsTestCases/src/java/sfBugs/Bug3464107.java | 1332 | package sfBugs;
import org.testng.annotations.Test;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;
// now https://sourceforge.net/p/findbugs/bugs/1013/
public class Bug3464107 {
@Test
@NoWarning("EC_BAD_ARRAY_COMPARE")
public void test() {
int[] numbers = { 1, 2, 3 };
int[] numbers2 = { 1, 2, 3 };
org.testng.Assert.assertEquals(numbers, numbers2);
org.testng.Assert.assertEquals((Object) numbers, (Object) numbers2);
org.testng.Assert.assertFalse(numbers.equals(numbers2));
}
@Test
@ExpectWarning("EC_INCOMPATIBLE_ARRAY_COMPARE")
public void test2() {
int[] numbers = { 1, 2, 3 };
long[] numbers2 = { 1, 2, 3 };
org.testng.Assert.assertEquals(numbers, numbers2);
}
@Test
@ExpectWarning("EC_INCOMPATIBLE_ARRAY_COMPARE")
public void test3() {
int[] numbers = { 1, 2, 3 };
long[] numbers2 = { 1, 2, 3 };
org.testng.Assert.assertEquals((Object) numbers, (Object) numbers2);
}
@Test
@NoWarning("EC")
public void test4() {
int[] numbers = { 1, 2, 3 };
long[] numbers2 = { 1, 2, 3 };
org.testng.Assert.assertFalse(numbers.equals(numbers2));
}
}
| lgpl-2.1 |
1frozenice1/Kaenguru | src/main/java/org/asozialesNetzwerk/Kaenguru/client/lib/libKeys.java | 380 | package org.asozialesNetzwerk.Kaenguru.client.lib;
import org.asozialesNetzwerk.Kaenguru.common.lib.LibMisc;
/**
* Created by Sebas on 12.03.2016.
*/
//for localisation
public final class libKeys {
public static final String CATEGORY = "keys." + LibMisc.KEYS_PREFIX + ".category";
public static final String TEST = "keys." + LibMisc.KEYS_PREFIX + ".test";
}
| lgpl-2.1 |
ngonga/adagio | src/org/aksw/hierarchy/ranking/ISIRanking.java | 6537 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.simba.hierarchy.ranking;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.simba.hierarchy.adagio.Adagio;
import org.simba.hierarchy.adagio.LabeledMatrix;
import org.simba.hierarchy.evaluation.Evaluation;
/**
* After "Finding a dominance order most consistent with a linear hierarchy: a
* new procedure and review", deVries 1996
*
* @author ngonga
*/
public class ISIRanking extends AbstractRanking {
public static int TMAX = 10;
public double[][] getDominance(LabeledMatrix m) {
double[][] dominance = new double[m.data.getRowDimension()][m.data.getColumnDimension()];
for (int i = 0; i < m.data.getRowDimension(); i++) {
for (int j = i; j < m.data.getColumnDimension(); j++) {
if (i == j) {
dominance[i][i] = 0;
} else if (m.data.get(i, j) > m.data.get(j, i)) {
dominance[i][j] = 1;
dominance[j][i] = 0;
} else if (m.data.get(i, j) < m.data.get(j, i)) {
dominance[j][i] = 1;
dominance[i][j] = 0;
} else {
if (m.data.get(i, j) > m.data.get(j, i)) {
dominance[i][j] = 0.5;
dominance[j][i] = 0.5;
}
}
}
}
return dominance;
}
public int getI(List<Integer> ranks, double[][] dominance) {
int d = 0;
for (int i = 0; i < ranks.size(); i++) {
for (int j = i + 1; j < ranks.size(); j++) {
if (dominance[ranks.get(j)][ranks.get(i)] > 0) {
d++;
}
}
}
return d;
}
public double getSI(List<Integer> ranks, double[][] dominance, LabeledMatrix m) {
double d = 0;
for (int i = 0; i < ranks.size(); i++) {
for (int j = i + 1; j < ranks.size(); j++) {
if (dominance[j][i] > 0) {
d = d + m.data.get(j, i) - m.data.get(i, j);
}
}
}
return d;
}
public List<Integer> clone(List<Integer> l) {
List<Integer> r = new ArrayList<>();
for (Integer i : l) {
r.add(i);
}
return r;
}
public Map<String, Integer> getRanks(LabeledMatrix m) {
List<Integer> ranks = new ArrayList<>();
List<Integer> bestRanking;
int tries = 0;
for (int i = 0; i < m.data.getRowDimension(); i++) {
ranks.add(i);
}
bestRanking = clone(ranks);
double[][] d = getDominance(m);
int Imin = getI(ranks, d);
double SImin = getSI(ranks, d, m);
boolean stop2 = false, stop1 = false;
boolean breakLoop;
double iterations = 0;
while (!stop1) {
//stop1 = true;
while (!stop2 && iterations<=TMAX*100) {
iterations++;
stop2 = true;
breakLoop = false;
for (int i = 0; i < m.data.getRowDimension(); i++) {
for (int j = i + 1; j < m.data.getRowDimension(); j++) {
if (d[ranks.get(j)][ranks.get(i)] > 0) //inconsistency
{
int net = 0;
for (int k = i; k < j; k++) {
if (m.data.get(ranks.get(j), ranks.get(k)) != m.data.get(ranks.get(k), ranks.get(j)))
{
net = net + (int) Math.signum(m.data.get(ranks.get(j), ranks.get(k)) - m.data.get(ranks.get(k), ranks.get(j)));
}
}
//if swapping fixes inconsistencies
if (net > 0) {
int temp = ranks.get(i);
ranks.set(i, ranks.get(j));
ranks.set(j, temp);
stop2 = false;
breakLoop = true;
break;
}
}
}
if (breakLoop) {
break;
}
}
}
int I = getI(ranks, d);
double SI = getSI(ranks, d, m);
if (I < Imin || (I == Imin && SI < SImin)) {
bestRanking = clone(ranks);
Imin = I;
SImin = SI;
//stop1 = false;
}
tries++;
if (SImin > 0 && tries < TMAX) {
stop1 = false;
for (int j = 0; j < ranks.size(); j++) {
for (int i = 0; i < j; i++) {
if (d[ranks.get(j)][ranks.get(i)] > 0) {
int random = (int) Math.random() * j;
int temp = ranks.get(random);
ranks.set(random, ranks.get(j));
ranks.set(j, temp);
}
}
}
} else {
stop1 = true;
}
}
//create output
Map<String, Integer> result = new HashMap<>();
for (int i = 0; i < bestRanking.size(); i++) {
result.put(m.labels.get(bestRanking.get(i)), i + 1);
}
return result;
}
@Override
public Map<String, Double> getScores(LabeledMatrix m) {
Map<String, Double> scores = new HashMap<>();
Map<String, Integer> ranks = getRanks(m);
for (String s : ranks.keySet()) {
scores.put(s, new Double(m.data.getRowDimension() - ranks.get(s) + 1));
}
return scores;
}
public String getName()
{
return "ISI";
}
public static void main(String args[]) {
// String path = "E:/Work/Projects/2014/HARBOR/MS/male_dominance_data (MS).txt";
String path = "E:/Work/Projects/2014/HARBOR/ShizukaMcDonald_Data/Collias1950-1.csv";
LabeledMatrix m = new LabeledMatrix(path, null);
// System.out.println(m);
Map<String, Integer> ranking = new ISIRanking().getRanks(m);
System.out.println(ranking);
}
}
| lgpl-2.1 |
agolinko/pdfparse | pdfparse-lib/src/main/java/org/pdfparse/parser/XRefTable.java | 3327 | package org.pdfparse.parser;
import org.pdfparse.cos.*;
import org.pdfparse.exception.EGenericException;
import org.pdfparse.exception.EParseError;
import org.pdfparse.utils.IntObjHashtable;
public class XRefTable implements ObjectRetriever {
private IntObjHashtable<XRefEntry> by_id;
private ParserSettings settings;
private ObjectParser parser;
public XRefTable(ParserSettings settings) {
by_id = new IntObjHashtable<XRefEntry>();
this.settings = settings;
}
public XRefEntry get(int id) {
return by_id.get(id);
}
public int[] getKeys() {
return by_id.getKeys();
}
public void add(int id, int gen, int offs) throws EParseError {
// Skip invalid or not-used objects (assumed that they are free objects)
if (offs == 0) {
Diagnostics.debugMessage(settings, "XREF: Got object with zero offset. Assumed that this was a free object(%d %d R)", id, gen);
return;
}
XRefEntry xref = new XRefEntry(id, gen, offs, false);
XRefEntry old_obj = by_id.get(id);
if (old_obj == null) {
by_id.put(id, xref);
} else if (old_obj.gen < gen) {
// override only if greater Generation
by_id.put(id, xref);
}
}
public void addCompressed(int id, int containerId, int indexWithinContainer) throws EParseError {
// Skip invalid or not-used objects (assumed that they are free objects)
if (containerId > 0) {
XRefEntry xref = new XRefEntry(id, containerId, indexWithinContainer, true);
by_id.put(id, xref);
} else {
Diagnostics.debugMessage(settings, "XREF: Got containerId which is zero. Assumed that this was a free object (%d 0 R)", id);
}
}
public void setParser(ObjectParser parser) {
this.parser = parser;
}
@Override
public COSObject getObject(COSReference ref) {
XRefEntry x = this.get(ref.id);
if (x == null) {
Diagnostics.debugMessage(settings, "No XRef entry for object %d %d R. Used COSNull instead", ref.id, ref.gen);
return new COSNull();
}
if (x.gen != ref.gen) {
Diagnostics.debugMessage(settings, "Object %s not found. But there is object with %d generation number", ref, x.gen);
}
if (x.cachedObject != null) {
return x.cachedObject;
}
if (parser != null) {
return parser.getObject(x);
}
throw new EGenericException("Trying to access %s. Object is not loaded/parsed yet", ref);
}
@Override
public COSDictionary getDictionary(COSReference ref) {
COSObject obj = this.getObject(ref);
if (obj instanceof COSDictionary)
return (COSDictionary) obj;
throw new EParseError("Dictionary expected for %s. But retrieved object is %s", ref, obj.getClass().getName());
}
@Override
public COSStream getStream(COSReference ref) {
COSObject obj = this.getObject(ref);
if (obj instanceof COSStream)
return (COSStream) obj;
throw new EParseError("Stream expected for %s. But retrieved object is %s", ref, obj.getClass().getName());
}
public void clear() {
by_id.clear();
}
}
| lgpl-2.1 |
phoenixctms/ctsms | core/src/test/java/org/phoenixctms/ctsms/domain/test/CvSectionDaoTransformTest.java | 1221 | // This file is part of the Phoenix CTMS project (www.phoenixctms.org),
// distributed under LGPL v2.1. Copyright (C) 2011 - 2017.
//
package org.phoenixctms.ctsms.domain.test;
import org.phoenixctms.ctsms.domain.DaoTransformTestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @see org.phoenixctms.ctsms.domain.CvSection
*/
@Test(groups={"transform","CvSectionDao"})
public class CvSectionDaoTransformTest extends DaoTransformTestBase {
/**
* Test for method CvSectionDao.toCvSectionVO
*
* @see org.phoenixctms.ctsms.domain.CvSectionDao#toCvSectionVO(org.phoenixctms.ctsms.domain.CvSection source, org.phoenixctms.ctsms.vo.CvSectionVO target)
*/
@Test
public void testToCvSectionVO() {
Assert.fail("Test 'CvSectionDaoTransformTest.testToCvSectionVO' not implemented!");
}
/**
* Test for method cvSectionVOToEntity
*
* @see org.phoenixctms.ctsms.domain.CvSectionDao#cvSectionVOToEntity(org.phoenixctms.ctsms.vo.CvSectionVO source, org.phoenixctms.ctsms.domain.CvSection target, boolean copyIfNull)
*/
@Test
public void testCvSectionVOToEntity() {
Assert.fail("Test 'CvSectionDaoTransformTest.testCvSectionVOToEntity' not implemented!");
}
} | lgpl-2.1 |
pezi/treedb-cmdb | src/main/java/at/treedb/at/treedb/util/ContentInfo.java | 4777 | /*
* (C) Copyright 2014-2016 Peter Sauer (http://treedb.at/).
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package at.treedb.util;
import java.util.ArrayList;
import at.treedb.ci.MimeType;
/**
* <p>
* Class for detecting the MIME type of a byte buffer/file.
* </p>
*
* @author Peter Sauer
*
*/
public class ContentInfo {
private static boolean contains(String headerStr, int start, byte[] data) {
int[] header = hexStringToByteArray(headerStr);
if (start + header.length > data.length) {
return false;
}
for (int i = 0; i < header.length; ++i) {
if (header[i] == -1) {
continue;
}
if (header[i] != (data[start + i] & 0xff)) {
return false;
}
}
return true;
}
private static int[] hexStringToByteArray(String s) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < s.length(); ++i) {
// convert wild card ? to -1
if (s.charAt(i) == '?') {
list.add(-1);
} else {
list.add(((byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)))
& 0xff);
++i;
}
}
int[] array = new int[list.size()];
for (int i = 0; i < list.size(); ++i) {
array[i] = list.get(i);
}
return array;
}
/**
* Tries to detect the MIME type of a byte buffer.
*
* @param data
* binary data
* @return {@code MimeType} or {@code null}, if detection was not possible
*/
public static MimeType getContentInfo(byte[] data) {
for (MimeType type : MimeType.values()) {
String[] headers = type.getHeaders();
for (String h : headers) {
if (h.equals("*")) {
continue;
}
int pos = h.indexOf("-");
int start = 0;
if (pos > 0) {
start = Integer.valueOf(h.substring(0, pos));
h = h.substring(pos + 1);
}
if (contains(h, start, data)) {
return type;
}
}
}
// MP3 test
if (data.length > 4) {
if ((data[0] & 0xff) == 0xff) {
int value = data[0] & 0xf0;
if (value == 0xe0 || value == 0xf0) {
return MimeType.MP3;
}
}
}
return null;
}
/**
* Counts how often each byte value appears in a range of bytes.
*
* @param data
* input buffer.
* @param start
* index into the buffer where the counting starts.
* @param length
* number of bytes to count.
*
* @return array with 256 entries that say how often each byte value
* appeared in the requested input buffer range.
**/
private static int[] countByteDistribution(byte[] data, int start, int length) {
final int[] countedData = new int[256];
for (int i = start; i < start + length; i++) {
countedData[data[i] & 0xFF]++;
}
return countedData;
}
/**
* Calculates the log2 of a value.
**/
private static double log2(double d) {
return Math.log(d) / Math.log(2.0);
}
/**
* Calculates the entropy of a sub-array.
*
* @param data
* The input data.
* @param start
* Index into the input data buffer where the entropy calculation
* begins.
* @param length
* Number of bytes to consider during entropy calculation.
*
* @return Entropy of the sub-array.
**/
public static double calculateEntropy(byte[] data, int start, int length) {
double entropy = 0;
int[] countedData = countByteDistribution(data, start, length);
for (int i = 0; i < 256; i++) {
final double px = 1.0 * countedData[i] / length;
if (px > 0) {
entropy += -px * log2(px);
}
}
return entropy;
}
}
| lgpl-2.1 |
esig/dss | validation-policy/src/main/java/eu/europa/esig/dss/validation/process/bbb/xcv/sub/checks/CertificateRevocationSelectorResultCheck.java | 3532 | /**
* DSS - Digital Signature Services
* Copyright (C) 2015 European Commission, provided under the CEF programme
*
* This file is part of the "DSS - Digital Signature Services" project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package eu.europa.esig.dss.validation.process.bbb.xcv.sub.checks;
import eu.europa.esig.dss.detailedreport.jaxb.XmlBlockType;
import eu.europa.esig.dss.detailedreport.jaxb.XmlCRS;
import eu.europa.esig.dss.detailedreport.jaxb.XmlConstraintsConclusion;
import eu.europa.esig.dss.detailedreport.jaxb.XmlMessage;
import eu.europa.esig.dss.enumerations.Indication;
import eu.europa.esig.dss.enumerations.SubIndication;
import eu.europa.esig.dss.i18n.I18nProvider;
import eu.europa.esig.dss.i18n.MessageTag;
import eu.europa.esig.dss.policy.jaxb.LevelConstraint;
import eu.europa.esig.dss.validation.process.ChainItem;
import java.util.List;
/**
* This class verifies the result of a {@code CertificateRevocationSelector}
*
* @param <T> {@link XmlConstraintsConclusion}
*/
public class CertificateRevocationSelectorResultCheck<T extends XmlConstraintsConclusion> extends ChainItem<T> {
/** CRS result */
protected final XmlCRS crsResult;
/**
* Default constructor
*
* @param i18nProvider {@link I18nProvider}
* @param result the result
* @param crsResult {@link XmlCRS}
* @param constraint {@link LevelConstraint}
*/
public CertificateRevocationSelectorResultCheck(I18nProvider i18nProvider, T result, XmlCRS crsResult,
LevelConstraint constraint) {
super(i18nProvider, result, constraint, crsResult.getId());
this.crsResult = crsResult;
}
@Override
protected XmlBlockType getBlockType() {
return XmlBlockType.CRS;
}
@Override
protected boolean process() {
return isValid(crsResult);
}
@Override
protected MessageTag getMessageTag() {
return MessageTag.BBB_XCV_IARDPFC;
}
@Override
protected MessageTag getErrorMessageTag() {
return MessageTag.BBB_XCV_IARDPFC_ANS;
}
@Override
protected Indication getFailedIndicationForConclusion() {
return crsResult.getConclusion().getIndication();
}
@Override
protected SubIndication getFailedSubIndicationForConclusion() {
return crsResult.getConclusion().getSubIndication();
}
@Override
protected List<XmlMessage> getPreviousErrors() {
return crsResult.getConclusion().getErrors();
}
@Override
protected String buildAdditionalInfo() {
if (crsResult.getLatestAcceptableRevocationId() != null) {
return i18nProvider.getMessage(MessageTag.LAST_ACCEPTABLE_REVOCATION, crsResult.getLatestAcceptableRevocationId());
}
return null;
}
}
| lgpl-2.1 |
bullda/DroidText | src/core/com/lowagie/text/pdf/PdfCopyFieldsImp.java | 26399 | /*
* $Id: PdfCopyFieldsImp.java 3763 2009-03-06 17:30:30Z blowagie $
* Copyright 2004 by Paulo Soares.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
package com.lowagie.text.pdf;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.exceptions.BadPasswordException;
/**
*
* @author psoares
*/
class PdfCopyFieldsImp extends PdfWriter {
private static final PdfName iTextTag = new PdfName("_iTextTag_");
private static final Integer zero = new Integer(0);
ArrayList readers = new ArrayList();
HashMap readers2intrefs = new HashMap();
HashMap pages2intrefs = new HashMap();
HashMap visited = new HashMap();
ArrayList fields = new ArrayList();
RandomAccessFileOrArray file;
HashMap fieldTree = new HashMap();
ArrayList pageRefs = new ArrayList();
ArrayList pageDics = new ArrayList();
PdfDictionary resources = new PdfDictionary();
PdfDictionary form;
boolean closing = false;
Document nd;
private HashMap tabOrder;
private ArrayList calculationOrder = new ArrayList();
private ArrayList calculationOrderRefs;
private boolean hasSignature;
PdfCopyFieldsImp(OutputStream os) throws DocumentException {
this(os, '\0');
}
PdfCopyFieldsImp(OutputStream os, char pdfVersion) throws DocumentException {
super(new PdfDocument(), os);
pdf.addWriter(this);
if (pdfVersion != 0)
super.setPdfVersion(pdfVersion);
nd = new Document();
nd.addDocListener(pdf);
}
void addDocument(PdfReader reader, List pagesToKeep) throws DocumentException, IOException {
if (!readers2intrefs.containsKey(reader) && reader.isTampered())
throw new DocumentException("The document was reused.");
reader = new PdfReader(reader);
reader.selectPages(pagesToKeep);
if (reader.getNumberOfPages() == 0)
return;
reader.setTampered(false);
addDocument(reader);
}
void addDocument(PdfReader reader) throws DocumentException, IOException {
if (!reader.isOpenedWithFullPermissions())
throw new BadPasswordException("PdfReader not opened with owner password");
openDoc();
if (readers2intrefs.containsKey(reader)) {
reader = new PdfReader(reader);
}
else {
if (reader.isTampered())
throw new DocumentException("The document was reused.");
reader.consolidateNamedDestinations();
reader.setTampered(true);
}
reader.shuffleSubsetNames();
readers2intrefs.put(reader, new IntHashtable());
readers.add(reader);
int len = reader.getNumberOfPages();
IntHashtable refs = new IntHashtable();
for (int p = 1; p <= len; ++p) {
refs.put(reader.getPageOrigRef(p).getNumber(), 1);
reader.releasePage(p);
}
pages2intrefs.put(reader, refs);
visited.put(reader, new IntHashtable());
fields.add(reader.getAcroFields());
updateCalculationOrder(reader);
}
private static String getCOName(PdfReader reader, PRIndirectReference ref) {
String name = "";
while (ref != null) {
PdfObject obj = PdfReader.getPdfObject(ref);
if (obj == null || obj.type() != PdfObject.DICTIONARY)
break;
PdfDictionary dic = (PdfDictionary)obj;
PdfString t = dic.getAsString(PdfName.T);
if (t != null) {
name = t.toUnicodeString()+ "." + name;
}
ref = (PRIndirectReference)dic.get(PdfName.PARENT);
}
if (name.endsWith("."))
name = name.substring(0, name.length() - 1);
return name;
}
/**
* @since 2.1.5; before 2.1.5 the method was private
*/
protected void updateCalculationOrder(PdfReader reader) {
PdfDictionary catalog = reader.getCatalog();
PdfDictionary acro = catalog.getAsDict(PdfName.ACROFORM);
if (acro == null)
return;
PdfArray co = acro.getAsArray(PdfName.CO);
if (co == null || co.size() == 0)
return;
AcroFields af = reader.getAcroFields();
for (int k = 0; k < co.size(); ++k) {
PdfObject obj = co.getPdfObject(k);
if (obj == null || !obj.isIndirect())
continue;
String name = getCOName(reader, (PRIndirectReference)obj);
if (af.getFieldItem(name) == null)
continue;
name = "." + name;
if (calculationOrder.contains(name))
continue;
calculationOrder.add(name);
}
}
void propagate(PdfObject obj, PdfIndirectReference refo, boolean restricted) throws IOException {
if (obj == null)
return;
// if (refo != null)
// addToBody(obj, refo);
if (obj instanceof PdfIndirectReference)
return;
switch (obj.type()) {
case PdfObject.DICTIONARY:
case PdfObject.STREAM: {
PdfDictionary dic = (PdfDictionary)obj;
for (Iterator it = dic.getKeys().iterator(); it.hasNext();) {
PdfName key = (PdfName)it.next();
if (restricted && (key.equals(PdfName.PARENT) || key.equals(PdfName.KIDS)))
continue;
PdfObject ob = dic.get(key);
if (ob != null && ob.isIndirect()) {
PRIndirectReference ind = (PRIndirectReference)ob;
if (!setVisited(ind) && !isPage(ind)) {
PdfIndirectReference ref = getNewReference(ind);
propagate(PdfReader.getPdfObjectRelease(ind), ref, restricted);
}
}
else
propagate(ob, null, restricted);
}
break;
}
case PdfObject.ARRAY: {
//PdfArray arr = new PdfArray();
for (Iterator it = ((PdfArray)obj).listIterator(); it.hasNext();) {
PdfObject ob = (PdfObject)it.next();
if (ob != null && ob.isIndirect()) {
PRIndirectReference ind = (PRIndirectReference)ob;
if (!isVisited(ind) && !isPage(ind)) {
PdfIndirectReference ref = getNewReference(ind);
propagate(PdfReader.getPdfObjectRelease(ind), ref, restricted);
}
}
else
propagate(ob, null, restricted);
}
break;
}
case PdfObject.INDIRECT: {
throw new RuntimeException("Reference pointing to reference.");
}
}
}
private void adjustTabOrder(PdfArray annots, PdfIndirectReference ind, PdfNumber nn) {
int v = nn.intValue();
ArrayList t = (ArrayList)tabOrder.get(annots);
if (t == null) {
t = new ArrayList();
int size = annots.size() - 1;
for (int k = 0; k < size; ++k) {
t.add(zero);
}
t.add(new Integer(v));
tabOrder.put(annots, t);
annots.add(ind);
}
else {
int size = t.size() - 1;
for (int k = size; k >= 0; --k) {
if (((Integer)t.get(k)).intValue() <= v) {
t.add(k + 1, new Integer(v));
annots.add(k + 1, ind);
size = -2;
break;
}
}
if (size != -2) {
t.add(0, new Integer(v));
annots.add(0, ind);
}
}
}
protected PdfArray branchForm(HashMap level, PdfIndirectReference parent, String fname) throws IOException {
PdfArray arr = new PdfArray();
for (Iterator it = level.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String name = (String) entry.getKey();
Object obj = entry.getValue();
PdfIndirectReference ind = getPdfIndirectReference();
PdfDictionary dic = new PdfDictionary();
if (parent != null)
dic.put(PdfName.PARENT, parent);
dic.put(PdfName.T, new PdfString(name, PdfObject.TEXT_UNICODE));
String fname2 = fname + "." + name;
int coidx = calculationOrder.indexOf(fname2);
if (coidx >= 0)
calculationOrderRefs.set(coidx, ind);
if (obj instanceof HashMap) {
dic.put(PdfName.KIDS, branchForm((HashMap)obj, ind, fname2));
arr.add(ind);
addToBody(dic, ind);
}
else {
ArrayList list = (ArrayList)obj;
dic.mergeDifferent((PdfDictionary)list.get(0));
if (list.size() == 3) {
dic.mergeDifferent((PdfDictionary)list.get(2));
int page = ((Integer)list.get(1)).intValue();
PdfDictionary pageDic = (PdfDictionary)pageDics.get(page - 1);
PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS);
if (annots == null) {
annots = new PdfArray();
pageDic.put(PdfName.ANNOTS, annots);
}
PdfNumber nn = (PdfNumber)dic.get(iTextTag);
dic.remove(iTextTag);
adjustTabOrder(annots, ind, nn);
}
else {
PdfArray kids = new PdfArray();
for (int k = 1; k < list.size(); k += 2) {
int page = ((Integer)list.get(k)).intValue();
PdfDictionary pageDic = (PdfDictionary)pageDics.get(page - 1);
PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS);
if (annots == null) {
annots = new PdfArray();
pageDic.put(PdfName.ANNOTS, annots);
}
PdfDictionary widget = new PdfDictionary();
widget.merge((PdfDictionary)list.get(k + 1));
widget.put(PdfName.PARENT, ind);
PdfNumber nn = (PdfNumber)widget.get(iTextTag);
widget.remove(iTextTag);
PdfIndirectReference wref = addToBody(widget).getIndirectReference();
adjustTabOrder(annots, wref, nn);
kids.add(wref);
propagate(widget, null, false);
}
dic.put(PdfName.KIDS, kids);
}
arr.add(ind);
addToBody(dic, ind);
propagate(dic, null, false);
}
}
return arr;
}
protected void createAcroForms() throws IOException {
if (fieldTree.isEmpty())
return;
form = new PdfDictionary();
form.put(PdfName.DR, resources);
propagate(resources, null, false);
form.put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g "));
tabOrder = new HashMap();
calculationOrderRefs = new ArrayList(calculationOrder);
form.put(PdfName.FIELDS, branchForm(fieldTree, null, ""));
if (hasSignature)
form.put(PdfName.SIGFLAGS, new PdfNumber(3));
PdfArray co = new PdfArray();
for (int k = 0; k < calculationOrderRefs.size(); ++k) {
Object obj = calculationOrderRefs.get(k);
if (obj instanceof PdfIndirectReference)
co.add((PdfIndirectReference)obj);
}
if (co.size() > 0)
form.put(PdfName.CO, co);
}
public void close() {
if (closing) {
super.close();
return;
}
closing = true;
try {
closeIt();
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/**
* Creates the new PDF by merging the fields and forms.
*/
protected void closeIt() throws IOException {
for (int k = 0; k < readers.size(); ++k) {
((PdfReader)readers.get(k)).removeFields();
}
for (int r = 0; r < readers.size(); ++r) {
PdfReader reader = (PdfReader)readers.get(r);
for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
pageRefs.add(getNewReference(reader.getPageOrigRef(page)));
pageDics.add(reader.getPageN(page));
}
}
mergeFields();
createAcroForms();
for (int r = 0; r < readers.size(); ++r) {
PdfReader reader = (PdfReader)readers.get(r);
for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
PdfDictionary dic = reader.getPageN(page);
PdfIndirectReference pageRef = getNewReference(reader.getPageOrigRef(page));
PdfIndirectReference parent = root.addPageRef(pageRef);
dic.put(PdfName.PARENT, parent);
propagate(dic, pageRef, false);
}
}
for (Iterator it = readers2intrefs.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
PdfReader reader = (PdfReader) entry.getKey();
try {
file = reader.getSafeFile();
file.reOpen();
IntHashtable t = (IntHashtable) entry.getValue();
int keys[] = t.toOrderedKeys();
for (int k = 0; k < keys.length; ++k) {
PRIndirectReference ref = new PRIndirectReference(reader, keys[k]);
addToBody(PdfReader.getPdfObjectRelease(ref), t.get(keys[k]));
}
}
finally {
try {
file.close();
reader.close();
}
catch (Exception e) {
// empty on purpose
}
}
}
pdf.close();
}
void addPageOffsetToField(HashMap fd, int pageOffset) {
if (pageOffset == 0)
return;
for (Iterator it = fd.values().iterator(); it.hasNext();) {
AcroFields.Item item = (AcroFields.Item)it.next();
for (int k = 0; k < item.size(); ++k) {
int p = item.getPage(k).intValue();
item.forcePage(k, p + pageOffset);
}
}
}
void createWidgets(ArrayList list, AcroFields.Item item) {
for (int k = 0; k < item.size(); ++k) {
list.add(item.getPage(k));
PdfDictionary merged = item.getMerged(k);
PdfObject dr = merged.get(PdfName.DR);
if (dr != null)
PdfFormField.mergeResources(resources, (PdfDictionary)PdfReader.getPdfObject(dr));
PdfDictionary widget = new PdfDictionary();
for (Iterator it = merged.getKeys().iterator(); it.hasNext();) {
PdfName key = (PdfName)it.next();
if (widgetKeys.containsKey(key))
widget.put(key, merged.get(key));
}
widget.put(iTextTag, new PdfNumber(item.getTabOrder(k).intValue() + 1));
list.add(widget);
}
}
void mergeField(String name, AcroFields.Item item) {
HashMap map = fieldTree;
StringTokenizer tk = new StringTokenizer(name, ".");
if (!tk.hasMoreTokens())
return;
while (true) {
String s = tk.nextToken();
Object obj = map.get(s);
if (tk.hasMoreTokens()) {
if (obj == null) {
obj = new HashMap();
map.put(s, obj);
map = (HashMap)obj;
continue;
}
else if (obj instanceof HashMap)
map = (HashMap)obj;
else
return;
}
else {
if (obj instanceof HashMap)
return;
PdfDictionary merged = item.getMerged(0);
if (obj == null) {
PdfDictionary field = new PdfDictionary();
if (PdfName.SIG.equals(merged.get(PdfName.FT)))
hasSignature = true;
for (Iterator it = merged.getKeys().iterator(); it.hasNext();) {
PdfName key = (PdfName)it.next();
if (fieldKeys.containsKey(key))
field.put(key, merged.get(key));
}
ArrayList list = new ArrayList();
list.add(field);
createWidgets(list, item);
map.put(s, list);
}
else {
ArrayList list = (ArrayList)obj;
PdfDictionary field = (PdfDictionary)list.get(0);
PdfName type1 = (PdfName)field.get(PdfName.FT);
PdfName type2 = (PdfName)merged.get(PdfName.FT);
if (type1 == null || !type1.equals(type2))
return;
int flag1 = 0;
PdfObject f1 = field.get(PdfName.FF);
if (f1 != null && f1.isNumber())
flag1 = ((PdfNumber)f1).intValue();
int flag2 = 0;
PdfObject f2 = merged.get(PdfName.FF);
if (f2 != null && f2.isNumber())
flag2 = ((PdfNumber)f2).intValue();
if (type1.equals(PdfName.BTN)) {
if (((flag1 ^ flag2) & PdfFormField.FF_PUSHBUTTON) != 0)
return;
if ((flag1 & PdfFormField.FF_PUSHBUTTON) == 0 && ((flag1 ^ flag2) & PdfFormField.FF_RADIO) != 0)
return;
}
else if (type1.equals(PdfName.CH)) {
if (((flag1 ^ flag2) & PdfFormField.FF_COMBO) != 0)
return;
}
createWidgets(list, item);
}
return;
}
}
}
void mergeWithMaster(HashMap fd) {
for (Iterator it = fd.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String name = (String) entry.getKey();
mergeField(name, (AcroFields.Item) entry.getValue());
}
}
void mergeFields() {
int pageOffset = 0;
for (int k = 0; k < fields.size(); ++k) {
HashMap fd = ((AcroFields)fields.get(k)).getFields();
addPageOffsetToField(fd, pageOffset);
mergeWithMaster(fd);
pageOffset += ((PdfReader)readers.get(k)).getNumberOfPages();
}
}
public PdfIndirectReference getPageReference(int page) {
return (PdfIndirectReference)pageRefs.get(page - 1);
}
protected PdfDictionary getCatalog(PdfIndirectReference rootObj) {
try {
PdfDictionary cat = pdf.getCatalog(rootObj);
if (form != null) {
PdfIndirectReference ref = addToBody(form).getIndirectReference();
cat.put(PdfName.ACROFORM, ref);
}
return cat;
}
catch (IOException e) {
throw new ExceptionConverter(e);
}
}
protected PdfIndirectReference getNewReference(PRIndirectReference ref) {
return new PdfIndirectReference(0, getNewObjectNumber(ref.getReader(), ref.getNumber(), 0));
}
protected int getNewObjectNumber(PdfReader reader, int number, int generation) {
IntHashtable refs = (IntHashtable)readers2intrefs.get(reader);
int n = refs.get(number);
if (n == 0) {
n = getIndirectReferenceNumber();
refs.put(number, n);
}
return n;
}
/**
* Sets a reference to "visited" in the copy process.
* @param ref the reference that needs to be set to "visited"
* @return true if the reference was set to visited
*/
protected boolean setVisited(PRIndirectReference ref) {
IntHashtable refs = (IntHashtable)visited.get(ref.getReader());
if (refs != null)
return (refs.put(ref.getNumber(), 1) != 0);
else
return false;
}
/**
* Checks if a reference has already been "visited" in the copy process.
* @param ref the reference that needs to be checked
* @return true if the reference was already visited
*/
protected boolean isVisited(PRIndirectReference ref) {
IntHashtable refs = (IntHashtable)visited.get(ref.getReader());
if (refs != null)
return refs.containsKey(ref.getNumber());
else
return false;
}
protected boolean isVisited(PdfReader reader, int number, int generation) {
IntHashtable refs = (IntHashtable)readers2intrefs.get(reader);
return refs.containsKey(number);
}
/**
* Checks if a reference refers to a page object.
* @param ref the reference that needs to be checked
* @return true is the reference refers to a page object.
*/
protected boolean isPage(PRIndirectReference ref) {
IntHashtable refs = (IntHashtable)pages2intrefs.get(ref.getReader());
if (refs != null)
return refs.containsKey(ref.getNumber());
else
return false;
}
RandomAccessFileOrArray getReaderFile(PdfReader reader) {
return file;
}
public void openDoc() {
if (!nd.isOpen())
nd.open();
}
protected static final HashMap widgetKeys = new HashMap();
protected static final HashMap fieldKeys = new HashMap();
static {
Integer one = new Integer(1);
widgetKeys.put(PdfName.SUBTYPE, one);
widgetKeys.put(PdfName.CONTENTS, one);
widgetKeys.put(PdfName.RECT, one);
widgetKeys.put(PdfName.NM, one);
widgetKeys.put(PdfName.M, one);
widgetKeys.put(PdfName.F, one);
widgetKeys.put(PdfName.BS, one);
widgetKeys.put(PdfName.BORDER, one);
widgetKeys.put(PdfName.AP, one);
widgetKeys.put(PdfName.AS, one);
widgetKeys.put(PdfName.C, one);
widgetKeys.put(PdfName.A, one);
widgetKeys.put(PdfName.STRUCTPARENT, one);
widgetKeys.put(PdfName.OC, one);
widgetKeys.put(PdfName.H, one);
widgetKeys.put(PdfName.MK, one);
widgetKeys.put(PdfName.DA, one);
widgetKeys.put(PdfName.Q, one);
fieldKeys.put(PdfName.AA, one);
fieldKeys.put(PdfName.FT, one);
fieldKeys.put(PdfName.TU, one);
fieldKeys.put(PdfName.TM, one);
fieldKeys.put(PdfName.FF, one);
fieldKeys.put(PdfName.V, one);
fieldKeys.put(PdfName.DV, one);
fieldKeys.put(PdfName.DS, one);
fieldKeys.put(PdfName.RV, one);
fieldKeys.put(PdfName.OPT, one);
fieldKeys.put(PdfName.MAXLEN, one);
fieldKeys.put(PdfName.TI, one);
fieldKeys.put(PdfName.I, one);
fieldKeys.put(PdfName.LOCK, one);
fieldKeys.put(PdfName.SV, one);
}
}
| lgpl-3.0 |
sefaakca/EvoSuite-Sefa | client/src/main/java/org/evosuite/ga/populationlimit/PopulationLimit.java | 1247 | /**
* Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package org.evosuite.ga.populationlimit;
import java.io.Serializable;
import java.util.List;
import org.evosuite.ga.Chromosome;
/**
* <p>PopulationLimit interface.</p>
*
* @author Gordon Fraser
*/
public interface PopulationLimit extends Serializable {
/**
* <p>isPopulationFull</p>
*
* @param population a {@link java.util.List} object.
* @return a boolean.
*/
public boolean isPopulationFull(List<? extends Chromosome> population);
}
| lgpl-3.0 |
klipdev/SpiderGps | workspace/SpiderGps/src3p/org/klipdev/spidergps3p/gpx/WptType.java | 14908 | //
// Ce fichier a été généré par l'implémentation de référence JavaTM Architecture for XML Binding (JAXB), v2.2.8-b130911.1802
// Voir <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Toute modification apportée à ce fichier sera perdue lors de la recompilation du schéma source.
// Généré le : 2015.10.08 à 10:48:36 PM CEST
//
package org.klipdev.spidergps3p.gpx;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
*
* wpt represents a waypoint, point of interest, or named feature on a map.
*
*
* <p>Classe Java pour wptType complex type.
*
* <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
*
* <pre>
* <complexType name="wptType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ele" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="time" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="magvar" type="{http://www.topografix.com/GPX/1/1}degreesType" minOccurs="0"/>
* <element name="geoidheight" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="cmt" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="desc" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="src" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="link" type="{http://www.topografix.com/GPX/1/1}linkType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="sym" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="fix" type="{http://www.topografix.com/GPX/1/1}fixType" minOccurs="0"/>
* <element name="sat" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/>
* <element name="hdop" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="vdop" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="pdop" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="ageofdgpsdata" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="dgpsid" type="{http://www.topografix.com/GPX/1/1}dgpsStationType" minOccurs="0"/>
* <element name="extensions" type="{http://www.topografix.com/GPX/1/1}extensionsType" minOccurs="0"/>
* </sequence>
* <attribute name="lat" use="required" type="{http://www.topografix.com/GPX/1/1}latitudeType" />
* <attribute name="lon" use="required" type="{http://www.topografix.com/GPX/1/1}longitudeType" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "wptType", propOrder = {
"ele",
"time",
"magvar",
"geoidheight",
"name",
"cmt",
"desc",
"src",
"link",
"sym",
"type",
"fix",
"sat",
"hdop",
"vdop",
"pdop",
"ageofdgpsdata",
"dgpsid",
"extensions"
})
public class WptType {
protected BigDecimal ele;
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar time;
protected BigDecimal magvar;
protected BigDecimal geoidheight;
protected String name;
protected String cmt;
protected String desc;
protected String src;
protected List<LinkType> link;
protected String sym;
protected String type;
protected String fix;
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger sat;
protected BigDecimal hdop;
protected BigDecimal vdop;
protected BigDecimal pdop;
protected BigDecimal ageofdgpsdata;
@XmlSchemaType(name = "integer")
protected Integer dgpsid;
protected ExtensionsType extensions;
@XmlAttribute(name = "lat", required = true)
protected BigDecimal lat;
@XmlAttribute(name = "lon", required = true)
protected BigDecimal lon;
/**
* Obtient la valeur de la propriété ele.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getEle() {
return ele;
}
/**
* Définit la valeur de la propriété ele.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setEle(BigDecimal value) {
this.ele = value;
}
/**
* Obtient la valeur de la propriété time.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getTime() {
return time;
}
/**
* Définit la valeur de la propriété time.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTime(XMLGregorianCalendar value) {
this.time = value;
}
/**
* Obtient la valeur de la propriété magvar.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getMagvar() {
return magvar;
}
/**
* Définit la valeur de la propriété magvar.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setMagvar(BigDecimal value) {
this.magvar = value;
}
/**
* Obtient la valeur de la propriété geoidheight.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getGeoidheight() {
return geoidheight;
}
/**
* Définit la valeur de la propriété geoidheight.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setGeoidheight(BigDecimal value) {
this.geoidheight = value;
}
/**
* Obtient la valeur de la propriété name.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Définit la valeur de la propriété name.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Obtient la valeur de la propriété cmt.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCmt() {
return cmt;
}
/**
* Définit la valeur de la propriété cmt.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCmt(String value) {
this.cmt = value;
}
/**
* Obtient la valeur de la propriété desc.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDesc() {
return desc;
}
/**
* Définit la valeur de la propriété desc.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDesc(String value) {
this.desc = value;
}
/**
* Obtient la valeur de la propriété src.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSrc() {
return src;
}
/**
* Définit la valeur de la propriété src.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSrc(String value) {
this.src = value;
}
/**
* Gets the value of the link property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the link property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLink().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link LinkType }
*
*
*/
public List<LinkType> getLink() {
if (link == null) {
link = new ArrayList<LinkType>();
}
return this.link;
}
/**
* Obtient la valeur de la propriété sym.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSym() {
return sym;
}
/**
* Définit la valeur de la propriété sym.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSym(String value) {
this.sym = value;
}
/**
* Obtient la valeur de la propriété type.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Définit la valeur de la propriété type.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Obtient la valeur de la propriété fix.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFix() {
return fix;
}
/**
* Définit la valeur de la propriété fix.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFix(String value) {
this.fix = value;
}
/**
* Obtient la valeur de la propriété sat.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getSat() {
return sat;
}
/**
* Définit la valeur de la propriété sat.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setSat(BigInteger value) {
this.sat = value;
}
/**
* Obtient la valeur de la propriété hdop.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getHdop() {
return hdop;
}
/**
* Définit la valeur de la propriété hdop.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setHdop(BigDecimal value) {
this.hdop = value;
}
/**
* Obtient la valeur de la propriété vdop.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getVdop() {
return vdop;
}
/**
* Définit la valeur de la propriété vdop.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setVdop(BigDecimal value) {
this.vdop = value;
}
/**
* Obtient la valeur de la propriété pdop.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getPdop() {
return pdop;
}
/**
* Définit la valeur de la propriété pdop.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setPdop(BigDecimal value) {
this.pdop = value;
}
/**
* Obtient la valeur de la propriété ageofdgpsdata.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getAgeofdgpsdata() {
return ageofdgpsdata;
}
/**
* Définit la valeur de la propriété ageofdgpsdata.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setAgeofdgpsdata(BigDecimal value) {
this.ageofdgpsdata = value;
}
/**
* Obtient la valeur de la propriété dgpsid.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getDgpsid() {
return dgpsid;
}
/**
* Définit la valeur de la propriété dgpsid.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setDgpsid(Integer value) {
this.dgpsid = value;
}
/**
* Obtient la valeur de la propriété extensions.
*
* @return
* possible object is
* {@link ExtensionsType }
*
*/
public ExtensionsType getExtensions() {
return extensions;
}
/**
* Définit la valeur de la propriété extensions.
*
* @param value
* allowed object is
* {@link ExtensionsType }
*
*/
public void setExtensions(ExtensionsType value) {
this.extensions = value;
}
/**
* Obtient la valeur de la propriété lat.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getLat() {
return lat;
}
/**
* Définit la valeur de la propriété lat.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setLat(BigDecimal value) {
this.lat = value;
}
/**
* Obtient la valeur de la propriété lon.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getLon() {
return lon;
}
/**
* Définit la valeur de la propriété lon.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setLon(BigDecimal value) {
this.lon = value;
}
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/repository/source/test-java/org/alfresco/repo/transfer/RepoTransferReceiverImplTest.java | 67009 | /*
* Copyright (C) 2009-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.transfer;
import static org.mockito.Mockito.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.policy.Behaviour.NotificationFrequency;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.repo.transfer.manifest.TransferManifestDeletedNode;
import org.alfresco.repo.transfer.manifest.TransferManifestHeader;
import org.alfresco.repo.transfer.manifest.TransferManifestNode;
import org.alfresco.repo.transfer.manifest.TransferManifestNormalNode;
import org.alfresco.repo.transfer.manifest.XMLTransferManifestWriter;
import org.alfresco.service.cmr.action.ActionService;
import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.Path;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.MutableAuthenticationService;
import org.alfresco.service.cmr.transfer.TransferException;
import org.alfresco.service.cmr.transfer.TransferProgress;
import org.alfresco.service.cmr.transfer.TransferServicePolicies;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.test_category.BaseSpringTestsCategory;
import org.alfresco.test_category.OwnJVMTestsCategory;
import org.alfresco.util.BaseAlfrescoSpringTest;
import org.alfresco.util.GUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.experimental.categories.Category;
import org.mockito.ArgumentCaptor;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionDefinition;
/**
* Unit test for RepoTransferReceiverImpl
*
* @author Brian Remmington
*/
@SuppressWarnings("deprecation")
@Category(BaseSpringTestsCategory.class)
public class RepoTransferReceiverImplTest extends BaseAlfrescoSpringTest
{
private static int fileCount = 0;
private static final Log log = LogFactory.getLog(RepoTransferReceiverImplTest.class);
private RepoTransferReceiverImpl receiver;
private SearchService searchService;
private String dummyContent;
private byte[] dummyContentBytes;
private NodeRef guestHome;
private PolicyComponent policyComponent;
@Override
public void runBare() throws Throwable
{
preventTransaction();
super.runBare();
}
/**
* Called during the transaction setup
*/
protected void onSetUp() throws Exception
{
super.onSetUp();
System.out.println("java.io.tmpdir == " + System.getProperty("java.io.tmpdir"));
// Get the required services
this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
this.contentService = (ContentService) this.applicationContext.getBean("contentService");
this.authenticationService = (MutableAuthenticationService) this.applicationContext
.getBean("authenticationService");
this.actionService = (ActionService) this.applicationContext.getBean("actionService");
this.transactionService = (TransactionService) this.applicationContext.getBean("transactionComponent");
this.authenticationComponent = (AuthenticationComponent) this.applicationContext
.getBean("authenticationComponent");
this.receiver = (RepoTransferReceiverImpl) this.getApplicationContext().getBean("transferReceiver");
this.policyComponent = (PolicyComponent) this.getApplicationContext().getBean("policyComponent");
this.searchService = (SearchService) this.getApplicationContext().getBean("searchService");
this.dummyContent = "This is some dummy content.";
this.dummyContentBytes = dummyContent.getBytes("UTF-8");
setTransactionDefinition(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
authenticationComponent.setSystemUserAsCurrentUser();
startNewTransaction();
String guestHomeQuery = "/app:company_home/app:guest_home";
ResultSet guestHomeResult = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_XPATH, guestHomeQuery);
assertEquals("", 1, guestHomeResult.length());
guestHome = guestHomeResult.getNodeRef(0);
endTransaction();
}
public void testDelete()
{
log.debug("start testDelete");
final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
final String uuid = GUID.generate();
class TestContext
{
ChildAssociationRef childAssoc;
};
RetryingTransactionCallback<TestContext> setupCB = new RetryingTransactionCallback<TestContext>()
{
@Override
public TestContext execute() throws Throwable
{
TestContext tc = new TestContext();
ResultSet rs = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_XPATH,
"/app:company_home");
assertEquals(1, rs.length());
NodeRef companyHome = rs.getNodeRef(0);
Map<QName, Serializable> props = new HashMap<QName, Serializable>();
props.put(ContentModel.PROP_NAME, uuid);
tc.childAssoc = nodeService.createNode(companyHome, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.APP_MODEL_1_0_URI, uuid), ContentModel.TYPE_CONTENT, props);
return tc;
}
};
final TestContext tc = tran.doInTransaction(setupCB, false, true);
RetryingTransactionCallback<Void> deleteCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
nodeService.deleteNode(tc.childAssoc.getChildRef());
return null;
}
};
tran.doInTransaction(deleteCB, false, true);
RetryingTransactionCallback<Void> validateCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
log.debug("Test that original node no longer exists...");
assertFalse(nodeService.exists(tc.childAssoc.getChildRef()));
log.debug("PASS - Original node no longer exists.");
NodeRef archiveNodeRef = new NodeRef(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE, tc.childAssoc.getChildRef().getId());
log.debug("Test that archive node exists...");
assertTrue(nodeService.exists(archiveNodeRef));
log.debug("PASS - Archive node exists.");
return null;
}
};
tran.doInTransaction(validateCB, false, true);
}
/**
* Tests start and end with regard to locking.
* @throws Exception
*/
public void DISABLED_testStartAndEnd() throws Exception
{
log.debug("start testStartAndEnd");
RetryingTransactionHelper trx = transactionService.getRetryingTransactionHelper();
RetryingTransactionCallback<Void> cb = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
log.debug("about to call start");
String transferId = receiver.start("1234", true, receiver.getVersion());
File stagingFolder = null;
try
{
System.out.println("TransferId == " + transferId);
stagingFolder = receiver.getStagingFolder(transferId);
assertTrue(receiver.getStagingFolder(transferId).exists());
NodeRef tempFolder = receiver.getTempFolder(transferId);
assertNotNull("tempFolder is null", tempFolder);
Thread.sleep(1000);
try
{
receiver.start("1234", true, receiver.getVersion());
fail("Successfully started twice!");
}
catch (TransferException ex)
{
// Expected
}
Thread.sleep(300);
try
{
receiver.start("1234", true, receiver.getVersion());
fail("Successfully started twice!");
}
catch (TransferException ex)
{
// Expected
}
try
{
receiver.end(new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate()).toString());
// fail("Successfully ended with transfer id that doesn't own lock.");
}
catch (TransferException ex)
{
// Expected
}
}
finally
{
log.debug("about to call end");
receiver.end(transferId);
/**
* Check clean-up
*/
if(stagingFolder != null)
{
assertFalse(stagingFolder.exists());
}
}
return null;
}
};
long oldRefreshTime = receiver.getLockRefreshTime();
try
{
receiver.setLockRefreshTime(500);
for (int i = 0; i < 5; i++)
{
log.info("test iteration:" + i);
trx.doInTransaction(cb, false, true);
}
}
finally
{
receiver.setLockRefreshTime(oldRefreshTime);
}
}
/**
* Tests start and end with regard to locking.
*
* Going to cut down the timeout to a very short period, the lock should expire
* @throws Exception
*/
public void DISABLED_testLockTimeout() throws Exception
{
log.info("start testLockTimeout");
RetryingTransactionHelper trx = transactionService.getRetryingTransactionHelper();
/**
* Simulates a client starting a transfer and then "going away";
*/
RetryingTransactionCallback<Void> startWithoutAnythingElse = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
log.debug("about to call start");
String transferId = receiver.start("1234", true, receiver.getVersion());
return null;
}
};
RetryingTransactionCallback<Void> slowTransfer = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
log.debug("about to call start");
String transferId = receiver.start("1234", true, receiver.getVersion());
Thread.sleep(1000);
receiver.saveSnapshot(transferId, null);
fail("did not timeout");
return null;
}
};
long lockRefreshTime = receiver.getLockRefreshTime();
long lockTimeOut = receiver.getLockTimeOut();
try
{
receiver.setLockRefreshTime(500);
receiver.setLockTimeOut(200);
/**
* This test simulates a client that starts a transfer and then "goes away".
* We kludge the timeouts to far shorter than normal to make the test run in a reasonable time.
*/
for (int i = 0; i < 3; i++)
{
log.info("test iteration:" + i);
trx.doInTransaction(startWithoutAnythingElse, false, true);
Thread.sleep(1000);
}
try
{
trx.doInTransaction(slowTransfer, false, true);
}
catch (Exception e)
{
// Expect to go here.
}
}
finally
{
receiver.setLockRefreshTime(lockRefreshTime);
receiver.setLockTimeOut(lockTimeOut);
}
log.info("end testLockTimeout");
}
public void testSaveContent() throws Exception
{
log.info("start testSaveContent");
final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
startNewTransaction();
try
{
String transferId = receiver.start("1234", true, receiver.getVersion());
try
{
String contentId = "mytestcontent";
receiver.saveContent(transferId, contentId, new ByteArrayInputStream(dummyContentBytes));
File contentFile = new File(receiver.getStagingFolder(transferId), contentId);
assertTrue(contentFile.exists());
assertEquals(dummyContentBytes.length, contentFile.length());
}
finally
{
receiver.end(transferId);
}
}
finally
{
endTransaction();
}
}
public void testSaveSnapshot() throws Exception
{
log.info("start testSaveSnapshot");
final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
startNewTransaction();
try
{
String transferId = receiver.start("1234", true, receiver.getVersion());
File snapshotFile = null;
try
{
TransferManifestNode node = createContentNode();
List<TransferManifestNode> nodes = new ArrayList<TransferManifestNode>();
nodes.add(node);
String snapshot = createSnapshot(nodes);
receiver.saveSnapshot(transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
File stagingFolder = receiver.getStagingFolder(transferId);
snapshotFile = new File(stagingFolder, "snapshot.xml");
assertTrue(snapshotFile.exists());
assertEquals(snapshot.getBytes("UTF-8").length, snapshotFile.length());
}
finally
{
receiver.end(transferId);
if (snapshotFile != null)
{
assertFalse(snapshotFile.exists());
}
}
}
finally
{
endTransaction();
}
}
public void testBasicCommit() throws Exception
{
log.info("start testBasicCommit");
final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
class TestContext
{
TransferManifestNode node = null;
String transferId = null;
}
RetryingTransactionCallback<TestContext> setupCB = new RetryingTransactionCallback<TestContext>()
{
@Override
public TestContext execute() throws Throwable
{
TestContext tc = new TestContext();
tc.node = createContentNode();
return tc;
}
};
final TestContext tc = tran.doInTransaction(setupCB, false, true);
RetryingTransactionCallback<Void> doPrepareCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
tc.transferId = receiver.start("1234", true, receiver.getVersion());
List<TransferManifestNode> nodes = new ArrayList<TransferManifestNode>();
nodes.add(tc.node);
String snapshot = createSnapshot(nodes);
receiver.saveSnapshot(tc.transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
receiver.saveContent(tc.transferId, tc.node.getUuid(), new ByteArrayInputStream(dummyContentBytes));
return null;
}
};
RetryingTransactionCallback<Void> doCommitCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
receiver.commit(tc.transferId);
return null;
}
};
RetryingTransactionCallback<Void> doEndCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
receiver.end(tc.transferId);
return null;
}
};
try
{
tran.doInTransaction(doPrepareCB, false, true);
tran.doInTransaction(doCommitCB, false, true);
}
finally
{
if(tc.transferId != null)
{
tran.doInTransaction(doEndCB, false, true);
}
}
RetryingTransactionCallback<Void> doValidateCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
assertTrue(nodeService.exists(tc.node.getNodeRef()));
nodeService.deleteNode(tc.node.getNodeRef());
return null;
}
};
tran.doInTransaction(doValidateCB, false, true);
}
/**
* Test More Complex Commit
*
* @throws Exception
*/
public void testMoreComplexCommit() throws Exception
{
log.info("start testMoreComplexCommit");
final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
class TestContext
{
List<TransferManifestNode> nodes = new ArrayList<TransferManifestNode>();
TransferManifestNormalNode node1 = null;
TransferManifestNormalNode node2 = null;
TransferManifestNode node3 = null;
TransferManifestNode node4 = null;
TransferManifestNode node5 = null;
TransferManifestNode node6 = null;
TransferManifestNode node7 = null;
TransferManifestNode node8 = null;
TransferManifestNode node9 = null;
TransferManifestNode node10 = null;
TransferManifestNormalNode node11 = null;
TransferManifestNode node12 = null;
String transferId = null;
};
RetryingTransactionCallback<TestContext> setupCB = new RetryingTransactionCallback<TestContext>()
{
@Override
public TestContext execute() throws Throwable
{
TestContext tc = new TestContext();
tc.node1 = createContentNode();
tc.nodes.add(tc.node1);
tc.node2 = createContentNode();
tc.nodes.add(tc.node2);
tc.node3 = createContentNode();
tc.nodes.add(tc.node3);
tc.node4 = createContentNode();
tc.nodes.add(tc.node4);
tc.node5 = createContentNode();
tc.nodes.add(tc.node5);
tc.node6 = createContentNode();
tc.nodes.add(tc.node6);
tc.node7 = createContentNode();
tc.nodes.add(tc.node7);
tc.node8 = createFolderNode();
tc.nodes.add(tc.node8);
tc.node9 = createFolderNode();
tc.nodes.add(tc.node9);
tc.node10 = createFolderNode();
tc.nodes.add(tc.node10);
tc.node11 = createFolderNode();
tc.nodes.add(tc.node11);
tc.node12 = createFolderNode();
tc.nodes.add(tc.node12);
associatePeers(tc.node1, tc.node2);
moveNode(tc.node2, tc.node11);
return tc;
}
};
final TestContext tc = tran.doInTransaction(setupCB, false, true);
RetryingTransactionCallback<Void> doPrepareCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
tc.transferId = receiver.start("1234", true, receiver.getVersion());
String snapshot = createSnapshot(tc.nodes);
receiver.saveSnapshot(tc.transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
for (TransferManifestNode node : tc.nodes)
{
receiver.saveContent(tc.transferId, node.getUuid(), new ByteArrayInputStream(dummyContentBytes));
}
return null;
}
};
RetryingTransactionCallback<Void> doCommitCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
log.info("testMoreComplexCommit - commit");
receiver.commit(tc.transferId);
log.info("testMoreComplexCommit - commited");
return null;
}
};
RetryingTransactionCallback<Void> doEndCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
// Needs to move elsewhere to allow other tests to pass.
receiver.end(tc.transferId);
return null;
}
};
try
{
tran.doInTransaction(doPrepareCB, false, true);
tran.doInTransaction(doCommitCB, false, true);
}
finally
{
if(tc.transferId != null)
{
tran.doInTransaction(doEndCB, false, true);
}
}
RetryingTransactionCallback<Void> validateCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
log.info("testMoreComplexCommit - validate nodes");
assertTrue(nodeService.getAspects(tc.node1.getNodeRef()).contains(ContentModel.ASPECT_ATTACHABLE));
assertFalse(nodeService.getSourceAssocs(tc.node2.getNodeRef(), ContentModel.ASSOC_ATTACHMENTS).isEmpty());
for (TransferManifestNode node : tc.nodes)
{
assertTrue(nodeService.exists(node.getNodeRef()));
}
return null;
}
};
tran.doInTransaction(validateCB, false, true);
}
/**
* Test Node Delete And Restore
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void testNodeDeleteAndRestore() throws Exception
{
log.info("start testNodeDeleteAndRestore");
final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
final TransferServicePolicies.OnEndInboundTransferPolicy mockedPolicyHandler =
mock(TransferServicePolicies.OnEndInboundTransferPolicy.class);
policyComponent.bindClassBehaviour(
TransferServicePolicies.OnEndInboundTransferPolicy.QNAME,
TransferModel.TYPE_TRANSFER_RECORD,
new JavaBehaviour(mockedPolicyHandler, "onEndInboundTransfer", NotificationFrequency.EVERY_EVENT));
class TestContext
{
String transferId;
TransferManifestNormalNode node1;
TransferManifestNormalNode node2;
TransferManifestNode node3;
TransferManifestNode node4;
TransferManifestNode node5;
TransferManifestNode node6;
TransferManifestNode node7;
TransferManifestNode node8;
TransferManifestNode node9;
TransferManifestNode node10;
TransferManifestNormalNode node11;
TransferManifestNode node12;
TransferManifestDeletedNode deletedNode8;
TransferManifestDeletedNode deletedNode2;
TransferManifestDeletedNode deletedNode11;
List<TransferManifestNode> nodes;
String errorMsgId;
};
RetryingTransactionCallback<TestContext> setupCB = new RetryingTransactionCallback<TestContext>()
{
@Override
public TestContext execute() throws Throwable
{
TestContext tc = new TestContext();
tc.nodes = new ArrayList<TransferManifestNode>();
tc.node1 = createContentNode();
tc.nodes.add(tc.node1);
tc.node2 = createContentNode();
tc.nodes.add(tc.node2);
tc.node3 = createContentNode();
tc.nodes.add(tc.node3);
tc.node4 = createContentNode();
tc.nodes.add(tc.node4);
tc.node5 = createContentNode();
tc.nodes.add(tc.node5);
tc.node6 = createContentNode();
tc.nodes.add(tc.node6);
tc.node7 = createContentNode();
tc.nodes.add(tc.node7);
tc.node8 = createFolderNode();
tc.nodes.add(tc.node8);
tc.node9 = createFolderNode();
tc.nodes.add(tc.node9);
tc.node10 = createFolderNode();
tc.nodes.add(tc.node10);
tc.node11 = createFolderNode();
tc.nodes.add(tc.node11);
tc.node12 = createFolderNode();
tc.nodes.add(tc.node12);
associatePeers(tc.node1, tc.node2);
moveNode(tc.node2, tc.node11);
tc.deletedNode8 = createDeletedNode(tc.node8);
tc.deletedNode2 = createDeletedNode(tc.node2);
tc.deletedNode11 = createDeletedNode(tc.node11);
return tc;
}
};
final TestContext tc = tran.doInTransaction(setupCB, false, true);
RetryingTransactionCallback<Void> doFirstPrepareCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
tc.transferId = receiver.start("1234", true, receiver.getVersion());
String snapshot = createSnapshot(tc.nodes);
log.debug(snapshot);
receiver.saveSnapshot(tc.transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
for (TransferManifestNode node : tc.nodes)
{
receiver.saveContent(tc.transferId, node.getUuid(), new ByteArrayInputStream(dummyContentBytes));
}
return null;
}
};
RetryingTransactionCallback<Void> doCommitCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
receiver.commit(tc.transferId);
return null;
}
};
RetryingTransactionCallback<Void> doEndCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
// Needs to move elsewhere to allow other tests to pass.
receiver.end(tc.transferId);
return null;
}
};
RetryingTransactionCallback<Void> validateFirstCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
assertTrue(nodeService.getAspects(tc.node1.getNodeRef()).contains(ContentModel.ASPECT_ATTACHABLE));
assertFalse(nodeService.getSourceAssocs(tc.node2.getNodeRef(), ContentModel.ASSOC_ATTACHMENTS).isEmpty());
ArgumentCaptor<String> transferIdCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Set> createdNodesCaptor = ArgumentCaptor.forClass(Set.class);
ArgumentCaptor<Set> updatedNodesCaptor = ArgumentCaptor.forClass(Set.class);
ArgumentCaptor<Set> deletedNodesCaptor = ArgumentCaptor.forClass(Set.class);
verify(mockedPolicyHandler, times(1)).onEndInboundTransfer(transferIdCaptor.capture(),
createdNodesCaptor.capture(),
updatedNodesCaptor.capture(),
deletedNodesCaptor.capture());
assertEquals(tc.transferId, transferIdCaptor.getValue());
Set capturedCreatedNodes = createdNodesCaptor.getValue();
assertEquals(tc.nodes.size(), capturedCreatedNodes.size());
for (TransferManifestNode node : tc.nodes)
{
assertTrue(nodeService.exists(node.getNodeRef()));
assertTrue(capturedCreatedNodes.contains(node.getNodeRef()));
}
return null;
}
};
/**
* First transfer test here
*/
reset(mockedPolicyHandler);
try
{
tran.doInTransaction(doFirstPrepareCB, false, true);
tran.doInTransaction(doCommitCB, false, true);
tran.doInTransaction(validateFirstCB, false, true);
}
finally
{
if(tc.transferId != null)
{
tran.doInTransaction(doEndCB, false, true);
}
}
/**
* Second transfer this time with some deleted nodes,
*
* nodes 8, 2, and 11 (11 and 2 are parent/child)
*/
reset(mockedPolicyHandler);
logger.debug("part 2 - transfer some deleted nodes");
RetryingTransactionCallback<Void> doSecondPrepareCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
// Now delete nodes 8, 2, and 11 (11 and 2 are parent/child)
tc.transferId = receiver.start("1234", true, receiver.getVersion());
String snapshot = createSnapshot(Arrays.asList(new TransferManifestNode[] { tc.deletedNode8,
tc.deletedNode2,
tc.deletedNode11 }));
log.debug(snapshot);
receiver.saveSnapshot(tc.transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
return null;
}
};
RetryingTransactionCallback<Void> validateSecondCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
ArgumentCaptor<String> transferIdCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Set> createdNodesCaptor = ArgumentCaptor.forClass(Set.class);
ArgumentCaptor<Set> updatedNodesCaptor = ArgumentCaptor.forClass(Set.class);
ArgumentCaptor<Set> deletedNodesCaptor = ArgumentCaptor.forClass(Set.class);
verify(mockedPolicyHandler, times(1)).onEndInboundTransfer(transferIdCaptor.capture(),
createdNodesCaptor.capture(),
updatedNodesCaptor.capture(),
deletedNodesCaptor.capture());
assertEquals(tc.transferId, transferIdCaptor.getValue());
Set capturedDeletedNodes = deletedNodesCaptor.getValue();
assertEquals(3, capturedDeletedNodes.size());
assertTrue(capturedDeletedNodes.contains(tc.deletedNode8.getNodeRef()));
assertTrue(capturedDeletedNodes.contains(tc.deletedNode2.getNodeRef()));
assertTrue(capturedDeletedNodes.contains(tc.deletedNode11.getNodeRef()));
log.debug("Test success of transfer...");
TransferProgress progress = receiver.getProgressMonitor().getProgress(tc.transferId);
assertEquals(TransferProgress.Status.COMPLETE, progress.getStatus());
NodeRef archiveNode8 = new NodeRef(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE, tc.node8.getNodeRef().getId());
NodeRef archiveNode2 = new NodeRef(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE, tc.node2.getNodeRef().getId());
NodeRef archiveNode11 = new NodeRef(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE, tc.node11.getNodeRef().getId());
assertTrue(nodeService.exists(archiveNode8));
assertTrue(nodeService.hasAspect(archiveNode8, ContentModel.ASPECT_ARCHIVED));
log.debug("Successfully tested existence of archive node: " + archiveNode8);
assertTrue(nodeService.exists(archiveNode2));
assertTrue(nodeService.hasAspect(archiveNode2, ContentModel.ASPECT_ARCHIVED));
log.debug("Successfully tested existence of archive node: " + archiveNode2);
assertTrue(nodeService.exists(archiveNode11));
assertTrue(nodeService.hasAspect(archiveNode11, ContentModel.ASPECT_ARCHIVED));
log.debug("Successfully tested existence of archive node: " + archiveNode11);
log.debug("Successfully tested existence of all archive nodes");
log.debug("Testing existence of original node: " + tc.node8.getNodeRef());
assertFalse(nodeService.exists(tc.node8.getNodeRef()));
log.debug("Testing existence of original node: " + tc.node2.getNodeRef());
assertFalse(nodeService.exists(tc.node2.getNodeRef()));
log.debug("Testing existence of original node: " + tc.node11.getNodeRef());
assertFalse(nodeService.exists(tc.node11.getNodeRef()));
log.debug("Successfully tested non-existence of all original nodes");
log.debug("Progress indication: " + progress.getCurrentPosition() + "/" + progress.getEndPosition());
return null;
}
};
try
{
tran.doInTransaction(doSecondPrepareCB, false, true);
tran.doInTransaction(doCommitCB, false, true);
tran.doInTransaction(validateSecondCB, false, true);
}
finally
{
if(tc.transferId != null)
{
tran.doInTransaction(doEndCB, false, true);
}
}
logger.debug("part 3 - restore orphan node which should fail");
System.out.println("Now try to restore orphan node 2.");
/**
* A third transfer. Expect an "orphan" failure, since its parent (node11) is deleted
*/
reset(mockedPolicyHandler);
String errorMsgId = null;
RetryingTransactionCallback<Void> doThirdPrepareCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
tc.transferId = receiver.start("1234", true, receiver.getVersion());
String snapshot = createSnapshot(Arrays.asList(new TransferManifestNode[] { tc.node2 }));
log.debug(snapshot);
receiver.saveSnapshot(tc.transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
receiver.saveContent(tc.transferId, tc.node2.getUuid(), new ByteArrayInputStream(dummyContentBytes));
return null;
}
};
RetryingTransactionCallback<Void> doCommitExpectingFailCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
try
{
receiver.commit(tc.transferId);
fail("Expected an exception");
}
catch (TransferException ex)
{
// Expected
tc.errorMsgId = ex.getMsgId();
ArgumentCaptor<String> transferIdCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Set> createdNodesCaptor = ArgumentCaptor.forClass(Set.class);
ArgumentCaptor<Set> updatedNodesCaptor = ArgumentCaptor.forClass(Set.class);
ArgumentCaptor<Set> deletedNodesCaptor = ArgumentCaptor.forClass(Set.class);
verify(mockedPolicyHandler, times(1)).onEndInboundTransfer(transferIdCaptor.capture(),
createdNodesCaptor.capture(), updatedNodesCaptor.capture(), deletedNodesCaptor.capture());
assertEquals(tc.transferId, transferIdCaptor.getValue());
assertTrue(createdNodesCaptor.getValue().isEmpty());
assertTrue(updatedNodesCaptor.getValue().isEmpty());
assertTrue(deletedNodesCaptor.getValue().isEmpty());
}
return null;
}
};
RetryingTransactionCallback<Void> validateThirdCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
TransferProgress progress = receiver.getProgressMonitor().getProgress(tc.transferId);
assertEquals(TransferProgress.Status.ERROR, progress.getStatus());
log.debug("Progress indication: " + progress.getCurrentPosition() + "/" + progress.getEndPosition());
assertNotNull("Progress error", progress.getError());
assertTrue(progress.getError() instanceof Exception);
assertTrue(tc.errorMsgId, tc.errorMsgId.contains("orphan"));
return null;
}
};
try
{
tran.doInTransaction(doThirdPrepareCB, false, true);
tran.doInTransaction(doCommitExpectingFailCB, false, true);
}
finally
{
if(tc.transferId != null)
{
tran.doInTransaction(doEndCB, false, true);
}
}
tran.doInTransaction(validateThirdCB, false, true);
log.debug("start testNodeDeleteAndRestore");
}
/**
* Test for fault raised as ALF-2772
* (https://issues.alfresco.com/jira/browse/ALF-2772) When transferring
* nodes it shouldn't matter the order in which they appear in the snapshot.
* That is to say, it shouldn't matter if a child node is listed before its
* parent node.
*
* Typically this is true, but in the special case where the parent node is
* being restored from the target's archive store then there is a fault. The
* process should be:
*
* 1. Process child node
* 2. Fail to find parent node
* 3. Place child node in temporary location and mark as an orphan
* 4. Process parent node
* 5. Create node to correspond to parent node
* 6. "Re-parent" orphaned child node with parent node
*
* However, in the case where the parent node is found in the target's
* archive store, the process is actually:
*
* 1. Process child node
* 2. Fail to find parent node
* 3. Place child node in temporary location and mark as an orphan
* 4. Process parent node
* 5. Find corresponding parent node in archive store and restore it
* 6. Update corresponding parent node
*
* Note that, in this case, we are not re-parenting the orphan as we should be.
*
* @throws Exception
*/
public void testJira_ALF_2772() throws Exception
{
log.debug("start testJira_ALF_2772");
final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
class TestContext
{
TransferManifestNormalNode node1 = null;
TransferManifestNormalNode node2 = null;
TransferManifestNormalNode node11 = null;
TransferManifestDeletedNode deletedNode11 = null;
String transferId = null;
};
RetryingTransactionCallback<TestContext> setupCB = new RetryingTransactionCallback<TestContext>()
{
@Override
public TestContext execute() throws Throwable
{
TestContext tc = new TestContext();
tc.node1 = createContentNode();
tc.node2 = createContentNode();
tc.node11 = createFolderNode();
associatePeers(tc.node1, tc.node2);
moveNode(tc.node2, tc.node11);
tc.deletedNode11 = createDeletedNode(tc.node11);
return tc;
}
};
final TestContext tc = tran.doInTransaction(setupCB, false, true);
RetryingTransactionCallback<Void> doEndCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
// Needs to move elsewhere to allow other tests to pass.
receiver.end(tc.transferId);
return null;
}
};
RetryingTransactionCallback<Void> doFirstCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
tc.transferId = receiver.start("1234", true, receiver.getVersion());
List<TransferManifestNode> nodes = new ArrayList<TransferManifestNode>();
//First we'll just send a folder node
nodes.add(tc.node11);
String snapshot = createSnapshot(nodes);
log.debug(snapshot);
receiver.saveSnapshot(tc.transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
for (TransferManifestNode node : nodes)
{
receiver.saveContent(tc.transferId, node.getUuid(), new ByteArrayInputStream(dummyContentBytes));
}
receiver.commit(tc.transferId);
for (TransferManifestNode node : nodes)
{
assertTrue(nodeService.exists(node.getNodeRef()));
}
return null;
}
};
/**
* First we'll just send a folder node
*/
try
{
tran.doInTransaction(doFirstCB, false, true);
}
finally
{
if(tc.transferId != null)
{
tran.doInTransaction(doEndCB, false, true);
}
}
RetryingTransactionCallback<Void> doSecondCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
tc.transferId = receiver.start("1234", true, receiver.getVersion());
String snapshot = createSnapshot(Arrays.asList(new TransferManifestNode[] { tc.deletedNode11 }));
log.debug(snapshot);
receiver.saveSnapshot(tc.transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
receiver.commit(tc.transferId);
return null;
}
};
RetryingTransactionCallback<Void> doValidateSecondCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
TransferProgress progress = receiver.getProgressMonitor().getProgress(tc.transferId);
assertEquals(TransferProgress.Status.COMPLETE, progress.getStatus());
NodeRef archivedNodeRef = new NodeRef(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE, tc.deletedNode11.getNodeRef().getId());
assertTrue(nodeService.exists(archivedNodeRef));
assertTrue(nodeService.hasAspect(archivedNodeRef, ContentModel.ASPECT_ARCHIVED));
log.debug("Successfully tested existence of archive node: " + tc.deletedNode11.getNodeRef());
log.debug("Successfully tested existence of all archive nodes");
log.debug("Testing existence of original node: " + tc.node11.getNodeRef());
assertFalse(nodeService.exists(tc.node11.getNodeRef()));
log.debug("Successfully tested non-existence of all original nodes");
log.debug("Progress indication: " + progress.getCurrentPosition() + "/" + progress.getEndPosition());
return null;
}
};
/**
* Then delete a folder node
*/
try
{
tran.doInTransaction(doSecondCB, false, true);
tran.doInTransaction(doValidateSecondCB, false, true);
}
finally
{
if(tc.transferId != null)
{
tran.doInTransaction(doEndCB, false, true);
}
}
/**
* Finally we transfer node2 and node11 (in that order)
*/
RetryingTransactionCallback<Void> doThirdCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
tc.transferId = receiver.start("1234", true, receiver.getVersion());
String snapshot = createSnapshot(Arrays.asList(new TransferManifestNode[] { tc.node2, tc.node11 }));
log.debug(snapshot);
receiver.saveSnapshot(tc.transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
receiver.saveContent(tc.transferId, tc.node2.getUuid(), new ByteArrayInputStream(dummyContentBytes));
receiver.commit(tc.transferId);
return null;
}
};
RetryingTransactionCallback<Void> doValidateThirdCB = new RetryingTransactionCallback<Void>()
{
@Override
public Void execute() throws Throwable
{
return null;
}
};
/**
* Then delete a folder node
*/
try
{
tran.doInTransaction(doThirdCB, false, true);
tran.doInTransaction(doValidateThirdCB, false, true);
}
finally
{
if(tc.transferId != null)
{
tran.doInTransaction(doEndCB, false, true);
}
}
}
/**
* Test for fault raised as MNT-11057
* (https://issues.alfresco.com/jira/browse/MNT-11057) Bug in replication process on Aliens.
*
* @throws Exception
*/
public void testMNT11057() throws Exception
{
String folder1Name = "H1";
String folder2Name = "H2";
String folder3Name = "H3";
//Step 1 transfer from repo A (H1 -> H2)
setDefaultRollback(true);
startNewTransaction();
String transferIdA1 = receiver.start("transferFromRepoA1", true, receiver.getVersion());
TransferManifestNormalNode folder1A1 = createFolderNode(folder1Name);
TransferManifestNormalNode folder2A1 = createFolderNode(folder2Name);
TransferManifestNormalNode folder3A1 = createFolderNode(folder3Name);
moveNode(folder2A1, folder1A1);
List<TransferManifestNode> nodesA1 = new ArrayList<TransferManifestNode>();
nodesA1.add(folder1A1);
nodesA1.add(folder2A1);
endTransaction();
this.setDefaultRollback(false);
startNewTransaction();
try
{
String snapshot = createSnapshot(nodesA1, "repo A");
log.debug(snapshot);
receiver.saveSnapshot(transferIdA1, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
for (TransferManifestNode node : nodesA1)
{
receiver.saveContent(transferIdA1, node.getUuid(), new ByteArrayInputStream(dummyContentBytes));
}
receiver.commit(transferIdA1);
for (TransferManifestNode node : nodesA1)
{
assertTrue(nodeService.exists(node.getNodeRef()));
}
}
finally
{
receiver.end(transferIdA1);
endTransaction();
}
//Step 2 trasfer from repo B (H1 -> H3)
setDefaultRollback(true);
startNewTransaction();
String transferIdB1 = receiver.start("transferFromRepoB1", true, receiver.getVersion());
TransferManifestNormalNode folder1B1 = createFolderNode(folder1Name);
TransferManifestNormalNode folder3B1 = createFolderNode(folder3Name);
moveNode(folder3B1, folder1B1);
List<TransferManifestNode> nodesB1 = new ArrayList<TransferManifestNode>();
nodesB1.add(folder1B1);
nodesB1.add(folder3B1);
endTransaction();
this.setDefaultRollback(false);
startNewTransaction();
try
{
String snapshot = createSnapshot(nodesB1, "repo B");
log.debug(snapshot);
receiver.saveSnapshot(transferIdB1, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
for (TransferManifestNode node : nodesB1)
{
receiver.saveContent(transferIdB1, node.getUuid(), new ByteArrayInputStream(dummyContentBytes));
}
receiver.commit(transferIdB1);
}
finally
{
receiver.end(transferIdB1);
endTransaction();
}
assertTrue(nodeService.exists(folder1A1.getNodeRef()));
log.info("has Alien");
log.info(nodeService.hasAspect(folder1A1.getNodeRef(), TransferModel.ASPECT_ALIEN));
assertTrue(nodeService.exists(folder2A1.getNodeRef()));
log.info("has Alien");
assertFalse(nodeService.hasAspect(folder2A1.getNodeRef(), TransferModel.ASPECT_ALIEN));
assertFalse(nodeService.exists(folder1B1.getNodeRef()));
assertTrue(nodeService.exists(folder3B1.getNodeRef()));
log.info("has Alien");
assertTrue(nodeService.hasAspect(folder3B1.getNodeRef(), TransferModel.ASPECT_ALIEN));
startNewTransaction();
moveNode(folder3A1, folder1A1);
moveNode(folder2A1, folder3A1);
nodesA1 = new ArrayList<TransferManifestNode>();
nodesA1.add(folder1A1);
nodesA1.add(folder3A1);
nodesA1.add(folder2A1);
endTransaction();
//Step 3 transfer from repo A again (H2 is moved to newly created H3 on A: H1 -> H3 -> H2)
startNewTransaction();
try
{
String transferId = receiver.start("transferFromRepoA1Again", true, receiver.getVersion());
String snapshot = createSnapshot(nodesA1, "repo A");
log.debug(snapshot);
receiver.saveSnapshot(transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
receiver.commit(transferId);
}
catch(Exception ex)
{
if(ex instanceof NullPointerException)
{
fail("Test of MNT-11057 failed: " + ex.getMessage());
}
}
finally
{
endTransaction();
}
}
public void testAsyncCommit() throws Exception
{
log.info("start testAsyncCommit");
this.setDefaultRollback(false);
final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();
startNewTransaction();
final String transferId = receiver.start("1234", true, receiver.getVersion());
endTransaction();
startNewTransaction();
final List<TransferManifestNode> nodes = new ArrayList<TransferManifestNode>();
final TransferManifestNormalNode node1 = createContentNode();
nodes.add(node1);
final TransferManifestNormalNode node2 = createContentNode();
nodes.add(node2);
TransferManifestNode node3 = createContentNode();
nodes.add(node3);
TransferManifestNode node4 = createContentNode();
nodes.add(node4);
TransferManifestNode node5 = createContentNode();
nodes.add(node5);
TransferManifestNode node6 = createContentNode();
nodes.add(node6);
TransferManifestNode node7 = createContentNode();
nodes.add(node7);
TransferManifestNode node8 = createFolderNode();
nodes.add(node8);
TransferManifestNode node9 = createFolderNode();
nodes.add(node9);
TransferManifestNode node10 = createFolderNode();
nodes.add(node10);
TransferManifestNormalNode node11 = createFolderNode();
nodes.add(node11);
TransferManifestNode node12 = createFolderNode();
nodes.add(node12);
associatePeers(node1, node2);
moveNode(node2, node11);
endTransaction();
String snapshot = createSnapshot(nodes);
startNewTransaction();
receiver.saveSnapshot(transferId, new ByteArrayInputStream(snapshot.getBytes("UTF-8")));
endTransaction();
for (TransferManifestNode node : nodes)
{
startNewTransaction();
receiver.saveContent(transferId, node.getUuid(), new ByteArrayInputStream(dummyContentBytes));
endTransaction();
}
startNewTransaction();
receiver.commitAsync(transferId);
endTransaction();
log.debug("Posted request for commit");
TransferProgressMonitor progressMonitor = receiver.getProgressMonitor();
TransferProgress progress = null;
while (progress == null || !TransferProgress.getTerminalStatuses().contains(progress.getStatus()))
{
Thread.sleep(500);
startNewTransaction();
progress = progressMonitor.getProgress(transferId);
endTransaction();
log.debug("Progress indication: " + progress.getStatus() + ": " + progress.getCurrentPosition() + "/"
+ progress.getEndPosition());
}
assertEquals(TransferProgress.Status.COMPLETE, progress.getStatus());
startNewTransaction();
try
{
assertTrue(nodeService.getAspects(node1.getNodeRef()).contains(ContentModel.ASPECT_ATTACHABLE));
assertFalse(nodeService.getSourceAssocs(node2.getNodeRef(), ContentModel.ASSOC_ATTACHMENTS).isEmpty());
for (TransferManifestNode node : nodes)
{
assertTrue(nodeService.exists(node.getNodeRef()));
}
}
finally
{
endTransaction();
}
}
/**
* @param nodeToDelete
* @return
*/
private TransferManifestDeletedNode createDeletedNode(TransferManifestNode nodeToDelete)
{
TransferManifestDeletedNode deletedNode = new TransferManifestDeletedNode();
deletedNode.setNodeRef(nodeToDelete.getNodeRef());
deletedNode.setParentPath(nodeToDelete.getParentPath());
deletedNode.setPrimaryParentAssoc(nodeToDelete.getPrimaryParentAssoc());
deletedNode.setUuid(nodeToDelete.getUuid());
return deletedNode;
}
/**
* move transfer node to new parent.
* @param childNode
* @param newParent
*/
private void moveNode(TransferManifestNormalNode childNode, TransferManifestNormalNode newParent)
{
List<ChildAssociationRef> currentParents = childNode.getParentAssocs();
List<ChildAssociationRef> newParents = new ArrayList<ChildAssociationRef>();
for (ChildAssociationRef parent : currentParents)
{
if (!parent.isPrimary())
{
newParents.add(parent);
}
else
{
ChildAssociationRef newPrimaryAssoc = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, newParent
.getNodeRef(), parent.getQName(), parent.getChildRef(), true, -1);
newParents.add(newPrimaryAssoc);
childNode.setPrimaryParentAssoc(newPrimaryAssoc);
Path newParentPath = new Path();
newParentPath.append(newParent.getParentPath());
newParentPath.append(new Path.ChildAssocElement(newParent.getPrimaryParentAssoc()));
childNode.setParentPath(newParentPath);
}
}
childNode.setParentAssocs(newParents);
}
private void associatePeers(TransferManifestNormalNode source, TransferManifestNormalNode target)
{
List<AssociationRef> currentReferencedPeers = source.getTargetAssocs();
if (currentReferencedPeers == null)
{
currentReferencedPeers = new ArrayList<AssociationRef>();
source.setTargetAssocs(currentReferencedPeers);
}
List<AssociationRef> currentRefereePeers = target.getSourceAssocs();
if (currentRefereePeers == null)
{
currentRefereePeers = new ArrayList<AssociationRef>();
target.setSourceAssocs(currentRefereePeers);
}
Set<QName> aspects = source.getAspects();
if (aspects == null)
{
aspects = new HashSet<QName>();
source.setAspects(aspects);
}
aspects.add(ContentModel.ASPECT_ATTACHABLE);
AssociationRef newAssoc = new AssociationRef(null, source.getNodeRef(), ContentModel.ASSOC_ATTACHMENTS, target
.getNodeRef());
currentRefereePeers.add(newAssoc);
currentReferencedPeers.add(newAssoc);
}
private String createSnapshot(List<TransferManifestNode> nodes) throws Exception
{
return createSnapshot(nodes, "repo 1");
}
private String createSnapshot(List<TransferManifestNode> nodes, String repoID) throws Exception
{
XMLTransferManifestWriter manifestWriter = new XMLTransferManifestWriter();
StringWriter output = new StringWriter();
manifestWriter.startTransferManifest(output);
TransferManifestHeader header = new TransferManifestHeader();
header.setCreatedDate(new Date());
header.setNodeCount(nodes.size());
header.setRepositoryId(repoID);
manifestWriter.writeTransferManifestHeader(header);
for (TransferManifestNode node : nodes)
{
manifestWriter.writeTransferManifestNode(node);
}
manifestWriter.endTransferManifest();
return output.toString();
}
/**
* @return
*/
private TransferManifestNormalNode createContentNode(/*String transferId*/) throws Exception
{
TransferManifestNormalNode node = new TransferManifestNormalNode();
String uuid = GUID.generate();
NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, uuid);
node.setNodeRef(nodeRef);
node.setUuid(uuid);
byte[] dummyContent = "This is some dummy content.".getBytes("UTF-8");
node.setType(ContentModel.TYPE_CONTENT);
/**
* Get guest home
*/
NodeRef parentFolder = guestHome;
String nodeName = uuid + ".testnode" + getNameSuffix();
List<ChildAssociationRef> parents = new ArrayList<ChildAssociationRef>();
ChildAssociationRef primaryAssoc = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, parentFolder, QName
.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nodeName), node.getNodeRef(), true, -1);
parents.add(primaryAssoc);
node.setParentAssocs(parents);
node.setParentPath(nodeService.getPath(parentFolder));
node.setPrimaryParentAssoc(primaryAssoc);
Map<QName, Serializable> props = new HashMap<QName, Serializable>();
props.put(ContentModel.PROP_NODE_UUID, uuid);
props.put(ContentModel.PROP_NAME, nodeName);
ContentData contentData = new ContentData("/" + uuid, "text/plain", dummyContent.length, "UTF-8");
props.put(ContentModel.PROP_CONTENT, contentData);
node.setProperties(props);
return node;
}
private TransferManifestNormalNode createFolderNode() throws Exception
{
return createFolderNode(null);
}
private TransferManifestNormalNode createFolderNode(String folderName) throws Exception
{
TransferManifestNormalNode node = new TransferManifestNormalNode();
String uuid = GUID.generate();
NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, uuid);
node.setNodeRef(nodeRef);
node.setUuid(uuid);
node.setType(ContentModel.TYPE_FOLDER);
/**
* Get guest home
*/
String guestHomeQuery = "/app:company_home/app:guest_home";
ResultSet guestHomeResult = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_XPATH, guestHomeQuery);
assertEquals("", 1, guestHomeResult.length());
NodeRef guestHome = guestHomeResult.getNodeRef(0);
NodeRef parentFolder = guestHome;
String nodeName = folderName == null ? uuid + ".folder" + getNameSuffix() : folderName;
List<ChildAssociationRef> parents = new ArrayList<ChildAssociationRef>();
ChildAssociationRef primaryAssoc = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, parentFolder, QName
.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nodeName), node.getNodeRef(), true, -1);
parents.add(primaryAssoc);
node.setParentAssocs(parents);
node.setParentPath(nodeService.getPath(parentFolder));
node.setPrimaryParentAssoc(primaryAssoc);
Map<QName, Serializable> props = new HashMap<QName, Serializable>();
props.put(ContentModel.PROP_NODE_UUID, uuid);
props.put(ContentModel.PROP_NAME, nodeName);
node.setProperties(props);
return node;
}
private String getNameSuffix()
{
return "" + fileCount++;
}
}
| lgpl-3.0 |
ist-dsi/giaf-client-financial-documents | src/main/java/pt/indra/mygiaf/services/ist/entities/external/CriarFatSimplSyncInDetalhe.java | 16526 |
package pt.indra.mygiaf.services.ist.entities.external;
import java.math.BigDecimal;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CriarFatSimplSyncInDetalhe complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CriarFatSimplSyncInDetalhe">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="armazemID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="artigo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="artigoCIVA" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="centroCusto" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="centroResponsabilidade" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="descricao" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="numeroLinha" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="observacao" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="precoUnitario" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="quantidade" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="referencia" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="rubricaContabilidade" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="subcentro" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="taxaDesconto" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="taxaIVA" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="tipoLinha" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="unidadeMedida" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CriarFatSimplSyncInDetalhe", propOrder = {
"armazemID",
"artigo",
"artigoCIVA",
"centroCusto",
"centroResponsabilidade",
"descricao",
"numeroLinha",
"observacao",
"precoUnitario",
"quantidade",
"referencia",
"rubricaContabilidade",
"subcentro",
"taxaDesconto",
"taxaIVA",
"tipoLinha",
"unidadeMedida"
})
public class CriarFatSimplSyncInDetalhe {
@XmlElementRef(name = "armazemID", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> armazemID;
@XmlElementRef(name = "artigo", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> artigo;
@XmlElementRef(name = "artigoCIVA", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> artigoCIVA;
@XmlElementRef(name = "centroCusto", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> centroCusto;
@XmlElementRef(name = "centroResponsabilidade", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> centroResponsabilidade;
@XmlElementRef(name = "descricao", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> descricao;
@XmlElementRef(name = "numeroLinha", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<Integer> numeroLinha;
@XmlElementRef(name = "observacao", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> observacao;
@XmlElementRef(name = "precoUnitario", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<BigDecimal> precoUnitario;
@XmlElementRef(name = "quantidade", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<BigDecimal> quantidade;
@XmlElementRef(name = "referencia", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> referencia;
@XmlElementRef(name = "rubricaContabilidade", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> rubricaContabilidade;
@XmlElementRef(name = "subcentro", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> subcentro;
@XmlElementRef(name = "taxaDesconto", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<BigDecimal> taxaDesconto;
@XmlElementRef(name = "taxaIVA", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<BigDecimal> taxaIVA;
@XmlElementRef(name = "tipoLinha", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> tipoLinha;
@XmlElementRef(name = "unidadeMedida", namespace = "http://external.entities.ist.services.mygiaf.indra.pt", type = JAXBElement.class, required = false)
protected JAXBElement<String> unidadeMedida;
/**
* Gets the value of the armazemID property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getArmazemID() {
return armazemID;
}
/**
* Sets the value of the armazemID property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setArmazemID(JAXBElement<String> value) {
this.armazemID = value;
}
/**
* Gets the value of the artigo property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getArtigo() {
return artigo;
}
/**
* Sets the value of the artigo property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setArtigo(JAXBElement<String> value) {
this.artigo = value;
}
/**
* Gets the value of the artigoCIVA property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getArtigoCIVA() {
return artigoCIVA;
}
/**
* Sets the value of the artigoCIVA property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setArtigoCIVA(JAXBElement<String> value) {
this.artigoCIVA = value;
}
/**
* Gets the value of the centroCusto property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getCentroCusto() {
return centroCusto;
}
/**
* Sets the value of the centroCusto property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setCentroCusto(JAXBElement<String> value) {
this.centroCusto = value;
}
/**
* Gets the value of the centroResponsabilidade property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getCentroResponsabilidade() {
return centroResponsabilidade;
}
/**
* Sets the value of the centroResponsabilidade property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setCentroResponsabilidade(JAXBElement<String> value) {
this.centroResponsabilidade = value;
}
/**
* Gets the value of the descricao property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getDescricao() {
return descricao;
}
/**
* Sets the value of the descricao property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setDescricao(JAXBElement<String> value) {
this.descricao = value;
}
/**
* Gets the value of the numeroLinha property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public JAXBElement<Integer> getNumeroLinha() {
return numeroLinha;
}
/**
* Sets the value of the numeroLinha property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public void setNumeroLinha(JAXBElement<Integer> value) {
this.numeroLinha = value;
}
/**
* Gets the value of the observacao property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getObservacao() {
return observacao;
}
/**
* Sets the value of the observacao property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setObservacao(JAXBElement<String> value) {
this.observacao = value;
}
/**
* Gets the value of the precoUnitario property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}
*
*/
public JAXBElement<BigDecimal> getPrecoUnitario() {
return precoUnitario;
}
/**
* Sets the value of the precoUnitario property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}
*
*/
public void setPrecoUnitario(JAXBElement<BigDecimal> value) {
this.precoUnitario = value;
}
/**
* Gets the value of the quantidade property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}
*
*/
public JAXBElement<BigDecimal> getQuantidade() {
return quantidade;
}
/**
* Sets the value of the quantidade property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}
*
*/
public void setQuantidade(JAXBElement<BigDecimal> value) {
this.quantidade = value;
}
/**
* Gets the value of the referencia property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getReferencia() {
return referencia;
}
/**
* Sets the value of the referencia property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setReferencia(JAXBElement<String> value) {
this.referencia = value;
}
/**
* Gets the value of the rubricaContabilidade property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getRubricaContabilidade() {
return rubricaContabilidade;
}
/**
* Sets the value of the rubricaContabilidade property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setRubricaContabilidade(JAXBElement<String> value) {
this.rubricaContabilidade = value;
}
/**
* Gets the value of the subcentro property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getSubcentro() {
return subcentro;
}
/**
* Sets the value of the subcentro property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setSubcentro(JAXBElement<String> value) {
this.subcentro = value;
}
/**
* Gets the value of the taxaDesconto property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}
*
*/
public JAXBElement<BigDecimal> getTaxaDesconto() {
return taxaDesconto;
}
/**
* Sets the value of the taxaDesconto property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}
*
*/
public void setTaxaDesconto(JAXBElement<BigDecimal> value) {
this.taxaDesconto = value;
}
/**
* Gets the value of the taxaIVA property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}
*
*/
public JAXBElement<BigDecimal> getTaxaIVA() {
return taxaIVA;
}
/**
* Sets the value of the taxaIVA property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}
*
*/
public void setTaxaIVA(JAXBElement<BigDecimal> value) {
this.taxaIVA = value;
}
/**
* Gets the value of the tipoLinha property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getTipoLinha() {
return tipoLinha;
}
/**
* Sets the value of the tipoLinha property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setTipoLinha(JAXBElement<String> value) {
this.tipoLinha = value;
}
/**
* Gets the value of the unidadeMedida property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getUnidadeMedida() {
return unidadeMedida;
}
/**
* Sets the value of the unidadeMedida property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setUnidadeMedida(JAXBElement<String> value) {
this.unidadeMedida = value;
}
}
| lgpl-3.0 |
NightKosh/Gravestone-mod-Extended | src/main/java/nightkosh/gravestone_extended/entity/monster/pet/EntitySkeletonCat.java | 2641 | package nightkosh.gravestone_extended.entity.monster.pet;
import net.minecraft.block.Block;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.*;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.init.SoundEvents;
import net.minecraft.util.DamageSource;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import nightkosh.gravestone_extended.core.GSLootTables;
import nightkosh.gravestone_extended.core.Resources;
import javax.annotation.Nullable;
/**
* GraveStone mod
*
* @author NightKosh
* @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
*/
public class EntitySkeletonCat extends EntityUndeadCat {
public EntitySkeletonCat(World world) {
super(world);
this.setMobType(EnumUndeadMobType.SKELETON);
this.tasks.addTask(1, new EntityAIRestrictSun(this));
this.tasks.addTask(1, new EntityAIFleeSun(this, 1));
this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityWolf.class, 6, 1, 1.2));
this.tasks.addTask(2, new EntityAIAttackMelee(this, 1, false));
this.tasks.addTask(4, new EntityAIMoveTowardsRestriction(this, 1));
this.tasks.addTask(6, new EntityAIWander(this, 1));
this.tasks.addTask(8, new EntityAIOcelotAttack(this));
this.tasks.addTask(7, new EntityAIWanderAvoidWater(this, 1));
}
@Override
@SideOnly(Side.CLIENT)
public ResourceLocation getTexture() {
return Resources.SKELETON_CAT;
}
@Override
protected void applyEntityAttributes() {
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(5);
this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.7);
this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).setBaseValue(1);
}
@Override
protected SoundEvent getAmbientSound() {
return SoundEvents.ENTITY_SKELETON_AMBIENT;
}
@Override
protected SoundEvent getHurtSound(DamageSource damageSource) {
return SoundEvents.ENTITY_SKELETON_HURT;
}
@Override
protected SoundEvent getDeathSound() {
return SoundEvents.ENTITY_SKELETON_DEATH;
}
@Override
protected void playStepSound(BlockPos pos, Block block) {
}
@Nullable
protected ResourceLocation getLootTable() {
return GSLootTables.SKELETON_CAT;
}
}
| lgpl-3.0 |
xXKeyleXx/MyPet | modules/v1_9_R2/src/main/java/de/Keyle/MyPet/compat/v1_9_R2/entity/types/EntityMyIronGolem.java | 4598 | /*
* This file is part of MyPet
*
* Copyright © 2011-2019 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyPet is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Keyle.MyPet.compat.v1_9_R2.entity.types;
import de.Keyle.MyPet.api.Configuration;
import de.Keyle.MyPet.api.entity.EntitySize;
import de.Keyle.MyPet.api.entity.MyPet;
import de.Keyle.MyPet.api.entity.types.MyIronGolem;
import de.Keyle.MyPet.compat.v1_9_R2.entity.EntityMyPet;
import net.minecraft.server.v1_9_R2.*;
import org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack;
@EntitySize(width = 1.4F, height = 2.7F)
public class EntityMyIronGolem extends EntityMyPet {
protected static final DataWatcherObject<Byte> UNUSED_WATCHER = DataWatcher.a(EntityMyIronGolem.class, DataWatcherRegistry.a);
int flowerCounter = 0;
boolean flower = false;
public EntityMyIronGolem(World world, MyPet myPet) {
super(world, myPet);
}
public boolean attack(Entity entity) {
boolean flag = false;
try {
this.world.broadcastEntityEffect(this, (byte) 4);
flag = super.attack(entity);
if (Configuration.MyPet.IronGolem.CAN_TOSS_UP && flag) {
entity.motY += 0.4000000059604645D;
this.makeSound("entity.irongolem.attack", 1.0F, 1.0F);
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
@Override
protected String getDeathSound() {
return "entity.irongolem.death";
}
@Override
protected String getHurtSound() {
return "entity.irongolem.hurt";
}
protected String getLivingSound() {
return null;
}
protected void initDatawatcher() {
super.initDatawatcher();
this.datawatcher.register(UNUSED_WATCHER, (byte) 0); // N/A
}
public boolean handlePlayerInteraction(EntityHuman entityhuman, EnumHand enumhand, ItemStack itemStack) {
if (super.handlePlayerInteraction(entityhuman, enumhand, itemStack)) {
return true;
}
if (getOwner().equals(entityhuman) && itemStack != null && canUseItem()) {
if (itemStack.getItem() == Item.getItemOf(Blocks.RED_FLOWER) && !getMyPet().hasFlower() && getOwner().getPlayer().isSneaking()) {
getMyPet().setFlower(CraftItemStack.asBukkitCopy(itemStack));
if (!entityhuman.abilities.canInstantlyBuild) {
if (--itemStack.count <= 0) {
entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null);
}
}
return true;
} else if (itemStack.getItem() == Items.SHEARS && getMyPet().hasFlower() && getOwner().getPlayer().isSneaking()) {
EntityItem entityitem = new EntityItem(this.world, this.locX, this.locY + 1, this.locZ, CraftItemStack.asNMSCopy(getMyPet().getFlower()));
entityitem.pickupDelay = 10;
entityitem.motY += (double) (this.random.nextFloat() * 0.05F);
this.world.addEntity(entityitem);
makeSound("entity.sheep.shear", 1.0F, 1.0F);
getMyPet().setFlower(null);
if (!entityhuman.abilities.canInstantlyBuild) {
itemStack.damage(1, entityhuman);
}
return true;
}
}
return false;
}
@Override
public void updateVisuals() {
flower = getMyPet().hasFlower();
flowerCounter = 0;
}
public MyIronGolem getMyPet() {
return (MyIronGolem) myPet;
}
@Override
public void playPetStepSound() {
makeSound("entity.irongolem.step", 1.0F, 1.0F);
}
public void onLivingUpdate() {
super.onLivingUpdate();
if (this.flower && this.flowerCounter-- <= 0) {
this.world.broadcastEntityEffect(this, (byte) 11);
flowerCounter = 300;
}
}
} | lgpl-3.0 |
Godin/sonar | server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/ScoreMatrixDumperImpl.java | 2182 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.ce.task.CeTask;
import static java.nio.charset.StandardCharsets.UTF_8;
public class ScoreMatrixDumperImpl implements ScoreMatrixDumper {
private static final Logger LOG = Loggers.get(ScoreMatrixDumperImpl.class);
private final Configuration configuration;
private final CeTask ceTask;
public ScoreMatrixDumperImpl(Configuration configuration, CeTask ceTask) {
this.configuration = configuration;
this.ceTask = ceTask;
}
@Override
public void dumpAsCsv(ScoreMatrix scoreMatrix) {
if (configuration.getBoolean("sonar.filemove.dumpCsv").orElse(false)) {
try {
Path tempFile = Files.createTempFile(String.format("score-matrix-%s", ceTask.getUuid()), ".csv");
try (BufferedWriter writer = Files.newBufferedWriter(tempFile, UTF_8)) {
writer.write(scoreMatrix.toCsv(';'));
}
LOG.info("File move similarity score matrix dumped as CSV: {}", tempFile);
} catch (IOException e) {
LOG.error("Failed to dump ScoreMatrix as CSV", e);
}
}
}
}
| lgpl-3.0 |
nikolamilosevic86/Marvin | src/SKOS/SKOSThesaurus.java | 1031 | package SKOS;
public class SKOSThesaurus {
private String filePath;
private String VocabularyName;
private String version;
private boolean used;
public SKOS Thesaurus;
/**
* @return the filePath
*/
public String getFilePath() {
return filePath;
}
/**
* @param filePath the filePath to set
*/
public void setFilePath(String filePath) {
this.filePath = filePath;
}
/**
* @return the version
*/
public String getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(String version) {
this.version = version;
}
/**
* @return the use
*/
public boolean isUsed() {
return used;
}
/**
* @param use the use to set
*/
public void setIsUsed(boolean use) {
this.used = use;
}
/**
* @return the vocabularyName
*/
public String getVocabularyName() {
return VocabularyName;
}
/**
* @param vocabularyName the vocabularyName to set
*/
public void setVocabularyName(String vocabularyName) {
VocabularyName = vocabularyName;
}
}
| lgpl-3.0 |
harshpoddar21/route_suggest_algo | jsprit-core/src/main/java/com/graphhopper/jsprit/core/algorithm/ruin/ReferencedJob.java | 479 | package com.graphhopper.jsprit.core.algorithm.ruin;
import com.graphhopper.jsprit.core.problem.job.Job;
/**
* Created by schroeder on 07/01/15.
*/
class ReferencedJob {
private Job job;
private double distance;
public ReferencedJob(Job job, double distance) {
super();
this.job = job;
this.distance = distance;
}
public Job getJob() {
return job;
}
public double getDistance() {
return distance;
}
}
| lgpl-3.0 |
SonarSource/sonar-javascript | javascript-checks/src/main/java/org/sonar/javascript/checks/ParenthesesCheck.java | 1416 | /*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.javascript.checks;
import org.sonar.check.Rule;
import org.sonar.plugins.javascript.api.EslintBasedCheck;
import org.sonar.plugins.javascript.api.JavaScriptRule;
import org.sonar.plugins.javascript.api.TypeScriptRule;
import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey;
@TypeScriptRule
@JavaScriptRule
@DeprecatedRuleKey(ruleKey = "Parentheses")
@Rule(key = "S1110")
public class ParenthesesCheck implements EslintBasedCheck {
@Override
public String eslintKey() {
return "no-redundant-parentheses";
}
}
| lgpl-3.0 |
Spoutcraft/SpoutcraftPlugin | src/main/java/org/getspout/spoutapi/event/inventory/InventoryPlayerClickEvent.java | 1765 | /*
* This file is part of SpoutcraftPlugin.
*
* Copyright (c) 2011 SpoutcraftDev <http://spoutcraft.org//>
* SpoutcraftPlugin is licensed under the GNU Lesser General Public License.
*
* SpoutcraftPlugin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SpoutcraftPlugin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.getspout.spoutapi.event.inventory;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
@Deprecated
public class InventoryPlayerClickEvent extends InventoryClickEvent {
private static final HandlerList handlers = new HandlerList();
public InventoryPlayerClickEvent(Player player, Inventory inventory, InventorySlotType type, ItemStack item, ItemStack cursor, int slot, boolean leftClick, boolean shift, Location location) {
super("InventoryPlayerClickEvent", player, inventory, type, item, cursor, slot, leftClick, shift, location);
}
@Override
protected int convertSlot(int slot) { // Why?
return slot;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
| lgpl-3.0 |
jasoncn90/dlna-for-android | dlna/src/com/jcn/dlna/sdk/WifiReceiver.java | 2045 | package com.jcn.dlna.sdk;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.jcn.dlna.sdk.dms.httpserver.HttpServer;
/**
* ÓÃÓÚ´¦ÀíwifiÁ¬½Ó±ä¸üµÄʼþ
*/
public class WifiReceiver {
private MyWifiReceiver receiver = null;
private boolean isConnected = false;
private WifiReceiver() {
}
private static WifiReceiver instance;
public static WifiReceiver getInstance() {
if (instance == null) {
instance = new WifiReceiver();
}
return instance;
}
public void register(Context context) {
isConnected = checkWifiIsConnected(context);
if (receiver == null) {
receiver = new MyWifiReceiver();
context.registerReceiver(receiver, new IntentFilter(
"android.net.conn.CONNECTIVITY_CHANGE"));
}
}
public void unregister(Context context) {
if (receiver != null) {
context.unregisterReceiver(receiver);
receiver = null;
}
}
public boolean isConnected() {
return isConnected;
}
private class MyWifiReceiver extends BroadcastReceiver {
@Override
synchronized public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(
ConnectivityManager.CONNECTIVITY_ACTION))
return;
if (HttpServer.getInstance() == null)
return;
if (!checkWifiIsConnected(context)) {
isConnected = false;
HttpServer.getInstance().stopServer();
} else {
isConnected = true;
HttpServer.getInstance().startServer();
}
}
}
private boolean checkWifiIsConnected(Context context) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!wifiInfo.isConnected()) {
return false;
} else {
return true;
}
}
}
| lgpl-3.0 |
kaetter/motolog | app/src/main/java/utils/FuellyScraper.java | 3045 | package utils;
import java.util.Calendar;
import java.util.Map;
import java.util.Set;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class FuellyScraper {
Context context;
SharedPreferences sharedPrefs;
Map<String, ?> allPrefs;
Set<String> allKeys;
String year, month, day;
int odometer;
double fuelAmount, cashPerLitre;
public FuellyScraper(Context context) {
this.context = context;
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
public void scrapeAndSubmit() {
allPrefs = sharedPrefs.getAll();
allKeys = allPrefs.keySet();
String[] allKeysString = allKeys.toArray(new String[0]);
for (String key : allKeysString) {
if (key.startsWith("Fuelly")) {
submitPost(key, sharedPrefs.getString(key, ""));
}
}
}
private void submitPost(String key, String data) {
year = key.split("\\|")[1];
month = key.split("\\|")[2];
day = key.split("\\|")[3];
odometer = Integer.parseInt(data.split("\\|")[0]);
fuelAmount = Double.parseDouble(data.split("\\|")[1]);
cashPerLitre = Double.parseDouble(data.split("\\|")[2]);
String username = sharedPrefs.getString("email", "");
String pass = sharedPrefs.getString("pwd", "");
/* if (!username.equals("") && !pass.equals("")) {
SendPostReqAsyncTask sendPostReqAsyndTask = new SendPostReqAsyncTask();
sendPostReqAsyndTask.execute(username, pass);
}*/
sharedPrefs.edit().remove(key).commit();
}
public void setFuellySharedPrefs(int odometer, double fuel,
double cashPerLitre, int year, int month, int day ) {
if (cashPerLitre > 15) {
cashPerLitre = 0;
}
Calendar cal = Calendar.getInstance();
StringBuilder sharedPrefsKey = new StringBuilder();
sharedPrefsKey.append("Fuelly").append("|")
.append(year).append("|")
.append(month).append("|")
.append(day).append("|")
.append(cal.get(Calendar.HOUR))
.append(cal.get(Calendar.MINUTE))
.append(cal.get(Calendar.SECOND));
StringBuilder sharedPrefsEntry = new StringBuilder();
sharedPrefsEntry.append(Integer.toString(odometer)).append("|")
.append(Double.toString(fuel)).append("|")
.append(Double.toString(cashPerLitre));
System.out.println(sharedPrefsKey.toString());
System.out.println(sharedPrefsEntry.toString());
sharedPrefs.edit().putString(sharedPrefsKey.toString(),
sharedPrefsEntry.toString()).commit();
System.out.println("The returned key" + sharedPrefs.getString(sharedPrefsKey.toString(), ""));
}
/*class SendPostReqAsyncTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
*//*if (FuellyPost.postEntry(context, params, odometer, fuelAmount,
cashPerLitre, year, month, day))
return "Fuelly submit Succesfull!";
else {
return "Fuelly submit UNSuccesfull!";
}*//*
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
*/
}
| lgpl-3.0 |
pith/kernel | core/src/test/java/io/nuun/kernel/core/pluginsit/dummy1/InterfaceWithCustom2Suffix.java | 950 | /**
* This file is part of Nuun IO Kernel Core.
*
* Nuun IO Kernel Core is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Nuun IO Kernel Core is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Nuun IO Kernel Core. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package io.nuun.kernel.core.pluginsit.dummy1;
import javax.annotation.Nullable;
@Nullable
public interface InterfaceWithCustom2Suffix
{
public String name();
}
| lgpl-3.0 |
Glydar/Glydar.next | glydar-core/src/main/java/org/glydar/core/plugin/CorePluginManager.java | 3497 | package org.glydar.core.plugin;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.ServiceLoader;
import java.util.logging.Level;
import org.glydar.api.Backend;
import org.glydar.api.logging.GlydarLogger;
import org.glydar.api.plugin.Plugin;
import org.glydar.api.plugin.PluginDescriptor;
import org.glydar.api.plugin.PluginManager;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class CorePluginManager implements PluginManager {
private static final String LOGGER_PREFIX = "Plugin Manager";
private final GlydarLogger logger;
private final Path folder;
private final List<PluginLoader> pluginLoaders;
private List<Plugin> plugins;
public CorePluginManager(Backend backend) {
this.logger = backend.getLogger(getClass(), LOGGER_PREFIX);
this.folder = backend.getPluginsFolder();
ServiceLoader<PluginLoader> pluginLoadersLoader = ServiceLoader.load(PluginLoader.class);
pluginLoaders = Lists.newArrayList(pluginLoadersLoader);
}
@Override
public void load() {
logger.info("Loading plugins using loaders :");
for (PluginLoader pluginLoader : pluginLoaders) {
logger.info(" - " + pluginLoader.getClass().getName());
}
if (!folder.toFile().exists()) {
logger.log(Level.INFO, "Unable to access `plugins` directory, creating the directory");
folder.toFile().mkdir();
}
DirectoryStream<Path> pluginPaths;
try {
pluginPaths = Files.newDirectoryStream(folder);
}
catch (IOException exc) {
logger.log(Level.SEVERE, "Unable to access `plugins` directory", exc);
return;
}
ImmutableList.Builder<Plugin> pluginsBuilder = ImmutableList.builder();
for (Path path : pluginPaths) {
if (path.getFileName().toString().startsWith(".")) {
continue;
}
try {
Plugin plugin = loadPlugin(path);
if (plugin == null) {
logger.warning("Unable to find suitable plugin loader for file " + path.getFileName());
}
else {
pluginsBuilder.add(plugin);
logger.info("Plugin " + pluginName(plugin) + " loaded.");
}
}
catch (PluginLoaderException exc) {
logger.log(Level.SEVERE, "Error while loading for file " + path.getFileName(), exc);
}
}
this.plugins = pluginsBuilder.build();
logger.info(plugins.size() + " plugins loaded");
}
private Plugin loadPlugin(Path path) {
for (PluginLoader pluginLoader : pluginLoaders) {
Plugin plugin = pluginLoader.load(path);
if (plugin != null) {
return plugin;
}
}
return null;
}
private String pluginName(Plugin plugin) {
PluginDescriptor descriptor = plugin.getDescriptor();
return descriptor.getName() + " v" + descriptor.getVersion();
}
@Override
public void enableAll() {
for (Plugin plugin : plugins) {
plugin.enable();
}
}
@Override
public void disableAll() {
for (Plugin plugin : plugins) {
plugin.disable();
}
}
}
| lgpl-3.0 |
solmix/hola | cluster/src/main/java/org/solmix/hola/cluster/loadbalance/RoundRobinLoadBalance.java | 2880 | package org.solmix.hola.cluster.loadbalance;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.solmix.hola.common.model.PropertiesUtils;
import org.solmix.hola.common.util.AtomicPositiveInteger;
import org.solmix.hola.rs.RemoteService;
import org.solmix.hola.rs.call.RemoteRequest;
import org.solmix.runtime.Extension;
@Extension( RoundRobinLoadBalance.NAME)
public class RoundRobinLoadBalance extends AbstractLoadBalance
{
public static final String NAME = "roundrobin";
private final ConcurrentMap<String, AtomicPositiveInteger> sequences = new ConcurrentHashMap<String, AtomicPositiveInteger>();
private final ConcurrentMap<String, AtomicPositiveInteger> weightSequences = new ConcurrentHashMap<String, AtomicPositiveInteger>();
@Override
protected <T> RemoteService<T> doSelect(List<RemoteService<T>> services, RemoteRequest request) {
String key =PropertiesUtils.getServiceKey(services.get(0).getServiceProperties()) + "." + request.getMethodName();
int length = services.size(); // 总个数
int maxWeight = 0; // 最大权重
int minWeight = Integer.MAX_VALUE; // 最小权重
for (int i = 0; i < length; i++) {
int weight = getWeight(services.get(i), request);
maxWeight = Math.max(maxWeight, weight); // 累计最大权重
minWeight = Math.min(minWeight, weight); // 累计最小权重
}
if (maxWeight > 0 && minWeight < maxWeight) { // 权重不一样
AtomicPositiveInteger weightSequence = weightSequences.get(key);
if (weightSequence == null) {
weightSequences.putIfAbsent(key, new AtomicPositiveInteger());
weightSequence = weightSequences.get(key);
}
int currentWeight = weightSequence.getAndIncrement() % maxWeight;
List<RemoteService<T>> weightInvokers = new ArrayList<RemoteService<T>>();
for (RemoteService<T> invoker : services) { // 筛选权重大于当前权重基数的Invoker
if (getWeight(invoker, request) > currentWeight) {
weightInvokers.add(invoker);
}
}
int weightLength = weightInvokers.size();
if (weightLength == 1) {
return weightInvokers.get(0);
} else if (weightLength > 1) {
services = weightInvokers;
length = services.size();
}
}
AtomicPositiveInteger sequence = sequences.get(key);
if (sequence == null) {
sequences.putIfAbsent(key, new AtomicPositiveInteger());
sequence = sequences.get(key);
}
// 取模轮循
return services.get(sequence.getAndIncrement() % length);
}
}
| lgpl-3.0 |
DivineCooperation/jul | schedule/src/main/java/org/openbase/jul/schedule/CloseableWriteLockWrapper.java | 1471 | package org.openbase.jul.schedule;
/*
* #%L
* JUL Schedule
* %%
* Copyright (C) 2015 - 2021 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
/**
* Can be used to make the @{Closeable} interface available to any @{ReadWriteLock} instance.
*
* @author <a href="mailto:divine@openbase.org">Divine Threepwood</a>
*/
public class CloseableWriteLockWrapper implements java.lang.AutoCloseable {
protected final ReadWriteLock lock;
public CloseableWriteLockWrapper(final ReadWriteLock lock) {
this(lock, true);
}
public CloseableWriteLockWrapper(final ReadWriteLock lock, final boolean allocate) {
this.lock = lock;
if (allocate) {
this.lock.lockWrite();
}
}
@Override
public void close() {
lock.unlockWrite();
}
}
| lgpl-3.0 |
mgarber/scriptureV2 | src/java/nextgen/core/berkeleydb/DatabaseStore.java | 1675 | package nextgen.core.berkeleydb;
import org.apache.log4j.Logger;
import com.sleepycat.je.Environment;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.evolve.Mutations;
/*
* http://docs.oracle.com/cd/E17277_02/html/GettingStartedGuide/persist_first.html
*/
/**
* A database store
* @author prussell
*
*/
public class DatabaseStore {
private EntityStore store;
@SuppressWarnings("unused")
private static Logger logger = Logger.getLogger(DatabaseStore.class.getName());
public DatabaseStore() {}
/**
* Set up the store
* @param env Database environment
* @param storeName Entity store name
* @param readOnly Whether the store should be read only
*/
public void setup(Environment env, String storeName, boolean readOnly) {
setup(env, storeName, null, readOnly);
}
/**
* Set up the store
* @param env Database environment
* @param storeName Entity store name
* @param Mutations Collection of mutations for configuring class evolution
* @param readOnly Whether the store should be read only
*/
public void setup(Environment env, String storeName, Mutations mutations, boolean readOnly) {
StoreConfig storeConfig = new StoreConfig();
storeConfig.setReadOnly(readOnly);
storeConfig.setAllowCreate(!readOnly);
if(mutations != null) {
storeConfig.setMutations(mutations);
}
store = new EntityStore(env, storeName, storeConfig);
}
/**
* Get the underlying EntityStore object
* @return
*/
public EntityStore getStore() {
return store;
}
/**
* Close the store
*/
public void close() {
if(store != null) {
store.close();
}
}
}
| lgpl-3.0 |
smallbirdking/Serveur_entreprise_EJB_projet | j2e/src/main/java/fr/unice/polytech/se/demo/domain/impl/IngredientFinderBean.java | 2780 | package fr.unice.polytech.se.demo.domain.impl;
import fr.unice.polytech.se.demo.domain.IngredientFinder;
import fr.unice.polytech.se.demo.entities.Ingredient;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;
/**
* Created by user on 31/03/15.
*/
@Stateless
public class IngredientFinderBean implements IngredientFinder {
@PersistenceContext
EntityManager entityManager;
@Override
public Ingredient findByName(String name) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Ingredient> criteria = builder.createQuery(Ingredient.class);
Root<Ingredient> from = criteria.from(Ingredient.class);
criteria.select(from);
criteria.where(builder.equal(from.get("name_Ingredient"), name));
TypedQuery<Ingredient> query = entityManager.createQuery(criteria);
try {
return query.getSingleResult();
} catch (Exception e) {
return null;
}
}
@Override
public Ingredient findByPrix(double n) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Ingredient> criteria = builder.createQuery(Ingredient.class);
Root<Ingredient> from = criteria.from(Ingredient.class);
criteria.select(from);
criteria.where(builder.equal(from.get("prix_Ingredient"), n));
TypedQuery<Ingredient> query = entityManager.createQuery(criteria);
try {
return query.getSingleResult();
} catch (Exception e) {
return null;
}
}
@Override
public Ingredient findById(long id) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Ingredient> criteria = builder.createQuery(Ingredient.class);
Root<Ingredient> from = criteria.from(Ingredient.class);
criteria.select(from);
criteria.where(builder.equal(from.get("id_Ingredient"), id));
TypedQuery<Ingredient> query = entityManager.createQuery(criteria);
try {
return query.getSingleResult();
} catch (Exception e) {
return null;
}
}
@Override
public List<Ingredient> findAll() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Ingredient> cq = cb.createQuery(Ingredient.class);
TypedQuery<Ingredient> allQuery = entityManager.createQuery(cq.select(cq
.from(Ingredient.class)));
return allQuery.getResultList();
}
}
| lgpl-3.0 |
PearXTeam/PearXLibMC | src/main/java/ru/pearx/libmc/common/structure/BlockUtils.java | 2195 | package ru.pearx.libmc.common.structure;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import java.util.Map;
/*
* Created by mrAppleXZ on 20.11.17 17:51.
*/
public class BlockUtils
{
public static NBTTagCompound serializeBlock(IBlockState state, BlockPos relativePos, TileEntity te)
{
NBTTagCompound block = new NBTTagCompound();
block.setInteger("x", relativePos.getX());
block.setInteger("y", relativePos.getY());
block.setInteger("z", relativePos.getZ());
block.setString("id", state.getBlock().getRegistryName().toString());
block.setInteger("meta", state.getBlock().getMetaFromState(state));
if (te != null)
{
NBTTagCompound tiletag = te.serializeNBT();
tiletag.removeTag("x");
tiletag.removeTag("y");
tiletag.removeTag("z");
block.setTag("tile", tiletag);
}
return block;
}
public static BlockPair deserializeBlock(NBTTagCompound tag, BlockPos absPos, Map<String, Block> blockCache, World w)
{
String id = tag.getString("id");
Block b;
if(blockCache != null)
{
if (!blockCache.containsKey(id))
blockCache.put(id, ForgeRegistries.BLOCKS.getValue(new ResourceLocation(id)));
b = blockCache.get(id);
}
else
b = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(id));
IBlockState state = b.getStateFromMeta(tag.getInteger("meta"));
if (tag.hasKey("tile"))
{
NBTTagCompound tile = tag.getCompoundTag("tile");
tile.setInteger("x", absPos.getX());
tile.setInteger("y", absPos.getY());
tile.setInteger("z", absPos.getZ());
return new BlockPair(state, TileEntity.create(w, tile));
}
return new BlockPair(state, null);
}
}
| lgpl-3.0 |
costing/lazyj | src/main/java/lazyj/page/tags/Dash.java | 1407 | /**
*
*/
package lazyj.page.tags;
import lazyj.page.StringFormat;
/**
* <i>dash</i> replaces all non-alphanumeric sequences of characters each with a single dash.
*
* @author costing
* @since 2006-10-13
* @see Under
*/
public final class Dash implements StringFormat {
/**
* Dashify a string (leave all the letters and digits, everything else is colapsed into '-')
*
* @param sTag ignored
* @param sOption always "dash"
* @param sValue original string
* @return dashified version of the original string
*/
@Override
public String format(final String sTag, final String sOption, final String sValue) {
return format(sValue);
}
/**
* Publicly available method to transform a string into a dashed representation of it, good to be
* used in rewritten URLs.
*
* @param sValue string to format
* @return dashified version of the string
*/
public static final String format(final String sValue){
if (sValue==null || sValue.length()==0)
return sValue;
final StringBuilder sb2 = new StringBuilder(sValue.length());
char cOld = '-';
for (int k = 0; k < sValue.length(); k++) {
char c = sValue.charAt(k);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
sb2.append(c);
cOld = c;
} else {
if (cOld != '-') {
sb2.append('-');
cOld = '-';
}
}
}
return sb2.toString();
}
}
| lgpl-3.0 |
Albertus82/JFaceUtils | src/test/java/io/github/albertus82/jface/JFaceMessagesTest.java | 1042 | package io.github.albertus82.jface;
import java.util.Locale;
import org.junit.Assert;
import org.junit.Test;
public class JFaceMessagesTest {
@Test
public void test1() {
JFaceMessages.setLanguage(Locale.ENGLISH.getLanguage());
Assert.assertEquals("OK", JFaceMessages.get("lbl.button.ok").toUpperCase());
}
@Test
public void test2() {
JFaceMessages.setLanguage(Locale.ENGLISH.getLanguage());
Assert.assertEquals(JFaceMessages.get("lbl.button.ok", "a", "b", 3, 4), JFaceMessages.get("lbl.button.ok"));
}
@Test
public void test3() {
JFaceMessages.setLanguage(Locale.ITALIAN.getLanguage());
Assert.assertEquals(JFaceMessages.get("lbl.preferences.header.restart", "a", "b", 3, 4), JFaceMessages.get("lbl.preferences.header.restart"));
}
@Test
public void test4() {
JFaceMessages.setLanguage(Locale.ITALIAN.getLanguage());
Assert.assertEquals(JFaceMessages.get("lbl.preferences.logging.overridden", "a", "b", 3, 4), JFaceMessages.get("lbl.preferences.logging.overridden"));
}
}
| lgpl-3.0 |
Xyene/JBL | src/test/java/benchmark/bcel/generic/DCMPG.java | 1756 | /*
* Copyright 2000-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package benchmark.bcel.generic;
/**
* DCMPG - Compare doubles: value1 > value2
* <PRE>Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 -></PRE>
* ..., result
*
* @version $Id: DCMPG.java 386056 2006-03-15 11:31:56Z tcurdt $
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
*/
public class DCMPG extends Instruction implements TypedInstruction, StackProducer, StackConsumer {
public DCMPG() {
super(benchmark.bcel.Constants.DCMPG, (short) 1);
}
/** @return Type.DOUBLE
*/
public Type getType( ConstantPoolGen cp ) {
return Type.DOUBLE;
}
/**
* Call corresponding visitor method(s). The order is:
* Call visitor methods of implemented interfaces first, then
* call methods according to the class hierarchy in descending order,
* i.e., the most specific visitXXX() call comes last.
*
* @param v Visitor object
*/
public void accept( Visitor v ) {
v.visitTypedInstruction(this);
v.visitStackProducer(this);
v.visitStackConsumer(this);
v.visitDCMPG(this);
}
}
| lgpl-3.0 |
impetus-opensource/jumbune | debugger/src/main/java/org/jumbune/debugger/log/processing/LPConstants.java | 5737 | package org.jumbune.debugger.log.processing;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jumbune.debugger.instrumentation.utils.InstrumentationMessageLoader;
import org.jumbune.debugger.instrumentation.utils.MessageConstants;
/**
* This is the interface for storing Constants.
*
*/
@SuppressWarnings("serial")
public interface LPConstants {
int SEVEN = 7;
int SIX = 6;
int FIVE = 5;
int FOUR = 4;
int THREE = 3;
int TWO = 2;
int ONE = 1;
String DEBUGGER_SUMMARY="debuggerSummary";
float SAMPLING_FRACTION=0.1f;
char DOT = '.';
char HASH = '#';
int MAPPER_REDUCER_INDEX = 1;
int METHOD_INDEX = 2;
int JOB_INDEX = 3;
int INSTANCE_INDEX = 4;
int MESSAGE_INDEX = 5;
int KEY_TYPE_INDEX = 6;
int KEY_VALUE_INDEX = 7;
String UNDERSCORE = "_";
String PIPE_SEPARATOR = "\\|";
String FILE_SEPARATOR = "/";
String COMMA = ",";
String EMPTY_STRING = "";
String LOG = "log";
String ENTERED_MAP_MESSAGE = MessageFormat.format(InstrumentationMessageLoader.getMessage(MessageConstants.ENTERED_MAPREDUCE), "map");
String EXITING_MAP_MESSAGE = MessageFormat.format(InstrumentationMessageLoader.getMessage(MessageConstants.EXITING_MAPREDUCE), "map");
String ENTERING_IF_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.MSG_BEFORE_IF);
String EXITED_IF_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.MSG_AFTER_IF);
String INSIDE_IF_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.MSG_IN_IF);
String ENTERED_REDUCE_MESSAGE = MessageFormat.format(InstrumentationMessageLoader.getMessage(MessageConstants.ENTERED_MAPREDUCE), "reduce");
String EXITING_REDUCE_MESSAGE = MessageFormat.format(InstrumentationMessageLoader.getMessage(MessageConstants.EXITING_MAPREDUCE), "reduce");
String MATCHING_REGEX_MESSAGE = "Matching against regular expression";
String VALIDATING_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.VALIDATION_KEY_VALUE);
String MAP_METHOD = "map";
String REDUCE_METHOD = "reduce";
String KEY = "K";
String FALSE = "false";
String NOT_AVAILABLE = "NOT AVAILABLE";
String LOG_FORMAT_EXCEPTION = "Error Parsing Log File";
String UNAVAILABLE = "Not Available";
String MAP_REDUCE_LOG_FILE = "mapreduce";
String INSIDE_ELSE_IF_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.MSG_IN_ELSEIF);
String INSIDE_ELSE_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.MSG_IN_ELSE);
String LOOP_EXECUTED_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.LOOP_EXECUTION);
String SETUP_METHOD = "setup";
String CLEANUP_METHOD = "cleanup";
String IF = "If#";
String ELSE_IF = "Else-if#";
String ELSE = "Else";
String SWITCH = "Switch#";
String SWITCH_CASE = "Case#";
String CONTEXT_WRITE = "ctxWrt";
String ENTERING_SWITCH_BLOCK_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.MSG_BEFORE_SWITCH);
String EXITED_SWITCH_BLOCK_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.MSG_AFTER_SWITCH);
String ENTERED_SWITCH_CASE_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.MSG_IN_SWITCHCASE);
String EXITING_SWITCH_CASE_MESSAGE = InstrumentationMessageLoader.getMessage(MessageConstants.MSG_OUT_SWITCHCASE);
String INFO_MESSAGE = "INFO";
String METHOD_ENTRY = InstrumentationMessageLoader.getMessage(MessageConstants.ENTERED_METHOD);
String METHOD_EXIT = InstrumentationMessageLoader.getMessage(MessageConstants.EXITING_METHOD);
String RETURN = "return";
String METHOD = "method";
String MR_CHAIN = "mrChain";
String JOB_CHAIN = "jobChain";
String JOB_ATTRIBUTE = "job_";
String DEBUG_ANALYSIS = "debugAnalysis";
String IF_BLOCK = "IfBlock#";
String LOOP_ENTRY = InstrumentationMessageLoader.getMessage(MessageConstants.ENTERED_LOOP);
String LOOP_EXIT = InstrumentationMessageLoader.getMessage(MessageConstants.EXITING_LOOP);
String LOOP = "Loop#";
String PARTITIONER_ENTRY = "PI";
String REDUCER_IDENTIFIER = "r";
/**
* METHODS_CHECK_LIST - the list containing the methods to be processed when current counter is not available
*/
List<String> METHODS_CHECK_LIST = new ArrayList<String>() {
{
add(ENTERED_MAP_MESSAGE);
add(ENTERED_REDUCE_MESSAGE);
add(PARTITIONER_ENTRY);
add(INFO_MESSAGE);
}
};
/**
* ENTERING_COUNTER_MESSAGES_MAP - the map containing the messages indicating the entry of various expression counters
*/
Map<String, Integer> ENTERING_COUNTER_MESSAGES_MAP = new HashMap<String, Integer>() {
{
put(ENTERING_IF_MESSAGE, ONE);
put(ENTERING_SWITCH_BLOCK_MESSAGE, TWO);
put(ENTERED_SWITCH_CASE_MESSAGE, THREE);
put(LOOP_ENTRY, FOUR);
put(INSIDE_IF_MESSAGE, FIVE);
put(INSIDE_ELSE_IF_MESSAGE, SIX);
put(INSIDE_ELSE_MESSAGE, SEVEN);
}
};
/**
* EXITING_COUNTER_MESSAGES_MAP - the map containing the messages indicating the exit of various expression counters
*/
Map<String, Integer> EXITING_COUNTER_MESSAGES_MAP = new HashMap<String, Integer>() {
{
put(EXITING_MAP_MESSAGE, ONE);
put(EXITING_REDUCE_MESSAGE, ONE);
put(METHOD_EXIT, TWO);
put(EXITED_IF_MESSAGE, THREE);
put(EXITED_SWITCH_BLOCK_MESSAGE, FOUR);
put(EXITING_SWITCH_CASE_MESSAGE, FOUR);
put(LOOP_EXIT,FOUR);
}
};
/**
* EXITING_COUNTER_MESSAGES_MAP - the map containing the messages indicating the exit of various expression counters
*/
Map<String, Integer> OTHER_COUNTER_MESSAGES_MAP = new HashMap<String, Integer>() {
{
put(ENTERED_MAP_MESSAGE, ONE);
put(ENTERED_REDUCE_MESSAGE, ONE);
put(CONTEXT_WRITE, TWO);
put(MATCHING_REGEX_MESSAGE, THREE);
put(VALIDATING_MESSAGE,THREE);
put(METHOD_ENTRY, FOUR);
}
};
} | lgpl-3.0 |
ACEMerlin/Kratos | kratos/src/main/java/kratos/card/utils/JsonVerify.java | 629 | package kratos.card.utils;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
/**
* To verify whether a json is legal
* Created by Wayne on 15/12/25.
*/
public class JsonVerify {
public static boolean isIllegalJson(String json) {
return !isLegalJson(json);
}
public static boolean isLegalJson(String json) {
if ((json).isEmpty()) {
return false;
}
try {
new JsonParser().parse(json);
return true;
} catch (JsonParseException e) {
e.printStackTrace();
return false;
}
}
}
| lgpl-3.0 |
1024122298/bergamot | bergamot-queue/src/main/java/com/intrbiz/bergamot/queue/UpdateQueue.java | 1300 | package com.intrbiz.bergamot.queue;
import java.util.Set;
import java.util.UUID;
import com.intrbiz.bergamot.model.message.update.Update;
import com.intrbiz.bergamot.queue.impl.RabbitUpdateQueue;
import com.intrbiz.bergamot.queue.key.UpdateKey;
import com.intrbiz.queue.Consumer;
import com.intrbiz.queue.DeliveryHandler;
import com.intrbiz.queue.QueueAdapter;
import com.intrbiz.queue.QueueManager;
import com.intrbiz.queue.RoutedProducer;
/**
* Send update events
*/
public abstract class UpdateQueue extends QueueAdapter
{
static
{
RabbitUpdateQueue.register();
}
public static UpdateQueue open()
{
return QueueManager.getInstance().queueAdapter(UpdateQueue.class);
}
public abstract RoutedProducer<Update, UpdateKey> publishUpdates(UpdateKey defaultKey);
public RoutedProducer<Update, UpdateKey> publishUpdates()
{
return this.publishUpdates(null);
}
public abstract Consumer<Update, UpdateKey> consumeUpdates(DeliveryHandler<Update> handler, UUID site, UUID check);
public abstract Consumer<Update, UpdateKey> consumeUpdates(DeliveryHandler<Update> handler);
public abstract Consumer<Update, UpdateKey> consumeUpdates(DeliveryHandler<Update> handler, Set<UpdateKey> bindings);
}
| lgpl-3.0 |
leodmurillo/sonar | sonar-squid/src/main/java/org/sonar/squid/indexer/QueryByParent.java | 1207 | /*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.squid.indexer;
import org.sonar.squid.api.Query;
import org.sonar.squid.api.SourceCode;
public class QueryByParent implements Query {
private final SourceCode parent;
public QueryByParent(SourceCode parent) {
this.parent = parent;
}
public boolean match(SourceCode unit) {
return unit.hasAmongParents(parent);
}
}
| lgpl-3.0 |