repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
netarchivesuite/netarchivesuite-svngit-migration | src/dk/netarkivet/archive/arcrepository/bitpreservation/DatabaseBasedActiveBitPreservation.java | 31663 | /* File: $Id$
* Revision: $Revision$
* Author: $Author$
* Date: $Date$
*
* The Netarchive Suite - Software to harvest and preserve websites
* Copyright 2004-2012 The Royal Danish Library, the Danish State and
* University Library, the National Library of France and the Austrian
* National Library.
*
* 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 dk.netarkivet.archive.arcrepository.bitpreservation;
import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import dk.netarkivet.archive.arcrepositoryadmin.BitPreservationDAO;
import dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheDatabase;
import dk.netarkivet.archive.arcrepositoryadmin.ReplicaFileInfo;
import dk.netarkivet.common.distribute.arcrepository.ArcRepositoryClientFactory;
import dk.netarkivet.common.distribute.arcrepository.PreservationArcRepositoryClient;
import dk.netarkivet.common.distribute.arcrepository.Replica;
import dk.netarkivet.common.exceptions.ArgumentNotValid;
import dk.netarkivet.common.exceptions.IOFailure;
import dk.netarkivet.common.exceptions.NotImplementedException;
import dk.netarkivet.common.utils.CleanupHook;
import dk.netarkivet.common.utils.CleanupIF;
import dk.netarkivet.common.utils.FileUtils;
/**
* The database based active bit preservation.
* This is the alternative to the FileBasedActiveBitPreservation.
*
* A database is used to handle the bitpreservation.
*/
public final class DatabaseBasedActiveBitPreservation implements
ActiveBitPreservation, CleanupIF {
/** The log.*/
private Log log
= LogFactory.getLog(DatabaseBasedActiveBitPreservation.class);
/**
* When replacing a broken file, the broken file is downloaded and stored in
* a temporary directory under Settings.COMMON_TEMP_DIR with this name.
* It can then be inspected at your leisure.
* TODO this is the same constant as in FileBasedActiveBitPreservation,
* thus change to global constant instead. Perhaps constant in parent class.
*/
private static final String REMOVED_FILES = "bitpreservation";
/** The current instance.*/
private static DatabaseBasedActiveBitPreservation instance;
/** Hook to close down this application.*/
private CleanupHook closeHook;
/** The instance to contain the access to the database.*/
private BitPreservationDAO cache;
/** The list of the replicas, which are having their filelist updated. */
private List<Replica> updateFilelistReplicas = Collections.synchronizedList(
new ArrayList<Replica>());
/** The list of the replicas, which are having their checksums updated. */
private List<Replica> updateChecksumReplicas = Collections.synchronizedList(
new ArrayList<Replica>());
/**
* Constructor.
* Initialises the database and closeHook.
*/
private DatabaseBasedActiveBitPreservation() {
// initialise the database.
cache = ReplicaCacheDatabase.getInstance();
// create and initialise the closing hook
closeHook = new CleanupHook(this);
Runtime.getRuntime().addShutdownHook(closeHook);
}
/**
* Method for retrieving the current instance of this class.
*
* @return The instance.
*/
public static synchronized DatabaseBasedActiveBitPreservation
getInstance() {
if (instance == null) {
instance = new DatabaseBasedActiveBitPreservation();
}
return instance;
}
/**
* Method for retrieving the filelist from a specific replica.
* A GetAllFilenamesMessage is sent to the specific replica.
*
* @param replica The replica to retrieve the filelist from.
* @return The names of the files in a File.
* @throws ArgumentNotValid If the replica is 'null'.
*/
private File getFilenamesAsFile(Replica replica) throws
ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// send request
log.info("Retrieving filelist from replica '" + replica + "'.");
// Retrieve a file containing the list of filenames of the replica.
File result = ArcRepositoryClientFactory.getPreservationInstance()
.getAllFilenames(replica.getId());
log.info("Retrieved filelist from replica '" + replica + "'.");
return result;
}
/**
* Method for retrieving the checksums from a specific replica.
* A GetAllChecksumsMessage is sent to the specific replica.
*
* @param replica The replica to retrieve the checksums from.
* @return A file containing the checksumjob results, i.e. a filename##checksum.
* @throws ArgumentNotValid If the replica is null.
*/
private File getChecksumListAsFile(Replica replica)
throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
log.info("Retrieving checksum from replica '" + replica + "'.");
// Request and retrieve a file containing the checksums of the replica,
// and return this
File outputFile = ArcRepositoryClientFactory.getPreservationInstance()
.getAllChecksums(replica.getId());
log.info("Retrieved checksum from replica '" + replica + "'.");
return outputFile;
}
/**
* Method to reestablish a file missing in a replica. The file is retrieved
* from a given bitarchive replica, which is known to contain a proper
* version of this file.
* The reestablishment is done by first retrieving the file and then
* sending out a store message with this file. Then any replica who is
* missing the file will obtain it.
*
* @param filename The name of the file to reestablish.
* @param repWithFile The replica where the file should be retrieved from.
* @throws IOFailure If the attempt to reestablish the file fails.
*/
private void reestablishMissingFile(String filename, Replica repWithFile)
throws IOFailure {
// send a GetFileMessage to this bitarchive replica for the file.
try {
// Contact the ArcRepository.
PreservationArcRepositoryClient arcrep = ArcRepositoryClientFactory
.getPreservationInstance();
// Create temporary file.
File tmpDir = FileUtils.createUniqueTempDir(FileUtils.getTempDir(),
REMOVED_FILES);
File missingFile = new File(tmpDir, filename);
// retrieve the file and send store message with it. Then the
// file will be stored in all replicas, where it is missing.
arcrep.getFile(filename, repWithFile, missingFile);
arcrep.store(missingFile);
// remove the temporary file afterwards.
tmpDir.delete();
// Update the checksum status for the file.
cache.updateChecksumStatus(filename);
} catch (Exception e) {
String errMsg = "Failed to reestablish '" + filename
+ "' with copy from '" + repWithFile + "'";
log.warn(errMsg);
// log error and report file.
throw new IOFailure(errMsg, e);
}
}
/**
* Method for retrieving a file from a bitarchive (for replacing a bad
* entry in another replica).
*
* @param filename The file to retrieve.
* @param repWithFile The replica where the file should be retrieved from.
* @return The file from the bitarchive.
*/
private File retrieveRemoteFile(String filename, Replica repWithFile) {
// Contact the ArcRepository.
PreservationArcRepositoryClient arcrep = ArcRepositoryClientFactory
.getPreservationInstance();
// Create temporary file.
File tmpDir = FileUtils.createUniqueTempDir(FileUtils.getTempDir(),
REMOVED_FILES);
File missingFile = new File(tmpDir, filename);
// retrieve the file and send store message with it. Then the
// file will be stored in all replicas, where it is missing.
arcrep.getFile(filename, repWithFile, missingFile);
return missingFile;
}
/**
* This method is used for making sure, that all replicas are up-to-date
* before trying to validate the checksums of the files within it.
*
* TODO set a time limit for last date to update. This has to be a variable
* in settings, which should have the default '0', meaning no time limit.
* If more time has passed than acceptable, then a new checksum job should
* be run. This has to do with assignment B.2.4 - Bitpreservation scheduler.
*/
private void initChecksumStatusUpdate() {
// go through all replicas.
for (Replica replica : Replica.getKnown()) {
// retrieve the date for the last checksum update.
Date csDate = cache.getDateOfLastWrongFilesUpdate(replica);
if (csDate == null) {
// run a checksum job on the replica.
log.info("Starting checksum update for replica " + replica);
runChecksum(replica);
log.info("Finished the checksum update for replica " + replica);
}
}
}
/**
* The method for retrieving the checksums for all the files within a
* replica.
* This method sends the checksum job to the replica archive.
*
* @param replica The replica to retrieve the checksums from.
*/
private void runChecksum(Replica replica) {
File checksumlistFile = null;
try {
checksumlistFile = getChecksumListAsFile(replica);
cache.addChecksumInformation(checksumlistFile, replica);
} finally {
if (checksumlistFile != null) {
FileUtils.remove(checksumlistFile);
}
}
}
/**
* Retrieves and update the status of a file for a specific replica.
*
* @param filename The name of the file.
*/
private void updateChecksumStatus(String filename) {
// retrieve the ArcRepositoryClient before using it in the for-loop.
PreservationArcRepositoryClient arcClient = ArcRepositoryClientFactory
.getPreservationInstance();
// retrieve the checksum status for the file for all the replicas
for(Replica replica : Replica.getKnown()) {
// retrieve the checksum.
String checksum = arcClient.getChecksum(replica.getId(),
filename);
// insert the checksum results for the file into the database.
cache.updateChecksumInformationForFileOnReplica(filename,
checksum, replica);
}
// Vote for the specific file.
cache.updateChecksumStatus(filename);
}
/**
* The method calculates the number of files which has a wrong checksum
* for the replica.
* This simple counts all the entries in the replicafileinfo table for the
* replica where the filelist_status is set to CORRUPT.
*
* @param replica The replica for which to count the number of changed
* files.
* @return The number of files for the replica where the checksum does not
* correspond to the checksum of the same file in the other replicas.
* @throws ArgumentNotValid If the replica is null.
*/
public long getNumberOfChangedFiles(Replica replica)
throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// Retrieves the number of entries in replicafileinfo which has
// filelist_status set to 'CORRUPT' and belong to the replica.
return cache.getNumberOfWrongFilesInLastUpdate(replica);
}
/**
* This method retrieves the name of all the files which has a wrong
* checksum for the replica.
* It simple returns the filename of all the entries in the
* replicafileinfo table for the replica where the filelist_status is
* set to CORRUPT.
*
* @param replica The replica for which the changed files should be found.
* @return The names of files in the replica where the checksum does not
* correspond to the checksum of the same file in the other replicas.
* @throws ArgumentNotValid If the replica is null.
*/
public Iterable<String> getChangedFiles(Replica replica)
throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// Retrieves the list of filenames for the entries in replicafileinfo
// which has filelist_status set to 'CORRUPT' and belong to the replica.
return cache.getWrongFilesInLastUpdate(replica);
}
/**
* This method calculates the number of files which are not found in the
* given replica.
* This simple counts all the entries in the replicafileinfo table for the
* replica where the filelist_status is set to MISSING.
*
* @param replica The replica for which to count the number of missing
* files.
* @return The number of files which is missing in the replica.
* @throws ArgumentNotValid If the replica is null.
*/
public long getNumberOfMissingFiles(Replica replica)
throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// Retrieves the number of entries in replicafileinfo which has
// filelist_status set to 'MISSING' and belong to the replica.
return cache.getNumberOfMissingFilesInLastUpdate(replica);
}
/**
* This method retrieves the name of all the files which are missing for
* the given replica.
* It simple returns the filename of all the entries in the
* replicafileinfo table for the replica where the filelist_status is
* set to MISSING.
*
* @param replica The replica for which the missing files should be found.
* @return The names of files in the replica which are missing.
* @throws ArgumentNotValid If the replica is null.
*/
public Iterable<String> getMissingFiles(Replica replica)
throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// Retrieves the list of filenames for the entries in replicafileinfo
// which has filelist_status set to 'MISSING' and belong to the replica.
return cache.getMissingFilesInLastUpdate(replica);
}
/**
* This method retrieves the date for the latest checksum update was
* performed for the replica. This means the date for the latest the
* replica has calculated the checksum of all the files within its archive.
*
* This method does not call out to the replicas. It only contacts the
* local database.
*
* @param replica The replica for which the date for last checksum update
* should be retrieved.
* @return The date for the last time the checksums has been update. If the
* checksum update has never occurred, then a null is returned.
* @throws ArgumentNotValid If the replica is null.
*/
public Date getDateForChangedFiles(Replica replica)
throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// Retrieves the checksum_updated date for the entry in the replica
// table in the database corresponding to the replica argument.
return cache.getDateOfLastWrongFilesUpdate(replica);
}
/**
* This method retrieves the date for the latest filelist update was
* performed for the replica. This means the date for the latest the
* replica has retrieved the list of all the files within the archive.
*
* This method does not call out to the replicas. It only contacts the
* local database.
*
* @param replica The replica for which the date for last filelist update
* should be retrieved.
* @return The date for the last time the filelist has been update. If the
* filelist update has never occurred, then a null is returned.
* @throws ArgumentNotValid If the replica is null.
*/
public Date getDateForMissingFiles(Replica replica)
throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// Retrieves the filelist_updated date for the entry in the replica
// table in the database corresponding to the replica argument.
return cache.getDateOfLastMissingFilesUpdate(replica);
}
/**
* The method is used to update the checksum for all the files in a replica.
* The checksum for the replica is retrieved through GetAllChecksumMessages.
* This will take a very large amount of time for the bitarchive, but a
* more limited amount of time for the checksumarchive.
*
* The corresponding replicafileinfo entries in the database for the
* retrieved checksum results will be updated. Then a checksum update will
* be performed to check for corrupted replicafileinfo.
*
* Each replica can only be updated once at the time.
*
* @param replica The replica to find the changed files for.
* @throws ArgumentNotValid If the replica is null.
*/
public void findChangedFiles(Replica replica)
throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// check whether a update of the replica is already in progress.
if(updateChecksumReplicas.contains(replica)) {
log.warn("A checksum update is already being performed for "
+ "replica '" + replica + "'. Operation ignored!");
return;
}
log.info("Initiating findChangedFiles for replica '" + replica + "'.");
updateChecksumReplicas.add(replica);
try {
// retrieve updated checksums from the replica.
runChecksum(replica);
// make sure, that all replicas are up-to-date.
initChecksumStatusUpdate();
// update to find changes.
cache.updateChecksumStatus();
log.info("Completed findChangedFiles for replica '" + replica
+ "'.");
} finally {
updateChecksumReplicas.remove(replica);
}
}
/**
* This method retrieves the filelist for the replica, and then it updates
* the database with this list of filenames.
* Each replica can only be updated once at the time.
*
* @param replica The replica to find the missing files for.
* @throws ArgumentNotValid If the replica is null.
*/
public void findMissingFiles(Replica replica)
throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// check whether a update of the replica is already in progress.
if(updateFilelistReplicas.contains(replica)) {
log.warn("A filelist update is already being performed for "
+ "replica '" + replica + "'. Operation ignored!");
return;
}
log.info("Initiating findMissingFiles for replica '" + replica + "'.");
updateFilelistReplicas.add(replica);
File filenamesFile = null;
try {
// retrieve the filelist from the replica
filenamesFile = getFilenamesAsFile(replica);
// put them into the database.
cache.addFileListInformation(filenamesFile, replica);
log.info("Completed findMissingFiles for replica '" + replica
+ "'.");
} finally {
updateFilelistReplicas.remove(replica);
if (filenamesFile != null) {
FileUtils.remove(filenamesFile);
}
}
}
/**
* Method for retrieving the FilePreservationState for a specific file.
*
* @param filename The name of the file for whom the FilePreservationState
* should be retrieved.
* @return The FilePreservationState for the file.
* @throws ArgumentNotValid If the filename is null or the empty string.
*/
@Override
public PreservationState getPreservationState(String filename)
throws ArgumentNotValid {
ArgumentNotValid.checkNotNullOrEmpty(filename, "String filename");
// Initialize the list of replicafileinfos, with one entry per replica.
List<ReplicaFileInfo> rfis = new ArrayList<ReplicaFileInfo>(
Replica.getKnown().size());
// update the checksum status for the file for all the replicas.
updateChecksumStatus(filename);
// Retrieve the replicafileinfo entries for the file.
for(Replica replica : Replica.getKnown()) {
rfis.add(cache.getReplicaFileInfo(filename, replica));
}
// use filename and replicafileinfos to make the resulting
// DatabasePreservationState.
return new DatabasePreservationState(filename, rfis);
}
/**
* Method for retrieving the FilePreservationState for a list of files.
*
* @param filenames The list of filenames whose FilePreservationState should
* be retrieved.
* @return A mapping between the filenames and their FilePreservationState.
* @throws ArgumentNotValid If the list of filenames are null.
*/
@Override
public Map<String, PreservationState> getPreservationStateMap(
String... filenames) throws ArgumentNotValid {
ArgumentNotValid.checkNotNull(filenames, "String... filenames");
// make the resulting map.
Map<String, PreservationState> res =
new HashMap<String, PreservationState>();
// retrieve the preservation states and put them into the map.
for(String file : filenames) {
res.put(file, getPreservationState(file));
}
return res;
}
/**
* This method finds the number of files which are known to be in the
* archive of a specific replica.
* This method will not go out to the replica, but only contact the local
* database.
* The number of files in the replica is retrieved from the database
* by counting the amount of files in the replicafileinfo table which
* belong to the replica and which has the filelist_status set to OK.
*
* @param replica The replica for which the number of files should be
* counted.
* @return The number of files for a specific replica.
* @throws ArgumentNotValid If the replica is null.
*/
public long getNumberOfFiles(Replica replica) throws ArgumentNotValid {
// validate
ArgumentNotValid.checkNotNull(replica, "Replica replica");
// returns the amount of files, which is not missing.
return cache.getNumberOfFiles(replica);
}
/**
* Check that the checksum of the file is indeed different to the value in
* admin data and reference replica. If so, remove missing file and upload
* it from reference replica to this replica.
*
* @param replica The replica to restore file to
* @param filename The name of the file
* @param credentials The credentials used to perform this replace operation
* @param checksum The known bad checksum. Only a file with this bad
* checksum is attempted repaired.
* @throws ArgumentNotValid If any of the arguments are not valid.
*/
public void replaceChangedFile(Replica replica, String filename,
String credentials, String checksum) throws ArgumentNotValid {
ArgumentNotValid.checkNotNull(replica, "Replica replica");
ArgumentNotValid.checkNotNullOrEmpty(filename, "String filename");
ArgumentNotValid.checkNotNullOrEmpty(checksum, "String checksum");
ArgumentNotValid.checkNotNullOrEmpty(credentials, "String credentials");
// find replica
Replica repWithFile = cache.getBitarchiveWithGoodFile(filename,
replica);
// retrieve the file from the replica.
File missingFile = retrieveRemoteFile(filename, repWithFile);
// upload the file to the replica where it is missing
ArcRepositoryClientFactory.getPreservationInstance().correct(
replica.getId(), checksum, missingFile, credentials);
}
/**
* This method is used to upload missing files to a replica.
* For each file a good version of this file is found, and it is
* reestablished on the replicas where it is missing.
*
* @param replica The replica where the files are missing.
* @param filenames The names of the files which are missing in the given
* replica.
* @throws ArgumentNotValid If the replica or list of filenames is null,
* or if the list of filenames is empty.
* @throws IOFailure If some files could not be established.
*/
public void uploadMissingFiles(Replica replica, String... filenames)
throws ArgumentNotValid, IOFailure {
ArgumentNotValid.checkNotNull(replica, "Replica replica");
ArgumentNotValid.checkNotNull(filenames, "String... filenames");
ArgumentNotValid.checkPositive(filenames.length, "Length of argument "
+ "String... filenames");
log.info("UploadMissingFiles initiated of " + filenames.length
+ " filenames");
// make record of files, which is not uploaded correct.
List<String> filesFailedReestablishment = new ArrayList<String>();
// For each file in filenames
for (String file : filenames) {
// retrieve a replica which has the file and the checksum_status
// is 'OK'. Though do not allow the replica where the file is
// missing to be returned.
Replica fileRep = cache.getBitarchiveWithGoodFile(file, replica);
// make sure, that a replica was found.
if (fileRep == null) {
// issue warning, report file, and continue to next file.
String errMsg = "No bitarchive replica contains a version of "
+ "the file with an acceptable checksum.";
log.warn(errMsg);
filesFailedReestablishment.add(file);
continue;
}
try {
// reestablish the missing file.
reestablishMissingFile(file, fileRep);
} catch (IOFailure e) {
// if error, then not successfully reestablishment for the file.
log.warn("The file '" + file + "' has not been reestablished "
+ "on replica '" + replica + "' with a correct version"
+ " from replica '" + fileRep + "'.", e);
filesFailedReestablishment.add(file);
}
}
// make warning if not all the files could be reestablished.
if (filesFailedReestablishment.size() > 0) {
throw new IOFailure("The following "
+ filesFailedReestablishment.size() + " out of "
+ filenames.length + " files could not be reestablished: "
+ filesFailedReestablishment);
}
log.info("UploadMissingFiles completed of "
+ filenames.length + " filenames");
}
/**
* This should reestablish the state for the file.
*
* @param filename The name of the file to change the state for.
* @throws ArgumentNotValid If the filename is invalid.
* @throws NotImplementedException This will not be implemented.
*/
@Override
public void changeStateForAdminData(String filename)
throws ArgumentNotValid, NotImplementedException {
ArgumentNotValid.checkNotNullOrEmpty(filename, "String filename");
// This function should not deal with admin.data.
throw new NotImplementedException("This will not be implemented");
}
/**
* Old method, which refers to the checksum replica part of admin data.
*
* @return Nothing, since it always throws an exception.
* @throws NotImplementedException This method will not be implemented.
*/
@Override
public Iterable<String> getMissingFilesForAdminData()
throws NotImplementedException {
// This function should not deal with admin.data.
throw new NotImplementedException("Old method, which refers to the "
+ "checksum replica part of admin data.");
}
/**
* Old method, which refers to the checksum replica part of admin data.
*
* @return Nothing, since it always throws an exception.
* @throws NotImplementedException This method will not be implemented.
*/
@Override
public Iterable<String> getChangedFilesForAdminData()
throws NotImplementedException {
// This function should not deal with admin.data.
throw new NotImplementedException("Old method, which refers to the "
+ "checksum replica part of admin data.");
}
/**
* Old method, which refers to the checksum replica part of admin data.
*
* @param filenames The list of filenames which should be added to admin
* data.
* @throws NotImplementedException This method will not be implemented.
* @throws ArgumentNotValid If filenames invalid.
*/
@Override
public void addMissingFilesToAdminData(String... filenames) throws
ArgumentNotValid, NotImplementedException {
ArgumentNotValid.checkNotNull(filenames, "String... filenames");
// This function should not deal with admin.data.
throw new NotImplementedException("Old method, which refers to the "
+ "checksum replica part of admin data.");
}
/**
* Method for closing the running instance of this class.
*/
public void close() {
if (closeHook != null) {
Runtime.getRuntime().removeShutdownHook(closeHook);
}
cleanup();
}
/**
* Method for cleaning up this instance.
*/
@Override
public void cleanup() {
instance = null;
cache.cleanup();
}
}
| lgpl-2.1 |
jecoli/jecoli | src/main/java/pt/uminho/ceb/biosystems/jecoli/algorithm/components/statistics/AlgorithmOverallRunsStatistics.java | 8256 | /**
* Copyright 2009,
* CCTC - Computer Science and Technology Center
* IBB-CEB - Institute for Biotechnology and Bioengineering - Centre of Biological Engineering
* University of Minho
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Public License for more details.
*
* You should have received a copy of the GNU Public License
* along with this code. If not, see <http://www.gnu.org/licenses/>.
*
* Created inside the SysBio Research Group <http://sysbio.di.uminho.pt/>
* University of Minho
*/
package pt.uminho.ceb.biosystems.jecoli.algorithm.components.statistics;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import pt.uminho.ceb.biosystems.jecoli.algorithm.components.algorithm.IAlgorithm;
import pt.uminho.ceb.biosystems.jecoli.algorithm.components.algorithm.IAlgorithmResult;
import pt.uminho.ceb.biosystems.jecoli.algorithm.components.algorithm.IAlgorithmStatistics;
import pt.uminho.ceb.biosystems.jecoli.algorithm.components.configuration.IConfiguration;
import pt.uminho.ceb.biosystems.jecoli.algorithm.components.representation.IRepresentation;
import pt.uminho.ceb.biosystems.jecoli.algorithm.components.solution.ISolution;
import pt.uminho.ceb.biosystems.jecoli.algorithm.components.solution.ISolutionContainer;
import pt.uminho.ceb.biosystems.jecoli.algorithm.components.solution.ISolutionSet;
import pt.uminho.ceb.biosystems.jecoli.algorithm.components.solution.SolutionCellContainer;
// TODO: Auto-generated Javadoc
/**
* The Class AlgorithmOverallRunsStatistics.
*/
public class AlgorithmOverallRunsStatistics<T extends IRepresentation> implements Serializable {
private static final long serialVersionUID = 1L;
/** The algorithm. */
protected IAlgorithm<T> algorithm;
/** The algorithm result list. */
protected List<IAlgorithmResult<T>> algorithmResultList;
/**
* Instantiates a new algorithm overall runs statistics.
*
* @param algorithm the algorithm
* @param algorithmRunStatisticsList the algorithm run statistics list
*
* @throws InvalidStatisticsParameterException the invalid statistics parameter exception
*/
public AlgorithmOverallRunsStatistics(IAlgorithm<T> algorithm, List<IAlgorithmResult<T>> algorithmRunStatisticsList) throws InvalidStatisticsParameterException {
if (algorithm == null)
throw new InvalidStatisticsParameterException("algorithm == NULL");
if (algorithmRunStatisticsList.size() < 0)
throw new InvalidStatisticsParameterException("numberOfRuns < 0");
this.algorithm = algorithm;
algorithmResultList = algorithmRunStatisticsList;
}
/**
* Gets the number of runs.
*
* @return the number of runs
*/
public int getNumberOfRuns() {
return algorithmResultList.size();
}
/**
* Gets the algorithm.
*
* @return the algorithm
*/
public IAlgorithm<T> getAlgorithm() {
return algorithm;
}
/**
* Gets the number of objectives.
*
* @return the number of objectives
*/
public int getNumberOfObjectives() {
IConfiguration<T> configuration = algorithm.getConfiguration();
int numberOfObjectives = configuration.getNumberOfObjectives();
return numberOfObjectives;
}
/**
* Gets the overall scalar fitness run statistics.
*
* @return the overall scalar fitness run statistics
*/
public OverallRunStatistics getOverallScalarFitnessRunStatistics() {
//double maxValue = Double.NEGATIVE_INFINITY;
//double minValue = Double.POSITIVE_INFINITY;
double bestValue = Double.NEGATIVE_INFINITY;
double meanValue = 0;
for (int i = 0; i < algorithmResultList.size(); i++) {
IAlgorithmResult<T> algorithmResult = algorithmResultList.get(i);
IAlgorithmStatistics<T> runStatistics = algorithmResult.getAlgorithmStatistics();
double currentBestValue;
currentBestValue = runStatistics.getRunMaxScalarFitnessValue();
bestValue = Math.max(currentBestValue, bestValue);
meanValue += currentBestValue;
//double currentMinValue = runStatistics.getRunMinScalarFitnessValue();
//double currentMeanValue = runStatistics.getRunMeanScalarFitnessValue();
//maxValue = Math.max(maxValue,currentMaxValue);
//minValue = Math.min(minValue,currentMinValue);
//meanValue += currentMeanValue;
}
meanValue /= algorithmResultList.size();
double stdDev = calculateStdDev(meanValue);
return new OverallRunStatistics(bestValue, meanValue, stdDev);
}
/**
* Calculate std dev.
*
* @param meanValue the mean value
*
* @return the double
*/
protected double calculateStdDev(double meanValue) {
double stdDev = 0;
for (IAlgorithmResult<T> algorithmResult : algorithmResultList) {
IAlgorithmStatistics<T> runStatistics = algorithmResult.getAlgorithmStatistics();
double currentValue = 0;
currentValue = runStatistics.getRunMaxScalarFitnessValue();
double differenceValue = currentValue - meanValue;
stdDev += Math.pow(differenceValue, 2);
}
stdDev /= algorithmResultList.size();
return Math.sqrt(stdDev);
}
/**
* Gets the best solution for each run.
*
* @return the best solution for each run
*/
public List<ISolution<T>> getBestSolutionForEachRun() {
List<ISolution<T>> bestSolutionList = new ArrayList<ISolution<T>>();
for (int i = 0; i < algorithmResultList.size(); i++) {
IAlgorithmResult<T> algorithmResult = algorithmResultList.get(i);
ISolutionContainer<T> solutionContainer = algorithmResult.getSolutionContainer();
SolutionCellContainer<T> container = solutionContainer.getBestSolutionCellContainer(true);
ISolution<T> solution = container.getSolution();
bestSolutionList.add(solution);
}
return bestSolutionList;
}
/**
* Adds the solutions to list.
*
* @param solutionSet the solution set
* @param bestSolutionList the best solution list
*/
protected void addSolutionsToList(ISolutionSet<T> solutionSet, List<ISolution<T>> bestSolutionList) {
for (ISolution<T> solution : bestSolutionList)
solutionSet.add(solution);
}
/**
* Gets the run statistics.
*
* @param objectivePosition the objective position
*
* @return the run statistics
*/
public IAlgorithmStatistics<T> getRunStatistics(int objectivePosition) {
IAlgorithmResult<T> algorithmResult = algorithmResultList.get(objectivePosition);
return algorithmResult.getAlgorithmStatistics();
}
/**
* Gets the objective overall run statistics.
*
* @param objectivePosition the objective position
*
* @return the objective overall run statistics
*/
public OverallRunStatistics getObjectiveOverallRunStatistics(int objectivePosition) {
//double maxValue = Double.NEGATIVE_INFINITY;
//double minValue = Double.POSITIVE_INFINITY;
double meanValue = 0;
double bestValue = Double.NEGATIVE_INFINITY;
;
for (int i = 0; i < algorithmResultList.size(); i++) {
IAlgorithmResult<T> algorithmResult = algorithmResultList.get(i);
IAlgorithmStatistics<T> runStatistics = algorithmResult.getAlgorithmStatistics();
double currentBestValue;
currentBestValue = runStatistics.getRunObjectiveMaxFitnessValue(objectivePosition);
bestValue = Math.max(currentBestValue, bestValue);
meanValue += currentBestValue;
// double currentMaxValue = runStatistics.getRunObjectiveMaxFitnessValue(objectivePosition);
// double currentMinValue = runStatistics.getRunObjectiveMinFitnessValue(objectivePosition);
// double currentMeanValue = runStatistics.getRunObjectiveMeanFitnessValue(objectivePosition);
// maxValue = Math.max(maxValue,currentMaxValue);
// minValue = Math.min(minValue,currentMinValue);
// meanValue += currentMeanValue;
}
meanValue /= algorithmResultList.size();
double stdDev = calculateStdDev(meanValue);
return new OverallRunStatistics(bestValue, meanValue, stdDev);
//return new OverallRunStatistics(maxValue,minValue,meanValue,stdDev);
}
}
| lgpl-2.1 |
optivo-org/fingbugs-1.3.9-optivo | src/java/edu/umd/cs/findbugs/ba/bcp/ByteCodePattern.java | 3492 | /*
* Bytecode Analysis Framework
* Copyright (C) 2003,2004 University of Maryland
*
* 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 edu.umd.cs.findbugs.ba.bcp;
/**
* A ByteCodePattern is a pattern matching a sequence of bytecode instructions.
*
* @author David Hovemeyer
* @see PatternElement
* @see PatternMatcher
*/
public class ByteCodePattern {
private PatternElement first, last;
private int interElementWild;
private int numElements;
private int dummyVariableCount;
/**
* Add a PatternElement to the end of the pattern.
*
* @param element the PatternElement
* @return this object
*/
public ByteCodePattern add(PatternElement element) {
if (first != null)
addInterElementWild();
addElement(element);
return this;
}
/**
* Add a wildcard to match between 0 and given number of instructions.
* If there is already a wildcard at the end of the current pattern,
* resets its max value to that given.
*
* @param numWild maximum number of instructions to be matched by
* the wildcard
*/
public ByteCodePattern addWild(int numWild) {
Wild wild = isLastWild();
if (wild != null)
wild.setMinAndMax(0, numWild);
else
addElement(new Wild(numWild));
return this;
}
/**
* Set number of inter-element wildcards to create between
* explicit PatternElements. By default, no implicit wildcards
* are created.
*
* @param numWild the number of wildcard instructions which
* may be matched between explicit PatternElements
* @return this object
*/
public ByteCodePattern setInterElementWild(int numWild) {
this.interElementWild = numWild;
return this;
}
/**
* Get the first PatternElement in the pattern.
*/
public PatternElement getFirst() {
return first;
}
/**
* Get a dummy variable name.
* The name returned will begin with the <code>'$'</code> character,
* and will be different than any previous dummy variable name allocated
* by this object. Dummy variable names are useful for creating
* PatternElements where you don't care whether the value it uses
* is the same as one used by another PatternElement.
*/
public String dummyVariable() {
StringBuilder buf = new StringBuilder();
buf.append("$_");
buf.append(dummyVariableCount++);
return buf.toString();
}
private void addInterElementWild() {
if (interElementWild > 0 && isLastWild() == null)
addElement(new Wild(interElementWild));
}
private void addElement(PatternElement element) {
element.setIndex(numElements++);
if (first == null) {
first = last = element;
} else {
last.setNext(element);
last = element;
}
}
private Wild isLastWild() {
if (last != null && last instanceof Wild)
return (Wild) last;
else
return null;
}
}
// vim:ts=4
| lgpl-2.1 |
fjalvingh/domui | to.etc.domui.demo/src/main/java/to/etc/domuidemo/pages/test/RowRendererFactoryTest.java | 1127 | package to.etc.domuidemo.pages.test;
import to.etc.domui.component.input.Text2;
import to.etc.domui.component.tbl.DataTable;
import to.etc.domui.component.tbl.RowRenderer;
import to.etc.domui.component.tbl.SimpleListModel;
import to.etc.domui.derbydata.db.Artist;
import to.etc.domui.dom.html.UrlPage;
import to.etc.webapp.query.QCriteria;
public class RowRendererFactoryTest extends UrlPage {
@Override public void createContent() throws Exception {
SimpleListModel<Artist> slm = new SimpleListModel<>(getSharedContext().query(QCriteria.create(Artist.class).eq("name", "Black Sabbath")));
RowRenderer<Artist> rr = new RowRenderer<>(Artist.class);
rr.column(String.class, "name").label("Read-only").factory(row -> {
Text2<String> ctrl = new Text2<>(String.class);
ctrl.bind().to(row, "name");
ctrl.setReadOnly(true);
return ctrl;
}
).editable();
rr.column(String.class, "name").label("Editable").factory(row -> {
Text2<String> ctrl = new Text2<>(String.class);
ctrl.bind().to(row, "name");
return ctrl;
}
);
DataTable<Artist> dt = new DataTable<>(slm, rr);
add(dt);
}
}
| lgpl-2.1 |
kenweezy/teiid | engine/src/test/java/org/teiid/query/validator/TestValidator.java | 100603 | /*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* 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 org.teiid.query.validator;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Ignore;
import org.junit.Test;
import org.teiid.api.exception.query.QueryMetadataException;
import org.teiid.api.exception.query.QueryParserException;
import org.teiid.api.exception.query.QueryResolverException;
import org.teiid.api.exception.query.QueryValidatorException;
import org.teiid.client.metadata.ParameterInfo;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidException;
import org.teiid.core.TeiidRuntimeException;
import org.teiid.core.types.DataTypeManager;
import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
import org.teiid.metadata.BaseColumn.NullType;
import org.teiid.metadata.Column;
import org.teiid.metadata.Column.SearchType;
import org.teiid.metadata.ColumnSet;
import org.teiid.metadata.MetadataStore;
import org.teiid.metadata.Procedure;
import org.teiid.metadata.ProcedureParameter;
import org.teiid.metadata.Schema;
import org.teiid.metadata.Table;
import org.teiid.query.analysis.AnalysisRecord;
import org.teiid.query.mapping.relational.QueryNode;
import org.teiid.query.mapping.xml.MappingDocument;
import org.teiid.query.mapping.xml.MappingElement;
import org.teiid.query.metadata.QueryMetadataInterface;
import org.teiid.query.metadata.TransformationMetadata;
import org.teiid.query.parser.QueryParser;
import org.teiid.query.processor.TestProcessor;
import org.teiid.query.resolver.QueryResolver;
import org.teiid.query.sql.LanguageObject;
import org.teiid.query.sql.lang.Command;
import org.teiid.query.sql.lang.ProcedureContainer;
import org.teiid.query.sql.symbol.GroupSymbol;
import org.teiid.query.sql.visitor.SQLStringVisitor;
import org.teiid.query.unittest.RealMetadataFactory;
@SuppressWarnings("nls")
public class TestValidator {
public static TransformationMetadata exampleMetadata() {
MetadataStore metadataStore = new MetadataStore();
// Create metadata objects
Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
Schema vModelObj2 = RealMetadataFactory.createVirtualModel("vTest", metadataStore); //$NON-NLS-1$
Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj); //$NON-NLS-1$
Column elemObj0 = RealMetadataFactory.createElement("e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
elemObj0.setNullType(NullType.No_Nulls);
Column elemObj1 = RealMetadataFactory.createElement("e1", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
elemObj1.setSelectable(false);
Column elemObj2 = RealMetadataFactory.createElement("e2", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
elemObj2.setSearchType(SearchType.Like_Only);
Column elemObj3 = RealMetadataFactory.createElement("e3", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
elemObj3.setSearchType(SearchType.All_Except_Like);
Table group2Obj = RealMetadataFactory.createPhysicalGroup("group2", modelObj); //$NON-NLS-1$
Column elemObj2_0 = RealMetadataFactory.createElement("e0", group2Obj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
elemObj2_0.setUpdatable(false);
RealMetadataFactory.createElement("e1", group2Obj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
Column elemObj2_2 = RealMetadataFactory.createElement("e2", group2Obj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
elemObj2_2.setUpdatable(false);
Table group3Obj = RealMetadataFactory.createPhysicalGroup("group3", modelObj); //$NON-NLS-1$
group3Obj.setSupportsUpdate(false);
RealMetadataFactory.createElement("e0", group3Obj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
RealMetadataFactory.createElement("e1", group3Obj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
RealMetadataFactory.createElement("e2", group3Obj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
// Create virtual group & elements.
QueryNode vNode = new QueryNode("SELECT * FROM test.group WHERE e2 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
Table vGroup = RealMetadataFactory.createVirtualGroup("vGroup", vModelObj2, vNode); //$NON-NLS-1$
RealMetadataFactory.createElements(vGroup,
new String[] { "e0", "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
QueryNode vNode2 = new QueryNode("SELECT * FROM test.group"); //$NON-NLS-1$ //$NON-NLS-2$
Table vGroup2 = RealMetadataFactory.createVirtualGroup("vMap", vModelObj2, vNode2); //$NON-NLS-1$
List<Column> vGroupE2 = RealMetadataFactory.createElements(vGroup2,
new String[] { "e0", "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
vGroupE2.get(0).setNullType(NullType.No_Nulls);
vGroupE2.get(1).setSelectable(false);
vGroupE2.get(2).setSearchType(SearchType.Like_Only);
vGroupE2.get(3).setSearchType(SearchType.All_Except_Like);
// Create virtual documents
MappingDocument doc = new MappingDocument(false);
MappingElement complexRoot = doc.addChildElement(new MappingElement("a0")); //$NON-NLS-1$
MappingElement sourceNode = complexRoot.addChildElement(new MappingElement("a1")); //$NON-NLS-1$
sourceNode.setSource("test.group"); //$NON-NLS-1$
sourceNode.addChildElement(new MappingElement("a2", "test.group.e1")); //$NON-NLS-1$ //$NON-NLS-2$
sourceNode.addChildElement(new MappingElement("b2", "test.group.e2")); //$NON-NLS-1$ //$NON-NLS-2$
sourceNode.addChildElement(new MappingElement("c2", "test.group.e3")); //$NON-NLS-1$ //$NON-NLS-2$
Schema docModel = RealMetadataFactory.createVirtualModel("vm1", metadataStore); //$NON-NLS-1$
RealMetadataFactory.createXmlDocument("doc1", docModel, doc); //$NON-NLS-1$
return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
}
public TransformationMetadata exampleMetadata1() {
MetadataStore metadataStore = new MetadataStore();
// Create metadata objects
Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj); //$NON-NLS-1$
Column elemObj0 = RealMetadataFactory.createElement("e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
Column elemObj1 = RealMetadataFactory.createElement("e1", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
Column elemObj2 = RealMetadataFactory.createElement("e2", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
RealMetadataFactory.createElement("e3", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
elemObj0.setNullType(NullType.No_Nulls);
elemObj1.setNullType(NullType.Nullable);
elemObj1.setDefaultValue(Boolean.TRUE.toString());
elemObj2.setNullType(NullType.Nullable);
elemObj2.setDefaultValue(Boolean.FALSE.toString());
return RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
}
/**
* Group has element with type object
* @return QueryMetadataInterface
*/
public static TransformationMetadata exampleMetadata2() {
MetadataStore metadataStore = new MetadataStore();
// Create metadata objects
Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj); //$NON-NLS-1$
RealMetadataFactory.createElements(groupObj, new String[] {
"e0", "e1", "e2", "e3", "e4", "e5" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
}, new String[] {
DataTypeManager.DefaultDataTypes.INTEGER,
DataTypeManager.DefaultDataTypes.STRING,
DataTypeManager.DefaultDataTypes.OBJECT,
DataTypeManager.DefaultDataTypes.BLOB,
DataTypeManager.DefaultDataTypes.CLOB,
DataTypeManager.DefaultDataTypes.XML,
});
return RealMetadataFactory.createTransformationMetadata(metadataStore, "example2");
}
public static TransformationMetadata exampleMetadata3() {
MetadataStore metadataStore = new MetadataStore();
// Create metadata objects
Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj); //$NON-NLS-1$
RealMetadataFactory.createElement("e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
Column elemObj1 = RealMetadataFactory.createElement("e1", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
elemObj1.setNullType(NullType.No_Nulls);
elemObj1.setDefaultValue(Boolean.FALSE.toString());
elemObj1.setAutoIncremented(true);
elemObj1.setNameInSource("e1:SEQUENCE=MYSEQUENCE.nextVal"); //$NON-NLS-1$
return RealMetadataFactory.createTransformationMetadata(metadataStore, "example3");
}
public static TransformationMetadata exampleMetadata4() {
MetadataStore metadataStore = new MetadataStore();
// Create metadata objects
Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj); //$NON-NLS-1$
RealMetadataFactory.createElement("e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
RealMetadataFactory.createElement("e1", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
RealMetadataFactory.createElement("e2", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
Schema vModelObj = RealMetadataFactory.createVirtualModel("vTest", metadataStore); //$NON-NLS-1$
QueryNode vNode = new QueryNode("SELECT * FROM test.group"); //$NON-NLS-1$ //$NON-NLS-2$
Table vGroupObj = RealMetadataFactory.createVirtualGroup("vGroup", vModelObj, vNode); //$NON-NLS-1$
Column vElemObj0 = RealMetadataFactory.createElement("e0", vGroupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
Column vElemObj1 = RealMetadataFactory.createElement("e1", vGroupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
RealMetadataFactory.createElement("e2", vGroupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
List<Column> elements = new ArrayList<Column>(2);
elements.add(vElemObj0);
elements.add(vElemObj1);
RealMetadataFactory.createAccessPattern("ap1", vGroupObj, elements); //e1 //$NON-NLS-1$
QueryNode vNode2 = new QueryNode("SELECT * FROM vTest.vGroup"); //$NON-NLS-1$ //$NON-NLS-2$
Table vGroupObj2 = RealMetadataFactory.createVirtualGroup("vGroup2", vModelObj, vNode2); //$NON-NLS-1$
Column vElemObj20 = RealMetadataFactory.createElement("e0", vGroupObj2, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
Column vElemObj21 = RealMetadataFactory.createElement("e1", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
RealMetadataFactory.createElement("e2", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
elements = new ArrayList<Column>(2);
elements.add(vElemObj20);
elements.add(vElemObj21);
RealMetadataFactory.createAccessPattern("vTest.vGroup2.ap1", vGroupObj2, elements); //e1 //$NON-NLS-1$
return RealMetadataFactory.createTransformationMetadata(metadataStore, "example4");
}
// ################################## TEST HELPERS ################################
static Command helpResolve(String sql, QueryMetadataInterface metadata) {
Command command = null;
try {
command = QueryParser.getQueryParser().parseCommand(sql);
QueryResolver.resolveCommand(command, metadata);
} catch(Exception e) {
throw new TeiidRuntimeException(e);
}
return command;
}
static Command helpResolve(String sql, GroupSymbol container, int type, QueryMetadataInterface metadata) throws QueryParserException, QueryResolverException, TeiidComponentException {
Command command = QueryParser.getQueryParser().parseCommand(sql);
QueryResolver.resolveCommand(command, container, type, metadata, false);
return command;
}
public static ValidatorReport helpValidate(String sql, String[] expectedStringArray, QueryMetadataInterface metadata) {
Command command = helpResolve(sql, metadata);
return helpRunValidator(command, expectedStringArray, metadata);
}
public static ValidatorReport helpRunValidator(Command command, String[] expectedStringArray, QueryMetadataInterface metadata) {
try {
ValidatorReport report = Validator.validate(command, metadata);
examineReport(command, expectedStringArray, report);
return report;
} catch(TeiidException e) {
throw new TeiidRuntimeException(e);
}
}
private static void examineReport(Object command,
String[] expectedStringArray, ValidatorReport report) {
// Get invalid objects from report
Collection<LanguageObject> actualObjs = new ArrayList<LanguageObject>();
report.collectInvalidObjects(actualObjs);
// Compare expected and actual objects
Set<String> expectedStrings = new HashSet<String>(Arrays.asList(expectedStringArray));
Set<String> actualStrings = new HashSet<String>();
for (LanguageObject obj : actualObjs) {
actualStrings.add(SQLStringVisitor.getSQLString(obj));
}
if(expectedStrings.size() == 0 && actualStrings.size() > 0) {
fail("Expected no failures but got some: " + report.getFailureMessage()); //$NON-NLS-1$
} else if(actualStrings.size() == 0 && expectedStrings.size() > 0) {
fail("Expected some failures but got none for sql = " + command); //$NON-NLS-1$
} else {
assertEquals("Expected and actual sets of strings are not the same: ", expectedStrings, actualStrings); //$NON-NLS-1$
}
}
private void helpValidateProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) {
QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
try {
validateProcedure(userUpdateStr, metadata);
} catch(TeiidException e) {
throw new TeiidRuntimeException(e);
}
}
private void validateProcedure(String userUpdateStr,
QueryMetadataInterface metadata) throws QueryResolverException,
QueryMetadataException, TeiidComponentException,
QueryValidatorException {
ProcedureContainer command = (ProcedureContainer)helpResolve(userUpdateStr, metadata);
Command proc = QueryResolver.expandCommand(command, metadata, AnalysisRecord.createNonRecordingRecord());
ValidatorReport report = Validator.validate(proc, metadata);
if(report.hasItems()) {
throw new QueryValidatorException(report.getFailureMessage());
}
report = Validator.validate(command, metadata);
if(report.hasItems()) {
throw new QueryValidatorException(report.getFailureMessage());
}
}
private void helpFailProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) {
QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
try {
validateProcedure(userUpdateStr, metadata);
fail("Expected failures for " + procedure);
} catch (QueryValidatorException e) {
} catch(TeiidException e) {
throw new RuntimeException(e);
}
}
// ################################## ACTUAL TESTS ################################
@Test public void testSelectStarWhereNoElementsAreNotSelectable() {
helpValidate("SELECT * FROM pm1.g5", new String[] {"SELECT * FROM pm1.g5"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateSelect1() {
helpValidate("SELECT e1, e2 FROM test.group", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateSelect2() {
helpValidate("SELECT e2 FROM test.group", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateCompare1() {
helpValidate("SELECT e2 FROM vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateCompare4() {
helpValidate("SELECT e3 FROM vTest.vMap WHERE e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateCompare6() {
helpValidate("SELECT e0 FROM vTest.vMap WHERE e0 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateCompareInHaving2() {
helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IS NULL", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateCompareInHaving3() {
helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IN ('a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateCompareInHaving4() {
helpValidate("SELECT e3 FROM vTest.vMap GROUP BY e3 HAVING e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateCompareInHaving5() {
helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testInvalidAggregate1() {
helpValidate("SELECT SUM(e3) FROM test.group GROUP BY e2", new String[] {"SUM(e3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidAggregate2() {
helpValidate("SELECT e3 FROM test.group GROUP BY e2", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidAggregate3() {
helpValidate("SELECT SUM(e2) FROM test.group GROUP BY e2", new String[] {"SUM(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidAggregate4() {
helpValidate("SELECT AVG(e2) FROM test.group GROUP BY e2", new String[] {"AVG(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidAggregate5() {
helpValidate("SELECT e1 || 'x' frOM pm1.g1 GROUP BY e2 + 1", new String[] {"e1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidAggregate6() {
helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1 HAVING e1 || 'x' > 0", new String[] {"e1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidAggregate7() {
helpValidate("SELECT StringKey, SUM(length(StringKey || 'x')) + 1 AS x FROM BQT1.SmallA GROUP BY StringKey || 'x' HAVING space(MAX(length((StringKey || 'x') || 'y'))) = ' '", //$NON-NLS-1$
new String[] {"StringKey"}, RealMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
}
@Test public void testInvalidAggregate8() {
helpValidate("SELECT max(ObjectValue) FROM BQT1.SmallA GROUP BY StringKey", //$NON-NLS-1$
new String[] {"MAX(ObjectValue)"}, RealMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
}
@Test public void testInvalidAggregate9() {
helpValidate("SELECT count(distinct ObjectValue) FROM BQT1.SmallA GROUP BY StringKey", //$NON-NLS-1$
new String[] {"COUNT(DISTINCT ObjectValue)"}, RealMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
}
/**
* previously failed on stringkey, which is not entirely correct
*/
@Test public void testInvalidAggregate10() {
helpValidate("SELECT xmlparse(document stringkey) FROM BQT1.SmallA GROUP BY xmlparse(document stringkey)", //$NON-NLS-1$
new String[] {"XMLPARSE(DOCUMENT stringkey)"}, RealMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
}
@Test public void testInvalidAggregateIssue190644() {
helpValidate("SELECT e3 + 1 from pm1.g1 GROUP BY e2 + 1 HAVING e2 + 1 = 5", new String[] {"e3"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidAggregate1() {
helpValidate("SELECT (e2 + 1) * 2 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testValidAggregate2() {
helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testValidAggregate3() {
helpValidate("SELECT sum (IntKey), case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
"FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end", //$NON-NLS-1$
new String[] {}, RealMetadataFactory.exampleBQTCached());
}
@Test public void testValidAggregate4() {
helpValidate("SELECT max(e1), e2 is null from pm1.g1 GROUP BY e2 is null", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testInvalidHaving1() {
helpValidate("SELECT e3 FROM test.group HAVING e3 > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidHaving2() {
helpValidate("SELECT e3 FROM test.group HAVING concat(e3,'a') > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testNestedAggregateInHaving() {
helpValidate("SELECT e0 FROM test.group GROUP BY e0 HAVING SUM(COUNT(e0)) > 0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testNestedAggregateInSelect() {
helpValidate("SELECT SUM(COUNT(e0)) FROM test.group GROUP BY e0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateCaseInGroupBy() {
helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY CASE e2 WHEN 0 THEN 1 ELSE 2 END", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testValidateFunctionInGroupBy() {
helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testInvalidScalarSubqueryInGroupBy() {
helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY (SELECT 1)", new String[] { "(SELECT 1)" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidConstantInGroupBy() {
helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY 1", new String[] { "1" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidReferenceInGroupBy() {
helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY ?", new String[] { "?" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateObjectType1() {
helpValidate("SELECT DISTINCT * FROM test.group", new String[] {"test.\"group\".e2", "test.\"group\".e3", "test.\"group\".e4", "test.\"group\".e5"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
}
@Test public void testValidateObjectType2() {
helpValidate("SELECT * FROM test.group ORDER BY e1, e2", new String[] {"e2"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateObjectType3() {
helpValidate("SELECT e2 AS x FROM test.group ORDER BY x", new String[] {"x"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateNonComparableType() {
helpValidate("SELECT e3 FROM test.group ORDER BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateNonComparableType1() {
helpValidate("SELECT e3 FROM test.group union SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateNonComparableType2() {
helpValidate("SELECT e3 FROM test.group GROUP BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateNonComparableType3() {
helpValidate("SELECT e3 FROM test.group intersect SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateNonComparableType4() {
helpValidate("SELECT e3 FROM test.group except SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateIntersectAll() {
helpValidate("SELECT e3 FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateSetSelectInto() {
helpValidate("SELECT e3 into #temp FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 INTO #temp FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInsert1() {
helpValidate("INSERT INTO test.group (e0) VALUES (null)", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
// non-null, no-default elements not left
@Test public void testInsert4() throws Exception {
QueryMetadataInterface metadata = exampleMetadata1();
Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e0) VALUES (2)"); //$NON-NLS-1$
QueryResolver.resolveCommand(command, metadata);
helpRunValidator(command, new String[] {}, metadata);
}
// non-null, no-default elements left
@Test public void testInsert5() throws Exception {
QueryMetadataInterface metadata = exampleMetadata1();
Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e1, e2) VALUES ('x', 'y')"); //$NON-NLS-1$
QueryResolver.resolveCommand(command, metadata);
helpRunValidator(command, new String[] {"test.\"group\".e0"}, metadata); //$NON-NLS-1$
}
@Test public void testValidateInsertElements1() throws Exception {
QueryMetadataInterface metadata = exampleMetadata();
Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e0, e1, e2) VALUES (5, 'x', 'y')"); //$NON-NLS-1$
QueryResolver.resolveCommand(command, metadata);
helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateInsertElements2() throws Exception {
QueryMetadataInterface metadata = exampleMetadata();
Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e1) VALUES ('y')"); //$NON-NLS-1$
QueryResolver.resolveCommand(command, metadata);
helpRunValidator(command, new String[] {}, metadata);
}
@Test public void testValidateInsertElements3_autoIncNotRequired() throws Exception {
helpValidate("INSERT INTO test.group (e0) VALUES (1)", new String[] {}, exampleMetadata3()); //$NON-NLS-1$
}
@Test public void testUpdate1() {
helpValidate("UPDATE test.group SET e0=null", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testUpdate2() {
helpValidate("UPDATE test.group SET e0=1, e0=2", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateUpdateElements1() throws Exception {
QueryMetadataInterface metadata = exampleMetadata();
Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e0 = 5, e1 = 'x', e2 = 'y'"); //$NON-NLS-1$
QueryResolver.resolveCommand(command, metadata);
helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateUpdateElements2() throws Exception {
QueryMetadataInterface metadata = exampleMetadata();
Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e1 = 'x'"); //$NON-NLS-1$
QueryResolver.resolveCommand(command, metadata);
helpRunValidator(command, new String[] {}, metadata);
}
@Test public void testXMLSerializeEncoding() {
helpValidate("SELECT xmlserialize(? AS CLOB ENCODING \"UTF-8\")", new String[] {"XMLSERIALIZE(? AS CLOB ENCODING \"UTF-8\")"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testXMLSerializeEncoding1() {
helpValidate("SELECT xmlserialize(? AS BLOB ENCODING \"UTF-8\" INCLUDING XMLDECLARATION)", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testXMLSerializeEncoding2() {
helpValidate("SELECT xmlserialize(? AS BLOB ENCODING \"UTF-75\" INCLUDING XMLDECLARATION)", new String[] {"XMLSERIALIZE(? AS BLOB ENCODING \"UTF-75\" INCLUDING XMLDECLARATION)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testXMLQuery1() {
helpValidate("SELECT * FROM vm1.doc1", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testXMLQuery2() {
helpValidate("SELECT * FROM vm1.doc1 where a2='x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testXMLQuery3() {
helpValidate("SELECT * FROM vm1.doc1 order by a2", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testXMLQuery6() {
helpValidate("SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1", new String[] {"\"xml\"", "SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
@Test public void testXMLQueryWithLimit() {
helpValidate("SELECT * FROM vm1.doc1 limit 1", new String[] {"SELECT * FROM vm1.doc1 LIMIT 1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** test rowlimit function is valid */
@Test public void testXMLQueryRowLimit() {
helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimit(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/** rowlimit function operand must be nonnegative integer */
@Test public void testXMLQueryRowLimit1() {
helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=-1", new String[] {"RowLimit(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimit function operand must be nonnegative integer */
@Test public void testXMLQueryRowLimit2() {
helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)='x'", new String[] {"RowLimit(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimit function cannot be nested within another function (this test inserts an implicit type conversion) */
@Test public void testXMLQueryRowLimitNested() {
helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=a2", new String[] {"RowLimit(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimit function cannot be nested within another function */
@Test public void testXMLQueryRowLimitNested2() {
helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimit(a2), string)=a2", new String[] {"convert(RowLimit(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimit function operand must be nonnegative integer */
@Test public void testXMLQueryRowLimit3a() {
helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2) = convert(a2, integer)", new String[] {"RowLimit(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimit function operand must be nonnegative integer */
@Test public void testXMLQueryRowLimit3b() {
helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimit(a2)", new String[] {"convert(a2, integer) = RowLimit(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimit function arg must be an element symbol */
@Test public void testXMLQueryRowLimit4() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit('x') = 3", new String[] {"rowlimit('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimit function arg must be an element symbol */
@Test public void testXMLQueryRowLimit5() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(concat(a2, 'x')) = 3", new String[] {"rowlimit(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimit function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitConjunct() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimit(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimit function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitCompound() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/** rowlimit function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitCompound2() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/** rowlimit function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitCompound3() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/** each rowlimit function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitCompound4() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/**
* It doesn't make sense to use rowlimit twice on same element, but can't be
* invalidated here (could be two different elements but in the same
* mapping class - needs to be caught in XMLPlanner)
*/
@Test public void testXMLQueryRowLimitCompound5() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testXMLQueryRowLimitInvalidCriteria() {
helpValidate("SELECT * FROM vm1.doc1 where not(rowlimit(a2) = 3)", new String[] {"NOT (rowlimit(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitInvalidCriteria2() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (3)", new String[] {"rowlimit(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitInvalidCriteria3() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) LIKE 'x'", new String[] {"rowlimit(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitInvalidCriteria4() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IS NULL", new String[] {"rowlimit(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitInvalidCriteria5() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitInvalidCriteria6() {
helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitInvalidCriteria6a() {
helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimit(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimit(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitInvalidCriteria7() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) BETWEEN 2 AND 3", new String[] {"rowlimit(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitInvalidCriteria8() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** using rowlimit pseudo-function in non-XML query is invalid */
@Test public void testNonXMLQueryRowLimit() {
helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimit(e1) = 2", new String[] {"rowlimit(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** test rowlimitexception function is valid */
@Test public void testXMLQueryRowLimitException() {
helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimitException(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/** rowlimitexception function operand must be nonnegative integer */
@Test public void testXMLQueryRowLimitException1() {
helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=-1", new String[] {"RowLimitException(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimitexception function operand must be nonnegative integer */
@Test public void testXMLQueryRowLimitException2() {
helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)='x'", new String[] {"RowLimitException(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimitexception function cannot be nested within another function (this test inserts an implicit type conversion) */
@Test public void testXMLQueryRowLimitExceptionNested() {
helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=a2", new String[] {"RowLimitException(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimitexception function cannot be nested within another function */
@Test public void testXMLQueryRowLimitExceptionNested2() {
helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimitException(a2), string)=a2", new String[] {"convert(RowLimitException(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimitexception function operand must be nonnegative integer */
@Test public void testXMLQueryRowLimitException3a() {
helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2) = convert(a2, integer)", new String[] {"RowLimitException(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimitexception function operand must be nonnegative integer */
@Test public void testXMLQueryRowLimitException3b() {
helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimitException(a2)", new String[] {"convert(a2, integer) = RowLimitException(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimitexception function arg must be an element symbol */
@Test public void testXMLQueryRowLimitException4() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception('x') = 3", new String[] {"rowlimitexception('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimitexception function arg must be an element symbol */
@Test public void testXMLQueryRowLimitException5() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(concat(a2, 'x')) = 3", new String[] {"rowlimitexception(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimitexception function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitExceptionConjunct() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimitexception(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** rowlimitexception function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitExceptionCompound() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/** rowlimitexception function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitExceptionCompound2() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/** rowlimitexception function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitExceptionCompound3() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/** each rowlimitexception function arg must be a single conjunct */
@Test public void testXMLQueryRowLimitExceptionCompound4() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
/**
* It doesn't make sense to use rowlimitexception twice on same element, but can't be
* invalidated here (could be two different elements but in the same
* mapping class - needs to be caught in XMLPlanner)
*/
@Test public void testXMLQueryRowLimitExceptionCompound5() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testXMLQueryRowLimitExceptionInvalidCriteria() {
helpValidate("SELECT * FROM vm1.doc1 where not(rowlimitexception(a2) = 3)", new String[] {"NOT (rowlimitexception(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitExceptionInvalidCriteria2() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (3)", new String[] {"rowlimitexception(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitExceptionInvalidCriteria3() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) LIKE 'x'", new String[] {"rowlimitexception(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitExceptionInvalidCriteria4() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IS NULL", new String[] {"rowlimitexception(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitExceptionInvalidCriteria5() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitExceptionInvalidCriteria6() {
helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitExceptionInvalidCriteria6a() {
helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitExceptionInvalidCriteria7() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) BETWEEN 2 AND 3", new String[] {"rowlimitexception(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXMLQueryRowLimitExceptionInvalidCriteria8() {
helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** using rowlimit pseudo-function in non-XML query is invalid */
@Test public void testNonXMLQueryRowLimitException() {
helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimitexception(e1) = 2", new String[] {"rowlimitexception(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/** using context pseudo-function in non-XML query is invalid */
@Test public void testNonXMLQueryContextOperator() {
helpValidate("SELECT e2 FROM vTest.vMap WHERE context(e1, e1) = 2", new String[] {"context(e1, e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateSubquery1() {
helpValidate("SELECT e2 FROM (SELECT e2 FROM vTest.vMap WHERE e2 = 'a') AS x", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateSubquery2() {
helpValidate("SELECT e2 FROM (SELECT e3 FROM vTest.vMap) AS x, vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateSubquery3() {
helpValidate("SELECT * FROM pm1.g1, (EXEC pm1.sq1( )) AS alias", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testValidateUnionWithSubquery() {
helpValidate("SELECT e2 FROM test.group2 union all SELECT e3 FROM test.group union all select * from (SELECT e1 FROM test.group) as subquery1", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateExistsSubquery() {
helpValidate("SELECT e2 FROM test.group2 WHERE EXISTS (SELECT e2 FROM vTest.vMap WHERE e2 = 'a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateScalarSubquery() {
helpValidate("SELECT e2, (SELECT e1 FROM vTest.vMap WHERE e2 = '3') FROM test.group2", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateAnyCompareSubquery() {
helpValidate("SELECT e2 FROM test.group2 WHERE e1 < ANY (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateAllCompareSubquery() {
helpValidate("SELECT e2 FROM test.group2 WHERE e1 = ALL (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateSomeCompareSubquery() {
helpValidate("SELECT e2 FROM test.group2 WHERE e1 <= SOME (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateCompareSubquery() {
helpValidate("SELECT e2 FROM test.group2 WHERE e1 >= (SELECT e1 FROM test.group WHERE e1 = 1)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateInClauseSubquery() {
helpValidate("SELECT e2 FROM test.group2 WHERE e1 IN (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateExec1() {
helpValidate("EXEC pm1.sq1()", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
// valid variable declared
@Test public void testCreateUpdateProcedure4() {
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
helpValidateProcedure(procedure, userUpdateStr,
Table.TriggerEvent.UPDATE);
}
// validating AssignmentStatement, more than one project symbol on the
// command
@Test public void testCreateUpdateProcedure11() {
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
procedure = procedure + "var1 = Select pm1.g1.e2, pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
helpFailProcedure(procedure, userUpdateStr,
Table.TriggerEvent.UPDATE);
}
// validating AssignmentStatement, more than one project symbol on the
// command
@Test public void testCreateUpdateProcedure12() {
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
procedure = procedure + "var1 = Select pm1.g1.e2, pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
helpFailProcedure(procedure, userUpdateStr,
Table.TriggerEvent.UPDATE);
}
// using aggregate function within a procedure - defect #8394
@Test public void testCreateUpdateProcedure31() {
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "DECLARE string MaxTran;\n"; //$NON-NLS-1$
procedure = procedure + "MaxTran = SELECT MAX(e1) FROM pm1.g1;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpValidateProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
// assigning null values to known datatype variable
@Test public void testCreateUpdateProcedure32() {
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "DECLARE string var;\n"; //$NON-NLS-1$
procedure = procedure + "var = null;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpValidateProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testDefect13643() {
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
procedure = procedure + "LOOP ON (SELECT * FROM pm1.g1) AS myCursor\n"; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "var1 = SELECT COUNT(*) FROM myCursor;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpFailProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testValidHaving() {
helpValidate(
"SELECT intnum " + //$NON-NLS-1$
"FROM bqt1.smalla " + //$NON-NLS-1$
"GROUP BY intnum " + //$NON-NLS-1$
"HAVING SUM(floatnum) > 1", //$NON-NLS-1$
new String[] { }, RealMetadataFactory.exampleBQTCached());
}
@Test public void testValidHaving2() {
String sql = "SELECT intkey FROM bqt1.smalla WHERE intkey = 1 " + //$NON-NLS-1$
"GROUP BY intkey HAVING intkey = 1"; //$NON-NLS-1$
helpValidate(sql, new String[] {}, RealMetadataFactory.exampleBQTCached());
}
@Test public void testVirtualProcedure(){
helpValidate("EXEC pm1.vsp1()", new String[] { }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testSelectWithNoFrom() {
helpValidate("SELECT 5", new String[] {}, exampleMetadata()); //$NON-NLS-1$
}
@Test public void testSelectIntoTempGroup() {
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
procedure = procedure + "SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpValidateProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
/**
* Defect 24346
*/
@Test public void testInvalidSelectIntoTempGroup() {
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
procedure = procedure + "SELECT e1, e2, e3 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
procedure = procedure + "SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpFailProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testInvalidSelectIntoTempGroup1() {
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "create local temporary table #myTempTable (e1 integer);\n"; //$NON-NLS-1$
procedure = procedure + "SELECT e1 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
procedure = procedure + "SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpFailProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testSelectIntoPhysicalGroup() {
helpValidate("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] { }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpValidateProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testSelectIntoPhysicalGroupNotUpdateable_Defect16857() {
helpValidate("SELECT e0, e1, e2 INTO test.group3 FROM test.group2", new String[] {"test.group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testSelectIntoElementsNotUpdateable() {
helpValidate("SELECT e0, e1, e2 INTO test.group2 FROM test.group3", new String[] {"test.group2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidSelectIntoTooManyElements() {
helpValidate("SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpFailProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testInvalidSelectIntoTooFewElements() {
helpValidate("SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpFailProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testInvalidSelectIntoIncorrectTypes() {
helpValidate("SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpFailProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testSelectIntoWithStar() {
helpResolve("SELECT * INTO pm1.g1 FROM pm1.g2", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testInvalidSelectIntoWithStar() {
helpValidate("SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1", new String[] {"SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpFailProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testSelectIntoVirtualGroup() {
helpValidate("SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
String procedure = "FOR EACH ROW "; //$NON-NLS-1$
procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
procedure = procedure + "SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
procedure = procedure + "END\n"; //$NON-NLS-1$
String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
helpValidateProcedure(procedure, userQuery,
Table.TriggerEvent.UPDATE);
}
@Test public void testVirtualProcedure2(){
helpValidate("EXEC pm1.vsp13()", new String[] { }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
//procedure that has another procedure in the transformation
@Test public void testVirtualProcedure3(){
helpValidate("EXEC pm1.vsp27()", new String[] { }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testNonEmbeddedSubcommand_defect11000() {
helpValidate("SELECT e0 FROM vTest.vGroup", new String[0], exampleMetadata()); //$NON-NLS-1$
}
@Test public void testValidateObjectInComparison() throws Exception {
String sql = "SELECT IntKey FROM BQT1.SmallA WHERE ObjectValue = 5"; //$NON-NLS-1$
ValidatorReport report = helpValidate(sql, new String[] {"ObjectValue = 5"}, RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
assertEquals("Non-comparable expression of type object cannot be used in comparison: ObjectValue = 5.", report.toString()); //$NON-NLS-1$
}
@Test public void testValidateAssignmentWithFunctionOnParameter_InServer() throws Exception{
String sql = "EXEC pm1.vsp36(5)"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
Command command = new QueryParser().parseCommand(sql);
QueryResolver.resolveCommand(command, metadata);
// Validate
ValidatorReport report = Validator.validate(command, metadata);
assertEquals(0, report.getItems().size());
}
@Test public void testDefect9917() throws Exception{
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
String sql = "SELECT lookup('pm1.g1', 'e1a', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
Command command = new QueryParser().parseCommand(sql);
try{
QueryResolver.resolveCommand(command, metadata);
fail("Did not get exception"); //$NON-NLS-1$
}catch(QueryResolverException e){
//expected
}
sql = "SELECT lookup('pm1.g1a', 'e1', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
command = new QueryParser().parseCommand(sql);
try{
QueryResolver.resolveCommand(command, metadata);
fail("Did not get exception"); //$NON-NLS-1$
}catch(QueryResolverException e){
//expected
}
}
@Test public void testLookupKeyElementComparable() throws Exception {
QueryMetadataInterface metadata = exampleMetadata2();
String sql = "SELECT lookup('test.group', 'e2', 'e3', convert(e2, blob)) AS x FROM test.group"; //$NON-NLS-1$
Command command = QueryParser.getQueryParser().parseCommand(sql);
QueryResolver.resolveCommand(command, metadata);
ValidatorReport report = Validator.validate(command, metadata);
assertEquals("Non-comparable expression of type blob cannot be used as LOOKUP key columns: test.\"group\".e3.", report.toString()); //$NON-NLS-1$
}
@Test public void testDefect12107() throws Exception{
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
String sql = "SELECT SUM(DISTINCT lookup('pm1.g1', 'e2', 'e2', e2)) FROM pm1.g1"; //$NON-NLS-1$
Command command = helpResolve(sql, metadata);
sql = "SELECT SUM(DISTINCT lookup('pm1.g1', 'e3', 'e2', e2)) FROM pm1.g1"; //$NON-NLS-1$
command = helpResolve(sql, metadata);
ValidatorReport report = Validator.validate(command, metadata);
assertEquals("The aggregate function SUM cannot be used with non-numeric expressions: SUM(DISTINCT lookup('pm1.g1', 'e3', 'e2', e2))", report.toString()); //$NON-NLS-1$
}
private ValidatorReport helpValidateInModeler(String procName, String procSql, QueryMetadataInterface metadata) throws Exception {
Command command = QueryParser.getQueryParser().parseCommand(procSql);
GroupSymbol group = new GroupSymbol(procName);
QueryResolver.resolveCommand(command, group, Command.TYPE_STORED_PROCEDURE, metadata, true);
// Validate
return Validator.validate(command, metadata);
}
@Test public void testValidateDynamicCommandWithNonTempGroup_InModeler() throws Exception{
// SQL is same as pm1.vsp36() in example1
String sql = "CREATE VIRTUAL PROCEDURE BEGIN execute string 'select ' || '1' as X integer into pm1.g3; END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
assertEquals(1, report.getItems().size());
assertEquals("Wrong number of elements being SELECTed INTO the target table. Expected 4 elements, but was 1.", report.toString()); //$NON-NLS-1$
}
@Test public void testValidateInModeler() throws Exception{
// SQL is same as pm1.vsp36() in example1
String sql = "CREATE VIRTUAL PROCEDURE BEGIN select 1, 2; END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
Command command = QueryParser.getQueryParser().parseCommand(sql);
GroupSymbol group = new GroupSymbol("pm1.vsp36");
QueryResolver.resolveCommand(command, group, Command.TYPE_STORED_PROCEDURE, metadata, true);
assertEquals(2, command.getResultSetColumns().size());
}
@Test public void testDynamicDupUsing() throws Exception {
String sql = "CREATE VIRTUAL PROCEDURE BEGIN execute string 'select ' || '1' as X integer into #temp using id=1, id=2; END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
assertEquals(1, report.getItems().size());
assertEquals("Elements cannot appear more than once in a SET or USING clause. The following elements are duplicated: [DVARS.id]", report.toString()); //$NON-NLS-1$
}
@Test public void testValidateAssignmentWithFunctionOnParameter_InModeler() throws Exception{
// SQL is same as pm1.vsp36() in example1
String sql = "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x = pm1.vsp36.param1 * 2; SELECT x; END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
assertEquals(0, report.getItems().size());
}
@Test public void testDefect12533() {
String sql = "SELECT BQT1.SmallA.DateValue, BQT2.SmallB.ObjectValue FROM BQT1.SmallA, BQT2.SmallB " + //$NON-NLS-1$
"WHERE BQT1.SmallA.DateValue = BQT2.SmallB.DateValue AND BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue " + //$NON-NLS-1$
"AND BQT1.SmallA.IntKey < 30 AND BQT2.SmallB.IntKey < 30 ORDER BY BQT1.SmallA.DateValue"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
// Validate
helpValidate(sql, new String[] {"BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue"}, metadata); //$NON-NLS-1$
}
@Test public void testDefect16772() throws Exception{
String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) SELECT 1 AS x; ELSE SELECT 0 AS x; END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata); //$NON-NLS-1$
assertEquals("Expected report to have no validation failures", false, report.hasItems()); //$NON-NLS-1$
}
@Test public void testDupLabel() throws Exception{
String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) x : begin SELECT 1 AS x; x: begin atomic select 2 as x; end end END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata); //$NON-NLS-1$
examineReport(sql, new String[] {"x : BEGIN ATOMIC\nSELECT 2 AS x;\nEND"}, report);
}
@Test public void testInvalidContinue() throws Exception{
String sql = "CREATE VIRTUAL PROCEDURE BEGIN continue; END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata); //$NON-NLS-1$
examineReport(sql, new String[] {"CONTINUE;"}, report);
}
@Test public void testInvalidLabel() throws Exception{
String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) x : begin continue y; end END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata); //$NON-NLS-1$
examineReport(sql, new String[] {"CONTINUE y;"}, report);
}
@Test public void testNonQueryAgg() throws Exception{
String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (max(pm1.vsp42.param1) > 0) SELECT 1 AS x; ELSE SELECT 0 AS x; END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata); //$NON-NLS-1$
examineReport(sql, new String[] {"MAX(pm1.vsp42.param1)"}, report);
}
@Test public void testDefect14886() throws Exception{
String sql = "CREATE VIRTUAL PROCEDURE BEGIN END"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
Command command = new QueryParser().parseCommand(sql);
QueryResolver.resolveCommand(command, metadata);
// Validate
ValidatorReport report = Validator.validate(command, metadata);
// Validate
assertEquals(0, report.getItems().size());
}
@Test public void testDefect21389() throws Exception{
String sql = "CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temptable FROM pm1.g1; INSERT INTO #temptable (e1) VALUES ('a'); END"; //$NON-NLS-1$
TransformationMetadata metadata = RealMetadataFactory.example1();
Column c = metadata.getElementID("pm1.g1.e1"); //$NON-NLS-1$
c.setUpdatable(false);
Command command = new QueryParser().parseCommand(sql);
QueryResolver.resolveCommand(command, metadata);
// Validate
ValidatorReport report = Validator.validate(command, metadata);
// Validate
assertEquals(0, report.getItems().size());
}
@Test public void testMakeNotDep() {
helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKENOTDEP group2, group3", new String[0], exampleMetadata()); //$NON-NLS-1$
}
@Test public void testInvalidMakeNotDep() {
helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKEDEP group2 MAKENOTDEP group2, group3", new String[] {"OPTION MAKEDEP group2 MAKENOTDEP group2, group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Test case 4237. This test simulates the way the modeler transformation
* panel uses the query resolver and validator to validate a transformation for
* a virtual procedure. The modeler has to supply external metadata for the
* virtual procedure group and parameter names (simulated in this test).
*
* This virtual procedure calls a physical stored procedure directly.
*/
@Test public void testCase4237() throws Exception {
QueryMetadataInterface metadata = helpCreateCase4237VirtualProcedureMetadata();
String sql = "CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sp(vm1.sp.in1); END"; //$NON-NLS-1$
Command command = helpResolve(sql, new GroupSymbol("vm1.sp"), Command.TYPE_STORED_PROCEDURE, metadata);
helpRunValidator(command, new String[0], metadata);
}
/**
* This test was already working before the case was logged, due for some reason
* to the exec() statement being inside an inline view. This is a control test.
*/
@Test public void testCase4237InlineView() throws Exception {
QueryMetadataInterface metadata = helpCreateCase4237VirtualProcedureMetadata();
String sql = "CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM (EXEC pm1.sp(vm1.sp.in1)) AS FOO; END"; //$NON-NLS-1$
Command command = helpResolve(sql, new GroupSymbol("vm1.sp"), Command.TYPE_STORED_PROCEDURE, metadata);
helpRunValidator(command, new String[0], metadata);
}
/**
* Create fake metadata for this case. Need a physical stored procedure and
* a virtual stored procedure which calls the physical one.
* @return
*/
private TransformationMetadata helpCreateCase4237VirtualProcedureMetadata() {
MetadataStore metadataStore = new MetadataStore();
Schema physicalModel = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
ColumnSet<Procedure> resultSet = RealMetadataFactory.createResultSet("pm1.rs", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ProcedureParameter inParam = RealMetadataFactory.createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
Procedure storedProcedure = RealMetadataFactory.createStoredProcedure("sp", physicalModel, Arrays.asList(inParam)); //$NON-NLS-1$ //$NON-NLS-2$
storedProcedure.setResultSet(resultSet);
Schema virtualModel = RealMetadataFactory.createVirtualModel("vm1", metadataStore); //$NON-NLS-1$
ColumnSet<Procedure> virtualResultSet = RealMetadataFactory.createResultSet("vm1.rs", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ProcedureParameter virtualInParam = RealMetadataFactory.createParameter("in1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
QueryNode queryNode = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sp(vm1.sp.in1); END"); //$NON-NLS-1$ //$NON-NLS-2$
Procedure virtualStoredProcedure = RealMetadataFactory.createVirtualProcedure("sp", virtualModel, Arrays.asList(virtualInParam), queryNode); //$NON-NLS-1$
virtualStoredProcedure.setResultSet(virtualResultSet);
return RealMetadataFactory.createTransformationMetadata(metadataStore, "case4237");
}
@Test public void testSelectIntoWithNull() {
helpValidate("SELECT null, null, null, null INTO pm1.g1 FROM pm1.g2", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testCreateWithNonSortablePrimaryKey() {
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
Command command = helpResolve("create local temporary table x (column1 string, column2 clob, primary key (column2))", metadata); //$NON-NLS-1$
helpRunValidator(command, new String[] {"column2"}, RealMetadataFactory.example1Cached());
}
@Test public void testDropNonTemporary() {
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
Command command = helpResolve("drop table pm1.g1", metadata); //$NON-NLS-1$
helpRunValidator(command, new String[] {command.toString()}, RealMetadataFactory.example1Cached());
}
@Test public void testNestedContexts() {
helpValidate("SELECT * FROM vm1.doc1 where context(a0, context(a0, a2))='x'", new String[] {"context(a0, context(a0, a2))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidContextElement() {
helpValidate("SELECT * FROM vm1.doc1 where context(1, a2)='x'", new String[] {"context(1, a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInsertIntoVirtualWithQuery() throws Exception {
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
Command command = helpResolve("insert into vm1.g1 select 1, 2, true, 3", metadata); //$NON-NLS-1$
ValidatorReport report = Validator.validate(command, metadata);
assertTrue(report.getItems().isEmpty());
}
@Test public void testDynamicIntoDeclaredTemp() throws Exception {
StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE ") //$NON-NLS-1$
.append("BEGIN\n") //$NON-NLS-1$
.append("CREATE LOCAL TEMPORARY TABLE x (column1 string);") //$NON-NLS-1$
.append("execute string 'SELECT e1 FROM pm1.g2' as e1 string INTO x;\n") //$NON-NLS-1$
.append("select cast(column1 as integer) from x;\n") //$NON-NLS-1$
.append("END\n"); //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata); //$NON-NLS-1$
assertEquals(report.toString(), 0, report.getItems().size());
}
@Test public void testVariablesGroupSelect() {
String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
procedure += "BEGIN\n"; //$NON-NLS-1$
procedure += "DECLARE integer VARIABLES.var1 = 1;\n"; //$NON-NLS-1$
procedure += "select * from variables;\n"; //$NON-NLS-1$
procedure += "END\n"; //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
Command command = helpResolve(procedure, metadata);
helpRunValidator(command, new String[] {"variables"}, metadata); //$NON-NLS-1$
}
@Test public void testClobEquals() {
TestValidator.helpValidate("SELECT * FROM test.group where e4 = '1'", new String[] {"e4 = '1'"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Should not fail since the update changing set is not really criteria
*/
@Test public void testUpdateWithClob() {
TestValidator.helpValidate("update test.group set e4 = ?", new String[] {}, TestValidator.exampleMetadata2()); //$NON-NLS-1$
}
@Test public void testBlobLessThan() {
TestValidator.helpValidate("SELECT * FROM test.group where e3 < ?", new String[] {"e3 < ?"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateCompare2() {
helpValidate("SELECT e2 FROM test.group WHERE e4 IS NULL", new String[] {}, exampleMetadata2()); //$NON-NLS-1$
}
@Test public void testValidateCompare3() {
helpValidate("SELECT e2 FROM test.group WHERE e4 IN ('a')", new String[] {"e4 IN ('a')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateCompare5() {
helpValidate("SELECT e2 FROM test.group WHERE e4 BETWEEN '1' AND '2'", new String[] {"e4 BETWEEN '1' AND '2'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateCompareInHaving1() {
helpValidate("SELECT e1 FROM test.group GROUP BY e1 HAVING convert(e1, clob) = 'a'", new String[] {"convert(e1, clob) = 'a'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateNoExpressionName() {
helpValidate("SELECT xmlelement(name a, xmlattributes('1'))", new String[] {"XMLATTRIBUTES('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateNoExpressionName1() {
helpValidate("SELECT xmlforest('1')", new String[] {"XMLFOREST('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testXpathValueValid_defect15088() {
String userSql = "SELECT xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', 'a/b/c')"; //$NON-NLS-1$
helpValidate(userSql, new String[] {}, RealMetadataFactory.exampleBQTCached());
}
@Test public void testXpathValueInvalid_defect15088() throws Exception {
String userSql = "SELECT xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', '//*[local-name()=''bookName\"]')"; //$NON-NLS-1$
helpValidate(userSql, new String[] {"xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', '//*[local-name()=''bookName\"]')"}, RealMetadataFactory.exampleBQTCached());
}
@Test public void testTextTableNoWidth() {
helpValidate("SELECT * from texttable(null columns x string width 1, y integer) as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH 1, y integer) AS x"}, RealMetadataFactory.exampleBQTCached());
}
@Test public void testTextTableInvalidDelimiter() {
helpValidate("SELECT * from texttable(null columns x string width 1 DELIMITER 'z') as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH 1 DELIMITER 'z') AS x"}, RealMetadataFactory.exampleBQTCached());
}
@Test public void testTextTableNoRowDelimiter() {
helpValidate("SELECT * from texttable(null columns x string NO ROW DELIMITER) as x", new String[] {"TEXTTABLE(null COLUMNS x string NO ROW DELIMITER) AS x"}, RealMetadataFactory.exampleBQTCached());
}
@Test public void testTextTableFixedSelector() {
helpValidate("SELECT * from texttable(null SELECTOR 'a' columns x string width 1) as x", new String[] {}, RealMetadataFactory.exampleBQTCached());
}
@Test public void testXMLNamespaces() {
helpValidate("select xmlforest(xmlnamespaces(no default, default 'http://foo'), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES(NO DEFAULT, DEFAULT 'http://foo')"}, RealMetadataFactory.example1Cached());
}
@Test public void testXMLNamespacesInvalid() {
helpValidate("select xmlforest(xmlnamespaces('http://foo' as \"1\"), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES('http://foo' AS \"1\")"}, RealMetadataFactory.example1Cached());
}
@Test public void testXMLNamespacesReserved() {
helpValidate("select xmlforest(xmlnamespaces('http://foo' as xmlns), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES('http://foo' AS xmlns)"}, RealMetadataFactory.example1Cached());
}
@Test public void testXMLTablePassingMultipleContext() {
helpValidate("select * from pm1.g1, xmltable('/' passing xmlparse(DOCUMENT '<a/>'), xmlparse(DOCUMENT '<b/>')) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>'), XMLPARSE(DOCUMENT '<b/>')) AS x"}, RealMetadataFactory.example1Cached());
}
@Test public void testInvalidDefault() {
helpValidate("select * from pm1.g1, xmltable('/' passing xmlparse(DOCUMENT '<a/>') columns y string default 'a', x string default (select e1 from pm1.g1)) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>') COLUMNS y string DEFAULT 'a', x string DEFAULT (SELECT e1 FROM pm1.g1)) AS x"}, RealMetadataFactory.example1Cached());
}
@Ignore("this is actually handled by saxon and will show up during resolving")
@Test public void testXMLTablePassingSameName() {
helpValidate("select * from pm1.g1, xmltable('/' passing {x '<a/>'} as a, {x '<b/>'} as a) as x", new String[] {"xmltable('/' passing e1, e1 || 'x') as x"}, RealMetadataFactory.example1Cached());
}
@Test public void testXMLTablePassingContextType() {
helpValidate("select * from pm1.g1, xmltable('/' passing 2) as x", new String[] {"XMLTABLE('/' PASSING 2) AS x"}, RealMetadataFactory.example1Cached());
}
@Test public void testXMLTableMultipleOrdinals() {
helpValidate("select * from pm1.g1, xmltable('/' passing XMLPARSE(DOCUMENT '<a/>') columns x for ordinality, y for ordinality) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>') COLUMNS x FOR ORDINALITY, y FOR ORDINALITY) AS x"}, RealMetadataFactory.example1Cached());
}
@Test public void testXMLTableContextRequired() {
helpValidate("select * from xmltable('/a/b' passing convert('<a/>', xml) as a columns x for ordinality, c integer path '.') as x", new String[] {"XMLTABLE('/a/b' PASSING convert('<a/>', xml) AS a COLUMNS x FOR ORDINALITY, c integer PATH '.') AS x"}, RealMetadataFactory.example1Cached());
}
@Test public void testObjectTablePassing() {
helpValidate("select * from objecttable('x' passing 'a' columns c integer 'row') as x", new String[] {"OBJECTTABLE('x' PASSING 'a' COLUMNS c integer 'row') AS x"}, RealMetadataFactory.example1Cached());
}
@Test public void testObjectTablePassingSameName() {
helpValidate("select * from objecttable('x' passing 'a' AS X, 'b' AS x columns c integer 'row') as x", new String[] {"OBJECTTABLE('x' PASSING 'a' AS X, 'b' AS x COLUMNS c integer 'row') AS x"}, RealMetadataFactory.example1Cached());
}
@Test public void testObjectTableLanguage() {
helpValidate("select * from objecttable(language 'foo!' 'x' columns c integer 'row') as x", new String[] {"OBJECTTABLE(LANGUAGE 'foo!' 'x' COLUMNS c integer 'row') AS x"}, RealMetadataFactory.example1Cached());
}
@Test public void testObjectTableScript() {
helpValidate("select * from objecttable('this. is not valid' columns c integer 'row') as x", new String[] {"OBJECTTABLE('this. is not valid' COLUMNS c integer 'row') AS x"}, RealMetadataFactory.example1Cached());
}
@Test public void testXMLQueryPassingContextType() {
helpValidate("select xmlquery('/' passing 2)", new String[] {"XMLQUERY('/' PASSING 2)"}, RealMetadataFactory.example1Cached());
}
@Test public void testQueryString() {
helpValidate("select querystring('/', '1')", new String[] {"QUERYSTRING('/', '1')"}, RealMetadataFactory.example1Cached());
}
@Test public void testXmlNameValidation() throws Exception {
helpValidate("select xmlelement(\":\")", new String[] {"XMLELEMENT(NAME \":\")"}, RealMetadataFactory.example1Cached());
}
@Test public void testXmlParse() throws Exception {
helpValidate("select xmlparse(content e2) from pm1.g1", new String[] {"XMLPARSE(CONTENT e2)"}, RealMetadataFactory.example1Cached());
}
@Test public void testDecode() throws Exception {
helpValidate("select to_bytes(e1, '?') from pm1.g1", new String[] {"to_bytes(e1, '?')"}, RealMetadataFactory.example1Cached());
}
@Test public void testValidateXMLAGG() {
helpValidate("SELECT XMLAGG(e1) from pm1.g1", new String[] {"XMLAGG(e1)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateBooleanAgg() {
helpValidate("SELECT EVERY(e1) from pm1.g1", new String[] {"EVERY(e1)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateStatAgg() {
helpValidate("SELECT stddev_pop(distinct e2) from pm1.g1", new String[] {"STDDEV_POP(DISTINCT e2)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testValidateScalarSubqueryTooManyColumns() {
helpValidate("SELECT e2, (SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidIntoSubquery() {
helpValidate("SELECT e2, (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidIntoSubquery1() {
helpValidate("SELECT e2 FROM pm1.g2 WHERE EXISTS (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidIntoSubquery2() {
helpValidate("SELECT * FROM (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') x", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidIntoSubquery3() {
helpValidate("SELECT e2 FROM pm1.g2 WHERE e2 in (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testInvalidIntoSubquery4() throws Exception {
StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE\n") //$NON-NLS-1$
.append("BEGIN\n") //$NON-NLS-1$
.append("loop on (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') as x\n") //$NON-NLS-1$
.append("BEGIN\nSELECT 1;\nEND\nSELECT 1\n;END\n"); //$NON-NLS-1$
QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
// Validate
ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata); //$NON-NLS-1$
examineReport(procedure, new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, report);
}
@Test public void testDisallowUpdateOnMultisourceElement() throws Exception {
Set<String> models = new HashSet<String>();
models.add("pm1");
ValidatorReport report = helpValidateInModeler("pm1.vsp36", "UPDATE PM1.G1 set SOURCE_NAME='blah'", new MultiSourceMetadataWrapper(RealMetadataFactory.example1(), models)); //$NON-NLS-1$
assertEquals(report.toString(), 1, report.getItems().size());
}
@Test public void testMultiSourceInsert() throws Exception {
Set<String> models = new HashSet<String>();
models.add("pm1");
helpValidate("insert into pm1.g1 (e1) values (1)", new String[] {"pm1.g1", "pm1.g1.SOURCE_NAME"}, new MultiSourceMetadataWrapper(RealMetadataFactory.example1(), models)); //$NON-NLS-1$
}
/**
* TODO: this should be allowable
*/
@Test public void testDisallowProjectIntoMultiSource() throws Exception {
Set<String> models = new HashSet<String>();
models.add("pm1");
helpValidate("insert into pm1.g1 select pm1.g1.*, 1 from pm1.g1", new String[] {"pm1.g1"}, new MultiSourceMetadataWrapper(RealMetadataFactory.example1(), models)); //$NON-NLS-1$
}
@Test public void testTextAggEncoding() throws Exception {
helpValidate("select textagg(for e1 encoding abc) from pm1.g1", new String[] {"TEXTAGG(FOR e1 ENCODING abc)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testTextAggHeader() throws Exception {
helpValidate("select textagg(for e1 || 1 HEADER) from pm1.g1", new String[] {"TEXTAGG(FOR (e1 || 1) HEADER)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testMultiSourceProcValue() throws Exception {
Set<String> models = new HashSet<String>();
models.add("MultiModel");
helpValidate("exec MultiModel.proc('a', (select 1))", new String[] {}, new MultiSourceMetadataWrapper(RealMetadataFactory.exampleMultiBinding(), models)); //$NON-NLS-1$
}
@Test public void testFailAggregateInGroupBy() {
helpValidate("SELECT max(e1) FROM pm1.g1 GROUP BY count(e2)", new String[] {"COUNT(e2)"}, RealMetadataFactory.example1Cached());
}
@Test public void testFailAggregateInWhere() {
helpValidate("SELECT e1 FROM pm1.g1 where count(e2) = 1", new String[] {"COUNT(e2)"}, RealMetadataFactory.example1Cached());
}
@Test public void testFailAggregateInFrom() {
helpValidate("SELECT g2.e1 FROM pm1.g1 inner join pm1.g2 on (avg(g1.e2) = g2.e2)", new String[] {"AVG(g1.e2)"}, RealMetadataFactory.example1Cached());
}
@Test public void testFailAggregateFilterSubquery() {
helpValidate("SELECT min(g1.e1) filter (where (select 1) = 1) from pm1.g1", new String[] {"(SELECT 1) = 1"}, RealMetadataFactory.example1Cached());
}
@Test public void testNestedAgg() {
helpValidate("SELECT min(g1.e1) filter (where max(e2) = 1) from pm1.g1", new String[] {"MAX(e2)"}, RealMetadataFactory.example1Cached());
}
@Test public void testWindowFunction() {
helpValidate("SELECT e1 from pm1.g1 where row_number() over (order by e2) = 1", new String[] {"ROW_NUMBER() OVER (ORDER BY e2)"}, RealMetadataFactory.example1Cached());
}
@Test public void testWindowFunction1() {
helpValidate("SELECT 1 from pm1.g1 having row_number() over (order by e2) = 1", new String[] {"e2", "ROW_NUMBER() OVER (ORDER BY e2)"}, RealMetadataFactory.example1Cached());
}
@Test public void testWindowFunctionWithoutOrdering() {
helpValidate("SELECT row_number() over () from pm1.g1", new String[] {"ROW_NUMBER() OVER ()"}, RealMetadataFactory.example1Cached());
}
@Test public void testWindowFunctionWithNestedOrdering() {
helpValidate("SELECT xmlagg(xmlelement(name x, e1) order by e2) over () from pm1.g1", new String[] {"XMLAGG(XMLELEMENT(NAME x, e1) ORDER BY e2) OVER ()"}, RealMetadataFactory.example1Cached());
}
@Test public void testWindowFunctionWithNestedaggAllowed() {
helpValidate("SELECT max(e1) over (order by max(e2)) from pm1.g1 group by e1", new String[] {}, RealMetadataFactory.example1Cached());
}
@Test public void testWindowFunctionWithNestedaggAllowed1() {
helpValidate("SELECT max(min(e1)) over (order by max(e2)) from pm1.g1 group by e1", new String[] {"MIN(e1)"}, RealMetadataFactory.example1Cached());
}
@Test public void testWindowFunctionWithoutFrom() {
helpValidate("select count(*) over () as y", new String[] {"COUNT(*) OVER ()"}, RealMetadataFactory.example1Cached());
}
@Test public void testWindowFunctionOrderedDistinct() {
helpValidate("select count(distinct e1) over (order by e2) as y from pm1.g1", new String[] {"COUNT(DISTINCT e1) OVER (ORDER BY e2)"}, RealMetadataFactory.example1Cached());
}
@Test public void testInvalidCorrelation() {
helpValidate("SELECT XMLELEMENT(NAME metadata, XMLFOREST(e1 AS objectName), (SELECT XMLAGG(XMLELEMENT(NAME subTypes, XMLFOREST(e1))) FROM pm1.g2 AS b WHERE b.e2 = a.e2)) FROM pm1.g1 AS a GROUP BY e1", new String[] {"a.e2"}, RealMetadataFactory.example1Cached());
}
@Test public void testUpdateError() {
String userUpdateStr = "UPDATE vm1.g2 SET e1='x'"; //$NON-NLS-1$
helpValidate(userUpdateStr, new String[]{"vm1.g2", "UPDATE vm1.g2 SET e1 = 'x'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testInsertError() {
String userUpdateStr = "INSERT into vm1.g2 (e1) values ('x')"; //$NON-NLS-1$
helpValidate(userUpdateStr, new String[]{"vm1.g2", "INSERT INTO vm1.g2 (e1) VALUES ('x')"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testMergeNoKey() {
String userUpdateStr = "MERGE into pm1.g2 (e1) values ('x')"; //$NON-NLS-1$
helpValidate(userUpdateStr, new String[]{"MERGE INTO pm1.g2 (e1) VALUES ('x')"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testDeleteError() {
String userUpdateStr = "DELETE from vm1.g2 where e1='x'"; //$NON-NLS-1$
helpValidate(userUpdateStr, new String[]{"vm1.g2"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testJsonArrayBlob() {
String sql = "select jsonArray(to_bytes('hello', 'us-ascii'))"; //$NON-NLS-1$
helpValidate(sql, new String[]{"jsonArray(to_bytes('hello', 'us-ascii'))"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testJsonArrayClob() {
String sql = "select jsonArray(cast('hello' as clob))"; //$NON-NLS-1$
helpValidate(sql, new String[]{}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testJsonObject() {
String sql = "select jsonObject(to_bytes('hello', 'us-ascii'))"; //$NON-NLS-1$
helpValidate(sql, new String[]{"JSONOBJECT(to_bytes('hello', 'us-ascii'))"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testWithValidation() {
String sql = "with a as (select jsonObject(to_bytes('hello', 'us-ascii')) as x) select a.x from a"; //$NON-NLS-1$
helpValidate(sql, new String[]{"JSONOBJECT(to_bytes('hello', 'us-ascii'))"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
}
@Test public void testInsertIntoVirtualWithQueryExpression() {
QueryMetadataInterface qmi = RealMetadataFactory.example1();
String sql = "select * from vm1.g1 as x"; //$NON-NLS-1$
TestProcessor.helpGetPlan(sql, qmi);
sql = "insert into vm1.g1 (e1, e2, e3, e4) select * from pm1.g1"; //$NON-NLS-1$
helpValidate(sql, new String[] {}, qmi);
}
}
| lgpl-2.1 |
jzuijlek/Lucee | core/src/main/java/lucee/runtime/ComponentScopeShadow.java | 11877 | /**
* 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 lucee.commons.collection.MapFactory;
import lucee.commons.collection.MapPro;
import lucee.commons.lang.CFTypes;
import lucee.runtime.component.Member;
import lucee.runtime.config.NullSupportHelper;
import lucee.runtime.dump.DumpData;
import lucee.runtime.dump.DumpProperties;
import lucee.runtime.dump.DumpTable;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.op.Duplicator;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.UDF;
import lucee.runtime.type.UDFPlus;
import lucee.runtime.type.dt.DateTime;
import lucee.runtime.type.it.EntryIterator;
import lucee.runtime.type.it.KeyIterator;
import lucee.runtime.type.it.StringIterator;
import lucee.runtime.type.it.ValueIterator;
import lucee.runtime.type.util.ComponentUtil;
import lucee.runtime.type.util.KeyConstants;
import lucee.runtime.type.util.MemberUtil;
import lucee.runtime.type.util.StructSupport;
import lucee.runtime.type.util.StructUtil;
public class ComponentScopeShadow extends StructSupport implements ComponentScope {
private static final long serialVersionUID = 4930100230796574243L;
private final ComponentImpl component;
private static final int access = Component.ACCESS_PRIVATE;
private final MapPro<Key, Object> shadow;
/**
* Constructor of the class
*
* @param component
* @param shadow
*/
public ComponentScopeShadow(ComponentImpl component, MapPro shadow) {
this.component = component;
this.shadow = shadow;
}
/**
* Constructor of the class
*
* @param component
* @param shadow
*/
public ComponentScopeShadow(ComponentImpl component, ComponentScopeShadow scope, boolean cloneShadow) {
this.component = component;
this.shadow = cloneShadow ? (MapPro) Duplicator.duplicateMap(scope.shadow, MapFactory.getConcurrentMap(), false) : scope.shadow;
}
@Override
public Component getComponent() {
return component.top;
}
@Override
public int getType() {
return SCOPE_VARIABLES;
}
@Override
public String getTypeAsString() {
return "variables";
}
@Override
public void initialize(PageContext pc) {}
@Override
public boolean isInitalized() {
return component.isInitalized();
}
@Override
public void release(PageContext pc) {}
@Override
public void clear() {
shadow.clear();
}
@Override
public boolean containsKey(Collection.Key key) {
return get(key, null) != null;
}
@Override
public Object get(Key key) throws PageException {
Object o = get(key, NullSupportHelper.NULL());
if (o != NullSupportHelper.NULL()) return o;
throw new ExpressionException("Component [" + component.getCallName() + "] has no accessible Member with name [" + key + "]");
}
@Override
public Object get(Key key, Object defaultValue) {
if (key.equalsIgnoreCase(KeyConstants._SUPER)) {
Component ac = ComponentUtil.getActiveComponent(ThreadLocalPageContext.get(), component);
return SuperComponent.superInstance((ComponentImpl) ac.getBaseComponent());
}
if (key.equalsIgnoreCase(KeyConstants._THIS)) return component.top;
if (key.equalsIgnoreCase(KeyConstants._STATIC)) return component.staticScope();
if (NullSupportHelper.full()) return shadow.g(key, defaultValue);
Object o = shadow.get(key);
if (o != null) return o;
return defaultValue;
}
@Override
public Iterator<Collection.Key> keyIterator() {
return new KeyIterator(keys());
}
@Override
public Iterator<String> keysAsStringIterator() {
return new StringIterator(keys());
}
@Override
public Iterator<Entry<Key, Object>> entryIterator() {
return new EntryIterator(this, keys());
}
@Override
public Iterator<Object> valueIterator() {
return new ValueIterator(this, keys());
}
@Override
public Collection.Key[] keys() {
Collection.Key[] keys = new Collection.Key[shadow.size() + 1];
Iterator<Key> it = shadow.keySet().iterator();
int index = 0;
while (it.hasNext()) {
keys[index++] = it.next();
}
keys[index] = KeyConstants._THIS;
return keys;
}
@Override
public Object remove(Collection.Key key) throws PageException {
if (key.equalsIgnoreCase(KeyConstants._this) || key.equalsIgnoreCase(KeyConstants._super) || key.equalsIgnoreCase(KeyConstants._static))
throw new ExpressionException("key [" + key.getString() + "] is part of the component and can't be removed");
if (NullSupportHelper.full()) return shadow.r(key);
Object o = shadow.remove(key);
if (o != null) return o;
throw new ExpressionException("can't remove key [" + key.getString() + "] from struct, key doesn't exist");
}
@Override
public Object removeEL(Key key) {
if (key.equalsIgnoreCase(KeyConstants._this) || key.equalsIgnoreCase(KeyConstants._super) || key.equalsIgnoreCase(KeyConstants._static)) return null;
return shadow.remove(key);
}
@Override
public Object set(Collection.Key key, Object value) throws ApplicationException {
if (key.equalsIgnoreCase(KeyConstants._this) || key.equalsIgnoreCase(KeyConstants._super) || key.equalsIgnoreCase(KeyConstants._static)) return value;
if (!component.afterConstructor && value instanceof UDF) {
component.addConstructorUDF(key, (UDF) value);
}
shadow.put(key, value);
return value;
}
@Override
public Object setEL(Collection.Key key, Object value) {
try {
return set(key, value);
}
catch (ApplicationException e) {
return value;
}
}
@Override
public int size() {
return keys().length;
}
@Override
public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) {
DumpTable cp = StructUtil.toDumpTable(this, "Component Variable Scope", pageContext, maxlevel, dp);
cp.setComment("Component: " + component.getPageSource().getComponentName());
return cp;
}
@Override
public boolean castToBooleanValue() throws PageException {
throw new ExpressionException("Can't cast Complex Object Type to a boolean value");
}
@Override
public Boolean castToBoolean(Boolean defaultValue) {
return defaultValue;
}
@Override
public DateTime castToDateTime() throws PageException {
throw new ExpressionException("Can't cast Complex Object Type to a Date Object");
}
@Override
public DateTime castToDateTime(DateTime defaultValue) {
return defaultValue;
}
@Override
public double castToDoubleValue() throws PageException {
throw new ExpressionException("Can't cast Complex Object Type to a numeric value");
}
@Override
public double castToDoubleValue(double defaultValue) {
return defaultValue;
}
@Override
public String castToString() throws PageException {
throw new ExpressionException("Can't cast Complex Object Type to a String");
}
@Override
public String castToString(String defaultValue) {
return defaultValue;
}
@Override
public int compareTo(boolean b) throws PageException {
throw new ExpressionException("can't compare Complex Object with a boolean value");
}
@Override
public int compareTo(DateTime dt) throws PageException {
throw new ExpressionException("can't compare Complex Object with a DateTime Object");
}
@Override
public int compareTo(double d) throws PageException {
throw new ExpressionException("can't compare Complex Object with a numeric value");
}
@Override
public int compareTo(String str) throws PageException {
throw new ExpressionException("can't compare Complex Object with a String");
}
/*
* public Object call(PageContext pc, String key, Object[] arguments) throws PageException { return
* call(pc, KeyImpl.init(key), arguments); }
*/
@Override
public Object call(PageContext pc, Collection.Key key, Object[] arguments) throws PageException {
// first check variables
Object o = shadow.get(key);
if (o instanceof UDFPlus) {
return ((UDFPlus) o).call(pc, key, arguments, false);
}
// then check in component
Member m = component.getMember(access, key, false, false);
if (m != null) {
if (m instanceof UDFPlus) return ((UDFPlus) m).call(pc, key, arguments, false);
}
return MemberUtil.call(pc, this, key, arguments, new short[] { CFTypes.TYPE_STRUCT }, new String[] { "struct" });
// throw ComponentUtil.notFunction(component, key, m!=null?m.getValue():null,access);
}
/*
* public Object callWithNamedValues(PageContext pc, String key,Struct args) throws PageException {
* return callWithNamedValues(pc, KeyImpl.init(key), args); }
*/
@Override
public Object callWithNamedValues(PageContext pc, Key key, Struct args) throws PageException {
// first check variables
Object o = shadow.get(key);
if (o instanceof UDFPlus) {
return ((UDFPlus) o).callWithNamedValues(pc, key, args, false);
}
Member m = component.getMember(access, key, false, false);
if (m != null) {
if (m instanceof UDFPlus) return ((UDFPlus) m).callWithNamedValues(pc, key, args, false);
return MemberUtil.callWithNamedValues(pc, this, key, args, CFTypes.TYPE_STRUCT, "struct");
// throw ComponentUtil.notFunction(component, key, m.getValue(),access);
}
return MemberUtil.callWithNamedValues(pc, this, key, args, CFTypes.TYPE_STRUCT, "struct");
// throw ComponentUtil.notFunction(component, key, null,access);
}
@Override
public Collection duplicate(boolean deepCopy) {
StructImpl sct = new StructImpl();
StructImpl.copy(this, sct, deepCopy);
return sct;
// MUST muss deepCopy checken
// return new ComponentScopeShadow(component,shadow);//new
// ComponentScopeThis(component.cloneComponentImpl());
}
/*
* public Object get(PageContext pc, String key, Object defaultValue) { return get(key,
* defaultValue); }
*/
@Override
public Object get(PageContext pc, Key key, Object defaultValue) {
return get(key, defaultValue);
}
@Override
public Object set(PageContext pc, Collection.Key propertyName, Object value) throws PageException {
return set(propertyName, value);
}
/*
* public Object setEL(PageContext pc, String propertyName, Object value) { return
* setEL(propertyName, value); }
*/
@Override
public Object setEL(PageContext pc, Collection.Key propertyName, Object value) {
return setEL(propertyName, value);
}
/*
* public Object get(PageContext pc, String key) throws PageException { return get(key); }
*/
@Override
public Object get(PageContext pc, Collection.Key key) throws PageException {
return get(key);
}
public MapPro<Key, Object> getShadow() {
return shadow;
}
@Override
public void setBind(boolean bind) {}
@Override
public boolean isBind() {
return true;
}
} | lgpl-2.1 |
tbaumeist/peersim-generic-DHT | test/peersim/dht/adversary/AdversaryManagerAbsoluteTest.java | 1059 | package peersim.dht.adversary;
import org.junit.BeforeClass;
import org.junit.Test;
import peersim.config.Configuration;
import peersim.core.Network;
import peersim.core.Node;
import peersim.dht.DHTProtocol;
import peersim.dht.base.Loader;
import static org.junit.Assert.assertTrue;
/**
* Created by baumeist on 8/11/17.
*/
public class AdversaryManagerAbsoluteTest extends Loader {
@BeforeClass
public static void setup() throws Exception {
initSimulator(Loader.BASE_PATH + "adversary_absolute.cfg");
assertTrue(Network.size() == 14);
}
@Test
public void execute() throws Exception {
int dhtId = Configuration.lookupPid("generic_dht");
int adversaryCount = 0;
for(int i =0; i < Network.size(); i++){
Node n = Network.get(i);
DHTProtocol dht = (DHTProtocol)n.getProtocol(dhtId);
if(dht.isAdversary())
adversaryCount++;
}
// should be a total of 14 nodes with 6 adversaries
assertTrue(adversaryCount == 6);
}
} | lgpl-2.1 |
jodygarnett/GeoGig | src/core/src/main/java/org/locationtech/geogig/plumbing/WalkGraphOp.java | 5647 | /* Copyright (c) 2013-2014 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Johnathan Garrett (LMN Solutions) - initial implementation
*/
package org.locationtech.geogig.plumbing;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.annotation.Nullable;
import org.locationtech.geogig.model.Bucket;
import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.RevCommit;
import org.locationtech.geogig.model.RevFeatureType;
import org.locationtech.geogig.model.RevObject;
import org.locationtech.geogig.model.RevTree;
import org.locationtech.geogig.plumbing.diff.PreOrderDiffWalk;
import org.locationtech.geogig.plumbing.diff.PreOrderDiffWalk.BucketIndex;
import org.locationtech.geogig.plumbing.diff.PreOrderDiffWalk.Consumer;
import org.locationtech.geogig.repository.AbstractGeoGigOp;
import org.locationtech.geogig.repository.NodeRef;
import org.locationtech.geogig.storage.ObjectDatabase;
import org.locationtech.geogig.storage.ObjectStore;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
public class WalkGraphOp extends AbstractGeoGigOp<Void> {
private String reference;
private Listener listener;
public static interface Listener {
public void featureType(RevFeatureType ftype);
public void commit(RevCommit commit);
public void feature(final NodeRef featureNode);
public void starTree(final NodeRef treeNode);
public void endTree(final NodeRef treeNode);
public void bucket(final BucketIndex bucketIndex, final Bucket bucket);
public void endBucket(final BucketIndex bucketIndex, final Bucket bucket);
}
public WalkGraphOp setListener(final Listener listener) {
this.listener = listener;
return this;
}
public WalkGraphOp setReference(final String reference) {
this.reference = reference;
return this;
}
@Override
protected Void _call() {
Preconditions.checkState(reference != null, "Reference not provided");
Preconditions.checkState(listener != null, "Listener not provided");
final ObjectDatabase odb = objectDatabase();
Optional<ObjectId> oid = command(RevParse.class).setRefSpec(reference).call();
Preconditions.checkArgument(oid.isPresent(), "Can't resolve reference '%s' at %s",
reference, repository().getLocation());
RevTree left = RevTree.EMPTY;
RevTree right;
RevObject revObject = odb.get(oid.get());
Preconditions.checkArgument(revObject instanceof RevCommit || revObject instanceof RevTree,
"'%s' can't be resolved to a tree: %s", reference, revObject.getType());
if (revObject instanceof RevCommit) {
RevCommit c = (RevCommit) revObject;
listener.commit(c);
right = odb.getTree(c.getTreeId());
} else {
right = (RevTree) revObject;
}
PreOrderDiffWalk walk = new PreOrderDiffWalk(left, right, odb, odb);
Consumer consumer = new Consumer() {
private WalkGraphOp.Listener listener = WalkGraphOp.this.listener;
private final ObjectStore odb = objectDatabase();
// used to report feature types only once
private Set<ObjectId> visitedTypes = new HashSet<ObjectId>();
@Override
public boolean tree(@Nullable NodeRef left, @Nullable NodeRef right) {
if (!right.getMetadataId().isNull()) {
ObjectId featureTypeId = right.getMetadataId();
if (!visitedTypes.contains(featureTypeId)) {
visitedTypes.add(featureTypeId);
listener.featureType(odb.getFeatureType(featureTypeId));
if (!featureTypeId.isNull()) {
checkExists(featureTypeId, right);
}
}
}
listener.starTree(right);
checkExists(right.getObjectId(), right);
return true;
}
@Override
public boolean feature(@Nullable NodeRef left, @Nullable NodeRef right) {
listener.feature(right);
checkExists(right.getObjectId(), right);
return true;
}
@Override
public void endTree(@Nullable NodeRef left, @Nullable NodeRef right) {
listener.endTree(right);
}
@Override
public boolean bucket(NodeRef lp, NodeRef rp, BucketIndex bucketIndex,
@Nullable Bucket left, @Nullable Bucket right) {
listener.bucket(bucketIndex, right);
checkExists(right.getObjectId(), right);
return true;
}
@Override
public void endBucket(NodeRef lp, NodeRef rp, BucketIndex bucketIndex,
@Nullable Bucket left, @Nullable Bucket right) {
listener.endBucket(bucketIndex, right);
}
private void checkExists(ObjectId id, Object o) {
if (!odb.exists(id)) {
throw new IllegalStateException("Object " + o + " not found.");
}
}
};
walk.walk(consumer);
return null;
}
}
| lgpl-2.1 |
magsilva/spin | src/test/java/spin/off/SpinOffTest.java | 2461 | /**
* Spin - transparent threading solution for non-freezing Swing applications.
* Copyright (C) 2002 Sven Meier
*
* 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 spin.off;
import javax.swing.SwingUtilities;
import junit.framework.TestCase;
import spin.Spin;
public class SpinOffTest extends TestCase {
private static final int DELAY = 3000;
private class Timer {
private long start;
public Timer() {
start = System.currentTimeMillis();
}
public long elapsed() {
return System.currentTimeMillis() - start;
}
}
public static interface OneIntProperty {
int getInt();
}
public void testEDTNotBlockedDuringInvocation() throws Exception {
class Flag {
public boolean flag1, flag2;
Throwable exception;
}
final Flag flag = new Flag();
OneIntProperty target = new OneIntProperty() {
public int getInt() {
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
}
return 0;
}
};
final OneIntProperty proxy = (OneIntProperty) Spin.off(target);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
proxy.getInt();
} catch (Throwable t) {
flag.exception = t;
} finally {
flag.flag1 = true;
}
}
});
Timer timer = new Timer();
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
flag.flag2 = true;
}
});
assertTrue("Second runnable took too long: " + timer.elapsed(), timer
.elapsed() < DELAY);
assertTrue("Second runnable didn't run", flag.flag2);
while (!flag.flag1) {
if (timer.elapsed() > DELAY * 2) {
fail("Original invocation timed out");
}
Thread.sleep(10);
}
assertNull("Unexpected exception in original invocation "
+ flag.exception, flag.exception);
}
}
| lgpl-2.1 |
BlesseNtumble/Traincraft-5 | src/main/java/train/common/blocks/tracks/BlockEnergyTrack.java | 4768 | /**
* A track that provides energy to ElectricTrains
*
* @author Spitfire4466
*/
package train.common.blocks.tracks;
import cpw.mods.fml.common.FMLCommonHandler;
import mods.railcraft.api.core.items.IToolCrowbar;
import mods.railcraft.api.tracks.ITrackPowered;
import net.minecraft.block.Block;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.IIcon;
import train.common.api.ElectricTrain;
import train.common.api.EntityRollingStock;
import train.common.library.TrackIDs;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class BlockEnergyTrack extends TrackBaseTraincraft implements ITrackPowered{
private byte delay = 0;
public double energy = 0;
public int maxEnergy = 1000;
public int maxInput = 1000;
public int output = 500;
private int transmitDistance=2;
public boolean isProvider = false;
public boolean addedToEnergyNet = false;
private Block thisBlock;
private int updateTicks = 0;
protected boolean powered = false;
public BlockEnergyTrack() {
this.speedController = SpeedControllerSteel.getInstance();
}
@Override
public TrackIDs getTrackType() {
return TrackIDs.ENERGY_TRACK;
}
private Block getThisBlock() {
if (thisBlock == null) {
thisBlock = getWorld().getBlock(getX(), getY(), getZ());
}
return thisBlock;
}
public boolean isSimulating()
{
return !FMLCommonHandler.instance().getEffectiveSide().isClient();
}
@Override
public void updateEntity() {
if (getWorld().isRemote) {
return;
}
updateTicks++;
if (isPowered() && updateTicks % 2==0) {
if(this.getEnergy()<this.getMaxEnergy())
this.energy++;
}
if (updateTicks % 50 == 0)
markBlockNeedsUpdate();
}
@Override
public IIcon getIcon() {
int meta = this.tileEntity.getBlockMetadata();
if (meta >= 6) {
if (energy > 0)
return getIcon(3);
return getIcon(2);
}
if (energy > 0)
return getIcon(1);
return getIcon(0);
}
@Override
public boolean isFlexibleRail() {
return true;
}
private void notifyNeighbors() {
Block block = getWorld().getBlock(getX(), getY(), getZ());
getWorld().notifyBlocksOfNeighborChange(getX(), getY(), getZ(), block);
getWorld().notifyBlocksOfNeighborChange(getX(), getY() - 1, getZ(), block);
markBlockNeedsUpdate();
}
@Override
public boolean blockActivated(EntityPlayer player) {
if (getWorld().isRemote) {
return false;
}
ItemStack current = player.getCurrentEquippedItem();
if ((current != null) && ((current.getItem() instanceof IToolCrowbar))) {
IToolCrowbar crowbar = (IToolCrowbar) current.getItem();
player.addChatMessage(new ChatComponentText("stored: " + ((int)this.energy) + "/"+(int)this.getMaxEnergy()+" EU"));
markBlockNeedsUpdate();
crowbar.onWhack(player, current, getX(), getY(), getZ());
sendUpdateToClient();
return true;
}
return false;
}
@Override
public void onMinecartPass(EntityMinecart cart) {
if (!(cart instanceof ElectricTrain)) {
return;
}
if ((this.energy > 20) && (((ElectricTrain) cart).fuelTrain) < (((ElectricTrain) cart).maxEnergy)) {
double transfered = this.energy * 0.05;
(((EntityRollingStock) cart).fuelTrain) += transfered;
this.energy -= transfered;
}
}
@Override
public boolean canUpdate() {
return true;
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound) {
super.writeToNBT(nbttagcompound);
nbttagcompound.setDouble("energy", energy);
nbttagcompound.setBoolean("powered", this.powered);
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound) {
super.readFromNBT(nbttagcompound);
this.energy = nbttagcompound.getDouble("energy");
this.powered = nbttagcompound.getBoolean("powered");
}
@Override
public void writePacketData(DataOutputStream data) throws IOException {
super.writePacketData(data);
data.writeDouble(this.energy);
data.writeBoolean(this.powered);
}
@Override
public void readPacketData(DataInputStream data) throws IOException {
super.readPacketData(data);
this.energy = data.readDouble();
this.powered = data.readBoolean();
markBlockNeedsUpdate();
}
@Override
public boolean isPowered() {
return this.powered;
}
@Override
public void setPowered(boolean powered) {
this.powered = powered;
}
@Override
public int getPowerPropagation(){
return this.transmitDistance;
}
public double getEnergy() {
return this.energy;
}
public double getMaxEnergy() {
return this.maxEnergy;
}
public void setEnergy(double joules) {
this.energy = (int) Math.max(Math.min(joules, getMaxEnergy()), 0.0D);
}
} | lgpl-2.1 |
raedle/univis | lib/jfreechart-1.0.1/src/org/jfree/chart/renderer/category/StatisticalBarRenderer.java | 16890 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* 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.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ---------------------------
* StatisticalBarRenderer.java
* ---------------------------
* (C) Copyright 2002-2005, by Pascal Collet and Contributors.
*
* Original Author: Pascal Collet;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Christian W. Zuckschwerdt;
*
* $Id: StatisticalBarRenderer.java,v 1.4.2.3 2005/12/02 10:40:17 mungady Exp $
*
* Changes
* -------
* 21-Aug-2002 : Version 1, contributed by Pascal Collet (DG);
* 01-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 24-Oct-2002 : Changes to dataset interface (DG);
* 05-Nov-2002 : Base dataset is now TableDataset not CategoryDataset (DG);
* 05-Feb-2003 : Updates for new DefaultStatisticalCategoryDataset (DG);
* 25-Mar-2003 : Implemented Serializable (DG);
* 30-Jul-2003 : Modified entity constructor (CZ);
* 06-Oct-2003 : Corrected typo in exception message (DG);
* 05-Nov-2004 : Modified drawItem() signature (DG);
* 15-Jun-2005 : Added errorIndicatorPaint attribute (DG);
*
*/
package org.jfree.chart.renderer.category;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.statistics.StatisticalCategoryDataset;
import org.jfree.io.SerialUtilities;
import org.jfree.ui.RectangleEdge;
import org.jfree.util.PaintUtilities;
import org.jfree.util.PublicCloneable;
/**
* A renderer that handles the drawing a bar plot where
* each bar has a mean value and a standard deviation line.
*
* @author Pascal Collet
*/
public class StatisticalBarRenderer extends BarRenderer
implements CategoryItemRenderer,
Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = -4986038395414039117L;
/** The paint used to show the error indicator. */
private transient Paint errorIndicatorPaint;
/**
* Default constructor.
*/
public StatisticalBarRenderer() {
super();
this.errorIndicatorPaint = Color.gray;
}
/**
* Returns the paint used for the error indicators.
*
* @return The paint used for the error indicators (possibly
* <code>null</code>).
*/
public Paint getErrorIndicatorPaint() {
return this.errorIndicatorPaint;
}
/**
* Sets the paint used for the error indicators (if <code>null</code>,
* the item outline paint is used instead)
*
* @param paint the paint (<code>null</code> permitted).
*/
public void setErrorIndicatorPaint(Paint paint) {
this.errorIndicatorPaint = paint;
notifyListeners(new RendererChangeEvent(this));
}
/**
* Draws the bar with its standard deviation line range for a single
* (series, category) data item.
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param dataArea the data area.
* @param plot the plot.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param data the data.
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param pass the pass index.
*/
public void drawItem(Graphics2D g2,
CategoryItemRendererState state,
Rectangle2D dataArea,
CategoryPlot plot,
CategoryAxis domainAxis,
ValueAxis rangeAxis,
CategoryDataset data,
int row,
int column,
int pass) {
// defensive check
if (!(data instanceof StatisticalCategoryDataset)) {
throw new IllegalArgumentException(
"Requires StatisticalCategoryDataset.");
}
StatisticalCategoryDataset statData = (StatisticalCategoryDataset) data;
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
drawHorizontalItem(g2, state, dataArea, plot, domainAxis,
rangeAxis, statData, row, column);
}
else if (orientation == PlotOrientation.VERTICAL) {
drawVerticalItem(g2, state, dataArea, plot, domainAxis, rangeAxis,
statData, row, column);
}
}
/**
* Draws an item for a plot with a horizontal orientation.
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param dataArea the data area.
* @param plot the plot.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param dataset the data.
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*/
protected void drawHorizontalItem(Graphics2D g2,
CategoryItemRendererState state,
Rectangle2D dataArea,
CategoryPlot plot,
CategoryAxis domainAxis,
ValueAxis rangeAxis,
StatisticalCategoryDataset dataset,
int row,
int column) {
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
// BAR Y
double rectY = domainAxis.getCategoryStart(
column, getColumnCount(), dataArea, xAxisLocation
);
int seriesCount = getRowCount();
int categoryCount = getColumnCount();
if (seriesCount > 1) {
double seriesGap = dataArea.getHeight() * getItemMargin()
/ (categoryCount * (seriesCount - 1));
rectY = rectY + row * (state.getBarWidth() + seriesGap);
}
else {
rectY = rectY + row * state.getBarWidth();
}
// BAR X
Number meanValue = dataset.getMeanValue(row, column);
double value = meanValue.doubleValue();
double base = 0.0;
double lclip = getLowerClip();
double uclip = getUpperClip();
if (uclip <= 0.0) { // cases 1, 2, 3 and 4
if (value >= uclip) {
return; // bar is not visible
}
base = uclip;
if (value <= lclip) {
value = lclip;
}
}
else if (lclip <= 0.0) { // cases 5, 6, 7 and 8
if (value >= uclip) {
value = uclip;
}
else {
if (value <= lclip) {
value = lclip;
}
}
}
else { // cases 9, 10, 11 and 12
if (value <= lclip) {
return; // bar is not visible
}
base = getLowerClip();
if (value >= uclip) {
value = uclip;
}
}
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transY1 = rangeAxis.valueToJava2D(base, dataArea, yAxisLocation);
double transY2 = rangeAxis.valueToJava2D(
value, dataArea, yAxisLocation
);
double rectX = Math.min(transY2, transY1);
double rectHeight = state.getBarWidth();
double rectWidth = Math.abs(transY2 - transY1);
Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth,
rectHeight);
Paint seriesPaint = getItemPaint(row, column);
g2.setPaint(seriesPaint);
g2.fill(bar);
if (state.getBarWidth() > 3) {
g2.setStroke(getItemStroke(row, column));
g2.setPaint(getItemOutlinePaint(row, column));
g2.draw(bar);
}
// standard deviation lines
double valueDelta = dataset.getStdDevValue(row, column).doubleValue();
double highVal = rangeAxis.valueToJava2D(
meanValue.doubleValue() + valueDelta, dataArea, yAxisLocation
);
double lowVal = rangeAxis.valueToJava2D(
meanValue.doubleValue() - valueDelta, dataArea, yAxisLocation
);
if (this.errorIndicatorPaint != null) {
g2.setPaint(this.errorIndicatorPaint);
}
else {
g2.setPaint(getItemOutlinePaint(row, column));
}
Line2D line = null;
line = new Line2D.Double(lowVal, rectY + rectHeight / 2.0d,
highVal, rectY + rectHeight / 2.0d);
g2.draw(line);
line = new Line2D.Double(highVal, rectY + rectHeight * 0.25,
highVal, rectY + rectHeight * 0.75);
g2.draw(line);
line = new Line2D.Double(lowVal, rectY + rectHeight * 0.25,
lowVal, rectY + rectHeight * 0.75);
g2.draw(line);
}
/**
* Draws an item for a plot with a vertical orientation.
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param dataArea the data area.
* @param plot the plot.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param dataset the data.
* @param row the row index (zero-based).
* @param column the column index (zero-based).
*/
protected void drawVerticalItem(Graphics2D g2,
CategoryItemRendererState state,
Rectangle2D dataArea,
CategoryPlot plot,
CategoryAxis domainAxis,
ValueAxis rangeAxis,
StatisticalCategoryDataset dataset,
int row,
int column) {
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
// BAR X
double rectX = domainAxis.getCategoryStart(
column, getColumnCount(), dataArea, xAxisLocation
);
int seriesCount = getRowCount();
int categoryCount = getColumnCount();
if (seriesCount > 1) {
double seriesGap = dataArea.getWidth() * getItemMargin()
/ (categoryCount * (seriesCount - 1));
rectX = rectX + row * (state.getBarWidth() + seriesGap);
}
else {
rectX = rectX + row * state.getBarWidth();
}
// BAR Y
Number meanValue = dataset.getMeanValue(row, column);
double value = meanValue.doubleValue();
double base = 0.0;
double lclip = getLowerClip();
double uclip = getUpperClip();
if (uclip <= 0.0) { // cases 1, 2, 3 and 4
if (value >= uclip) {
return; // bar is not visible
}
base = uclip;
if (value <= lclip) {
value = lclip;
}
}
else if (lclip <= 0.0) { // cases 5, 6, 7 and 8
if (value >= uclip) {
value = uclip;
}
else {
if (value <= lclip) {
value = lclip;
}
}
}
else { // cases 9, 10, 11 and 12
if (value <= lclip) {
return; // bar is not visible
}
base = getLowerClip();
if (value >= uclip) {
value = uclip;
}
}
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transY1 = rangeAxis.valueToJava2D(base, dataArea, yAxisLocation);
double transY2 = rangeAxis.valueToJava2D(
value, dataArea, yAxisLocation
);
double rectY = Math.min(transY2, transY1);
double rectWidth = state.getBarWidth();
double rectHeight = Math.abs(transY2 - transY1);
Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth,
rectHeight);
Paint seriesPaint = getItemPaint(row, column);
g2.setPaint(seriesPaint);
g2.fill(bar);
if (state.getBarWidth() > 3) {
g2.setStroke(getItemStroke(row, column));
g2.setPaint(getItemOutlinePaint(row, column));
g2.draw(bar);
}
// standard deviation lines
double valueDelta = dataset.getStdDevValue(row, column).doubleValue();
double highVal = rangeAxis.valueToJava2D(
meanValue.doubleValue() + valueDelta, dataArea, yAxisLocation
);
double lowVal = rangeAxis.valueToJava2D(
meanValue.doubleValue() - valueDelta, dataArea, yAxisLocation
);
if (this.errorIndicatorPaint != null) {
g2.setPaint(this.errorIndicatorPaint);
}
else {
g2.setPaint(getItemOutlinePaint(row, column));
}
Line2D line = null;
line = new Line2D.Double(rectX + rectWidth / 2.0d, lowVal,
rectX + rectWidth / 2.0d, highVal);
g2.draw(line);
line = new Line2D.Double(rectX + rectWidth / 2.0d - 5.0d, highVal,
rectX + rectWidth / 2.0d + 5.0d, highVal);
g2.draw(line);
line = new Line2D.Double(rectX + rectWidth / 2.0d - 5.0d, lowVal,
rectX + rectWidth / 2.0d + 5.0d, lowVal);
g2.draw(line);
}
/**
* Tests this renderer for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof StatisticalBarRenderer)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
StatisticalBarRenderer that = (StatisticalBarRenderer) obj;
if (!PaintUtilities.equal(this.errorIndicatorPaint,
that.errorIndicatorPaint)) {
return false;
}
return true;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.errorIndicatorPaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.errorIndicatorPaint = SerialUtilities.readPaint(stream);
}
}
| lgpl-2.1 |
TheGreyGhost/MissingTextures | src/main/java/missingtextures/mt20_texture_malformed/StartupClientOnly.java | 879 | package missingtextures.mt20_texture_malformed;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.registry.GameRegistry;
/**
* User: The Grey Ghost
* Date: 10/05/2015
*/
public class StartupClientOnly
{
public static void preInitClientOnly()
{
}
public static void initClientOnly()
{
Item itemBlockSimple = GameRegistry.findItem("missingtextures", "mt20_blockname");
ModelResourceLocation itemModelResourceLocation = new ModelResourceLocation("missingtextures:mt20_blockname", "inventory");
final int DEFAULT_ITEM_SUBTYPE = 0;
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(itemBlockSimple, DEFAULT_ITEM_SUBTYPE, itemModelResourceLocation);
}
public static void postInitClientOnly()
{
}
}
| lgpl-2.1 |
ManolitoOctaviano/Language-Identification | src/test/de/danielnaber/languagetool/AbstractSecurityTestCase.java | 2329 | /* LanguageTool, a natural language style checker
* Copyright (C) 2009 Daniel Naber (http://www.danielnaber.de)
*
* 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 de.danielnaber.languagetool;
import junit.framework.TestCase;
import java.security.Permission;
/**
* @author Charlie Collins (Maven Test Example from
* http://www.screaming-penguin.com/node/7570)
*/
public class AbstractSecurityTestCase extends TestCase {
public AbstractSecurityTestCase(String name) {
super(name);
}
protected static class ExitException extends SecurityException {
private static final long serialVersionUID = 1L;
public final int status;
public ExitException(int status) {
super("There is no escape!");
this.status = status;
}
}
private static class NoExitSecurityManager extends SecurityManager {
@Override
public void checkPermission(@SuppressWarnings("unused") Permission perm) {
// allow anything.
}
@Override
@SuppressWarnings("unused")
public void checkPermission(Permission perm, Object context) {
// allow anything.
}
@Override
public void checkExit(int status) {
super.checkExit(status);
throw new ExitException(status);
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
System.setSecurityManager(new NoExitSecurityManager());
}
@Override
protected void tearDown() throws Exception {
System.setSecurityManager(null);
super.tearDown();
}
//get rid of JUnit warning for this helper class
public void testSomething() {
}
}
| lgpl-2.1 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-properties/src/main/java/org/xwiki/properties/annotation/PropertyName.java | 1454 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.properties.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use this annotation to add a display name to a property bean method.
*
* @version $Id$
* @since 2.1M1
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Inherited
public @interface PropertyName
{
/**
* @return the description.
*/
String value();
}
| lgpl-2.1 |
GateNLP/gateplugin-LearningFramework | src/main/java/org/apache/commons/clipatched/OptionValidator.java | 3153 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.clipatched;
/**
* Validates an Option string.
*
* @version $Id: OptionValidator.java 1544819 2013-11-23 15:34:31Z tn $
* @since 1.1
*/
final class OptionValidator
{
/**
* Validates whether <code>opt</code> is a permissible Option
* shortOpt. The rules that specify if the <code>opt</code>
* is valid are:
*
* <ul>
* <li>a single character <code>opt</code> that is either
* ' '(special case), '?', '@' or a letter</li>
* <li>a multi character <code>opt</code> that only contains
* letters.</li>
* </ul>
* <p>
* In case {@code opt} is {@code null} no further validation is performed.
*
* @param opt The option string to validate, may be null
* @throws IllegalArgumentException if the Option is not valid.
*/
static void validateOption(String opt) throws IllegalArgumentException
{
// if opt is NULL do not check further
if (opt == null)
{
return;
}
// handle the single character opt
if (opt.length() == 1)
{
char ch = opt.charAt(0);
if (!isValidOpt(ch))
{
throw new IllegalArgumentException("Illegal option name '" + ch + "'");
}
}
// handle the multi character opt
else
{
for (char ch : opt.toCharArray())
{
if (!isValidChar(ch))
{
throw new IllegalArgumentException("The option '" + opt + "' contains an illegal "
+ "character : '" + ch + "'");
}
}
}
}
/**
* Returns whether the specified character is a valid Option.
*
* @param c the option to validate
* @return true if <code>c</code> is a letter, '?' or '@', otherwise false.
*/
private static boolean isValidOpt(char c)
{
return isValidChar(c) || c == '?' || c == '@';
}
/**
* Returns whether the specified character is a valid character.
*
* @param c the character to validate
* @return true if <code>c</code> is a letter.
*/
private static boolean isValidChar(char c)
{
return Character.isJavaIdentifierPart(c);
}
}
| lgpl-2.1 |
xwiki/xwiki-platform | xwiki-platform-core/xwiki-platform-extension/xwiki-platform-extension-test/xwiki-platform-extension-test-pageobjects/src/main/java/org/xwiki/extension/test/po/distribution/ReportDistributionStep.java | 1093 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.extension.test.po.distribution;
/**
* The Report step UI.
*
* @version $Id$
* @since 10.7RC1
*/
public class ReportDistributionStep extends AbstractDistributionPage
{
}
| lgpl-2.1 |
JakiHappyCity/ChromaCraft | src/main/java/cc/api/ITEHasChroma.java | 967 | package cc.api;
import java.util.UUID;
/**
* Created by jakihappycity on 06.11.15.
*/
public interface ITEHasChroma {
/**
* this is used to get current Chroma of your tile entities
* @return current amount of Chroma
*/
public abstract int getChroma();
/**
* this is used to get max Chroma of your tile entities
* @return max amount of Chroma the device can store
*/
public abstract int getMaxChroma();
/**
* this is used to set current Chroma of your tile entities
* @param i - the amount to add. Use negative values to remove Chroma
* @return true if was successful, false if not
*/
public abstract boolean setChroma(int i);
/**
* this is used to set maxChroma of your tile entities
* @param f - the amount to set.
* @return true if was successful, false if not
*/
public abstract boolean setMaxChroma(float f);
public abstract UUID getUUID();
}
| lgpl-2.1 |
geotools/geotools | modules/unsupported/process-raster/src/test/java/org/geotools/process/raster/GridCoverageAngleCalcTest.java | 3554 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2014, Open Source Geospatial Foundation (OSGeo)
* (C) 2001-2014 TOPP - www.openplans.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;
* 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.process.raster;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.referencing.CRS;
import org.junit.Assert;
import org.junit.Test;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
public class GridCoverageAngleCalcTest {
private static final double TOLERANCE = 0.001d;
@Test
public void testLambertConic() throws Exception {
//
// Test some points within a custom Lambert Conformal Conic projection
// used by the HRRR forecast model.
//
String wktString =
"PROJCS[\"Lambert_Conformal_Conic\","
+ "GEOGCS[\"GCS_unknown\",DATUM[\"D_unknown\","
+ "SPHEROID[\"Sphere\",6367470,0]],PRIMEM[\"Greenwich\",0],"
+ "UNIT[\"Degree\",0.017453292519943295]],"
+ "PROJECTION[\"Lambert_Conformal_Conic_1SP\"],"
+ "PARAMETER[\"latitude_of_origin\",38.5],"
+ "PARAMETER[\"central_meridian\",-97.5],"
+ "PARAMETER[\"scale_factor\",1],"
+ "PARAMETER[\"false_easting\",0],"
+ "PARAMETER[\"false_northing\",0],UNIT[\"m\",1.0]]";
CoordinateReferenceSystem crs = CRS.parseWKT(wktString);
GridConvergenceAngleCalc angleCalc = new GridConvergenceAngleCalc(crs);
DirectPosition2D position =
new DirectPosition2D(crs, 2626.018310546785 * 1000, -1118.3695068359375 * 1000);
Assert.assertEquals(16.0573598047079d, angleCalc.getConvergenceAngle(position), TOLERANCE);
position =
new DirectPosition2D(crs, -1201.9818115234375 * 1000, -1172.3695068359375 * 1000);
Assert.assertEquals(
-7.461565880473206d, angleCalc.getConvergenceAngle(position), TOLERANCE);
}
@Test
public void testEPSG3411() throws Exception {
//
// Test Oklahoma in EPSG:3411 Northern Hemis. Sea Ice Polar Stereo.
//
CoordinateReferenceSystem crs = CRS.decode("EPSG:3411");
GridConvergenceAngleCalc angleCalc = new GridConvergenceAngleCalc(crs);
DirectPosition2D position = new DirectPosition2D(crs, -5050427.62537, -3831167.39071);
Assert.assertEquals(
-52.81667373163404d, angleCalc.getConvergenceAngle(position), TOLERANCE);
}
@Test
public void testEPSG3031() throws Exception {
//
// Test Antarctic Polar Stereo EPSG:3031
//
//
CoordinateReferenceSystem crs = CRS.decode("EPSG:3031");
GridConvergenceAngleCalc angleCalc = new GridConvergenceAngleCalc(crs);
DirectPosition2D position = new DirectPosition2D(crs, 5450569.17764, -5333348.64467);
Assert.assertEquals(
-134.37722187798775d, angleCalc.getConvergenceAngle(position), TOLERANCE);
}
}
| lgpl-2.1 |
samskivert/samskivert | src/main/java/com/samskivert/util/Predicate.java | 9391 | //
// samskivert library - useful routines for java programs
// Copyright (C) 2001-2012 Michael Bayne, et al.
// http://github.com/samskivert/samskivert/blob/master/COPYING
package com.samskivert.util;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.samskivert.annotation.ReplacedBy;
/**
* Arbitrates membership. Example usage. Find the best kind of peanut butter:
* <pre>{@code
* public Iterator<PeanutButter> findBestKinds (Collection<PeanutButter> pbs)
* {
* return new Predicate<PeanutButter>() {
* public boolean isMatch (PeanutButter pb)
* {
* return pb.isCreamy() && !pb.containsPartiallyHydrogenatedOils();
* }
* }.filter(pbs.iterator());
* }
* }</pre>
* An interface like this may someday be in the Java library, but until then...
*/
@ReplacedBy("com.google.common.base.Predicate")
public abstract class Predicate<T>
{
//--------------------------------------------------------------------
// But first, some handy utility classes:
/**
* A simple predicate that includes an object if it is an instance
* of the specified class.
*/
public static class InstanceOf<T> extends Predicate<T>
{
public InstanceOf (Class<?> clazz)
{
_class = clazz;
}
@Override public boolean isMatch (T obj)
{
return _class.isInstance(obj);
}
/** The class that must be implemented by applicants. */
protected Class<?> _class;
}
/**
* Includes an object if and only if all the predicates with which it
* was constructed also include the object. The predicates
* are tested in the order specified and testing is halted as soon
* as one does not include the object. If the Predicate is constructed
* with no arguments, it will behave like TRUE.
*/
public static class And<T> extends Predicate<T>
{
public And (Predicate<T> ... preds)
{
_preds = preds;
}
@Override public boolean isMatch (T obj)
{
for (Predicate<T> pred : _preds) {
if (!pred.isMatch(obj)) {
return false;
}
}
return true;
}
/** The predicates that all must be satisfied. */
protected Predicate<T>[] _preds;
}
/**
* Includes an object if at least one of the predicates specified in the
* constructor include the object. The predicates are tested in the
* order specified and testing is halted as soon as one includes
* the object. If the predicate is constructed with no arguments,
* it will behave like FALSE.
*/
public static class Or<T> extends Predicate<T>
{
public Or (Predicate<T> ... preds)
{
_preds = preds;
}
@Override public boolean isMatch (T obj)
{
for (Predicate<T> pred : _preds) {
if (pred.isMatch(obj)) {
return true;
}
}
return false;
}
protected Predicate<T>[] _preds;
}
/**
* Negates any other predicate.
*/
public static class Not<T> extends Predicate<T>
{
public Not (Predicate<T> negated)
{
_pred = negated;
}
@Override public boolean isMatch (T obj)
{
return !_pred.isMatch(obj);
}
protected Predicate<T> _pred;
}
/**
* Returns a type-safe reference to the shared instance of a predicate that always returns
* <code>true</code>.
*/
public static <T> Predicate<T> trueInstance ()
{
@SuppressWarnings("unchecked") Predicate<T> pred = (Predicate<T>)TRUE_INSTANCE;
return pred;
}
/**
* Returns a type-safe reference to the shared instance of a predicate that always returns
* <code>false</code>.
*/
public static <T> Predicate<T> falseInstance ()
{
@SuppressWarnings("unchecked") Predicate<T> pred = (Predicate<T>)FALSE_INSTANCE;
return pred;
}
//--------------------------------------------------------------------
// Here's the sole abstract method in the Predicate class:
/**
* Does the specified object belong to the special set that we test for?
*/
public abstract boolean isMatch (T obj);
//--------------------------------------------------------------------
// And finally, some handy utility methods:
/**
* Return a new iterator that contains only matching elements from
* the input iterator.
*/
public <E extends T> Iterator<E> filter (final Iterator<E> input)
{
return new Iterator<E>() {
// from Iterator
public boolean hasNext ()
{
return _found || findNext();
}
// from Iterator
public E next ()
{
if (_found || findNext()) {
_found = false;
return _last;
} else {
throw new NoSuchElementException();
}
}
// from Iterator
public void remove ()
{
if (_removeable) {
_removeable = false;
input.remove();
} else {
throw new IllegalStateException();
}
}
private boolean findNext ()
{
boolean result = false;
while (input.hasNext()) {
E candidate = input.next();
if (isMatch(candidate)) {
_last = candidate;
result = true;
break;
}
}
_found = result;
_removeable = result;
return result;
}
private E _last;
private boolean _found; // because _last == null is a valid element
private boolean _removeable;
};
}
/**
* Remove non-matching elements from the specified collection.
*/
public <E extends T> void filter (Collection<E> coll)
{
for (Iterator<E> itr = coll.iterator(); itr.hasNext(); ) {
if (!isMatch(itr.next())) {
itr.remove();
}
}
}
/**
* Create an Iterable view of the specified Iterable that only contains
* elements that match the predicate.
* This Iterable can be iterated over at any time in the future to
* view the current predicate-matching elements of the input Iterable.
*/
public <E extends T> Iterable<E> createView (final Iterable<E> input)
{
return new Iterable<E>() {
public Iterator<E> iterator() {
return filter(input.iterator());
}
};
}
/**
* Create a view of the specified collection that only contains elements
* that match the predicate.
* This collection can be examined at any time in the future to view
* the current predicate-matching elements of the input collection.
*
* Note that the view is not modifiable and currently has poor
* implementations of some methods.
*/
public <E extends T> Collection<E> createView (final Collection<E> input)
{
// TODO: create a collection of the same type?
return new AbstractCollection<E>() {
@Override public int size ()
{
// oh god, oh god: we iterate and count
int size = 0;
for (Iterator<E> iter = iterator(); iter.hasNext(); ) {
iter.next();
size++;
}
return size;
}
@Override public boolean add (E element)
{
return input.add(element);
}
@Override public boolean remove (Object element)
{
return input.remove(element);
}
@Override public boolean contains (Object element)
{
try {
@SuppressWarnings("unchecked")
E elem = (E) element;
return isMatch(elem) && input.contains(elem);
} catch (ClassCastException cce) {
// since it's not an E, it can't be a member of our view
return false;
}
}
@Override public Iterator<E> iterator ()
{
return filter(input.iterator());
}
};
}
/** A shared predicate instance that always matches its input. */
protected static final Predicate<Object> TRUE_INSTANCE = new Predicate<Object>() {
@Override public boolean isMatch (Object object) {
return true;
}
};
/** A shared predicate instance that never matches its input. */
protected static final Predicate<Object> FALSE_INSTANCE = new Predicate<Object>() {
@Override public boolean isMatch (Object object) {
return false;
}
};
}
| lgpl-2.1 |
magsilva/jazzy | src/com/swabunga/spell/engine/SpellDictionary.java | 3900 | /*
Jazzy - a Java library for Spell Checking
Copyright (C) 2001 Mindaugas Idzelis
Full text of license can be found in LICENSE.txt
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 com.swabunga.spell.engine;
import java.util.List;
/**
* An interface for all dictionary implementations. It defines the most basic
* operations on a dictionary: adding words, checking if a word is correct, and getting a list
* of suggestions for misspelled words.
*/
public interface SpellDictionary {
/**
* Add a word permanently to the dictionary.
* @param word The word to add to the dictionary
*/
public boolean addWord(String word);
/**
* Evaluates if the word is correctly spelled against the dictionary.
* @param word The word to verify if it's spelling is OK.
* @return Indicates if the word is present in the dictionary.
*/
public boolean isCorrect(String word);
/**
* Returns a list of Word objects that are the suggestions to any word.
* If the word is correctly spelled, then this method
* could return just that one word, or it could still return a list
* of words with similar spellings.
* <br/>
* Each suggested word has a score, which is an integer
* that represents how different the suggested word is from the sourceWord.
* If the words are the exactly the same, then the score is 0.
* You can get the dictionary to only return the most similar words by setting
* an appropriately low threshold value.
* If you set the threshold value too low, you may get no suggestions for a given word.
* <p>
* This method is only needed to provide backward compatibility.
* @see #getSuggestions(String, int, int[][])
*
* @param sourceWord the string that we want to get a list of spelling suggestions for
* @param scoreThreshold Any words that have score less than this number are returned.
* @return List a List of suggested words
* @see com.swabunga.spell.engine.Word
*
*/
public List getSuggestions(String sourceWord, int scoreThreshold);
/**
* Returns a list of Word objects that are the suggestions to any word.
* If the word is correctly spelled, then this method
* could return just that one word, or it could still return a list
* of words with similar spellings.
* <br/>
* Each suggested word has a score, which is an integer
* that represents how different the suggested word is from the sourceWord.
* If the words are the exactly the same, then the score is 0.
* You can get the dictionary to only return the most similar words by setting
* an appropriately low threshold value.
* If you set the threshold value too low, you may get no suggestions for a given word.
* <p>
* @param sourceWord the string that we want to get a list of spelling suggestions for
* @param scoreThreshold Any words that have score less than this number are returned.
* @param Two dimensional int array used to calculate edit distance. Allocating
* this memory outside of the function will greatly improve efficiency.
* @return List a List of suggested words
* @see com.swabunga.spell.engine.Word
*/
public List getSuggestions(String sourceWord, int scoreThreshold , int[][] matrix);
}
| lgpl-2.1 |
the-realest-stu/Adventurers-Toolbox | src/main/java/toolbox/client/models/HoeModel.java | 10018 | package toolbox.client.models;
import java.util.Collection;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import api.materials.AdornmentMaterial;
import api.materials.HaftMaterial;
import api.materials.HandleMaterial;
import api.materials.HeadMaterial;
import api.materials.Materials;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.model.ItemOverride;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ItemLayerModel;
import net.minecraftforge.client.model.PerspectiveMapWrapper;
import net.minecraftforge.client.model.SimpleModelState;
import net.minecraftforge.common.model.IModelState;
import net.minecraftforge.common.model.TRSRTransformation;
import toolbox.Toolbox;
import toolbox.common.items.ModItems;
import toolbox.common.items.tools.IAdornedTool;
import toolbox.common.items.tools.IHaftTool;
import toolbox.common.items.tools.IHandleTool;
import toolbox.common.items.tools.IHeadTool;
import toolbox.common.materials.ModMaterials;
public class HoeModel implements IModel {
public static final ModelResourceLocation LOCATION = new ModelResourceLocation(
new ResourceLocation(Toolbox.MODID, "hoe"), "inventory");
public static final IModel MODEL = new HoeModel();
@Nullable
private final ResourceLocation headTexture;
@Nullable
private final ResourceLocation haftTexture;
@Nullable
private final ResourceLocation handleTexture;
@Nullable
private final ResourceLocation adornmentTexture;
public HoeModel() {
headTexture = null;
haftTexture = null;
handleTexture = null;
adornmentTexture = null;
}
public HoeModel(ResourceLocation head, ResourceLocation haft, ResourceLocation handle, ResourceLocation adornment) {
this.headTexture = head;
this.haftTexture = haft;
this.handleTexture = handle;
this.adornmentTexture = adornment;
}
@Override
public IModel retexture(ImmutableMap<String, String> textures) {
ResourceLocation head = null;
ResourceLocation haft = null;
ResourceLocation handle = null;
ResourceLocation adornment = null;
if (textures.containsKey("head")) {
head = new ResourceLocation(Materials.head_registry.get(textures.get("head")).getModId(), "items/hoe/head_" + textures.get("head"));
}
if (textures.containsKey("haft")) {
haft = new ResourceLocation(Materials.haft_registry.get(textures.get("haft")).getModId(), "items/hoe/haft_" + textures.get("haft"));
}
if (textures.containsKey("handle")) {
handle = new ResourceLocation(Materials.handle_registry.get(textures.get("handle")).getModId(), "items/hoe/handle_" + textures.get("handle"));
}
if (textures.containsKey("adornment")) {
adornment = new ResourceLocation(Materials.adornment_registry.get(textures.get("adornment")).getModId(), "items/hoe/adornment_" + textures.get("adornment"));
}
return new HoeModel(head, haft, handle, adornment);
}
@Override
public IModel process(ImmutableMap<String, String> customData) {
ResourceLocation head = null;
ResourceLocation haft = null;
ResourceLocation handle = null;
ResourceLocation adornment = null;
if (customData.containsKey("head")) {
head = new ResourceLocation(Materials.head_registry.get(customData.get("head")).getModId(), "items/hoe/head_" + customData.get("head"));
}
if (customData.containsKey("haft")) {
haft = new ResourceLocation(Materials.haft_registry.get(customData.get("haft")).getModId(), "items/hoe/haft_" + customData.get("haft"));
}
if (customData.containsKey("handle")) {
handle = new ResourceLocation(Materials.handle_registry.get(customData.get("handle")).getModId(), "items/hoe/handle_" + customData.get("handle"));
}
if (customData.containsKey("adornment")) {
adornment = new ResourceLocation(Materials.adornment_registry.get(customData.get("adornment")).getModId(), "items/hoe/adornment_" + customData.get("adornment"));
}
return new HoeModel(head, haft, handle, adornment);
}
@Override
public Collection<ResourceLocation> getDependencies() {
return ImmutableList.of();
}
@Override
public Collection<ResourceLocation> getTextures() {
ImmutableList.Builder<ResourceLocation> builder = ImmutableList.builder();
for (HeadMaterial mat : Materials.head_registry.values()) {
builder.add(new ResourceLocation(mat.getModId(), "items/hoe/head_" + mat.getName()));
}
for (HaftMaterial mat : Materials.haft_registry.values()) {
builder.add(new ResourceLocation(mat.getModId(), "items/hoe/haft_" + mat.getName()));
}
for (HandleMaterial mat : Materials.handle_registry.values()) {
builder.add(new ResourceLocation(mat.getModId(), "items/hoe/handle_" + mat.getName()));
}
for (AdornmentMaterial mat : Materials.adornment_registry.values()) {
builder.add(new ResourceLocation(mat.getModId(), "items/hoe/adornment_" + mat.getName()));
}
Collection textures = builder.build();
return textures;
}
@Override
public IBakedModel bake(IModelState state, VertexFormat format,
java.util.function.Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) {
ImmutableMap<TransformType, TRSRTransformation> transformMap = PerspectiveMapWrapper.getTransforms(state);
TRSRTransformation transform = (TRSRTransformation.identity());
ImmutableList.Builder<BakedQuad> builder = ImmutableList.builder();
if (headTexture != null && haftTexture != null && handleTexture != null) {
ImmutableList.Builder<ResourceLocation> texBuilder = ImmutableList.builder();
if (haftTexture != null) {
texBuilder.add(haftTexture);
}
if (headTexture != null) {
texBuilder.add(headTexture);
}
if (handleTexture != null) {
texBuilder.add(handleTexture);
}
if (adornmentTexture != null) {
texBuilder.add(adornmentTexture);
}
ImmutableList<ResourceLocation> textures = texBuilder.build();
IBakedModel model = (new ItemLayerModel(textures)).bake(state, format, bakedTextureGetter);
builder.addAll(model.getQuads(null, null, 0));
}
return new BakedHoeModel(this, builder.build(), format, Maps.immutableEnumMap(transformMap),
Maps.<String, IBakedModel>newHashMap());
}
@Override
public IModelState getDefaultState() {
return TRSRTransformation.identity();
}
public enum LoaderHoe implements ICustomModelLoader {
INSTANCE;
@Override
public boolean accepts(ResourceLocation modelLocation) {
return modelLocation.getResourceDomain().equals(Toolbox.MODID)
&& modelLocation.getResourcePath().equals("hoe");
}
@Override
public IModel loadModel(ResourceLocation modelLocation) {
return MODEL;
}
@Override
public void onResourceManagerReload(IResourceManager resourceManager) {
}
}
private static final class BakedHoeOverrideHandler extends ItemOverrideList {
public static final BakedHoeOverrideHandler INSTANCE = new BakedHoeOverrideHandler();
private BakedHoeOverrideHandler() {
super(ImmutableList.<ItemOverride>of());
}
@Override
@Nonnull
public IBakedModel handleItemState(@Nonnull IBakedModel originalModel, @Nonnull ItemStack stack,
@Nullable World world, @Nullable EntityLivingBase entity) {
if (stack.getItem() != ModItems.hoe) {
return originalModel;
}
BakedHoeModel model = (BakedHoeModel) originalModel;
String key = IHeadTool.getHeadMat(stack).getName() + "|"
+ IHaftTool.getHaftMat(stack).getName() + "|"
+ IHandleTool.getHandleMat(stack).getName() + "|"
+ IAdornedTool.getAdornmentMat(stack).getName();
if (!model.cache.containsKey(key)) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
builder.put("head", IHeadTool.getHeadMat(stack).getName());
builder.put("haft", IHaftTool.getHaftMat(stack).getName());
builder.put("handle", IHandleTool.getHandleMat(stack).getName());
if (IAdornedTool.getAdornmentMat(stack) != ModMaterials.ADORNMENT_NULL) {
builder.put("adornment", IAdornedTool.getAdornmentMat(stack).getName());
}
IModel parent = model.parent.retexture(builder.build());
Function<ResourceLocation, TextureAtlasSprite> textureGetter;
textureGetter = new Function<ResourceLocation, TextureAtlasSprite>() {
public TextureAtlasSprite apply(ResourceLocation location) {
return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(location.toString());
}
};
IBakedModel bakedModel = parent.bake(new SimpleModelState(model.transforms), model.format,
textureGetter);
model.cache.put(key, bakedModel);
return bakedModel;
}
return model.cache.get(key);
}
}
private static final class BakedHoeModel extends BakedToolModel {
public BakedHoeModel(HoeModel parent, ImmutableList<BakedQuad> quads, VertexFormat format,
ImmutableMap<ItemCameraTransforms.TransformType, TRSRTransformation> transforms,
Map<String, IBakedModel> cache) {
super(parent, quads, format, transforms, cache);
}
@Override
public ItemOverrideList getOverrides() {
return BakedHoeOverrideHandler.INSTANCE;
}
}
}
| lgpl-2.1 |
hwellmann/omadac | appl/plugins/jpa/src/org/omadac/jpa/TxCallable.java | 764 | /*
* Omadac - The Open Map Database Compiler
* http://omadac.org
*
* (C) 2010, Harald Wellmann and Contributors
*
* 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.omadac.jpa;
import javax.persistence.EntityManager;
public interface TxCallable<T>
{
T run(EntityManager aManager);
}
| lgpl-2.1 |
fastcat-co/analytics | analytics-server/src/test/java/org/fastcatsearch/analytics/util/FormatterTest.java | 475 | package org.fastcatsearch.analytics.util;
import static org.junit.Assert.*;
import org.junit.Test;
public class FormatterTest {
@Test
public void test() {
for(long l = 0;l < 1024*1024*1024 ; l++) {
String str =Formatter.getFormatSize(l);
System.out.println(l + " > " + str);
}
}
@Test
public void testLarge() {
for(long l = 8000000000L;l > 0 ; l--) {
String str =Formatter.getFormatSize(l);
System.out.println(l + " > " + str);
}
}
}
| lgpl-2.1 |
geotools/geotools | modules/extension/xsd/xsd-gml2/src/main/java/org/geotools/gml2/bindings/GMLMultiPointPropertyTypeBinding.java | 3124 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2008, 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.gml2.bindings;
import java.util.List;
import javax.xml.namespace.QName;
import org.eclipse.xsd.XSDElementDeclaration;
import org.geotools.gml2.GML;
import org.geotools.xsd.AbstractComplexBinding;
import org.geotools.xsd.ElementInstance;
import org.geotools.xsd.Node;
import org.locationtech.jts.geom.MultiPoint;
/**
* Binding object for the type http://www.opengis.net/gml:MultiPointPropertyType.
*
* <p>
*
* <pre>
* <code>
* <complexType name="MultiPointPropertyType">
* <annotation>
* <documentation> Encapsulates a MultiPoint element to
* represent the following discontiguous geometric
* properties: multiLocation, multiPosition,
* multiCenterOf. </documentation>
* </annotation>
* <complexContent>
* <restriction base="gml:GeometryAssociationType">
* <sequence minOccurs="0">
* <element ref="gml:MultiPoint"/>
* </sequence>
* <attributeGroup ref="xlink:simpleLink"/>
* <attribute ref="gml:remoteSchema" use="optional"/>
* </restriction>
* </complexContent>
* </complexType>
*
* </code>
* </pre>
*
* @generated
*/
public class GMLMultiPointPropertyTypeBinding extends AbstractComplexBinding {
/** @generated */
@Override
public QName getTarget() {
return GML.MultiPointPropertyType;
}
/**
*
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated modifiable
*/
@Override
public Class getType() {
return MultiPoint.class;
}
/**
*
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated modifiable
*/
@Override
public Object parse(ElementInstance instance, Node node, Object value) throws Exception {
return node.getChildValue(MultiPoint.class);
}
@Override
public Object getProperty(Object object, QName name) throws Exception {
return GML2EncodingUtils.GeometryPropertyType_getProperty((MultiPoint) object, name, false);
}
@Override
public List<Object[]> getProperties(Object object, XSDElementDeclaration element)
throws Exception {
return GML2EncodingUtils.GeometryPropertyType_getProperties((MultiPoint) object);
}
}
| lgpl-2.1 |
zear/fled | src/gui/ObjectPanel.java | 11844 | package gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.ListIterator;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import level.*;
import util.*;
public class ObjectPanel extends JPanel
{
private MapPanel mapPanel = null;
private ListCellRenderer<Object> renderer;
//private LinkedList<GameObject> availableObjectsList;
private LinkedList<GameObject> addedObjectsList;
private DefaultListModel<GameObject> availableListModel;
private DefaultListModel<GameObject> addedListModel;
private JList <GameObject> availableObjects;
private JList <GameObject> addedObjects;
private JScrollPane availablePane;
private JScrollPane addedPane;
private JButton buttonAdd = new JButton("Add");
private JButton buttonRemove = new JButton("Remove");
private ButtonGroup radioDirection = new ButtonGroup();
private JRadioButton directionLeft = new JRadioButton("left");
private JRadioButton directionRight = new JRadioButton("right");
private JLabel availableLabel = new JLabel("Available:");
private JLabel addedLabel = new JLabel("Added to level:");
private JLabel directionLabel = new JLabel("Object direction:");
class ObjectCellRenderer extends JLabel implements ListCellRenderer<Object>
{
public ObjectCellRenderer()
{
setOpaque(true);
}
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
if (value instanceof GameObject)
setText(((GameObject)value).getName() + " ["+((GameObject)value).getX()+","+((GameObject)value).getY()+"]");
else
setText(value.toString());
Color background;
Color foreground;
// check if this cell represents the current DnD drop location
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null && !dropLocation.isInsert() && dropLocation.getIndex() == index)
{
background = Color.BLUE;
foreground = Color.WHITE;
// check if this cell is selected
}
else if (isSelected)
{
background = Color.BLUE;
foreground = Color.WHITE;
// unselected, and not the DnD drop location
}
else
{
background = Color.WHITE;
foreground = Color.BLACK;
}
setBackground(background);
setForeground(foreground);
return this;
}
}
public ObjectPanel()
{
this.renderer = new ObjectCellRenderer();
this.radioDirection.add(directionLeft);
this.radioDirection.add(directionRight);
buttonAdd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (availableListModel != null)
{
int selectedIndex = availableObjects.getSelectedIndex();
if (selectedIndex != -1)
{
addNewObject(availableListModel.get(selectedIndex).getName());
}
}
}
});
buttonRemove.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
deleteSelectedObject();
}
});
directionLeft.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (addedObjects != null && addedObjects.getSelectedIndex() != -1)
{
addedListModel.get(addedObjects.getSelectedIndex()).setDirection(false);
mapPanel.level.setModified(true);
mapPanel.repaint();
}
}
});
directionRight.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (addedObjects != null && addedObjects.getSelectedIndex() != -1)
{
addedListModel.get(addedObjects.getSelectedIndex()).setDirection(true);
mapPanel.level.setModified(true);
mapPanel.repaint();
}
}
});
}
void addListeners()
{
// if (availableObjects != null)
// {
// availableObjects.addListSelectionListener(new ListSelectionListener()
// {
// public void valueChanged(ListSelectionEvent e)
// {
// if (e.getValueIsAdjusting() == false)
// {
// if (availableObjects.getSelectedIndex() == -1)
// {
// //No selection
// }
// else
// {
// System.out.printf("Selected: %s [%d,%d]\n", availableListModel.get(availableObjects.getSelectedIndex()).getName(), availableListModel.get(availableObjects.getSelectedIndex()).getX(), availableListModel.get(availableObjects.getSelectedIndex()).getY());
// }
// }
// }
// });
// }
if (addedObjects != null)
{
addedObjects.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
if (e.getValueIsAdjusting() == false)
{
if (addedObjects.getSelectedIndex() == -1)
{
//No selection
}
else
{
GameObject selObj = addedListModel.get(addedObjects.getSelectedIndex());
mapPanel.setSelectedObject(selObj);
mapPanel.setObjectIsNew(false);
if (selObj.getDirection())
{
directionRight.setSelected(true);
}
else
{
directionLeft.setSelected(true);
}
}
}
}
});
}
}
void loadObjects()
{
this.availableListModel = new DefaultListModel<GameObject>();
this.addedListModel = new DefaultListModel<GameObject>();
// Check a directory for object files
File folder = new File(Data.getDataDirectory() + "/data/obj/");
File [] listOfFiles = folder.listFiles();
FileRead fp = null;
String line;
String [] words;
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
try
{
fp = new FileRead((File)listOfFiles[i]);
}
catch (FileNotFoundException e)
{
System.out.printf("Failed to load object: %s\n", listOfFiles[i].getName());
}
GameObject newObj = null;
int tmpW = 0;
int tmpH = 0;
boolean parsingFrames = false;
while (fp.hasNext())
{
line = fp.getLine();
if (line == null)
break;
words = line.split("\\s");
if (words[0].equals("NAME"))
{
newObj = new GameObject();
this.availableListModel.addElement(newObj);
newObj.setName(words[1]);
continue;
}
else if (words[0].equals("WIDTH"))
{
tmpW = Integer.parseInt(words[1]);
continue;
}
else if (words[0].equals("HEIGHT"))
{
tmpH = Integer.parseInt(words[1]);
continue;
}
else if (words[0].equals("IMG"))
{
if (newObj != null)
{
newObj.setImgTemplate(words[1], Integer.parseInt(words[2]), Integer.parseInt(words[3]));
newObj.setW(tmpW);
newObj.setH(tmpH);
}
continue;
}
else if (words[0].equals("IDLE"))
{
parsingFrames = true;
continue;
}
else if (parsingFrames)
{
if (words[0].equals("LEFT"))
{
newObj.setOffset(false, Integer.parseInt(words[1]), Integer.parseInt(words[2]));
continue;
}
else if (words[0].equals("RIGHT"))
{
newObj.setOffset(true, Integer.parseInt(words[1]), Integer.parseInt(words[2]));
break;
}
}
}
fp.close();
}
}
// Load objects present in the level file
this.addedObjectsList = this.mapPanel.level.getObjectList();
for (GameObject curObj : this.addedObjectsList)
{
curObj.setImgTemplate(this.getObjectTemplateByName(curObj.getName()).getImgTemplate());
this.addedListModel.addElement(curObj);
}
this.availableObjects = new JList<>(this.availableListModel);
this.availableObjects.setCellRenderer(this.renderer);
this.addedObjects = new JList<>(this.addedListModel);
this.addedObjects.setCellRenderer(this.renderer);
this.availableObjects.setLayoutOrientation(JList.VERTICAL);
this.availableObjects.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.addedObjects.setLayoutOrientation(JList.VERTICAL);
this.addedObjects.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.addListeners();
availablePane = new JScrollPane(availableObjects);
addedPane = new JScrollPane(addedObjects);
JPanel buttonContainer = new JPanel();
JPanel directionContainer = new JPanel();
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
this.removeAll();
this.add(availableLabel);
this.add(availablePane);
this.add(addedLabel);
this.add(addedPane);
this.add(buttonContainer);
this.add(directionLabel);
this.add(directionContainer);
availableLabel.setAlignmentX(this.LEFT_ALIGNMENT);
availablePane.setAlignmentX(this.LEFT_ALIGNMENT);
addedLabel.setAlignmentX(this.LEFT_ALIGNMENT);
addedPane.setAlignmentX(this.LEFT_ALIGNMENT);
buttonContainer.setAlignmentX(this.LEFT_ALIGNMENT);
directionLabel.setAlignmentX(this.LEFT_ALIGNMENT);
directionContainer.setAlignmentX(this.LEFT_ALIGNMENT);
buttonContainer.add(buttonAdd);
buttonContainer.add(buttonRemove);
directionContainer.add(directionLeft);
directionContainer.add(directionRight);
this.repaint();
}
public void addNewObject(GameObject model)
{
if (model == null)
return;
GameObject newObj = new GameObject();
newObj.setName(model.getName());
newObj.setImgTemplate(model.getImgTemplate());
newObj.setDirection(model.getDirection());
addedObjectsList.push(newObj);
addedListModel.addElement(newObj);
addedObjects.setSelectedValue(newObj, true);
mapPanel.setObjectIsNew(true);
mapPanel.level.setModified(true);
mapPanel.repaint();
}
public void addNewObject(String name)
{
if (name == null)
return;
if (availableListModel != null)
{
Object[] availableArray = availableListModel.toArray();
for (Object obj : availableArray)
{
GameObject gObj = (GameObject)obj;
if (gObj.getName().equals(name))
{
GameObject newObj = new GameObject();
newObj.setName(gObj.getName());
newObj.setImgTemplate(gObj.getImgTemplate());
addedObjectsList.push(newObj);
addedListModel.addElement(newObj);
addedObjects.setSelectedValue(newObj, true);
mapPanel.setObjectIsNew(true);
mapPanel.level.setModified(true);
mapPanel.repaint();
break;
}
}
}
}
public void setObjectDirection(GameObject obj, boolean direction)
{
obj.setDirection(direction);
mapPanel.level.setModified(true);
mapPanel.repaint();
if (obj == getSelectedObject())
{
directionLeft.setSelected(!direction);
directionRight.setSelected(direction);
}
}
public void setSelectedObject(GameObject selObj)
{
addedObjects.setSelectedValue(selObj, true);
}
public void deleteSelectedObject()
{
if (addedListModel != null)
{
int selectedIndex = addedObjects.getSelectedIndex();
if (selectedIndex != -1)
{
GameObject objToRem = addedListModel.get(selectedIndex);
ListIterator<GameObject> objsli = addedObjectsList.listIterator();
while (objsli.hasNext())
{
if (objsli.next() == objToRem)
{
objsli.remove();
addedListModel.remove(selectedIndex);
addedObjects.setSelectedIndex(selectedIndex == 0 ? 0 : selectedIndex - 1);
mapPanel.level.setModified(true);
break;
}
}
mapPanel.repaint();
}
}
}
public GameObject getSelectedObject()
{
if (addedListModel != null)
{
int selectedIndex = addedObjects.getSelectedIndex();
if (selectedIndex != -1)
return addedListModel.get(selectedIndex);
else
return null;
}
else
{
return null;
}
}
void setPanels(MapPanel newMapPanel)
{
this.mapPanel = newMapPanel;
}
GameObject getObjectTemplateByName(String objName)
{
if (this.availableListModel != null)
{
for (int i = 0; i < this.availableListModel.getSize(); i++)
{
if (this.availableListModel.get(i).getName().equals(objName))
return this.availableListModel.get(i);
}
return null;
}
else
{
return null;
}
}
}
| lgpl-2.1 |
HickGamer/Better-Utilites | Reference Code/Progressive Automation Code/java/com/vanhal/progressiveautomation/items/ItemRFEngine.java | 3923 | package com.vanhal.progressiveautomation.items;
import java.text.DecimalFormat;
import java.util.List;
import com.vanhal.progressiveautomation.PAConfig;
import cofh.api.energy.IEnergyContainerItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.oredict.ShapedOreRecipe;
public class ItemRFEngine extends BaseItem implements IEnergyContainerItem {
protected int maxCharge = 100000;
private static DecimalFormat rfDecimalFormat = new DecimalFormat("###,###,###,###,###");
public ItemRFEngine() {
super("RFEngine");
//setTextureName(Ref.MODID+":RFEngine");
setMaxStackSize(1);
setMaxCharge(PAConfig.rfStored);
}
public ItemRFEngine(String name) {
super(name);
}
public void setMaxCharge(int amount) {
maxCharge = amount;
}
public int getMaxCharge() {
return maxCharge;
}
public int getCharge(ItemStack itemStack) {
initNBT(itemStack);
return itemStack.getTagCompound().getInteger("charge");
}
public void setCharge(ItemStack itemStack, int charge) {
initNBT(itemStack);
itemStack.getTagCompound().setInteger("charge", charge);
}
public int addCharge(ItemStack itemStack, int amount) {
int amountUsed = amount;
int current = getCharge(itemStack);
if ((current + amount)>maxCharge) amountUsed = (maxCharge-current);
if ((current + amount)<0) amountUsed = (current);
current += amount;
if (current>=maxCharge) current = maxCharge;
if (current<0) current = 0;
setCharge(itemStack, current);
return amountUsed;
}
protected void initNBT(ItemStack itemStack) {
if (itemStack.getTagCompound() == null) {
itemStack.setTagCompound(new NBTTagCompound());
itemStack.getTagCompound().setInteger("charge", 0);
}
}
protected boolean isInit(ItemStack itemStack) {
return (itemStack.getTagCompound() != null);
}
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean par) {
if ( (itemStack!=null) && (isInit(itemStack)) ) {
int charge = getCharge(itemStack);
list.add(TextFormatting.RED + "" +
String.format("%s", rfDecimalFormat.format(charge)) + "/" +
String.format("%s", rfDecimalFormat.format(maxCharge)) + " RF");
} else {
list.add(TextFormatting.GRAY + "Add to the fuel slot to");
list.add(TextFormatting.GRAY + "power a machine with RF");
}
}
@SideOnly(Side.CLIENT)
public boolean showDurabilityBar(ItemStack itemStack) {
return isInit(itemStack);
}
@SideOnly(Side.CLIENT)
public double getDurabilityForDisplay(ItemStack itemStack) {
return 1.0 - (double)getCharge(itemStack) / (double)maxCharge;
}
protected void addNormalRecipe() {
ShapedOreRecipe recipe = new ShapedOreRecipe(new ItemStack(this), new Object[]{
"iii", "grg", "iii", 'i', Items.IRON_INGOT, 'r', Blocks.REDSTONE_BLOCK, 'g', Items.GOLD_INGOT});
GameRegistry.addRecipe(recipe);
}
protected void addUpgradeRecipe() {
addNormalRecipe();
}
@Override
public int receiveEnergy(ItemStack itemStack, int maxReceive, boolean simulate) {
if (simulate) return maxReceive;
return addCharge(itemStack, maxReceive);
}
@Override
public int extractEnergy(ItemStack itemStack, int maxExtract, boolean simulate) {
if (simulate) return maxExtract;
return addCharge(itemStack, maxExtract * -1);
}
@Override
public int getEnergyStored(ItemStack container) {
return getCharge(container);
}
@Override
public int getMaxEnergyStored(ItemStack container) {
return getMaxCharge();
}
}
| lgpl-2.1 |
richard-yin/ForgeRestart | src/main/java/io/github/richardyin/forgerestart/AutoRestart.java | 1948 | package io.github.richardyin.forgerestart;
import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import net.minecraft.client.Minecraft;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.transformers.ForgeAccessTransformer;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
@Mod(modid = AutoRestart.MODID, version = AutoRestart.VERSION)
public class AutoRestart {
public static final String MODID = "ForgeRestart";
public static final String VERSION = "0.1";
private long delay = 0;
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
//Calculate delay based on config file input
Configuration config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
int hrs = config.getInt("Hours", "Time", -1, -1, 23, "Hour of the day; 0-23; -1 to disable");
int mins = config.getInt("Minutes", "Time", 0, 0, 59, "Minute of the day; 0-59");
Calendar stopTime = Calendar.getInstance();
stopTime.set(Calendar.MINUTE, mins);
stopTime.set(Calendar.HOUR, hrs);
Calendar nowTime = Calendar.getInstance();
if(nowTime.getTimeInMillis() > stopTime.getTimeInMillis())
stopTime.add(Calendar.DATE, 1); //stop tomorrow if past stop time
delay = stopTime.getTimeInMillis() - nowTime.getTimeInMillis();
}
@EventHandler
public void init(FMLInitializationEvent event) {
//Schedule event
Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {
@Override
public void run() {
MinecraftServer.getServer().stopServer();
}
}, delay, TimeUnit.MILLISECONDS);
}
}
| lgpl-2.1 |
ceph/cephfs-hadoop | src/main/java/org/apache/hadoop/fs/ceph/CephFileSystem.java | 20819 | // -*- mode:Java; tab-width:2; c-basic-offset:2; indent-tabs-mode:t -*-
/**
*
* 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.
*
*
* Implements the Hadoop FS interfaces to allow applications to store
* files in Ceph.
*/
package org.apache.hadoop.fs.ceph;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.net.URI;
import java.net.InetAddress;
import java.util.EnumSet;
import java.lang.Math;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.net.DNS;
import org.apache.hadoop.fs.FsStatus;
import com.ceph.fs.CephFileAlreadyExistsException;
import com.ceph.fs.CephNotDirectoryException;
import com.ceph.fs.CephMount;
import com.ceph.fs.CephStat;
import com.ceph.fs.CephStatVFS;
import com.ceph.crush.Bucket;
import com.ceph.fs.CephFileExtent;
/**
* Known Issues:
*
* 1. Per-file replication and block size are ignored.
*/
public class CephFileSystem extends FileSystem {
private static final Log LOG = LogFactory.getLog(CephFileSystem.class);
private URI uri;
private Path workingDir;
private CephFsProto ceph = null;
private static final int CEPH_STRIPE_COUNT = 1;
private TreeMap<Integer, String> datapools = null;
/**
* Create a new CephFileSystem.
*/
public CephFileSystem() {
}
/**
* Create a new CephFileSystem.
*/
public CephFileSystem(Configuration conf) {
setConf(conf);
}
/**
* Create an absolute path using the working directory.
*/
private Path makeAbsolute(Path path) {
if (path.isAbsolute()) {
return path;
}
return new Path(workingDir, path);
}
public URI getUri() {
return uri;
}
@Override
public void initialize(URI uri, Configuration conf) throws IOException {
super.initialize(uri, conf);
if (ceph == null) {
ceph = new CephTalker(conf, LOG);
}
ceph.initialize(uri, conf);
setConf(conf);
this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
this.workingDir = getHomeDirectory();
}
/**
* Open a Ceph file and attach the file handle to an FSDataInputStream.
* @param path The file to open
* @param bufferSize Ceph does internal buffering; but you can buffer in
* the Java code too if you like.
* @return FSDataInputStream reading from the given path.
* @throws IOException if the path DNE or is a
* directory, or there is an error getting data to set up the FSDataInputStream.
*/
public FSDataInputStream open(Path path, int bufferSize) throws IOException {
path = makeAbsolute(path);
// throws filenotfoundexception if path is a directory
int fd = ceph.open(path, CephMount.O_RDONLY, 0);
/* get file size */
CephStat stat = new CephStat();
ceph.fstat(fd, stat);
CephInputStream istream = new CephInputStream(getConf(), ceph, fd,
stat.size, bufferSize);
return new FSDataInputStream(istream);
}
/**
* Close down the CephFileSystem. Runs the base-class close method
* and then kills the Ceph client itself.
*/
@Override
public void close() throws IOException {
super.close(); // this method does stuff, make sure it's run!
ceph.shutdown();
}
/**
* Get an FSDataOutputStream to append onto a file.
* @param path The File you want to append onto
* @param bufferSize Ceph does internal buffering but you can buffer in the Java code as well if you like.
* @param progress The Progressable to report progress to.
* Reporting is limited but exists.
* @return An FSDataOutputStream that connects to the file on Ceph.
* @throws IOException If the file cannot be found or appended to.
*/
public FSDataOutputStream append(Path path, int bufferSize,
Progressable progress) throws IOException {
path = makeAbsolute(path);
if (progress != null) {
progress.progress();
}
int fd = ceph.open(path, CephMount.O_WRONLY|CephMount.O_APPEND, 0);
if (progress != null) {
progress.progress();
}
CephOutputStream ostream = new CephOutputStream(getConf(), ceph, fd,
bufferSize);
return new FSDataOutputStream(ostream, statistics);
}
public Path getWorkingDirectory() {
return workingDir;
}
@Override
public void setWorkingDirectory(Path dir) {
workingDir = makeAbsolute(dir);
}
/**
* Create a directory and any nonexistent parents. Any portion
* of the directory tree can exist without error.
* @param path The directory path to create
* @param perms The permissions to apply to the created directories.
* @return true if successful, false otherwise
* @throws IOException if the path is a child of a file.
*/
@Override
public boolean mkdirs(Path path, FsPermission perms) throws IOException {
path = makeAbsolute(path);
boolean result = false;
try {
ceph.mkdirs(path, (int) perms.toShort());
result = true;
} catch (CephFileAlreadyExistsException e) {
result = true;
}
return result;
}
/**
* Create a directory and any nonexistent parents. Any portion
* of the directory tree can exist without error.
* Apply umask from conf
* @param f The directory path to create
* @return true if successful, false otherwise
* @throws IOException if the path is a child of a file.
*/
@Override
public boolean mkdirs(Path f) throws IOException {
return mkdirs(f, FsPermission.getDirDefault().applyUMask(FsPermission.getUMask(getConf())));
}
/**
* Get stat information on a file. This does not fill owner or group, as
* Ceph's support for these is a bit different than HDFS'.
* @param path The path to stat.
* @return FileStatus object containing the stat information.
* @throws FileNotFoundException if the path could not be resolved.
*/
public FileStatus getFileStatus(Path path) throws IOException {
path = makeAbsolute(path);
CephStat stat = new CephStat();
ceph.lstat(path, stat);
FileStatus status = new FileStatus(stat.size, stat.isDir(),
ceph.get_file_replication(path), stat.blksize, stat.m_time,
stat.a_time, new FsPermission((short) stat.mode),
System.getProperty("user.name"), null, path.makeQualified(this));
return status;
}
/**
* Get the FileStatus for each listing in a directory.
* @param path The directory to get listings from.
* @return FileStatus[] containing one FileStatus for each directory listing;
* null if path does not exist.
*/
public FileStatus[] listStatus(Path path) throws IOException {
path = makeAbsolute(path);
if (isFile(path))
return new FileStatus[] { getFileStatus(path) };
String[] dirlist = ceph.listdir(path);
if (dirlist != null) {
FileStatus[] status = new FileStatus[dirlist.length];
for (int i = 0; i < status.length; i++) {
status[i] = getFileStatus(new Path(path, dirlist[i]));
}
return status;
}
else {
throw new FileNotFoundException("File " + path + " does not exist.");
}
}
@Override
public void setPermission(Path path, FsPermission permission) throws IOException {
path = makeAbsolute(path);
ceph.chmod(path, permission.toShort());
}
@Override
public void setTimes(Path path, long mtime, long atime) throws IOException {
path = makeAbsolute(path);
CephStat stat = new CephStat();
int mask = 0;
if (mtime != -1) {
mask |= CephMount.SETATTR_MTIME;
stat.m_time = mtime;
}
if (atime != -1) {
mask |= CephMount.SETATTR_ATIME;
stat.a_time = atime;
}
ceph.setattr(path, stat, mask);
}
/**
* Get data pools from configuration.
*
* Package-private: used by unit tests
*/
String[] getConfiguredDataPools() {
String pool_list = getConf().get(
CephConfigKeys.CEPH_DATA_POOLS_KEY,
CephConfigKeys.CEPH_DATA_POOLS_DEFAULT);
if (pool_list != null)
return pool_list.split(",");
return new String[0];
}
/**
* Lookup pool size by name.
*
* Package-private: used by unit tests
*/
int getPoolReplication(String pool_name) throws IOException {
int pool_id = ceph.get_pool_id(pool_name);
return ceph.get_pool_replication(pool_id);
}
/**
* Select a data pool given the requested replication factor.
*/
private String selectDataPool(Path path, int repl_wanted) throws IOException {
/* map pool size -> pool name */
TreeMap<Integer, String> pools = new TreeMap<Integer, String>();
/*
* Start with a mapping for the default pool. An error here would indicate
* something bad, so we throw any exceptions. For configured pools we
* ignore some errors.
*/
int fd = ceph.__open(new Path("/"), CephMount.O_RDONLY, 0);
String pool_name = ceph.get_file_pool_name(fd);
ceph.close(fd);
int replication = getPoolReplication(pool_name);
pools.put(new Integer(replication), pool_name);
/*
* Insert extra data pools from configuration. Errors are logged (most
* likely a non-existant pool), and a configured pool will override the
* default pool.
*/
String[] conf_pools = getConfiguredDataPools();
for (String name : conf_pools) {
try {
replication = getPoolReplication(name);
pools.put(new Integer(replication), name);
} catch (IOException e) {
LOG.warn("Error looking up replication of pool: " + name + ", " + e);
}
}
/* Choose smallest entry >= target, or largest in map. */
Map.Entry<Integer, String> entry = pools.ceilingEntry(new Integer(repl_wanted));
if (entry == null)
entry = pools.lastEntry();
/* should always contain default pool */
assert(entry != null);
replication = entry.getKey().intValue();
pool_name = entry.getValue();
/* log non-exact match cases */
if (replication != repl_wanted) {
LOG.info("selectDataPool path=" + path + " pool:repl=" +
pool_name + ":" + replication + " wanted=" + repl_wanted);
}
return pool_name;
}
/**
* Create a new file and open an FSDataOutputStream that's connected to it.
* @param path The file to create.
* @param permission The permissions to apply to the file.
* @param overwrite If true, overwrite any existing file with
* this name; otherwise don't.
* @param bufferSize Ceph does internal buffering, but you can buffer
* in the Java code too if you like.
* @param replication Replication factor. See documentation on the
* "ceph.data.pools" configuration option.
* @param blockSize Ignored by Ceph. You can set client-wide block sizes
* via the fs.ceph.blockSize param if you like.
* @param progress A Progressable to report back to.
* Reporting is limited but exists.
* @return An FSDataOutputStream pointing to the created file.
* @throws IOException if the path is an
* existing directory, or the path exists but overwrite is false, or there is a
* failure in attempting to open for append with Ceph.
*/
public FSDataOutputStream create(Path path, FsPermission permission,
boolean overwrite, int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
path = makeAbsolute(path);
boolean exists = exists(path);
if (progress != null) {
progress.progress();
}
int flags = CephMount.O_WRONLY | CephMount.O_CREAT;
if (exists) {
if (overwrite)
flags |= CephMount.O_TRUNC;
else
throw new FileAlreadyExistsException();
} else {
Path parent = path.getParent();
if (parent != null)
if (!mkdirs(parent))
throw new IOException("mkdirs failed for " + parent.toString());
}
if (progress != null) {
progress.progress();
}
/* Sanity check. Ceph interface uses int for striping strategy */
if (blockSize > Integer.MAX_VALUE) {
blockSize = Integer.MAX_VALUE;
LOG.info("blockSize too large. Rounding down to " + blockSize);
}
/*
* If blockSize <= 0 then we complain. We need to explicitly check for the
* < 0 case (as opposed to allowing Ceph to raise an exception) because
* the ceph_open_layout interface accepts -1 to request Ceph-specific
* defaults.
*/
if (blockSize <= 0)
throw new IllegalArgumentException("Invalid block size: " + blockSize);
/*
* Ceph may impose alignment restrictions on file layout. In this case we
* check if the requested block size is aligned to the granularity of a
* stripe unit used in the file system. When the block size is not aligned
* we automatically adjust to the next largest multiple of stripe unit
* granularity.
*/
int su = ceph.get_stripe_unit_granularity();
if (blockSize % su != 0) {
long newBlockSize = blockSize - (blockSize % su) + su;
LOG.debug("fix alignment: blksize " + blockSize + " new blksize " + newBlockSize);
blockSize = newBlockSize;
}
/*
* The default Ceph data pool is selected to store files unless a specific
* data pool is provided when a file is created. Since a pool has a fixed
* replication factor, in order to achieve a requested replication factor,
* we must select an appropriate data pool to place the file into.
*/
String datapool = selectDataPool(path, replication);
int fd = ceph.open(path, flags, (int)permission.toShort(), (int)blockSize,
CEPH_STRIPE_COUNT, (int)blockSize, datapool);
if (progress != null) {
progress.progress();
}
OutputStream ostream = new CephOutputStream(getConf(), ceph, fd,
bufferSize);
return new FSDataOutputStream(ostream, statistics);
}
/**
* Opens an FSDataOutputStream at the indicated Path with write-progress
* reporting. Same as create(), except fails if parent directory doesn't
* already exist.
* @param path the file name to open
* @param permission
* @param overwrite if a file with this name already exists, then if true,
* the file will be overwritten, and if false an error will be thrown.
* @param bufferSize the size of the buffer to be used.
* @param replication required block replication for the file.
* @param blockSize
* @param progress
* @throws IOException
* @see #setPermission(Path, FsPermission)
* @deprecated API only for 0.20-append
*/
@Deprecated
public FSDataOutputStream createNonRecursive(Path path, FsPermission permission,
boolean overwrite,
int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
path = makeAbsolute(path);
Path parent = path.getParent();
if (parent != null) {
CephStat stat = new CephStat();
ceph.lstat(parent, stat); // handles FileNotFoundException case
if (stat.isFile())
throw new FileAlreadyExistsException(parent.toString());
}
return this.create(path, permission, overwrite,
bufferSize, replication, blockSize, progress);
}
/**
* Rename a file or directory.
* @param src The current path of the file/directory
* @param dst The new name for the path.
* @return true if the rename succeeded, false otherwise.
*/
@Override
public boolean rename(Path src, Path dst) throws IOException {
src = makeAbsolute(src);
dst = makeAbsolute(dst);
try {
CephStat stat = new CephStat();
ceph.lstat(dst, stat);
if (stat.isDir())
return rename(src, new Path(dst, src.getName()));
return false;
} catch (FileNotFoundException e) {}
try {
ceph.rename(src, dst);
} catch (FileNotFoundException e) {
throw e;
} catch (Exception e) {
return false;
}
return true;
}
/**
* Get a BlockLocation object for each block in a file.
*
* @param file A FileStatus object corresponding to the file you want locations for.
* @param start The offset of the first part of the file you are interested in.
* @param len The amount of the file past the offset you are interested in.
* @return A BlockLocation[] where each object corresponds to a block within
* the given range.
*/
@Override
public BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len) throws IOException {
Path abs_path = makeAbsolute(file.getPath());
int fh = ceph.open(abs_path, CephMount.O_RDONLY, 0);
if (fh < 0) {
LOG.error("getFileBlockLocations:got error " + fh + ", exiting and returning null!");
return null;
}
ArrayList<BlockLocation> blocks = new ArrayList<BlockLocation>();
long curPos = start;
long endOff = curPos + len;
do {
CephFileExtent extent = ceph.get_file_extent(fh, curPos);
int[] osds = extent.getOSDs();
String[] names = new String[osds.length];
String[] hosts = new String[osds.length];
String[] racks = new String[osds.length];
for (int i = 0; i < osds.length; i++) {
InetAddress addr = ceph.get_osd_address(osds[i]);
names[i] = addr.getHostAddress();
/*
* Grab the hostname and rack from the crush hierarchy. Current we
* hard code the item types. For a more general treatment, we'll need
* a new configuration option that allows users to map their custom
* crush types to hosts and topology.
*/
Bucket[] path = ceph.get_osd_crush_location(osds[i]);
for (Bucket bucket : path) {
String type = bucket.getType();
if (type.compareTo("host") == 0)
hosts[i] = bucket.getName();
else if (type.compareTo("rack") == 0)
racks[i] = bucket.getName();
}
}
blocks.add(new BlockLocation(names, hosts, racks,
extent.getOffset(), extent.getLength()));
curPos += extent.getLength();
} while(curPos < endOff);
ceph.close(fh);
BlockLocation[] locations = new BlockLocation[blocks.size()];
locations = blocks.toArray(locations);
return locations;
}
@Deprecated
public boolean delete(Path path) throws IOException {
return delete(path, false);
}
public boolean delete(Path path, boolean recursive) throws IOException {
path = makeAbsolute(path);
/* path exists? */
FileStatus status;
try {
status = getFileStatus(path);
} catch (FileNotFoundException e) {
return false;
}
/* we're done if its a file */
if (status.isFile()) {
ceph.unlink(path);
return true;
}
/* get directory contents */
FileStatus[] dirlist = listStatus(path);
if (dirlist == null)
return false;
if (!recursive && dirlist.length > 0)
throw new IOException("Directory " + path.toString() + "is not empty.");
for (FileStatus fs : dirlist) {
if (!delete(fs.getPath(), recursive))
return false;
}
ceph.rmdir(path);
return true;
}
@Override
public short getDefaultReplication() {
return ceph.getDefaultReplication();
}
@Override
public long getDefaultBlockSize() {
return getConf().getLong(
CephConfigKeys.CEPH_OBJECT_SIZE_KEY,
CephConfigKeys.CEPH_OBJECT_SIZE_DEFAULT);
}
@Override
public FsStatus getStatus(Path p) throws IOException {
CephStatVFS stat = new CephStatVFS();
ceph.statfs(p, stat);
FsStatus status = new FsStatus(stat.bsize * stat.blocks,
stat.bsize * (stat.blocks - stat.bavail),
stat.bsize * stat.bavail);
return status;
}
@Override
protected int getDefaultPort() {
return getConf().getInt(
CephConfigKeys.CEPH_PORT,
CephConfigKeys.CEPH_PORT_DEFAULT);
}
}
| lgpl-2.1 |
metteo/jts | jts-test-builder/src/main/java/com/vividsolutions/jtstest/testbuilder/ui/tools/PanTool.java | 2543 | /*
* The JTS Topology Suite is a collection of Java classes that
* implement the fundamental operations required to validate a given
* geo-spatial data set to a known topological specification.
*
* Copyright (C) 2001 Vivid Solutions
*
* 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
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jtstest.testbuilder.ui.tools;
import java.awt.Cursor;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import com.vividsolutions.jtstest.*;
import com.vividsolutions.jtstest.testbuilder.AppCursors;
import com.vividsolutions.jtstest.testbuilder.GeometryEditPanel;
/**
* @version 1.7
*/
public class PanTool extends BasicTool {
private static PanTool singleton = null;
public static PanTool getInstance() {
if (singleton == null)
singleton = new PanTool();
return singleton;
}
private Point2D source;
private PanTool() {
}
public Cursor getCursor() {
return AppCursors.HAND;
}
public void activate() {
source = null;
}
public void mousePressed(MouseEvent e) {
source = toModel(e.getPoint());
}
public void mouseReleased(MouseEvent e) {
if (source == null)
return;
Point2D destination = toModel(e.getPoint());
pan(panel(), source, destination);
}
public static void pan(GeometryEditPanel panel, Point2D source, Point2D destination ) {
double xDisplacement = destination.getX() - source.getX();
double yDisplacement = destination.getY() - source.getY();
panel.zoomPan(xDisplacement, yDisplacement);
}
}
| lgpl-2.1 |
kenzaburo/OpenSaf-FrameWork | java/ais_api_test/src/org/opensaf/ais/clm/test/TrackClusterCallbackForTest.java | 2847 | /* -*- OpenSAF -*-
*
* (C) Copyright 2008 The OpenSAF 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. This file and program are licensed
* under the GNU Lesser General Public License Version 2.1, February 1999.
* The complete license can be accessed from the following location:
* http://opensource.org/licenses/lgpl-license.php
* See the Copying file included with the OpenSAF distribution for full
* licensing terms.
*
* Author(s): Nokia Siemens Networks, OptXware Research & Development LLC.
*/
package org.opensaf.ais.clm.test;
import org.opensaf.ais.test.*;
import org.saforum.ais.AisStatus;
import org.saforum.ais.clm.ClusterNotificationBuffer;
import org.saforum.ais.clm.TrackClusterCallback;
import junit.framework.Assert;
// CLASS DEFINITION
/**
*
* @author Nokia Siemens Networks
* @author Jozsef BIRO
*/
public class TrackClusterCallbackForTest implements TrackClusterCallback {
// INSTANCE FIELDS
int cbCount;
boolean called;
Thread cbThread;
/**
* The value of the notificationBuffer parameter passed to
* trackClusterCallback.
*/
ClusterNotificationBuffer notificationBuffer;
/**
* The value of the numberOfMembers parameter passed to
* trackClusterCallback.
*/
int numberOfMembers;
/**
* The value of the error parameter passed to trackClusterCallback.
*/
AisStatus error;
// INSTANCE METHODS
public synchronized void trackClusterCallback(
ClusterNotificationBuffer notificationBuffer, int numberOfMembers,
AisStatus error) {
System.out.println("JAVA TEST CALLBACK: Executing trackClusterCallback( "
+ notificationBuffer + ", " + numberOfMembers + ", "
+ error + " ) on " + this);
Utils.s_printClusterNotificationBuffer(notificationBuffer,
"The Cluster as returned by the callback: ");
cbCount++;
called = true;
cbThread = Thread.currentThread();
this.notificationBuffer = notificationBuffer;
this.numberOfMembers = numberOfMembers;
this.error = error;
}
synchronized void assertCalled() {
Assert.assertTrue(called);
Assert.assertNotNull(cbThread);
Assert.assertNotNull(notificationBuffer);
Assert.assertTrue(numberOfMembers > 0);
Assert.assertTrue(error.getValue() != 0);
// Assert.assertEquals( error, AisErrorException.OK );
}
synchronized void assertNotCalled() {
Assert.assertFalse(called);
Assert.assertNull(cbThread);
Assert.assertNull(notificationBuffer);
Assert.assertTrue(numberOfMembers == 0);
Assert.assertTrue(error.getValue() == 0);
}
synchronized void reset() {
called = false;
cbThread = null;
notificationBuffer = null;
numberOfMembers = 0;
error = null;
}
synchronized void fullReset() {
reset();
cbCount = 0;
}
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | engine/wizard-core/src/main/java/org/pentaho/reporting/engine/classic/wizard/WizardOverrideFormattingFunction.java | 5616 | /*!
* 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-2017 Hitachi Vantara.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.wizard;
import org.pentaho.reporting.engine.classic.core.AttributeNames;
import org.pentaho.reporting.engine.classic.core.ReportElement;
import org.pentaho.reporting.engine.classic.core.function.AbstractElementFormatFunction;
import org.pentaho.reporting.engine.classic.core.function.StructureFunction;
import org.pentaho.reporting.engine.classic.core.style.ElementStyleKeys;
import org.pentaho.reporting.engine.classic.core.style.TextStyleKeys;
import org.pentaho.reporting.engine.classic.wizard.model.ElementFormatDefinition;
import org.pentaho.reporting.engine.classic.wizard.model.FieldDefinition;
import org.pentaho.reporting.libraries.base.util.StringUtils;
public class WizardOverrideFormattingFunction extends AbstractElementFormatFunction implements StructureFunction {
public WizardOverrideFormattingFunction() {
}
public int getProcessingPriority() {
// executed after the metadata has been applied, but before the style-expressions get applied.
return 6000;
}
/**
* Evaluates all defined style-expressions of the given element.
*
* @param e the element that should be updated.
* @return true, if attributes or style were changed, false if no change was made.
*/
protected boolean evaluateElement( final ReportElement e ) {
if ( e == null ) {
throw new NullPointerException();
}
boolean retval = false;
final Object maybeFormatData = e.getAttribute( AttributeNames.Wizard.NAMESPACE, "CachedWizardFormatData" );
if ( maybeFormatData instanceof ElementFormatDefinition ) {
final ElementFormatDefinition formatDefinition = (ElementFormatDefinition) maybeFormatData;
if ( formatDefinition.getBackgroundColor() != null ) {
e.getStyle().setStyleProperty( ElementStyleKeys.BACKGROUND_COLOR, formatDefinition.getBackgroundColor() );
retval = true;
}
if ( formatDefinition.getFontColor() != null ) {
e.getStyle().setStyleProperty( ElementStyleKeys.PAINT, formatDefinition.getFontColor() );
retval = true;
}
if ( formatDefinition.getFontBold() != null ) {
e.getStyle().setStyleProperty( TextStyleKeys.BOLD, formatDefinition.getFontBold() );
retval = true;
}
if ( formatDefinition.getFontItalic() != null ) {
e.getStyle().setStyleProperty( TextStyleKeys.ITALIC, formatDefinition.getFontItalic() );
retval = true;
}
if ( formatDefinition.getFontName() != null ) {
e.getStyle().setStyleProperty( TextStyleKeys.FONT, formatDefinition.getFontName() );
retval = true;
}
if ( formatDefinition.getFontUnderline() != null ) {
e.getStyle().setStyleProperty( TextStyleKeys.UNDERLINED, formatDefinition.getFontUnderline() );
retval = true;
}
if ( formatDefinition.getFontItalic() != null ) {
e.getStyle().setStyleProperty( TextStyleKeys.ITALIC, formatDefinition.getFontItalic() );
retval = true;
}
if ( formatDefinition.getFontSize() != null ) {
e.getStyle().setStyleProperty( TextStyleKeys.FONTSIZE, formatDefinition.getFontSize() );
retval = true;
}
if ( formatDefinition.getFontStrikethrough() != null ) {
e.getStyle().setStyleProperty( TextStyleKeys.STRIKETHROUGH, formatDefinition.getFontStrikethrough() );
retval = true;
}
if ( formatDefinition.getHorizontalAlignment() != null ) {
e.getStyle().setStyleProperty( ElementStyleKeys.ALIGNMENT, formatDefinition.getHorizontalAlignment() );
retval = true;
}
if ( formatDefinition.getVerticalAlignment() != null ) {
e.getStyle().setStyleProperty( ElementStyleKeys.VALIGNMENT, formatDefinition.getVerticalAlignment() );
retval = true;
}
}
final Object maybeFieldData = e.getAttribute( AttributeNames.Wizard.NAMESPACE, "CachedWizardFieldData" );
if ( maybeFieldData instanceof FieldDefinition ) {
final FieldDefinition fieldDefinition = (FieldDefinition) maybeFieldData;
if ( fieldDefinition.getDataFormat() != null ) {
e.setAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.FORMAT_STRING,
fieldDefinition.getDataFormat() );
retval = true;
}
if ( fieldDefinition.getNullString() != null ) {
e.setAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.NULL_VALUE,
fieldDefinition.getNullString() );
retval = true;
}
if ( "label".equals( e.getElementType().getMetaData().getName() ) &&
!StringUtils.isEmpty( fieldDefinition.getDisplayName() ) ) {
e.setAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.VALUE, fieldDefinition.getDisplayName() );
}
}
return retval;
}
}
| lgpl-2.1 |
champtar/fmj-sourceforge-mirror | src/org/rubycoder/gsm/InvalidGSMFrameException.java | 649 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.rubycoder.gsm;
/**
*
* @author kane
*/
public class InvalidGSMFrameException extends Exception
{
/**
* Creates a new instance of <tt>InvalidGSMFrameException</tt> without
* detail message.
*/
public InvalidGSMFrameException()
{
}
/**
* Constructs an instance of <tt>InvalidGSMFrameException</tt> with the
* specified detail message.
*
* @param msg
* the detail message.
*/
public InvalidGSMFrameException(String msg)
{
super(msg);
}
}
| lgpl-2.1 |
darkeports/tc5-port | src/main/java/thaumcraft/common/tiles/devices/TileArcaneEar.java | 6878 | /* */ package thaumcraft.common.tiles.devices;
/* */
/* */ import java.util.ArrayList;
/* */ import java.util.WeakHashMap;
/* */ import net.minecraft.block.Block;
/* */ import net.minecraft.block.material.Material;
/* */ import net.minecraft.block.state.IBlockState;
/* */ import net.minecraft.nbt.NBTTagCompound;
/* */ import net.minecraft.tileentity.TileEntity;
/* */ import net.minecraft.util.BlockPos;
/* */ import net.minecraft.util.EnumFacing;
/* */ import net.minecraft.util.ITickable;
/* */ import net.minecraft.world.World;
/* */ import net.minecraft.world.WorldProvider;
/* */ import thaumcraft.common.blocks.IBlockEnabled;
/* */ import thaumcraft.common.lib.utils.BlockStateUtils;
/* */
/* */ public class TileArcaneEar extends TileEntity implements ITickable
/* */ {
/* 20 */ public byte note = 0;
/* 21 */ public byte tone = 0;
/* 22 */ public int redstoneSignal = 0;
/* */
/* */
/* */
/* */
/* */ public void writeToNBT(NBTTagCompound par1NBTTagCompound)
/* */ {
/* 29 */ super.writeToNBT(par1NBTTagCompound);
/* 30 */ par1NBTTagCompound.setByte("note", this.note);
/* 31 */ par1NBTTagCompound.setByte("tone", this.tone);
/* */ }
/* */
/* */
/* */
/* */
/* */ public void readFromNBT(NBTTagCompound par1NBTTagCompound)
/* */ {
/* 39 */ super.readFromNBT(par1NBTTagCompound);
/* 40 */ this.note = par1NBTTagCompound.getByte("note");
/* 41 */ this.tone = par1NBTTagCompound.getByte("tone");
/* */
/* 43 */ if (this.note < 0)
/* */ {
/* 45 */ this.note = 0;
/* */ }
/* */
/* 48 */ if (this.note > 24)
/* */ {
/* 50 */ this.note = 24;
/* */ }
/* */ }
/* */
/* */
/* */ public void update()
/* */ {
/* 57 */ if (!this.worldObj.isRemote) {
/* 58 */ if (this.redstoneSignal > 0) {
/* 59 */ this.redstoneSignal -= 1;
/* 60 */ if (this.redstoneSignal == 0) {
/* 61 */ EnumFacing facing = BlockStateUtils.getFacing(getBlockMetadata()).getOpposite();
/* 62 */ TileEntity tileentity = this.worldObj.getTileEntity(this.pos);
/* 63 */ this.worldObj.setBlockState(this.pos, this.worldObj.getBlockState(this.pos).withProperty(IBlockEnabled.ENABLED, Boolean.valueOf(false)), 3);
/* 64 */ if (tileentity != null)
/* */ {
/* 66 */ tileentity.validate();
/* 67 */ this.worldObj.setTileEntity(this.pos, tileentity);
/* */ }
/* 69 */ this.worldObj.notifyBlockOfStateChange(this.pos, getBlockType());
/* 70 */ this.worldObj.notifyBlockOfStateChange(this.pos.offset(facing), getBlockType());
/* 71 */ this.worldObj.markBlockForUpdate(this.pos);
/* */ }
/* */ }
/* 74 */ ArrayList<Integer[]> nbe = (ArrayList)noteBlockEvents.get(Integer.valueOf(this.worldObj.provider.getDimensionId()));
/* 75 */ if (nbe != null) {
/* 76 */ for (Integer[] dat : nbe) {
/* 77 */ if ((dat[3].intValue() == this.tone) && (dat[4].intValue() == this.note) &&
/* 78 */ (getDistanceSq(dat[0].intValue() + 0.5D, dat[1].intValue() + 0.5D, dat[2].intValue() + 0.5D) <= 4096.0D)) {
/* 79 */ EnumFacing facing = BlockStateUtils.getFacing(getBlockMetadata()).getOpposite();
/* 80 */ triggerNote(this.worldObj, this.pos, false);
/* 81 */ this.redstoneSignal = 10;
/* 82 */ TileEntity tileentity = this.worldObj.getTileEntity(this.pos);
/* 83 */ this.worldObj.setBlockState(this.pos, this.worldObj.getBlockState(this.pos).withProperty(IBlockEnabled.ENABLED, Boolean.valueOf(true)), 3);
/* 84 */ if (tileentity != null)
/* */ {
/* 86 */ tileentity.validate();
/* 87 */ this.worldObj.setTileEntity(this.pos, tileentity);
/* */ }
/* 89 */ this.worldObj.notifyBlockOfStateChange(this.pos, getBlockType());
/* 90 */ this.worldObj.notifyBlockOfStateChange(this.pos.offset(facing), getBlockType());
/* 91 */ this.worldObj.markBlockForUpdate(this.pos);
/* 92 */ break;
/* */ }
/* */ }
/* */ }
/* */ }
/* */ }
/* */
/* */
/* 100 */ public static WeakHashMap<Integer, ArrayList<Integer[]>> noteBlockEvents = new WeakHashMap();
/* */
/* */ public void updateTone() {
/* */ try {
/* 104 */ EnumFacing facing = BlockStateUtils.getFacing(getBlockMetadata()).getOpposite();
/* 105 */ Material var5 = this.worldObj.getBlockState(this.pos.offset(facing)).getBlock().getMaterial();
/* 106 */ this.tone = 0;
/* 107 */ if (var5 == Material.rock)
/* */ {
/* 109 */ this.tone = 1;
/* */ }
/* */
/* 112 */ if (var5 == Material.sand)
/* */ {
/* 114 */ this.tone = 2;
/* */ }
/* */
/* 117 */ if (var5 == Material.glass)
/* */ {
/* 119 */ this.tone = 3;
/* */ }
/* */
/* 122 */ if (var5 == Material.wood)
/* */ {
/* 124 */ this.tone = 4;
/* */ }
/* 126 */ markDirty();
/* */ }
/* */ catch (Exception e) {}
/* */ }
/* */
/* */
/* */
/* */
/* */ public void changePitch()
/* */ {
/* 136 */ this.note = ((byte)((this.note + 1) % 25));
/* 137 */ markDirty();
/* */ }
/* */
/* */
/* */
/* */
/* */ public void triggerNote(World world, BlockPos pos, boolean sound)
/* */ {
/* 145 */ byte var6 = -1;
/* 146 */ if (sound) {
/* 147 */ EnumFacing facing = BlockStateUtils.getFacing(getBlockMetadata()).getOpposite();
/* 148 */ Material var5 = world.getBlockState(pos.offset(facing)).getBlock().getMaterial();
/* 149 */ var6 = 0;
/* 150 */ if (var5 == Material.rock)
/* */ {
/* 152 */ var6 = 1;
/* */ }
/* */
/* 155 */ if (var5 == Material.sand)
/* */ {
/* 157 */ var6 = 2;
/* */ }
/* */
/* 160 */ if (var5 == Material.glass)
/* */ {
/* 162 */ var6 = 3;
/* */ }
/* */
/* 165 */ if (var5 == Material.wood)
/* */ {
/* 167 */ var6 = 4;
/* */ }
/* */ }
/* 170 */ world.addBlockEvent(pos, getBlockType(), var6, this.note);
/* */ }
/* */ }
/* Location: C:\Users\Alex\Desktop\Thaumcraft-1.8.9-5.2.4-deobf.jar!\thaumcraft\common\tiles\devices\TileArcaneEar.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | lgpl-2.1 |
deegree/deegree3 | deegree-datastores/deegree-mdstores/deegree-mdstore-iso/src/main/java/org/deegree/metadata/iso/persistence/sql/ServiceManagerProvider.java | 3342 | //$HeadURL: svn+ssh://mschneider@svn.wald.intevation.org/deegree/deegree3/trunk/deegree-core/deegree-core-metadata/src/main/java/org/deegree/metadata/iso/persistence/TransactionHelper.java $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.metadata.iso.persistence.sql;
import java.util.Iterator;
import java.util.ServiceLoader;
import org.deegree.commons.config.ResourceInitException;
import org.deegree.protocol.csw.MetadataStoreException;
/**
* Provides access to the sql service manager.
*
* @author <a href="mailto:goltz@lat-lon.de">Lyn Goltz</a>
* @author last edited by: $Author: lyn $
*
* @version $Revision: $, $Date: $
*/
public class ServiceManagerProvider {
private ServiceManager serviceManager;
private static ServiceManagerProvider instance;
private ServiceManagerProvider() throws MetadataStoreException {
Iterator<ServiceManager> iter = ServiceLoader.load( ServiceManager.class ).iterator();
while ( iter.hasNext() ) {
if ( serviceManager != null ) {
String msg = "It is not allowed to specify more than one service manager. Please check "
+ ServiceManager.class.getName();
throw new MetadataStoreException( msg );
}
serviceManager = iter.next();
}
if ( serviceManager == null ) {
serviceManager = new DefaultServiceManager();
}
}
/**
* @return the {@link ServiceManager}, never <code>null</code>
*/
public ServiceManager getServiceManager() {
return serviceManager;
}
/**
* @return the one and only instance of the {@link ServiceManagerProvider}, never <code>null</code>
* @throws ResourceInitException
* if more than one {@link ServiceManager} was found
*/
public synchronized static ServiceManagerProvider getInstance()
throws MetadataStoreException {
if ( instance == null ) {
instance = new ServiceManagerProvider();
}
return instance;
}
} | lgpl-2.1 |
CreativeMD/LittleTiles | src/main/java/com/creativemd/littletiles/common/action/block/LittleActionDestroyBoxes.java | 16705 | package com.creativemd.littletiles.common.action.block;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import com.creativemd.creativecore.common.utils.mc.WorldUtils;
import com.creativemd.littletiles.common.action.LittleAction;
import com.creativemd.littletiles.common.action.LittleActionCombined;
import com.creativemd.littletiles.common.action.LittleActionException;
import com.creativemd.littletiles.common.action.block.LittleActionDestroy.StructurePreview;
import com.creativemd.littletiles.common.structure.LittleStructure;
import com.creativemd.littletiles.common.structure.exception.CorruptedConnectionException;
import com.creativemd.littletiles.common.structure.exception.NotYetConnectedException;
import com.creativemd.littletiles.common.tile.LittleTile;
import com.creativemd.littletiles.common.tile.math.box.LittleAbsoluteBox;
import com.creativemd.littletiles.common.tile.math.box.LittleBox;
import com.creativemd.littletiles.common.tile.math.box.LittleBoxReturnedVolume;
import com.creativemd.littletiles.common.tile.math.box.LittleBoxes;
import com.creativemd.littletiles.common.tile.parent.IParentTileList;
import com.creativemd.littletiles.common.tile.parent.ParentTileList;
import com.creativemd.littletiles.common.tile.preview.LittleAbsolutePreviews;
import com.creativemd.littletiles.common.tile.preview.LittlePreview;
import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles;
import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles.TileEntityInteractor;
import com.creativemd.littletiles.common.util.grid.LittleGridContext;
import com.creativemd.littletiles.common.util.ingredient.LittleIngredients;
import com.creativemd.littletiles.common.util.ingredient.LittleInventory;
import com.creativemd.littletiles.common.util.place.PlacementMode;
import com.creativemd.littletiles.common.util.selection.selector.TileSelector;
import io.netty.buffer.ByteBuf;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class LittleActionDestroyBoxes extends LittleActionBoxes {
public LittleActionDestroyBoxes(LittleBoxes boxes) {
super(boxes);
}
public LittleActionDestroyBoxes() {
}
public List<StructurePreview> destroyedStructures;
public LittleAbsolutePreviews previews;
private boolean containsStructure(LittleStructure structure) {
for (StructurePreview structurePreview : destroyedStructures) {
if (structurePreview.structure == structure)
return true;
}
return false;
}
public boolean shouldSkipTile(IParentTileList parent, LittleTile tile) {
return false;
}
public boolean doneSomething;
public LittleIngredients action(EntityPlayer player, TileEntityLittleTiles te, List<LittleBox> boxes, boolean simulate, LittleGridContext context) {
doneSomething = false;
if (previews == null)
previews = new LittleAbsolutePreviews(te.getPos(), context);
LittleIngredients ingredients = new LittleIngredients();
List<LittleTile> placedTiles = new ArrayList<>();
List<LittleTile> destroyedTiles = new ArrayList<>();
for (IParentTileList parent : te.groups()) {
if (parent.isStructure()) {
if (simulate)
continue;
boolean intersects = false;
outer_loop: for (LittleTile tile : parent)
for (int j = 0; j < boxes.size(); j++)
if (tile.intersectsWith(boxes.get(j))) {
intersects = true;
break outer_loop;
}
if (!intersects)
continue;
try {
LittleStructure structure = parent.getStructure();
if (!containsStructure(structure))
destroyedStructures.add(new StructurePreview(structure));
} catch (CorruptedConnectionException | NotYetConnectedException e) {}
} else {
for (LittleTile tile : parent) {
if (shouldSkipTile(parent, tile))
continue;
LittleBox intersecting = null;
boolean intersects = false;
for (int j = 0; j < boxes.size(); j++) {
if (tile.intersectsWith(boxes.get(j))) {
intersects = true;
intersecting = boxes.get(j);
break;
}
}
if (!intersects)
continue;
doneSomething = true;
if (!tile.equalsBox(intersecting)) {
double volume = 0;
LittlePreview preview = tile.getPreviewTile();
List<LittleBox> cutout = new ArrayList<>();
LittleBoxReturnedVolume returnedVolume = new LittleBoxReturnedVolume();
List<LittleBox> newBoxes = tile.cutOut(boxes, cutout, returnedVolume);
if (newBoxes != null) {
if (!simulate) {
for (int i = 0; i < newBoxes.size(); i++) {
LittleTile newTile = tile.copy();
newTile.setBox(newBoxes.get(i));
placedTiles.add(newTile);
}
destroyedTiles.add(tile);
}
for (int l = 0; l < cutout.size(); l++) {
volume += cutout.get(l).getPercentVolume(context);
if (!simulate) {
LittlePreview preview2 = preview.copy();
preview2.box = cutout.get(l).copy();
previews.addPreview(te.getPos(), preview2, context);
}
}
}
if (volume > 0)
ingredients.add(getIngredients(preview, volume));
if (returnedVolume.has())
ingredients.add(getIngredients(preview, returnedVolume.getPercentVolume(context)));
} else {
ingredients.add(getIngredients(parent, tile));
if (!simulate) {
previews.addTile(parent, tile);
destroyedTiles.add(tile);
}
}
}
}
}
if (!simulate) {
te.updateTiles(x -> {
ParentTileList parent = x.noneStructureTiles();
parent.removeAll(destroyedTiles);
parent.addAll(placedTiles);
});
}
return ingredients;
}
@Override
public void action(World world, EntityPlayer player, BlockPos pos, IBlockState state, List<LittleBox> boxes, LittleGridContext context) throws LittleActionException {
fireBlockBreakEvent(world, pos, player);
TileEntity tileEntity = loadTe(player, world, pos, null, true, 0);
if (tileEntity instanceof TileEntityLittleTiles) {
TileEntityLittleTiles te = (TileEntityLittleTiles) tileEntity;
if (context != te.getContext()) {
if (context.size < te.getContext().size) {
for (LittleBox box : boxes)
box.convertTo(context, te.getContext());
context = te.getContext();
} else
te.convertTo(context);
}
if (checkAndGive(player, new LittleInventory(player), action(player, (TileEntityLittleTiles) tileEntity, boxes, true, context)))
action(player, (TileEntityLittleTiles) tileEntity, boxes, false, context);
((TileEntityLittleTiles) tileEntity).combineTiles();
if (!doneSomething)
((TileEntityLittleTiles) tileEntity).convertBlockToVanilla();
}
}
@Override
protected boolean action(EntityPlayer player) throws LittleActionException {
destroyedStructures = new ArrayList<>();
return super.action(player);
}
@Override
public void actionDone(EntityPlayer player, World world) {
for (StructurePreview structure : destroyedStructures) {
try {
if (!structure.structure.mainBlock.isRemoved()) {
if (needIngredients(player) && !world.isRemote) {
ItemStack stack = structure.structure.getStructureDrop();
if (!stack.isEmpty() && !player.addItemStackToInventory(stack))
WorldUtils.dropItem(player, stack);
}
structure.structure.onLittleTileDestroy();
}
} catch (CorruptedConnectionException | NotYetConnectedException e) {}
}
}
@Override
public boolean canBeReverted() {
return true;
}
@Override
public LittleAction revert(EntityPlayer player) {
boolean additionalPreviews = previews != null && previews.size() > 0;
LittleAction[] actions = new LittleAction[(additionalPreviews ? 1 : 0) + destroyedStructures.size()];
if (additionalPreviews) {
previews.convertToSmallest();
actions[0] = new LittleActionPlaceAbsolute(previews, PlacementMode.fill, true);
}
for (int i = 0; i < destroyedStructures.size(); i++)
actions[(additionalPreviews ? 1 : 0) + i] = destroyedStructures.get(i).getPlaceAction();
return new LittleActionCombined(actions);
}
public static class LittleActionDestroyBoxesFiltered extends LittleActionDestroyBoxes {
public TileSelector selector;
public LittleActionDestroyBoxesFiltered(LittleBoxes boxes, TileSelector selector) {
super(boxes);
this.selector = selector;
}
public LittleActionDestroyBoxesFiltered() {
}
@Override
public void writeBytes(ByteBuf buf) {
super.writeBytes(buf);
writeSelector(selector, buf);
}
@Override
public void readBytes(ByteBuf buf) {
super.readBytes(buf);
selector = readSelector(buf);
}
@Override
public boolean shouldSkipTile(IParentTileList parent, LittleTile tile) {
return !selector.is(parent, tile);
}
}
public static List<LittleTile> removeBox(TileEntityLittleTiles te, LittleGridContext context, LittleBox toCut, boolean update, LittleBoxReturnedVolume returnedVolume) {
if (context != te.getContext()) {
if (context.size > te.getContext().size)
te.convertTo(context);
else {
toCut.convertTo(context, te.getContext());
context = te.getContext();
}
}
List<LittleTile> removed = new ArrayList<>();
Consumer<TileEntityInteractor> consumer = x -> {
List<LittleTile> toAdd = new ArrayList<>();
for (LittleTile tile : x.noneStructureTiles()) {
if (!tile.intersectsWith(toCut))
continue;
x.noneStructureTiles().remove(tile);
if (!tile.equalsBox(toCut)) {
double volume = 0;
LittlePreview preview = tile.getPreviewTile();
List<LittleBox> cutout = new ArrayList<>();
List<LittleBox> boxes = new ArrayList<>();
boxes.add(toCut);
List<LittleBox> newBoxes = tile.cutOut(boxes, cutout, returnedVolume);
if (newBoxes != null) {
for (LittleBox box : newBoxes) {
LittleTile copy = tile.copy();
copy.setBox(box);
toAdd.add(copy);
}
for (LittleBox box : cutout) {
LittleTile copy = tile.copy();
copy.setBox(box);
removed.add(copy);
}
}
} else
removed.add(tile);
}
x.noneStructureTiles().addAll(toAdd);
};
if (update)
te.updateTiles(consumer);
else
te.updateTilesSecretly(consumer);
return removed;
}
public static List<LittleTile> removeBoxes(TileEntityLittleTiles te, LittleGridContext context, List<LittleBox> boxes) {
if (context != te.getContext()) {
if (context.size > te.getContext().size)
te.convertTo(context);
else {
for (LittleBox box : boxes) {
box.convertTo(context, te.getContext());
}
context = te.getContext();
}
}
List<LittleTile> removed = new ArrayList<>();
te.updateTiles(x -> {
List<LittleTile> toAdd = new ArrayList<>();
for (Iterator<LittleTile> iterator = x.noneStructureTiles().iterator(); iterator.hasNext();) {
LittleTile tile = iterator.next();
LittleBox intersecting = null;
boolean intersects = false;
for (int j = 0; j < boxes.size(); j++) {
if (tile.intersectsWith(boxes.get(j))) {
intersects = true;
intersecting = boxes.get(j);
break;
}
}
if (!intersects)
continue;
iterator.remove();
if (!tile.equalsBox(intersecting)) {
double volume = 0;
LittlePreview preview = tile.getPreviewTile();
List<LittleBox> cutout = new ArrayList<>();
LittleBoxReturnedVolume returnedVolume = new LittleBoxReturnedVolume();
List<LittleBox> newBoxes = tile.cutOut(boxes, cutout, returnedVolume);
if (newBoxes != null) {
for (LittleBox box : newBoxes) {
LittleTile copy = tile.copy();
copy.setBox(box);
toAdd.add(copy);
}
for (LittleBox box : cutout) {
LittleTile copy = tile.copy();
copy.setBox(box);
removed.add(copy);
}
if (returnedVolume.has())
removed.add(returnedVolume.createFakeTile(tile));
}
} else
removed.add(tile);
}
x.noneStructureTiles().addAll(toAdd);
});
return removed;
}
@Override
public LittleAction flip(Axis axis, LittleAbsoluteBox box) {
return assignFlip(new LittleActionDestroyBoxes(), axis, box);
}
}
| lgpl-2.1 |
johnscancella/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/detect/SynchronizationOnSharedBuiltinConstant.java | 5437 | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2004-2006 University of Maryland
*
* 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 edu.umd.cs.findbugs.detect;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.bcel.Const;
import org.apache.bcel.classfile.Code;
import edu.umd.cs.findbugs.BugAccumulator;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.StringAnnotation;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.FieldSummary;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
public class SynchronizationOnSharedBuiltinConstant extends OpcodeStackDetector {
final Set<String> badSignatures;
final BugAccumulator bugAccumulator;
public SynchronizationOnSharedBuiltinConstant(BugReporter bugReporter) {
this.bugAccumulator = new BugAccumulator(bugReporter);
badSignatures = new HashSet<String>();
badSignatures.addAll(Arrays.asList(new String[] { "Ljava/lang/Boolean;", "Ljava/lang/Double;", "Ljava/lang/Float;",
"Ljava/lang/Byte;", "Ljava/lang/Character;", "Ljava/lang/Short;", "Ljava/lang/Integer;", "Ljava/lang/Long;" }));
}
private static boolean newlyConstructedObject(OpcodeStack.Item item) {
XMethod method = item.getReturnValueOf();
if (method == null) {
return false;
}
return Const.CONSTRUCTOR_NAME.equals(method.getName());
}
private static final Pattern identified = Pattern.compile("\\p{Alnum}+");
BugInstance pendingBug;
int monitorEnterPC;
String syncSignature;
boolean isSyncOnBoolean;
@Override
public void visit(Code obj) {
super.visit(obj);
accumulateBug();
bugAccumulator.reportAccumulatedBugs();
}
@Override
public void sawOpcode(int seen) {
switch (seen) {
case Const.MONITORENTER:
OpcodeStack.Item top = stack.getStackItem(0);
if (pendingBug != null) {
accumulateBug();
}
monitorEnterPC = getPC();
syncSignature = top.getSignature();
isSyncOnBoolean = false;
Object constant = top.getConstant();
if ("Ljava/lang/String;".equals(syncSignature) && constant instanceof String) {
pendingBug = new BugInstance(this, "DL_SYNCHRONIZATION_ON_SHARED_CONSTANT", NORMAL_PRIORITY)
.addClassAndMethod(this);
String value = (String) constant;
if (identified.matcher(value).matches()) {
pendingBug.addString(value).describe(StringAnnotation.STRING_CONSTANT_ROLE);
}
} else if (badSignatures.contains(syncSignature)) {
isSyncOnBoolean = "Ljava/lang/Boolean;".equals(syncSignature);
XField field = top.getXField();
FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary();
OpcodeStack.Item summary = fieldSummary.getSummary(field);
int priority = NORMAL_PRIORITY;
if (isSyncOnBoolean) {
priority--;
}
if (newlyConstructedObject(summary)) {
pendingBug = new BugInstance(this, "DL_SYNCHRONIZATION_ON_UNSHARED_BOXED_PRIMITIVE", NORMAL_PRIORITY)
.addClassAndMethod(this).addType(syncSignature).addOptionalField(field)
.addOptionalLocalVariable(this, top);
} else if (isSyncOnBoolean) {
pendingBug = new BugInstance(this, "DL_SYNCHRONIZATION_ON_BOOLEAN", priority).addClassAndMethod(this)
.addOptionalField(field).addOptionalLocalVariable(this, top);
} else {
pendingBug = new BugInstance(this, "DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE", priority).addClassAndMethod(this)
.addType(syncSignature).addOptionalField(field).addOptionalLocalVariable(this, top);
}
}
break;
case Const.MONITOREXIT:
accumulateBug();
break;
default:
break;
}
}
private void accumulateBug() {
if (pendingBug == null) {
return;
}
bugAccumulator.accumulateBug(pendingBug, SourceLineAnnotation.fromVisitedInstruction(this, monitorEnterPC));
pendingBug = null;
}
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/internal/FilterImpl.java | 5034 | /*
* 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>.
*/
package org.hibernate.internal;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.Filter;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.type.Type;
/**
* Implementation of FilterImpl. FilterImpl implements the user's
* view into enabled dynamic filters, allowing them to set filter parameter values.
*
* @author Steve Ebersole
*/
public class FilterImpl implements Filter, Serializable {
public static final String MARKER = "$FILTER_PLACEHOLDER$";
private transient FilterDefinition definition;
private String filterName;
private Map<String,Object> parameters = new HashMap<String, Object>();
void afterDeserialize(SessionFactoryImpl factory) {
definition = factory.getFilterDefinition(filterName);
validate();
}
/**
* Constructs a new FilterImpl.
*
* @param configuration The filter's global configuration.
*/
public FilterImpl(FilterDefinition configuration) {
this.definition = configuration;
filterName = definition.getFilterName();
}
public FilterDefinition getFilterDefinition() {
return definition;
}
/**
* Get the name of this filter.
*
* @return This filter's name.
*/
public String getName() {
return definition.getFilterName();
}
public Map<String,?> getParameters() {
return parameters;
}
/**
* Set the named parameter's value for this filter.
*
* @param name The parameter's name.
* @param value The value to be applied.
* @return This FilterImpl instance (for method chaining).
* @throws IllegalArgumentException Indicates that either the parameter was undefined or that the type
* of the passed value did not match the configured type.
*/
public Filter setParameter(String name, Object value) throws IllegalArgumentException {
// Make sure this is a defined parameter and check the incoming value type
// TODO: what should be the actual exception type here?
Type type = definition.getParameterType( name );
if ( type == null ) {
throw new IllegalArgumentException( "Undefined filter parameter [" + name + "]" );
}
if ( value != null && !type.getReturnedClass().isAssignableFrom( value.getClass() ) ) {
throw new IllegalArgumentException( "Incorrect type for parameter [" + name + "]" );
}
parameters.put( name, value );
return this;
}
/**
* Set the named parameter's value list for this filter. Used
* in conjunction with IN-style filter criteria.
*
* @param name The parameter's name.
* @param values The values to be expanded into an SQL IN list.
* @return This FilterImpl instance (for method chaining).
*/
public Filter setParameterList(String name, Collection values) throws HibernateException {
// Make sure this is a defined parameter and check the incoming value type
if ( values == null ) {
throw new IllegalArgumentException( "Collection must be not null!" );
}
Type type = definition.getParameterType( name );
if ( type == null ) {
throw new HibernateException( "Undefined filter parameter [" + name + "]" );
}
if ( !values.isEmpty() ) {
Class elementClass = values.iterator().next().getClass();
if ( !type.getReturnedClass().isAssignableFrom( elementClass ) ) {
throw new HibernateException( "Incorrect type for parameter [" + name + "]" );
}
}
parameters.put( name, values );
return this;
}
/**
* Set the named parameter's value list for this filter. Used
* in conjunction with IN-style filter criteria.
*
* @param name The parameter's name.
* @param values The values to be expanded into an SQL IN list.
* @return This FilterImpl instance (for method chaining).
*/
public Filter setParameterList(String name, Object[] values) throws IllegalArgumentException {
return setParameterList( name, Arrays.asList( values ) );
}
/**
* Get the value of the named parameter for the current filter.
*
* @param name The name of the parameter for which to return the value.
* @return The value of the named parameter.
*/
public Object getParameter(String name) {
return parameters.get( name );
}
/**
* Perform validation of the filter state. This is used to verify the
* state of the filter after its enablement and before its use.
*
* @throws HibernateException If the state is not currently valid.
*/
public void validate() throws HibernateException {
// for each of the defined parameters, make sure its value
// has been set
for ( final String parameterName : definition.getParameterNames() ) {
if ( parameters.get( parameterName ) == null ) {
throw new HibernateException(
"Filter [" + getName() + "] parameter [" + parameterName + "] value not set"
);
}
}
}
}
| lgpl-2.1 |
STEMLab/JInedit | src/main/java/edu/pnu/util/IndoorGMLJAXBConvertor.java | 39778 | package edu.pnu.util;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBElement;
import net.opengis.gml.v_3_2_1.AbstractFeatureType;
import net.opengis.gml.v_3_2_1.AbstractGMLType;
import net.opengis.gml.v_3_2_1.AbstractRingPropertyType;
import net.opengis.gml.v_3_2_1.BoundingShapeType;
import net.opengis.gml.v_3_2_1.CodeType;
import net.opengis.gml.v_3_2_1.CurvePropertyType;
import net.opengis.gml.v_3_2_1.DirectPositionType;
import net.opengis.gml.v_3_2_1.EnvelopeType;
import net.opengis.gml.v_3_2_1.FeaturePropertyType;
import net.opengis.gml.v_3_2_1.LineStringType;
import net.opengis.gml.v_3_2_1.LinearRingType;
import net.opengis.gml.v_3_2_1.OrientableCurveType;
import net.opengis.gml.v_3_2_1.OrientableSurfaceType;
import net.opengis.gml.v_3_2_1.PointPropertyType;
import net.opengis.gml.v_3_2_1.PointType;
import net.opengis.gml.v_3_2_1.PolygonType;
import net.opengis.gml.v_3_2_1.ShellPropertyType;
import net.opengis.gml.v_3_2_1.ShellType;
import net.opengis.gml.v_3_2_1.SignType;
import net.opengis.gml.v_3_2_1.SolidPropertyType;
import net.opengis.gml.v_3_2_1.SolidType;
import net.opengis.gml.v_3_2_1.StringOrRefType;
import net.opengis.gml.v_3_2_1.SurfacePropertyType;
import net.opengis.indoorgml.core.AbstractFeature;
import net.opengis.indoorgml.core.CellSpace;
import net.opengis.indoorgml.core.CellSpaceBoundary;
import net.opengis.indoorgml.core.CellSpaceBoundaryOnFloor;
import net.opengis.indoorgml.core.CellSpaceOnFloor;
import net.opengis.indoorgml.core.Edges;
import net.opengis.indoorgml.core.IndoorFeatures;
import net.opengis.indoorgml.core.InterEdges;
import net.opengis.indoorgml.core.InterLayerConnection;
import net.opengis.indoorgml.core.MultiLayeredGraph;
import net.opengis.indoorgml.core.Nodes;
import net.opengis.indoorgml.core.PrimalSpaceFeatures;
import net.opengis.indoorgml.core.SpaceLayer;
import net.opengis.indoorgml.core.SpaceLayers;
import net.opengis.indoorgml.core.State;
import net.opengis.indoorgml.core.Transition;
import net.opengis.indoorgml.core.v_1_0.CellSpaceBoundaryPropertyType;
import net.opengis.indoorgml.core.v_1_0.CellSpaceBoundaryType;
import net.opengis.indoorgml.core.v_1_0.CellSpacePropertyType;
import net.opengis.indoorgml.core.v_1_0.CellSpaceType;
import net.opengis.indoorgml.core.v_1_0.EdgesType;
import net.opengis.indoorgml.core.v_1_0.IndoorFeaturesType;
import net.opengis.indoorgml.core.v_1_0.InterEdgesType;
import net.opengis.indoorgml.core.v_1_0.InterLayerConnectionMemberType;
import net.opengis.indoorgml.core.v_1_0.InterLayerConnectionType;
import net.opengis.indoorgml.core.v_1_0.MultiLayeredGraphType;
import net.opengis.indoorgml.core.v_1_0.NodesType;
import net.opengis.indoorgml.core.v_1_0.ObjectFactory;
import net.opengis.indoorgml.core.v_1_0.PrimalSpaceFeaturesPropertyType;
import net.opengis.indoorgml.core.v_1_0.PrimalSpaceFeaturesType;
import net.opengis.indoorgml.core.v_1_0.SpaceLayerMemberType;
import net.opengis.indoorgml.core.v_1_0.SpaceLayerPropertyType;
import net.opengis.indoorgml.core.v_1_0.SpaceLayerType;
import net.opengis.indoorgml.core.v_1_0.SpaceLayersType;
import net.opengis.indoorgml.core.v_1_0.StateMemberType;
import net.opengis.indoorgml.core.v_1_0.StatePropertyType;
import net.opengis.indoorgml.core.v_1_0.StateType;
import net.opengis.indoorgml.core.v_1_0.TransitionMemberType;
import net.opengis.indoorgml.core.v_1_0.TransitionPropertyType;
import net.opengis.indoorgml.core.v_1_0.TransitionType;
import net.opengis.indoorgml.geometry.AbstractGeometry;
import net.opengis.indoorgml.geometry.LineString;
import net.opengis.indoorgml.geometry.LinearRing;
import net.opengis.indoorgml.geometry.Point;
import net.opengis.indoorgml.geometry.Polygon;
import net.opengis.indoorgml.geometry.Shell;
import net.opengis.indoorgml.geometry.Solid;
import org.geotools.geometry.jts.JTSFactoryFinder;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.GeometryFactory;
import edu.pnu.project.BoundaryType;
import edu.pnu.project.StateOnFloor;
import edu.pnu.project.TransitionOnFloor;
public class IndoorGMLJAXBConvertor {
private int numberOfCell = 0;
private int numberOfState = 0;
private int numberOfState2 = 0;
private int numberOfTransition = 0;
private int numberOfTransition2 = 0;
private boolean isLayer2 = false;
private Envelope envelope;
private double minZ = Double.NaN;
private double maxZ = Double.NaN;
private ObjectFactory IGMLFactory;
private net.opengis.gml.v_3_2_1.ObjectFactory GMLFactory;
private boolean is3DGeometry;
private IndoorFeatures indoorFeatures;
private Map<String, Object> idRegistry;
private Map<CellSpaceBoundary, CellSpaceBoundary> boundary3DMap;
private int orientableSurface_Label;
public IndoorGMLJAXBConvertor(IndoorFeatures indoorFeatures, boolean is3DGeometry) {
this.IGMLFactory = new net.opengis.indoorgml.core.v_1_0.ObjectFactory();
this.GMLFactory = new net.opengis.gml.v_3_2_1.ObjectFactory();
this.indoorFeatures = indoorFeatures;
this.is3DGeometry = is3DGeometry;
idRegistry = new HashMap<String, Object>();
}
//code for jsk
public IndoorGMLJAXBConvertor(IndoorFeatures indoorFeatures, boolean is3DGeometry, Map<CellSpaceBoundary, CellSpaceBoundary> boundary3DMap) {
this.IGMLFactory = new net.opengis.indoorgml.core.v_1_0.ObjectFactory();
this.GMLFactory = new net.opengis.gml.v_3_2_1.ObjectFactory();
this.indoorFeatures = indoorFeatures;
this.is3DGeometry = is3DGeometry;
idRegistry = new HashMap<String, Object>();
this.boundary3DMap = boundary3DMap;
orientableSurface_Label = 1;
}
public JAXBElement<IndoorFeaturesType> getJAXBElement() {
IndoorFeaturesType indoorFeaturesType = createIndoorFeaturesType(null, indoorFeatures);
JAXBElement<IndoorFeaturesType> je = IGMLFactory.createIndoorFeatures(indoorFeaturesType);
/*
System.out.println("Number of Cell : " + numberOfCell);
System.out.println("Number of State : " + numberOfState);
System.out.println("Number of Transition : " + numberOfTransition);
System.out.println("Number of State2 : " + numberOfState2);
System.out.println("Number of Transition2 : " + numberOfTransition2);
*/
return je;
}
private IndoorFeaturesType createIndoorFeaturesType(IndoorFeaturesType target, IndoorFeatures indoorFeatures) {
if(target == null) {
target = IGMLFactory.createIndoorFeaturesType();
}
// 준석햄 데이터를 위한 ID 생성
String generatedID = generateGMLID(indoorFeatures);
target.setId(generatedID);
//target.setId(indoorFeatures.getGmlID());
target.getName().add(createCodeType(null, indoorFeatures.getGmlID(), null));
MultiLayeredGraphType multiLayeredGraphType = createMultiLayeredGraphType(null, indoorFeatures.getMultiLayeredGraph());
target.setMultiLayeredGraph(multiLayeredGraphType);
PrimalSpaceFeaturesType primalSpaceFeaturesType = createPrimalSpaceFeaturesType(null, indoorFeatures.getPrimalSpaceFeatures());
PrimalSpaceFeaturesPropertyType primalSpaceFeaturesPropertyType = IGMLFactory.createPrimalSpaceFeaturesPropertyType();
primalSpaceFeaturesPropertyType.setPrimalSpaceFeatures(primalSpaceFeaturesType);
target.setPrimalSpaceFeatures(primalSpaceFeaturesPropertyType);
idCheck(target);
// BoundedBy
BoundingShapeType boundingShapeType = createBoundedBy(null);
target.setBoundedBy(boundingShapeType);
return target;
}
private BoundingShapeType createBoundedBy(BoundingShapeType target) {
if (target == null) {
target = GMLFactory.createBoundingShapeType();
}
EnvelopeType envelopeType = GMLFactory.createEnvelopeType();
DirectPositionType lowerCorner = GMLFactory.createDirectPositionType();
lowerCorner.getValue().add(envelope.getMinX());
lowerCorner.getValue().add(envelope.getMinY());
lowerCorner.getValue().add(minZ);
envelopeType.setLowerCorner(lowerCorner);
DirectPositionType upperCorner = GMLFactory.createDirectPositionType();
upperCorner.getValue().add(envelope.getMaxX());
upperCorner.getValue().add(envelope.getMaxY());
upperCorner.getValue().add(maxZ);
envelopeType.setUpperCorner(upperCorner);
envelopeType.setSrsDimension(BigInteger.valueOf(3));
envelopeType.setSrsName("EPSG::4326"); // WGS84
JAXBElement<EnvelopeType> jEnvelope = GMLFactory.createEnvelope(envelopeType);
target.setEnvelope(jEnvelope);
return target;
}
private PrimalSpaceFeaturesType createPrimalSpaceFeaturesType(PrimalSpaceFeaturesType target, PrimalSpaceFeatures primalSpaceFeatures) {
if(target == null) {
target = IGMLFactory.createPrimalSpaceFeaturesType();
}
String generatedID = generateGMLID(primalSpaceFeatures);
target.setId(generatedID);
//target.setId(primalSpaceFeatures.getGmlID());
target.getName().add(createCodeType(null, primalSpaceFeatures.getGmlID(), null));
ArrayList<CellSpaceOnFloor> cellSpaceOnFloors = primalSpaceFeatures.getCellSpaceOnFloors();
for(CellSpaceOnFloor cellSpaceOnFloor : cellSpaceOnFloors) {
target = createCellSpaceType(target, cellSpaceOnFloor);
}
ArrayList<CellSpaceBoundaryOnFloor> cellSpaceBoundaryOnFloors = primalSpaceFeatures.getCellSpaceBoundaryOnFloors();
for(CellSpaceBoundaryOnFloor cellSpaceBoundaryOnFloor : cellSpaceBoundaryOnFloors) {
target = createCellSpaceBoundaryType(target, cellSpaceBoundaryOnFloor);
}
idCheck(target);
return target;
}
private PrimalSpaceFeaturesType createCellSpaceType(PrimalSpaceFeaturesType target, CellSpaceOnFloor cellSpaceOnFloor) {
int count = 0;
ArrayList<CellSpace> cellSpaceMember = cellSpaceOnFloor.getCellSpaceMember();
for(CellSpace cellSpace : cellSpaceMember) {
//cellSpaceMemberType = IGMLFactory.createCellSpaceMemberType();
String description = cellSpace.getDescription("Usage");
if (description == null || description.equals("")) {
cellSpace.setDescription("Usage", "Room");
description = cellSpace.getDescription("Usage");
}
setFloorDescription(cellSpace, cellSpaceOnFloor.getFloorProperty().getLevel());
CellSpaceType cellSpaceType = createCellSpaceType(null, cellSpace);
//cellSpaceMemberType.setCellSpace(cellSpaceType);
FeaturePropertyType featurePropertyType = GMLFactory.createFeaturePropertyType();
JAXBElement<CellSpaceType> jCellSpaceType = IGMLFactory.createCellSpace(cellSpaceType);
featurePropertyType.setAbstractFeature(jCellSpaceType);
target.getCellSpaceMember().add(featurePropertyType);
}
System.out.println("Floor : " + cellSpaceOnFloor.getFloorProperty().getLevel() + " stair count : " + count);
return target;
}
private CellSpaceType createCellSpaceType(CellSpaceType target, CellSpace cellSpace) {
numberOfCell++;
if(target == null) {
target = IGMLFactory.createCellSpaceType();
}
String generatedID = generateGMLID(cellSpace);
target.setId(generatedID);
//target.setId(cellSpace.getGmlID());
target.getName().add(createCodeType(null, cellSpace.getGmlID(), null));
target.setDescription(createStringOrRefType(null, cellSpace.getDescription()));
State duality = cellSpace.getDuality();
if(duality != null) {
StatePropertyType statePropertyType = IGMLFactory.createStatePropertyType();
// 준석햄 데이터를 위한 ID 생성
String generatedHref = generateGMLID(duality);
statePropertyType.setHref("#" + generatedHref);
//statePropertyType.setHref("#" + duality.getGmlID());
target.setDuality(statePropertyType);
}
ArrayList<CellSpaceBoundary> partialBoundedBy = cellSpace.getPartialBoundedBy();
for(CellSpaceBoundary cellSpaceBoundary : partialBoundedBy) {
if(is3DGeometry && cellSpaceBoundary.getGeometry3D() == null) continue;
else if(!is3DGeometry && cellSpaceBoundary.getGeometry2D() == null) continue;
CellSpaceBoundaryPropertyType cellSpaceBoundaryPropertyType = IGMLFactory.createCellSpaceBoundaryPropertyType();
String generatedHref = generateGMLID(cellSpaceBoundary);
cellSpaceBoundaryPropertyType.setHref("#" + generatedHref);
//cellSpaceBoundaryPropertyType.setHref("#" + cellSpaceBoundary.getGmlID());
target.getPartialboundedBy().add(cellSpaceBoundaryPropertyType);
}
if(is3DGeometry) {
// geometry3D solid
SolidPropertyType solidPropertyType = createSolidPropertyType(null, cellSpace.getGeometry3D());
target.setGeometry3D(solidPropertyType);
} else {
// geometry2D only polygon
SurfacePropertyType surfacePropertyType = createSurfacePropertyType(null, cellSpace.getGeometry2D());
target.setGeometry2D(surfacePropertyType);
}
// ExternalReference
idCheck(target);
return target;
}
private PrimalSpaceFeaturesType createCellSpaceBoundaryType(PrimalSpaceFeaturesType target, CellSpaceBoundaryOnFloor cellSpaceBoundaryOnFloor) {
ArrayList<CellSpaceBoundary> cellSpaceBoundaryMember = cellSpaceBoundaryOnFloor.getCellSpaceBoundaryMember();
for(CellSpaceBoundary cellSpaceBoundary : cellSpaceBoundaryMember) {
//cellSpaceBoundaryMemberType = IGMLFactory.createCellSpaceBoundaryMemberType();
if(is3DGeometry && cellSpaceBoundary.getGeometry3D() == null) continue;
else if(!is3DGeometry && cellSpaceBoundary.getGeometry2D() == null) continue;
setFloorDescription(cellSpaceBoundary, cellSpaceBoundaryOnFloor.getFloorProperty().getLevel());
CellSpaceBoundaryType cellSpaceBoundaryType = createCellSpaceBoundaryType(null, cellSpaceBoundary);
//cellSpaceBoundaryMemberType.setCellSpaceBoundary(cellSpaceBoundaryType);
FeaturePropertyType featurePropertyType = GMLFactory.createFeaturePropertyType();
JAXBElement<CellSpaceBoundaryType> jCellSpaceBoundaryType = IGMLFactory.createCellSpaceBoundary(cellSpaceBoundaryType);
featurePropertyType.setAbstractFeature(jCellSpaceBoundaryType);
target.getCellSpaceBoundaryMember().add(featurePropertyType);
}
return target;
}
private CellSpaceBoundaryType createCellSpaceBoundaryType(CellSpaceBoundaryType target, CellSpaceBoundary cellSpaceBoundary) {
if (cellSpaceBoundary.getBoundaryType() == BoundaryType.Door) {
cellSpaceBoundary.setDescription("Usage", "Door");
if (cellSpaceBoundary.getDuality() == null) {
System.out.println("****** " + cellSpaceBoundary.getGmlID() + " don't have duliaty !! ********");
}
}
if(target == null) {
target = IGMLFactory.createCellSpaceBoundaryType();
}
String generatedID = generateGMLID(cellSpaceBoundary);
target.setId(generatedID);
//target.setId(cellSpaceBoundary.getGmlID());
target.getName().add(createCodeType(null, cellSpaceBoundary.getGmlID(), null));
target.setDescription(createStringOrRefType(null, cellSpaceBoundary.getDescription()));
Transition duality = cellSpaceBoundary.getDuality();
if(duality != null) {
TransitionPropertyType transitionPropertyType = IGMLFactory.createTransitionPropertyType();
String generatedHref = generateGMLID(duality);
transitionPropertyType.setHref("#" + generatedHref);
//transitionPropertyType.setHref("#" + duality.getGmlID());
target.setDuality(transitionPropertyType);
}
if(is3DGeometry) {
// geometry3D solid
SurfacePropertyType surfacePropertyType = createSurfacePropertyType(null, cellSpaceBoundary.getGeometry3D());
target.setGeometry3D(surfacePropertyType);
} else {
// geometry2D only polygon
CurvePropertyType curvePropertyType = createCurvePropertyType(null, cellSpaceBoundary.getGeometry2D());
target.setGeometry2D(curvePropertyType);
}
// ExternalReference
idCheck(target);
return target;
}
private MultiLayeredGraphType createMultiLayeredGraphType(MultiLayeredGraphType target, MultiLayeredGraph multiLayeredGraph) {
if(target == null) {
target = IGMLFactory.createMultiLayeredGraphType();
}
String generatedID = generateGMLID(multiLayeredGraph);
target.setId(generatedID);
//target.setId(multiLayeredGraph.getGmlID());
target.getName().add(createCodeType(null, multiLayeredGraph.getName(), null));
target.setDescription(createStringOrRefType(null, multiLayeredGraph.getDescription()));
ArrayList<SpaceLayers> spaceLayersList = multiLayeredGraph.getSpaceLayers();
for(SpaceLayers spaceLayers : spaceLayersList) {
SpaceLayersType spaceLayersType = createSpaceLayersType(null, spaceLayers);
target.getSpaceLayers().add(spaceLayersType);
}
ArrayList<InterEdges> interEdgesList = multiLayeredGraph.getInterEdges();
for(InterEdges interEdges : interEdgesList) {
InterEdgesType interEdgesType = createInterEdgesType(null, interEdges);
if (interEdgesType != null) {
target.getInterEdges().add(interEdgesType);
}
}
return target;
}
private SpaceLayersType createSpaceLayersType(SpaceLayersType target, SpaceLayers spaceLayers) {
if(target == null) {
target = IGMLFactory.createSpaceLayersType();
}
String generatedID = generateGMLID(spaceLayers);
target.setId(generatedID);
//target.setId(spaceLayers.getGmlID());
target.getName().add(createCodeType(null, spaceLayers.getGmlID(), null));
target.setDescription(createStringOrRefType(null, spaceLayers.getDescription()));
ArrayList<SpaceLayer> spaceLayerList = spaceLayers.getSpaceLayerMember();
for(SpaceLayer spaceLayer : spaceLayerList) {
SpaceLayerMemberType spaceLayerMemberType = IGMLFactory.createSpaceLayerMemberType();
SpaceLayerType spaceLayerType = createSpaceLayerType(null, spaceLayer);
spaceLayerMemberType.setSpaceLayer(spaceLayerType);
target.getSpaceLayerMember().add(spaceLayerMemberType);
}
idCheck(target);
return target;
}
private SpaceLayerType createSpaceLayerType(SpaceLayerType target, SpaceLayer spaceLayer) {
if (spaceLayer.getGmlID().equalsIgnoreCase("IS2")) {
isLayer2 = true;
}
if(target == null) {
target = IGMLFactory.createSpaceLayerType();
}
String generatedID = generateGMLID(spaceLayer);
target.setId(generatedID);
//target.setId(spaceLayer.getGmlID());
target.getName().add(createCodeType(null, spaceLayer.getGmlID(), null));
target.setDescription(createStringOrRefType(null, spaceLayer.getDescription()));
ArrayList<Nodes> nodesList = spaceLayer.getNodes();
for(Nodes nodes : nodesList) {
NodesType nodesType = createNodesType(null, nodes);
target.getNodes().add(nodesType);
}
ArrayList<Edges> edgesList = spaceLayer.getEdges();
for(Edges edges : edgesList) {
EdgesType edgesType = createEdgesType(null, edges);
target.getEdges().add(edgesType);
}
idCheck(target);
return target;
}
private NodesType createNodesType(NodesType target, Nodes nodes) {
if(target == null) {
target = IGMLFactory.createNodesType();
}
String generatedID = generateGMLID(nodes);
target.setId(generatedID);
//target.setId(nodes.getGmlID());
target.getName().add(createCodeType(null, nodes.getGmlID(), null));
target.setDescription(createStringOrRefType(null, nodes.getDescription()));
ArrayList<StateOnFloor> stateOnFloorList = nodes.getStateOnFloors();
for(StateOnFloor stateOnFloor : stateOnFloorList) {
target = createStateType(target, stateOnFloor);
}
idCheck(target);
return target;
}
private NodesType createStateType(NodesType target, StateOnFloor stateOnFloor) {
ArrayList<State> stateList = stateOnFloor.getStateMember();
for(State state : stateList) {
setFloorDescription(state, stateOnFloor.getFloorProperty().getLevel());
StateMemberType stateMemberType = IGMLFactory.createStateMemberType();
StateType stateType = createStateType(null, state);
stateMemberType.setState(stateType);
target.getStateMember().add(stateMemberType);
}
return target;
}
private StateType createStateType(StateType target, State state) {
numberOfState++;
if (isLayer2) {
numberOfState2++;
}
if(target == null) {
target = IGMLFactory.createStateType();
}
String generatedID = generateGMLID(state);
target.setId(generatedID);
//target.setId(state.getGmlID());
target.getName().add(createCodeType(null, state.getGmlID(), null));
target.setDescription(createStringOrRefType(null, state.getDescription()));
ArrayList<Transition> connects = state.getTransitionReference();
if(state.getTransitionReference().size() > 0) {
for(Transition connect : connects) {
TransitionPropertyType transitionPropertyType = IGMLFactory.createTransitionPropertyType();
String generatedHref = generateGMLID(connect);
transitionPropertyType.setHref("#" + generatedHref);
//transitionPropertyType.setHref("#" + connect.getGmlID());
target.getConnects().add(transitionPropertyType);
}
}
CellSpace duality = state.getDuality();
if(duality != null) {
CellSpacePropertyType cellSpacePropertyType = IGMLFactory.createCellSpacePropertyType();
String generatedHref = generateGMLID(duality);
cellSpacePropertyType.setHref("#" + generatedHref);
//cellSpacePropertyType.setHref("#" + duality.getGmlID());
target.setDuality(cellSpacePropertyType);
}
PointPropertyType pointPropertyType = createPointPropertyType(null, state.getPosition());
target.setGeometry(pointPropertyType);
/*
if(state.getName() != null) {
CodeType codeType = GMLFactory.createCodeType();
codeType.setValue(state.getName());
stateType.getName().add(codeType);
}*/
idCheck(target);
return target;
}
private EdgesType createEdgesType(EdgesType target, Edges edges) {
if(target == null) {
target = IGMLFactory.createEdgesType();
}
String generatedID = generateGMLID(edges);
target.setId(generatedID);
//target.setId(edges.getGmlID());
target.getName().add(createCodeType(null, edges.getGmlID(), null));
target.setDescription(createStringOrRefType(null, edges.getDescription()));
ArrayList<TransitionOnFloor> transitionOnFloorList = edges.getTransitionOnFloors();
for(TransitionOnFloor transitionOnFloor : transitionOnFloorList) {
target = createTransitionType(target, transitionOnFloor);
}
idCheck(target);
return target;
}
private EdgesType createTransitionType(EdgesType target, TransitionOnFloor transitionOnFloor) {
// TODO Auto-generated method stub
ArrayList<Transition> transitionList = transitionOnFloor.getTransitionMember();
for(Transition transition : transitionList) {
setFloorDescription(transition, transitionOnFloor.getFloorProperty().getLevel());
TransitionMemberType transitionMemberType = IGMLFactory.createTransitionMemberType();
TransitionType transitionType = createTransitionType(null, transition);
transitionMemberType.setTransition(transitionType);
target.getTransitionMember().add(transitionMemberType);
}
return target;
}
private TransitionType createTransitionType(TransitionType target, Transition transition) {
numberOfTransition++;
if (isLayer2) {
numberOfTransition2++;
}
if(target == null) {
target = IGMLFactory.createTransitionType();
}
String generatedID = generateGMLID(transition);
target.setId(generatedID);
//target.setId(transition.getGmlID());
target.getName().add(createCodeType(null, transition.getGmlID(), null));
target.setDescription(createStringOrRefType(null, transition.getDescription()));
State[] states = transition.getStates();
for(State state : states) {
StatePropertyType statePropertyType = IGMLFactory.createStatePropertyType();
String generatedHref = generateGMLID(state);
statePropertyType.setHref("#" + generatedHref);
//statePropertyType.setHref("#" + state.getGmlID());
target.getConnects().add(statePropertyType);
}
CellSpaceBoundary duality = transition.getDuality();
if(is3DGeometry && duality != null) {
if (boundary3DMap.containsKey(duality)) {
duality = boundary3DMap.get(duality);
}
CellSpaceBoundaryPropertyType cellSpaceBoundaryPropertyType = IGMLFactory.createCellSpaceBoundaryPropertyType();
String generatedHref = generateGMLID(duality);
cellSpaceBoundaryPropertyType.setHref("#" + generatedHref);
//cellSpaceBoundaryPropertyType.setHref("#" + duality.getGmlID());
target.setDuality(cellSpaceBoundaryPropertyType);
}
target.setWeight(transition.getWeight());
CurvePropertyType curvePropertyType = createCurvePropertyType(null, transition.getPath());
target.setGeometry(curvePropertyType);
/*
if(transition.getName() != null) {
CodeType codeType = GMLFactory.createCodeType();
codeType.setValue(transition.getName());
transitionType.getName().add(codeType);
}
*/
idCheck(target);
return target;
}
private InterEdgesType createInterEdgesType(InterEdgesType target, InterEdges interEdges) {
if (interEdges.getInterLayerConnectionMember().size() == 0) {
return null;
}
if(target == null) {
target = IGMLFactory.createInterEdgesType();
}
String generatedID = generateGMLID(interEdges);
target.setId(generatedID);
//target.setId(interEdges.getGmlID());
target.getName().add(createCodeType(null, interEdges.getGmlID(), null));
target.setDescription(createStringOrRefType(null, interEdges.getDescription()));
ArrayList<InterLayerConnection> interLayerConnectionList = interEdges.getInterLayerConnectionMember();
for(InterLayerConnection interLayerConnection : interLayerConnectionList) {
InterLayerConnectionMemberType interLayerConnectionMemberType = IGMLFactory.createInterLayerConnectionMemberType();
InterLayerConnectionType interLayerConnectionType = createInterLayerConnectionType(null, interLayerConnection);
interLayerConnectionMemberType.setInterLayerConnection(interLayerConnectionType);
target.getInterLayerConnectionMember().add(interLayerConnectionMemberType);
}
idCheck(target);
return target;
}
private InterLayerConnectionType createInterLayerConnectionType(InterLayerConnectionType target, InterLayerConnection interLayerConnection) {
if(target == null) {
target = IGMLFactory.createInterLayerConnectionType();
}
String generatedID = generateGMLID(interLayerConnection);
target.setId(generatedID);
//target.setId(interLayerConnection.getGmlID());
target.getName().add(createCodeType(null, interLayerConnection.getGmlID(), null));
target.setDescription(createStringOrRefType(null, interLayerConnection.getDescription()));
target.setTypeOfTopoExpression(interLayerConnection.getTopology());
target.setComment(interLayerConnection.getComment());
State[] interConnects = interLayerConnection.getInterConnects();
for(State state : interConnects) {
StatePropertyType statePropertyType = IGMLFactory.createStatePropertyType();
statePropertyType.setHref("#" + state.getGmlID());
target.getInterConnects().add(statePropertyType);
}
SpaceLayer[] connectedLayers = interLayerConnection.getConnectedLayers();
for(SpaceLayer spaceLayer : connectedLayers) {
SpaceLayerPropertyType spaceLayerPropertyType = IGMLFactory.createSpaceLayerPropertyType();
spaceLayerPropertyType.setHref("#" + spaceLayer.getGmlID());
target.getConnectedLayers().add(spaceLayerPropertyType);
}
idCheck(target);
return target;
}
private PointPropertyType createPointPropertyType(PointPropertyType target, Point point) {
if(target == null) {
target = GMLFactory.createPointPropertyType();
}
PointType pointType = GMLFactory.createPointType();
//준석햄 데이터를 위한 ID 생성
String generatedID = generateGMLID(point);
pointType.setId(generatedID);
//pointType.setId(point.getGMLID());
pointType.getName().add(createCodeType(null, point.getGMLID(), null));
DirectPositionType directPositionType = GMLFactory.createDirectPositionType();
directPositionType.getValue().add(point.getRealX());
directPositionType.getValue().add(point.getRealY());
directPositionType.getValue().add(point.getZ());
pointType.setPos(directPositionType);
target.setPoint(pointType);
idCheck(pointType);
expandEnvelope(point.getRealX(), point.getRealY(), point.getZ());
return target;
}
private CurvePropertyType createCurvePropertyType(CurvePropertyType target, LineString lineString) {
if(target == null) {
target = GMLFactory.createCurvePropertyType();
}
if(is3DGeometry && lineString.getxLinkGeometry() != null) {
OrientableCurveType orientableCurveType = GMLFactory.createOrientableCurveType();
CurvePropertyType baseCurvePropertyType = GMLFactory.createCurvePropertyType();
baseCurvePropertyType.setHref("#" + lineString.getxLinkGeometry().getGMLID());
orientableCurveType.setBaseCurve(baseCurvePropertyType);
if(lineString.getIsReversed()) {
orientableCurveType.setOrientation(SignType.VALUE_1);
} else {
orientableCurveType.setOrientation(SignType.VALUE_2);
}
JAXBElement<OrientableCurveType> jOrientableCurveType = GMLFactory.createOrientableCurve(orientableCurveType);
target.setAbstractCurve(jOrientableCurveType);
} else {
LineStringType lineStringType = GMLFactory.createLineStringType();
String generatedID = generateGMLID(lineString);
lineStringType.setId(generatedID);
//lineStringType.setId(lineString.getGMLID());
//lineStringType.getName().add(createCodeType(lineString.getGMLID(), null));
ArrayList<Point> points = lineString.getPoints();
for(int i = 0; i < points.size(); i++) {
Point point = points.get(i);
DirectPositionType directPositionType = GMLFactory.createDirectPositionType();
directPositionType.getValue().add(point.getRealX());
directPositionType.getValue().add(point.getRealY());
directPositionType.getValue().add(point.getZ());
JAXBElement<DirectPositionType> jPosition = GMLFactory.createPos(directPositionType);
lineStringType.getPosOrPointPropertyOrPointRep().add(jPosition);
expandEnvelope(point.getRealX(), point.getRealY(), point.getZ());
}
JAXBElement<LineStringType> jAbstractCurve = GMLFactory.createLineString(lineStringType);
target.setAbstractCurve(jAbstractCurve);
idCheck(lineStringType);
}
return target;
}
private AbstractRingPropertyType createAbstractRingPropertyType(AbstractRingPropertyType target, LinearRing linearRing) {
if(target == null) {
target = GMLFactory.createAbstractRingPropertyType();
}
LinearRingType linearRingType = GMLFactory.createLinearRingType();
ArrayList<Point> points = linearRing.getPoints();
for(int i = 0; i < points.size(); i++) {
Point point = points.get(i);
DirectPositionType directPositonType = GMLFactory.createDirectPositionType();
directPositonType.getValue().add(point.getRealX());
directPositonType.getValue().add(point.getRealY());
directPositonType.getValue().add(point.getZ());
JAXBElement<DirectPositionType> jPosition = GMLFactory.createPos(directPositonType);
linearRingType.getPosOrPointPropertyOrPointRep().add(jPosition);
expandEnvelope(point.getRealX(), point.getRealY(), point.getZ());
}
JAXBElement<LinearRingType> jExteriorRing = GMLFactory.createLinearRing(linearRingType);
target.setAbstractRing(jExteriorRing);
return target;
}
private SurfacePropertyType createSurfacePropertyType(SurfacePropertyType target, Polygon polygon) {
if(target == null) {
target = GMLFactory.createSurfacePropertyType();
}
if(polygon.getxLinkGeometry() != null) {
OrientableSurfaceType orientableSurfaceType = GMLFactory.createOrientableSurfaceType();
orientableSurfaceType.setId("OrientableSurface" + orientableSurface_Label++);
SurfacePropertyType baseSurfacePropertyType = GMLFactory.createSurfacePropertyType();
baseSurfacePropertyType.setHref("#" + polygon.getxLinkGeometry().getGMLID());
orientableSurfaceType.setBaseSurface(baseSurfacePropertyType);
if(polygon.getIsReversed()) {
orientableSurfaceType.setOrientation(SignType.VALUE_1);
} else {
orientableSurfaceType.setOrientation(SignType.VALUE_2);
}
JAXBElement<OrientableSurfaceType> jOrientableSurfaceType = GMLFactory.createOrientableSurface(orientableSurfaceType);
target.setAbstractSurface(jOrientableSurfaceType);
idCheck(orientableSurfaceType);
} else {
PolygonType polygonType = GMLFactory.createPolygonType();
String generatedID = generateGMLID(polygon);
polygonType.setId(generatedID);
//polygonType.setId(polygon.getGMLID());
polygonType.getName().add(createCodeType(null, polygon.getGMLID(), null));
// exterior
AbstractRingPropertyType abstractRingPropertyType = createAbstractRingPropertyType(null, polygon.getExteriorRing());
polygonType.setExterior(abstractRingPropertyType);
// interior
ArrayList<LinearRing> interiorRings = polygon.getInteriorRing();
for(LinearRing interiorRing : interiorRings) {
abstractRingPropertyType = createAbstractRingPropertyType(null, interiorRing);
polygonType.getInterior().add(abstractRingPropertyType);
}
JAXBElement<PolygonType> jPolygonType = GMLFactory.createPolygon(polygonType);
target.setAbstractSurface(jPolygonType);
idCheck(polygonType);
}
return target;
}
private ShellPropertyType createShellPropertyType(ShellPropertyType target, Shell shell) {
if(target == null) {
target = GMLFactory.createShellPropertyType();
}
ShellType shellType = GMLFactory.createShellType();
ArrayList<Polygon> surfaceMember = shell.getSurfaceMember();
for(Polygon polygon : surfaceMember) {
SurfacePropertyType surfacePropertyType = createSurfacePropertyType(null, polygon);
shellType.getSurfaceMember().add(surfacePropertyType);
}
/*Polygon polygon = surfaceMember.get(surfaceMember.size() - 1);
surfacePropertyType = GMLFactory.createSurfacePropertyType();
visit(polygon);
shellType.getSurfaceMember().add(surfacePropertyType);*/
target.setShell(shellType);
return target;
}
private SolidPropertyType createSolidPropertyType(SolidPropertyType target, Solid solid) {
// TODO Auto-generated method stub
if(target == null) {
target = GMLFactory.createSolidPropertyType();
}
SolidType solidType = GMLFactory.createSolidType();
String generatedID = generateGMLID(solid);
solidType.setId(generatedID);
//solidType.setId(solid.getGMLID());
//solidType.getName().add(createCodeType(solid.getGMLID(), null));
// exteior
ShellPropertyType shellPropertyType = createShellPropertyType(null, solid.getExteriorShell());
solidType.setExterior(shellPropertyType);
// interior
JAXBElement<SolidType> jSolidType = GMLFactory.createSolid(solidType);
target.setAbstractSolid(jSolidType);
idCheck(solidType);
return target;
}
private CodeType createCodeType(CodeType target, String name, String codeSpace) {
if(name == null && codeSpace == null)
return null;
if(target == null) {
target = GMLFactory.createCodeType();
}
if(name != null) {
target.setValue(name);
}
if(codeSpace != null) {
target.setCodeSpace(codeSpace);
}
return target;
}
private StringOrRefType createStringOrRefType(StringOrRefType target, String value) {
if(value == null || value.equals(""))
return null;
if(target == null) {
target= GMLFactory.createStringOrRefType();
}
target.setValue(value);
return target;
}
private void setFloorDescription(AbstractFeature target, String floor) {
String[] splits = floor.split("_");
if (splits.length < 2) {
return;
}
String section = splits[0];
floor = splits[1];
if (floor.contains("F")) {
floor = floor.replace("F", "");
}
int intFloor;
if (floor.startsWith("B")) {
floor = floor.replace("B", "");
intFloor = -1 * Integer.parseInt(floor);
} else {
intFloor = Integer.parseInt(floor);
}
target.setDescription("Section", section);
target.setDescription("Floor", String.valueOf(intFloor));
}
private void idCheck(AbstractFeatureType target) {
if (idRegistry.containsKey(target.getId())) {
System.out.println("** Chekcer : " + target.getId() + " found");
} else {
idRegistry.put(target.getId(), target);
}
}
private void idCheck(AbstractGMLType target) {
if (idRegistry.containsKey(target.getId())) {
System.out.println("** Chekcer : " + target.getId() + " found");
} else {
idRegistry.put(target.getId(), target);
}
}
private String generateGMLID(AbstractFeature target) {
return target.getGmlID();
/*
String origin = target.getGmlID();
String intValue = origin.replaceAll("[^0-9]", "");
String typeCode = getIDTypeCode(target);
StringBuffer sb = new StringBuffer();
sb.append(intValue);
sb.append(typeCode);
String generated = sb.toString();
return generated;
*/
}
private String generateGMLID(AbstractGeometry target) {
return target.getGMLID();
/*
String origin = target.getGMLID();
String intValue = origin.replaceAll("[^0-9]", "");
String typeCode = getIDTypeCode(target);
StringBuffer sb = new StringBuffer();
sb.append(intValue);
sb.append(typeCode);
String generated = sb.toString();
return generated;
*/
}
private String getIDTypeCode(Object object) {
String code = null;
if (object instanceof IndoorFeatures) {
code = "01";
} else if (object instanceof PrimalSpaceFeatures) {
code = "02";
} else if (object instanceof CellSpace) {
code = "03";
} else if (object instanceof CellSpaceBoundary) {
code = "04";
} else if (object instanceof MultiLayeredGraph) {
code = "05";
} else if (object instanceof SpaceLayers) {
code = "06";
} else if (object instanceof SpaceLayer) {
code = "07";
} else if (object instanceof Nodes) {
code = "08";
} else if (object instanceof State) {
code = "09";
} else if (object instanceof Edges) {
code = "10";
} else if (object instanceof Transition) {
code = "11";
} else if (object instanceof InterEdges) {
code = "12";
} else if (object instanceof InterLayerConnection) {
code = "13";
} else if (object instanceof Point) {
code = "20";
} else if (object instanceof LineString) {
code = "21";
} else if (object instanceof Polygon) {
code = "22";
} else if (object instanceof Solid) {
code = "23";
}
return code;
}
private void expandEnvelope(double x, double y, double z) {
if (envelope == null) {
envelope = new Envelope();
minZ = z;
maxZ = z;
}
envelope.expandToInclude(x, y);
if (minZ > z) {
minZ = z;
}
if (maxZ < z) {
maxZ = z;
}
}
}
| lgpl-2.1 |
esig/dss | dss-pades-openpdf/src/test/java/eu/europa/esig/dss/pades/validation/DSS1823Test.java | 1588 | /**
* 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.pades.validation;
import java.io.IOException;
import eu.europa.esig.dss.model.DSSDocument;
import eu.europa.esig.dss.model.DSSException;
import eu.europa.esig.dss.pades.exception.InvalidPasswordException;
import eu.europa.esig.dss.pdf.PdfDocumentReader;
import eu.europa.esig.dss.pdf.openpdf.ITextDocumentReader;
public class DSS1823Test extends DSS1823 {
@Override
protected PdfDocumentReader loadPDFDocument(DSSDocument dssDocument) {
try {
return new ITextDocumentReader(dssDocument);
} catch (InvalidPasswordException | IOException e) {
throw new DSSException("Unable to load document");
}
}
}
| lgpl-2.1 |
mengy007/MrFusion-1.8.9 | src/main/java/com/techmafia/mcmods/mrfusion/utility/LogHelper.java | 987 | package com.techmafia.mcmods.mrfusion.utility;
import com.techmafia.mcmods.mrfusion.reference.Reference;
import net.minecraftforge.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
/**
* Created by Meng on 7/27/2015.
*/
public class LogHelper {
public static void log(Level logLevel, Object object) {
FMLLog.log(Reference.MOD_NAME, logLevel, String.valueOf(object));
}
public static void all(Object object) { log(Level.ALL, object); }
public static void debug(Object object) { log(Level.DEBUG, object); }
public static void error(Object object) { log(Level.ERROR, object); }
public static void fatal(Object object) { log(Level.FATAL, object); }
public static void info(Object object) { log(Level.INFO, object); }
public static void off(Object object) { log(Level.OFF, object); }
public static void trace(Object object) { log(Level.TRACE, object); }
public static void warn(Object object) { log(Level.WARN, object); }
}
| lgpl-2.1 |
elias54/Fake-Ores-2 | src/main/java/fr/elias/client/LayerBossPhases.java | 3010 | package fr.elias.client;
import fr.elias.common.EntityOresBoss;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.client.renderer.entity.layers.LayerRenderer;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ResourceLocation;
public class LayerBossPhases implements LayerRenderer {
protected static final ResourceLocation enchantmentEffectTexture = new ResourceLocation("textures/misc/enchanted_item_glint.png");
private final RenderLivingBase<?> renderer;
private final ModelBase modelBoss;
public LayerBossPhases(RenderLivingBase<?> rendererIn, ModelBase modelBoss2) {
this.renderer = rendererIn;
this.modelBoss = modelBoss2;
}
@Override
public void doRenderLayer(EntityLivingBase entitylivingbaseIn, float limbSwing, float limbSwingAmount, float partialTicks, float ageInTicks, float netHeadYaw, float headPitch, float scale) {
this.renderBossPhasesEffect(renderer, entitylivingbaseIn, modelBoss, limbSwing, limbSwingAmount, partialTicks, ageInTicks, netHeadYaw, headPitch, scale);
}
public static void renderBossPhasesEffect(RenderLivingBase<?> renderLivingBase, EntityLivingBase entityLivingBase, ModelBase model, float limbSwing, float limbSwingAmount, float partialTicks, float ageInTicks, float netHeadYaw, float headPitch, float scale) {
EntityOresBoss entityOresBoss = (EntityOresBoss) entityLivingBase;
float f = (float) entityLivingBase.ticksExisted + ageInTicks;
renderLivingBase.bindTexture(enchantmentEffectTexture);
GlStateManager.enableBlend();
GlStateManager.depthFunc(514);
GlStateManager.depthMask(false);
float f1 = 0.5F;
GlStateManager.color(f1, f1, f1, 1.0F);
for (int i = 0; i < 2; ++i) {
GlStateManager.disableLighting();
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_COLOR, GlStateManager.DestFactor.ONE);
float f2 = 0.76F;
switch (entityOresBoss.getPhase()) {
case 2:
GlStateManager.color(0.0F, 0.65F * f2, 0.15F * f2, 1.0F);
break;
case 3:
GlStateManager.color(0.8F * f2, 0.15F * f2, 0.15F * f2, 1.0F);
break;
default:
GlStateManager.color(0.0F, 0.0F, 0.0F, 0.0F);
break;
}
GlStateManager.matrixMode(5890);
GlStateManager.loadIdentity();
float f3 = 0.33333334F;
GlStateManager.scale(f3, f3, f3);
GlStateManager.rotate(30.0F - (float) i * 60.0F, 0.0F, 0.0F, 1.0F);
GlStateManager.translate(0.0F, f * (0.001F + (float) i * 0.003F) * 20.0F, 0.0F);
GlStateManager.matrixMode(5888);
model.render(entityLivingBase, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale);
}
GlStateManager.matrixMode(5890);
GlStateManager.loadIdentity();
GlStateManager.matrixMode(5888);
GlStateManager.enableLighting();
GlStateManager.depthMask(true);
GlStateManager.depthFunc(515);
GlStateManager.disableBlend();
}
@Override
public boolean shouldCombineTextures() {
return false;
}
}
| lgpl-2.1 |
xwiki/xwiki-commons | xwiki-commons-tools/xwiki-commons-tool-verification-resources/src/test/resources/org/xwiki/tool/checkstyle/test/unstable/TestClassWithUnstableAnnotationShouldBeRemovedMultipleSince.java | 1111 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.tool.checkstyle.test;
import org.xwiki.stability.Unstable;
/**
* Whatever.
*
* @since 6.0
* @since 5.0
*/
@Unstable
public class TestClassWithUnstableAnnotationShouldBeRemovedMultipleSince
{
} | lgpl-2.1 |
esig/dss | dss-tsl-validation/src/main/java/eu/europa/esig/dss/tsl/cache/CacheKey.java | 2217 | /**
* 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.tsl.cache;
import eu.europa.esig.dss.spi.DSSUtils;
import java.util.Objects;
/**
* Defines a key for a cache record
*/
public class CacheKey {
/**
* Key of the entry
*/
private final String key;
/**
* The default constructor of CacheKey
*
* @param url
* {@link String} url string of the related file entry
*/
public CacheKey(final String url) {
Objects.requireNonNull(url, "URL cannot be null.");
this.key = DSSUtils.getNormalizedString(url);
}
/**
* Returns encoded key
*
* @return {@link String} key
*/
public String getKey() {
return key;
}
@Override
public String toString() {
return String.format("CacheKey with the key [%s]", key);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CacheKey other = (CacheKey) obj;
if (key == null) {
if (other.key != null) {
return false;
}
} else if (!key.equals(other.key)) {
return false;
}
return true;
}
}
| lgpl-2.1 |
myeeboy/xdoc | src/com/hg/doc/DocUtil.java | 16549 | /*
* ===========================================================
* XDOC mini : a free XML Document Engine
* ===========================================================
*
* (C) Copyright 2004-2015, by WangHuigang.
*
* Project Info: http://myxdoc.sohuapps.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.
*/
package com.hg.doc;
import java.awt.Font;
import java.awt.Point;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.dom4j.Document;
import com.hg.data.BlkExpression;
import com.hg.data.DbTypes;
import com.hg.data.MathExpression;
import com.hg.data.Parser;
import com.hg.data.RowSet;
import com.hg.util.DateUtil;
import com.hg.util.HgException;
import com.hg.util.MapUtil;
import com.hg.util.StrUtil;
import com.hg.util.XUrl;
import com.hg.util.XmlUtil;
public class DocUtil {
public static EleBase cloneEle(XDoc doc, EleBase ele) {
return XDocXml.toDocEle(doc, XDocXml.toXmlEle(ele));
}
public static EleRect getRect(XDoc xdoc, String name) {
EleRect rect = null;
EleBase ele = null;
if (name.startsWith("<")) {
try {
ele = XDocXml.toDocEle(xdoc, XmlUtil.parseText(name).getRootElement());
} catch (Exception e) {
}
}
if (ele != null && ele instanceof EleRect) {
rect = (EleRect) ele;
}
return rect;
}
public static final float dpi = 96;
public static void fixHeads(XDoc doc) {
ArrayList tmpHeads = doc.heads;
doc.heads = new ArrayList();
Heading heading, tmpHeading;
boolean find = false;
for (int i = 0; i < tmpHeads.size(); i++) {
heading = (Heading) tmpHeads.get(i);
find = false;
for (int j = i - 1; j >= 0; j--) {
tmpHeading = (Heading) tmpHeads.get(j);
if (tmpHeading.level() < heading.level()) {
if (tmpHeading.cheads == null) {
tmpHeading.cheads = new ArrayList();
tmpHeading.cheads.add(heading);
} else if (!((Heading) tmpHeading.cheads.get(tmpHeading.cheads.size() - 1)).name().equals(heading.name())) {
tmpHeading.cheads.add(heading);
} else {
tmpHeads.remove(i--);
}
find = true;
break;
}
}
if (!find) {
if (doc.heads.size() == 0 || !((Heading) doc.heads.get(doc.heads.size() - 1)).name().equals(heading.name())) {
doc.heads.add(heading);
} else if (doc.heads.size() > 0) {
tmpHeads.remove(i--);
}
}
}
}
/**
* 非格式属性
*/
public static final String[] noStyleAtt = new String[] {"name", "top", "left", "width", "height", "row", "rowSpan", "col", "colSpan", "line"};
public static boolean isXDoc(String url) {
if (url.endsWith(".xdoc")) {
return true;
} else if (url.endsWith(".zip")) {
try {
ZipInputStream zin = new ZipInputStream((new XUrl(url).getInputStream()));
ZipEntry en = zin.getNextEntry();
zin.close();
return en.getName().endsWith(".xdoc");
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
public static void setCRectToView(EleRect rect) {
EleRect crect;
Point p = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i = 0; i < rect.eleList.size(); i++) {
if (rect.eleList.get(i) instanceof EleRect) {
crect = (EleRect) rect.eleList.get(i);
if (crect.left < p.x) {
p.x = crect.left;
}
if (crect.top < p.y) {
p.y = crect.top;
}
}
}
for (int i = 0; i < rect.eleList.size(); i++) {
if (rect.eleList.get(i) instanceof EleRect) {
crect = (EleRect) rect.eleList.get(i);
crect.left -= p.x;
crect.top -= p.y;
}
}
}
public static XDoc errDoc(Throwable t) {
return DocUtil.strDoc(HgException.getStackTraceMsg(t));
}
public static XDoc strDoc(String str) {
XDoc xdoc = new XDoc();
ElePara para = new ElePara(xdoc);
xdoc.paraList.add(para);
EleText txt = new EleText(xdoc);
txt.text = str;
para.eleList.add(txt);
return xdoc;
}
public static List toTabs(XDoc xdoc) {
ArrayList tabs = new ArrayList();
for (int i = 0; i < xdoc.rectList.size(); i++) {
tabs.add(toTab((EleBase) xdoc.rectList.get(i)));
}
ElePara para;
for (int i = 0; i < xdoc.paraList.size(); i++) {
para = (ElePara) xdoc.paraList.get(i);
for (int j = 0; j < para.eleList.size(); j++) {
if (para.eleList.size() == 1
&& para.eleList.get(0) instanceof EleText
&& ((EleText) para.eleList.get(0)).text.length() == 0) {
continue;
}
tabs.add(toTab((EleBase) para.eleList.get(j)));
}
}
return tabs;
}
private static EleTable toTab(EleBase ele) {
EleTable tab;
if (ele instanceof EleTable) {
tab = (EleTable) ele;
} else if (ele instanceof EleRect) {
EleRect rect = (EleRect) ele;
tab = new EleTable(rect.xdoc);
tab.rows = String.valueOf(rect.height);
tab.cols = String.valueOf(rect.width);
tab.eleList.add(new EleCell(rect));
} else {
tab = new EleTable(ele.xdoc);
if (ele instanceof EleText) {
EleRect rect = new EleRect(ele.xdoc);
ElePara para = new ElePara(ele.xdoc);
para.eleList.add(ele);
rect.eleList.add(para);
tab.eleList.add(new EleCell(rect));
}
}
return tab;
}
public static EleBase copy(XDoc xdoc, EleBase ele) {
return XDocXml.toDocEle(xdoc, XDocXml.toXmlEle(ele));
}
private static int[] headingSize = new int[] {29,24,21,20,18,16};
public static int headingFontSize(int n) {
return (n == 0 || n > headingSize.length) ? XFont.defaultFontSize : headingSize[n - 1];
}
public static int headingSpacing(int n) {
int spacing = 0;
if (n > 0) {
if (n < headingSize.length) {
spacing = headingSize[n - 1] / 2 * 2;
} else if (n > 0 && n < headingSize.length) {
spacing = 4;
}
}
return spacing;
}
public static void setHeadingStyle(ElePara para, int n) {
para.heading = n;
if (para.eleList.size() == 1 && para.eleList.get(0) instanceof EleText) {
EleText txt = ((EleText) para.eleList.get(0));
txt.fontName = n != 0 ? XFont.titleFontName : XFont.defaultFontName;
txt.fontSize = headingFontSize(n);
txt.valign = n == 0 ? "bottom" : "center";
}
para.lineSpacing = headingSpacing(n);
}
public static void autoSize(EleBase ele) {
for (int i = 0; i < ele.eleList.size(); i++) {
autoSize((EleBase) ele.eleList.get(i));
}
if (ele instanceof EleRect) {
((EleRect) ele).autoSize();
}
}
public static boolean isFirstPage(Map paramMap) {
return MapUtil.getBool(paramMap, "firstPage", false);
}
/**
* 根据流内容识别格式
* @param in
* @return
* @throws IOException
* @throws HgException
*/
public static String dataFormat(String urlStr) throws Exception {
//自动识别格式
XUrl url = new XUrl(urlStr);
InputStream in = url.getInputStream();
String format = "txt";
byte[] buf = new byte[256];
in.read(buf);
String str = new String(buf).toLowerCase();
if (str.startsWith("{\\rtf1")) {
format = "rtf";
} else if (str.startsWith("pk")) {
format = "zip";
} else if (str.startsWith("<html") || str.startsWith("<!doctype html")) {
format = "html";
} else if (str.startsWith("<?xml")) {
format = "xml";
} else if (str.startsWith("邢")) {
format = "doc";
}
in.close();
return format;
}
public static Font getDefultFont() {
return XFont.createFont(XFont.defaultFontName, Font.PLAIN, XFont.defaultFontSize);
}
/**
* 修正为绝对路径
* @param path
* @param doc
* @return
*/
public static String fixPath(String path, Document doc) {
if (!path.startsWith("/") && doc != null && doc.getRootElement() != null) {
path = "/" + doc.getRootElement().getName() + "/" + path;
}
return path;
}
public static boolean withSource = false;
public static boolean prettyFormat = false;
public static boolean isWithSource(Map params) {
return MapUtil.getBool(params, "_source", withSource);
}
private static final String[] fullFormat = new String[] {"xdoc", "json", "zip", "pdf", "docx", "jar", "jpd", "fpd", "epub", "png"};
public static boolean isFullFormat(String format) {
for (int i = 0; i < fullFormat.length; i++) {
if (fullFormat[i].equals(format)) {
return true;
}
}
return false;
}
/**
* 修改段落文字属性
* @param e
* @param fontName
* @param fontSizeChange
*/
public static void setPTAtt(EleBase e, String fontName, int fontSizeChange,int lineSpacing, int indentLeft, int indentRight) {
ElePara para;
EleText txt;
EleBase ce;
for (int i = 0; i < e.eleList.size(); i++) {
ce = (EleBase) e.eleList.get(i);
if (ce instanceof EleText) {
txt = (EleText) ce;
if (fontName.length() > 0) {
txt.fontName = fontName;
}
txt.fontSize = txt.fontSize + fontSizeChange;
if (txt.fontSize < 6) {
txt.fontSize = 6;
}
} else if (ce instanceof ElePara) {
para = (ElePara) ce;
para.indentLeft += indentLeft;
para.indentLeft += indentRight;
para.lineSpacing += lineSpacing;
setPTAtt(ce, fontName, fontSizeChange, lineSpacing, indentLeft, indentRight);
} else {
setPTAtt(ce, fontName, fontSizeChange, lineSpacing, indentLeft, indentRight);
}
}
}
public static int getMaxLoop() {
return maxLoop;
}
/**
* 最大循环数
*/
private static int maxLoop = -1;
public static String fixHref(String href, String name) {
return href.equals("#") ? DocUtil.INNER_HREF_PREFIX + name : href;
}
/**
* 文档内内部HREF前缀
*/
public static final String INNER_HREF_PREFIX = "@:";
public static ThreadLocal tlUserDocPath = new ThreadLocal();
public static String serverDocPath = "";
public static String getUserDocPath() {
String upath = (String) tlUserDocPath.get();
return upath != null ? upath : serverDocPath;
}
public static boolean isDynamic(String url) {
return url.startsWith("{")
|| url.startsWith("<")
|| url.startsWith("text:")
|| url.startsWith("data:");
}
public static boolean isBlank(EleRect base) {
return base.name.equals(DocConst.BLANK_RECT) || base.name.startsWith(DocConst.BLANK_RECT_PREFIX);
}
public static String fixFileName(String name) {
return StrUtil.replaceAll(name, "/", "_");
}
public static String fixStoreId(String id) {
String format = "xdat";
id = id.toLowerCase();
int pos = id.lastIndexOf('.');
if (pos >= 0) {
format = id.substring(pos + 1);
id = id.substring(0, pos);
}
StringBuffer sb = new StringBuffer("_");
int i = 0;
if (id.startsWith("a_")) {
sb.append("a_");
i = 2;
}
char c;
for (; i < 32; i++) {
if (i < id.length()) {
c = id.charAt(i);
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'z') {
sb.append(c);
} else {
sb.append((char) (((int) c) % 26 + (int) 'a'));
}
} else {
sb.append('0');
}
}
sb.append(".").append(format);
return sb.toString();
}
public static String simplifyIdName(String name) {
int pos = name.lastIndexOf(".");
if (pos > 0 && name.startsWith("_")) {
for (int i = pos - 1; i >= 0; i--) {
if (name.charAt(i) != '0') {
name = name.substring(0, i + 1) + name.substring(pos);
break;
}
}
}
return name;
}
/**
* 执行打印期表达式
* @param text
* @param xdoc
* @return
*/
public static String printEval(String text, XDoc xdoc) {
if (text.length() > 0 && text.indexOf(DocConst.PRINTMARK_PRE) >= 0) {
String str = text;
//分解出表达式计算
StringBuffer sb = new StringBuffer();
int pos = str.indexOf(DocConst.PRINTMARK_PRE);
if (pos >= 0) {
String expStr;
BlkExpression blkExp = new BlkExpression(null);
blkExp.varMap.put("PAGE", new Long(xdoc.getViewPage()));
blkExp.varMap.put("PAGES", new Long(xdoc.getViewPages()));
blkExp.varMap.put("PAGENO", new Long(xdoc.getViewPage()));
blkExp.varMap.put("PAGECOUNT", new Long(xdoc.getViewPages()));
blkExp.varMap.put("HEADING", xdoc.getViewHeading());
while (pos >= 0) {
if (pos > 0) {
sb.append(str.substring(0, pos));
}
str = str.substring(pos + DocConst.PRINTMARK_PRE.length());
pos = str.indexOf(DocConst.PRINTMARK_POST);
if (pos > 0) {
expStr = str.substring(0, pos).trim();
if (expStr.length() > 0) {
if (expStr.charAt(0) == '\\') {
sb.append(DocConst.PRINTMARK_PRE).append(str.substring(1, pos)).append(DocConst.PRINTMARK_POST);
} else {
try {
expStr = Parser.pretreat(expStr)[0];
MathExpression mathExp = new MathExpression(blkExp, expStr);
mathExp.eval(null);
if (mathExp.resultDataType == DbTypes.DATE) {
sb.append(DateUtil.toDateTimeString((Date) mathExp.result));
} else {
if (mathExp.result instanceof RowSet) {
RowSet rowSet = (RowSet) mathExp.result;
if (rowSet.size() > 0 && rowSet.fieldSize() > 0) {
sb.append(rowSet.getCellValue(0, 0));
}
} else {
sb.append(mathExp.result);
}
}
} catch (Exception e) {
sb.append(DocConst.PRINTMARK_PRE).append(str.substring(0, pos)).append("/*").append(e.getMessage()).append("*/").append(DocConst.PRINTMARK_POST);
}
}
}
str = str.substring(pos + DocConst.PRINTMARK_POST.length());
} else if (pos == 0) {
str = str.substring(1);
} else {
str = DocConst.PRINTMARK_PRE + str;
break;
}
pos = str.indexOf(DocConst.PRINTMARK_PRE);
}
}
sb.append(str);
return sb.toString();
} else {
return text;
}
}
}
| lgpl-2.1 |
retoo/pystructure | parser/org/python/pydev/parser/jython/ReaderCharStream.java | 6388 | package org.python.pydev.parser.jython;
/**
* An implementation of interface CharStream, where the data is read from a Reader. This file started life as a copy of ASCII_CharStream.java.
*/
public final class ReaderCharStream implements CharStream {
int bufsize;
int available;
int tokenBegin;
public int bufpos = -1;
private int bufline[];
private int bufcolumn[];
private int column = 0;
private int line = 1;
private boolean prevCharIsCR = false;
private boolean prevCharIsLF = false;
private java.io.Reader inputStream;
private char[] buffer;
private int maxNextCharInd = 0;
private int inBuf = 0;
private static final boolean DEBUG = false;
private final void ExpandBuff(boolean wrapAround) {
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try {
if (wrapAround) {
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos += (bufsize - tokenBegin));
} else {
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos -= tokenBegin);
}
} catch (Throwable t) {
throw new Error(t.getMessage());
}
bufsize += 2048;
available = bufsize;
tokenBegin = 0;
}
private final void FillBuff() throws java.io.IOException {
if (maxNextCharInd == available) {
if (available == bufsize) {
if (tokenBegin > 2048) {
bufpos = maxNextCharInd = 0;
available = tokenBegin;
} else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
} else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) {
inputStream.close();
throw new java.io.IOException();
} else
maxNextCharInd += i;
return;
} catch (java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
public final char BeginToken() throws java.io.IOException {
tokenBegin = -1;
char c = readChar();
tokenBegin = bufpos;
if(DEBUG){
System.out.println("ReaderCharStream: BeginToken >>"+(int)c+"<<");
}
return c;
}
private final void UpdateLineColumn(char c) {
column++;
if (prevCharIsLF) {
prevCharIsLF = false;
line += (column = 1);
} else if (prevCharIsCR) {
prevCharIsCR = false;
if (c == '\n') {
prevCharIsLF = true;
} else
line += (column = 1);
}
switch (c) {
case '\r':
prevCharIsCR = true;
break;
case '\n':
prevCharIsLF = true;
break;
// ok, this was commented out because the position would not reflect correctly the positions found in the ast.
// this may have other problems, but they have to be analyzed better to see the problems this may bring
// (files that mix tabs and spaces may suffer, but I could not find out very well the problems -- anyway,
// restricting the analysis to files that have only tabs or only spaces seems reasonable -- shortcuts are available
// so that we can convert a file from one type to another, so, what remains is making some lint analysis to be sure of it).
// case '\t' :
// column--;
// column += (8 - (column & 07));
// break;
default:
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
public final char readChar() throws java.io.IOException {
if (inBuf > 0) {
--inBuf;
return buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos];
}
if (++bufpos >= maxNextCharInd)
FillBuff();
char c = buffer[bufpos];
UpdateLineColumn(c);
if(DEBUG){
System.out.println("ReaderCharStream: readChar >>"+(int)c+"<<");
}
return (c);
}
/**
* @deprecated
* @see #getEndColumn
*/
public final int getColumn() {
return bufcolumn[bufpos];
}
/**
* @deprecated
* @see #getEndLine
*/
public final int getLine() {
return bufline[bufpos];
}
public final int getEndColumn() {
return bufcolumn[bufpos];
}
public final int getEndLine() {
return bufline[bufpos];
}
public final int getBeginColumn() {
return bufcolumn[tokenBegin];
}
public final int getBeginLine() {
return bufline[tokenBegin];
}
public final void backup(int amount) {
if(DEBUG){
System.out.println("ReaderCharStream: backup >>"+amount+"<<");
}
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
public ReaderCharStream(java.io.Reader dstream) {
inputStream = dstream;
line = 1;
column = 0;
available = bufsize = 4096;
buffer = new char[bufsize];
bufline = new int[bufsize];
bufcolumn = new int[bufsize];
}
public final String GetImage() {
String s = null;
if (bufpos >= tokenBegin)
s = new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
s = new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1);
if(DEBUG){
System.out.println("ReaderCharStream: GetImage >>"+s+"<<");
}
return s;
}
public final char[] GetSuffix(int len) {
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else {
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
if(DEBUG){
System.out.println("ReaderCharStream: GetSuffix:"+len+" >>"+new String(ret)+"<<");
}
return ret;
}
public void Done() {
buffer = null;
bufline = null;
bufcolumn = null;
}
}
| lgpl-2.1 |
dmcennis/jAudio2Dev | src/jAudioFeatureExtractor/OuterFrame.java | 9341 | /*
* @(#)OuterFrame.java 1.0 April 5, 2005.
*
* McGill Univarsity
*/
package jAudioFeatureExtractor;
import jAudioFeatureExtractor.actions.ExecuteBatchAction;
import org.multihelp.HelpWindow;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Locale;
import java.util.ResourceBundle;
//import javax.help.*;
//import javax.help.*;
/**
* A panel holding various components of the jAudio Feature Extractor GUI
*
* @author Cory McKay
*/
public class OuterFrame extends JFrame {
/* FIELDS ***************************************************************** */
static final long serialVersionUID = 1;
static public final ResourceBundle resourceBundle = ResourceBundle.getBundle("Translations");
/**
* A panel allowing the user to select files to extract features from.
* <p>
* Audio files may also be played, edited and generated here. MIDI files may
* be converted to audio.
*/
public RecordingSelectorPanel recording_selector_panel;
/**
* A panel allowing the user to select features to extract from audio files
* and extract the features. Basic feature parameters may be set and feature
* values and definitions can be saved to disk.
*/
public FeatureSelectorPanel feature_selector_panel;
/**
* A class that contains all the logic for handling events fired from this
* gui. Utilizes the Mediator pattern to control dependencies between
* objects. Also contains all the menu bar actions.
*/
public Controller controller;
/**
* Global menu bar for this application
*/
public JMenuBar menu;
/**
* Radio button for choosing the ACE data format
*/
public JRadioButtonMenuItem ace;
/**
* Radio button for chosing the ARFF data format
*/
public JRadioButtonMenuItem arff;
/**
* Window for displaying the help system.
*/
public HelpWindow helpWindow=null;
/* CONSTRUCTOR ************************************************************ */
/**
* Basic constructor that sets up the GUI.
*/
public OuterFrame(Controller c) {
// Splash code modified by Daniel McEnnis from Graphic Java: Mastering the JFC: AWT
SplashFrame splash = new SplashFrame();
splash.loadSplash();
// Set window title
setTitle("jAudio Feature Extractor");
// Make quit when exit box pressed
setDefaultCloseOperation(EXIT_ON_CLOSE);
// set controller
controller = c;
ace = new JRadioButtonMenuItem("ACE");
arff = new JRadioButtonMenuItem("ARFF");
ButtonGroup bg = new ButtonGroup();
bg.add(ace);
bg.add(arff);
// Instantiate panels
recording_selector_panel = new RecordingSelectorPanel(this, c);
feature_selector_panel = new FeatureSelectorPanel(this, c);
controller.normalise = new JCheckBoxMenuItem(resourceBundle.getString("normalise.recordings"),
false);
Color blue = new Color((float) 0.75, (float) 0.85, (float) 1.0);
this.getContentPane().setBackground(blue);
feature_selector_panel.setBackground(blue);
recording_selector_panel.setBackground(blue);
ace.setSelected(true);
ace.addActionListener(controller.outputTypeAction);
arff.addActionListener(controller.outputTypeAction);
controller.extractionThread = new ExtractionThread(controller, this);
controller.executeBatchAction = new ExecuteBatchAction(controller, this);
JRadioButtonMenuItem sample8 = new JRadioButtonMenuItem("8");
JRadioButtonMenuItem sample11 = new JRadioButtonMenuItem("11.025");
JRadioButtonMenuItem sample16 = new JRadioButtonMenuItem("16");
JRadioButtonMenuItem sample22 = new JRadioButtonMenuItem("22.05");
JRadioButtonMenuItem sample44 = new JRadioButtonMenuItem("44.1");
ButtonGroup sr = new ButtonGroup();
sr.add(sample8);
sr.add(sample11);
sr.add(sample16);
sr.add(sample22);
sr.add(sample44);
sample16.setSelected(true);
sample8.addActionListener(controller.samplingRateAction);
sample11.addActionListener(controller.samplingRateAction);
sample16.addActionListener(controller.samplingRateAction);
sample22.addActionListener(controller.samplingRateAction);
sample44.addActionListener(controller.samplingRateAction);
controller.samplingRateAction.setTarget(new JRadioButtonMenuItem[] {
sample8, sample11, sample16, sample22, sample44 });
controller.removeBatch = new JMenu();
controller.viewBatch = new JMenu();
JMenuItem helpTopics = new JMenuItem(resourceBundle.getString("help.topics"));
menu = new JMenuBar();
menu.setBackground(blue);
JMenu fileMenu = new JMenu(resourceBundle.getString("file"));
fileMenu.add(c.saveAction);
fileMenu.add(c.saveBatchAction);
fileMenu.add(c.loadAction);
fileMenu.add(c.loadBatchAction);
fileMenu.addSeparator();
fileMenu.add(c.addBatchAction);
fileMenu.add(c.executeBatchAction);
controller.removeBatch = new JMenu(resourceBundle.getString("remove.batch"));
controller.removeBatch.setEnabled(false);
fileMenu.add(c.removeBatch);
controller.viewBatch = new JMenu(resourceBundle.getString("view.batch"));
controller.viewBatch.setEnabled(false);
fileMenu.add(c.viewBatch);
fileMenu.addSeparator();
fileMenu.add(c.exitAction);
JMenu editMenu = new JMenu(resourceBundle.getString("edit"));
editMenu.add(c.cutAction);
editMenu.add(c.copyAction);
editMenu.add(c.pasteAction);
JMenu recordingMenu = new JMenu(resourceBundle.getString("recording"));
recordingMenu.add(c.addRecordingsAction);
recordingMenu.add(c.editRecordingsAction);
recordingMenu.add(c.removeRecordingsAction);
recordingMenu.add(c.recordFromMicAction);
recordingMenu.add(c.synthesizeAction);
recordingMenu.add(c.viewFileInfoAction);
recordingMenu.add(c.storeSamples);
recordingMenu.add(c.validate);
JMenu analysisMenu = new JMenu(resourceBundle.getString("analysis"));
analysisMenu.add(c.globalWindowChangeAction);
c.outputType = new JMenu(resourceBundle.getString("output.format"));
c.outputType.add(ace);
c.outputType.add(arff);
analysisMenu.add(c.outputType);
c.sampleRate = new JMenu(resourceBundle.getString("sample.rate.khz"));
c.sampleRate.add(sample8);
c.sampleRate.add(sample11);
c.sampleRate.add(sample16);
c.sampleRate.add(sample22);
c.sampleRate.add(sample44);
analysisMenu.add(c.sampleRate);
analysisMenu.add(controller.normalise);
JMenu playbackMenu = new JMenu(resourceBundle.getString("playback"));
playbackMenu.add(c.playNowAction);
playbackMenu.add(c.playSamplesAction);
playbackMenu.add(c.stopPlayBackAction);
playbackMenu.add(c.playMIDIAction);
JMenu helpMenu = new JMenu(resourceBundle.getString("help"));
helpMenu.add(helpTopics);
helpMenu.add(c.aboutAction);
// HelpSet hs = getHelpSet("Sample.hs");
// HelpBroker hb = hs.createHelpBroker();
//
// CSH.setHelpIDString(helpTopics, "top");
// helpTopics.addActionListener(new CSH.DisplayHelpFromSource(hb));
helpTopics.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e) {
System.out.println(resourceBundle.getString("help.window.started"));
if(helpWindow == null){
helpWindow = new HelpWindow();
}
}
});
menu.add(fileMenu);
menu.add(editMenu);
menu.add(recordingMenu);
menu.add(analysisMenu);
menu.add(playbackMenu);
menu.add(helpMenu);
// Add items to GUI
setLayout(new BorderLayout(8, 8));
add(recording_selector_panel, BorderLayout.WEST);
add(feature_selector_panel, BorderLayout.EAST);
add(menu, BorderLayout.NORTH);
this.setIconImage(Toolkit.getDefaultToolkit().getImage("jAudioLogo3-16.bmp"));
// Display GUI
pack();
splash.endSplash();
splash = null;
setVisible(true);
}
/**
* This method creates the online help system.
*
* @param helpsetfile
* Name of the file where the help file metadata is stored.
* @return Reference to a newly created help set.
*/
public HelpWindow getHelpSet(String helpsetfile) {
HelpWindow hs = new HelpWindow();
return hs;
}
// helper class for creating a splashscreen from Graphic Java: Mastering the JFC: AWT
protected class SplashFrame extends Frame{
private Window window = new Window(this);
private Image image = Toolkit.getDefaultToolkit().getImage("jAudioLogo3-400.jpg");
private ImageCanvas canvas;
public void loadSplash(){
canvas = new ImageCanvas(image);
window.add(canvas,"Center");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation(screenSize.width/2-200,screenSize.height/2-200);
window.setSize(400,400);
window.pack();
window.show();
window.toFront();
}
public void endSplash(){
window.dispose();
}
}
protected class ImageCanvas extends Canvas{
private Image image;
public ImageCanvas(Image image){
this.image=image;
MediaTracker mt = new MediaTracker(this);
mt.addImage(image,0);
try{
mt.waitForID(0);
}catch(Exception e){
e.printStackTrace();
}
}
public void paint(Graphics g){
g.drawImage(image,0,0,this);
}
public void update(Graphics g){
paint(g);
}
public Dimension getPreferredSize(){
return new Dimension(400,400);
}
}
} | lgpl-2.1 |
irockel/tda | tda-visualvm-module/tda-visualvm-module/src/net/java/dev/tda/visualvm/Install.java | 1118 | /*
* This file is part of TDA - Thread Dump Analysis Tool.
*
* TDA is free software; you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* TDA 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public License
* along with TDA; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.java.dev.tda.visualvm;
import org.openide.modules.ModuleInstall;
/**
*
* @author irockel
*/
public class Install extends ModuleInstall {
@Override
public void restored() {
try {
TDAViewProvider.initialize();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| lgpl-2.1 |
davidB/spoon-maven-plugin | src/main/java/net/sf/alchim/spoon/contrib/maven/AbstractCleanMojo.java | 1340 | package net.sf.alchim.spoon.contrib.maven;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import net.sf.alchim.spoon.contrib.launcher.Launcher;
import net.sf.alchim.spoon.contrib.misc.PathHelper;
/**
* Restore sourceDirectory to original.
*
* @author dwayne
*/
public abstract class AbstractCleanMojo extends AbstractMojo {
/**
* @parameter expression="${project}"
* @required
* @readonly
*/
protected MavenProject project;
abstract protected List<String> getSourceRoots() throws Exception;
public void execute() throws MojoExecutionException {
try {
String pathList = System.getProperty(Launcher.SRC_ROOTS);
if (pathList == null) {
getLog().info("nothing to restore");
return;
}
getLog().info("restore source directories to original");
List<String> l = getSourceRoots();
if ( l != null ) {
l.clear();
l.addAll(PathHelper.split(pathList));
}
} catch (Exception exc) {
throw new MojoExecutionException("fail to execute", exc);
}
}
}
| lgpl-2.1 |
jbossws/jbossws-cxf | modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/samples/logicalhandler/SOAPEndpointJAXB.java | 1850 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, 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.logicalhandler;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
@WebService(name = "SOAPEndpoint", targetNamespace = "http://org.jboss.ws/jaxws/samples/logicalhandler")
public interface SOAPEndpointJAXB
{
@WebMethod
@WebResult(targetNamespace = "http://org.jboss.ws/jaxws/samples/logicalhandler", name = "result")
@RequestWrapper(className = "org.jboss.test.ws.jaxws.samples.logicalhandler.Echo")
@ResponseWrapper(className = "org.jboss.test.ws.jaxws.samples.logicalhandler.EchoResponse")
public String echo(@WebParam(targetNamespace = "http://org.jboss.ws/jaxws/samples/logicalhandler", name="String_1") String string1);
}
| lgpl-2.1 |
free-erp/invoicing | invoicing_client/src/org/free_erp/client/ui/forms/basic/CSubjectDialog.java | 6215 | /*
* Copyright 2013, TengJianfa , and other individual contributors as indicated
* by the @authors tag. See the copyright.txt 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.free_erp.client.ui.forms.basic;
import com.jdatabeans.beans.CPanel;
import com.jdatabeans.beans.data.IDataRow;
import com.jdatabeans.beans.data.IDataSource;
import com.jdatabeans.beans.data.IDbSupport;
import com.jdatabeans.beans.data.JDataField;
import com.jdatabeans.beans.data.ObjectDataRow;
import com.jdatabeans.print.CPrintDialog;
import com.jdatabeans.util.MessageBox;
import org.free_erp.client.ui.forms.CBaseDetailedDialog;
import org.free_erp.client.ui.main.Main;
import org.free_erp.client.ui.util.ReportUtilities;
import org.free_erp.client.ui.util.ReportVO;
import com.jdatabeans.beans.CPagePane;
import org.free_erp.service.entity.accounting.Subject;
import org.free_erp.service.entity.accounting.SubjectCatalog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Image;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JPanel;
/**
*
* @author afa
*/
public class CSubjectDialog extends CBaseDetailedDialog
{
private CSubjectManageWindow manageWindow;
protected JDataField idField;
private JDataField nameField;
private JDataField shortNameField;
private JDataField helpCodeField;
private JDataField commentField;
private SubjectCatalog subjectCatalog;
public CSubjectDialog(Frame parent, IDataSource dataSource, IDbSupport support)
{
super(parent, dataSource, support);
this.stopButton.setVisible(false);
this.initC();
}
public CSubjectDialog(Frame parent, CSubjectManageWindow manageWindow, IDataSource dataSource, IDbSupport support)
{
super(parent, dataSource, support);
this.toolBar.remove(this.stopButton);
this.rejiggerTypeButton.setVisible(false);
this.manageWindow = manageWindow;
this.initC();
}
private void initC()
{
this.setTitle("»á¼Æ¿ÆÄ¿");
this.setSize(730, 210);
idField = new JDataField("number", String.class, dataSource);
idField.setEnabled(false);
nameField = new JDataField("name", String.class, dataSource);
nameField.setRequired("¿ÆÄ¿Ãû³Æ", true);
nameField.setMaxLength(30);
shortNameField = new JDataField("shortName",String.class,dataSource);
shortNameField.setMaxLength(30);
helpCodeField = new JDataField("code",String.class,dataSource);
helpCodeField.setMaxLength(10);
commentField = new JDataField("comments",String.class,dataSource);
commentField.setMaxLength(255);
//JTabbedPane tabbedPane = new JTabbedPane();
JPanel p = new JPanel();
p.setLayout(null);
p.setPreferredSize(new Dimension(730, 180));
CPagePane panel = new CPagePane();
this.getContentPane().add("Center", p);
p.setLayout(null);
p.add(panel);
panel.setBounds(20, 5, 690, 120);
int x = 80;
int y = 10; // row
panel.addComponent(idField, x, y, 130, 20, "¿ÆÄ¿±àºÅ", 60);
panel.addComponent(nameField, x + 200, y, 250, 20, "¿ÆÄ¿Ãû³Æ", 60);
y += ROW_SPAN;
x = 80;
panel.addComponent(shortNameField, x, y, 130, 20, "¼ò³Æ", 60);
panel.addComponent(helpCodeField, x + 200, y, 250, 20, "Öú¼ÇÂë", 60);
y += ROW_SPAN;
x = 80;
panel.addComponent(commentField, x, y, 450, 20, "±¸×¢", 60);
}
public void doSaveAndNew()
{
// TODO Auto-generated method stub
if (this.doSave())
{
this.newDataRow();
}
//this.dataSource
}
public boolean newDataRow()
{
this.saveButton.setEnabled(true);
this.saveAndNewButton.setEnabled(true);
SubjectCatalog catalog = null;
if(subjectCatalog != null)
{
catalog = subjectCatalog;
}
if (this.manageWindow != null)
{
catalog = (SubjectCatalog)this.manageWindow.getCurrentCatalog();
}
if (catalog == null)
{
//get the default catalog;
//temp
MessageBox.showMessageDialog(this, "ÄúûÓÐÑ¡ÔñÀà±ð,ÇëÏÈÑ¡ÔñÀà±ð!"); //¿´ÐèÇóÈçºÎ¶¨Òå
return false;
// catalog = new CustomerCatalog();
// catalog.setId(1);
}
Subject subject = new Subject();
subject.setCatalog(catalog);
subjectCatalog = catalog;
subject.setMainSubjectCatalog(catalog.getMainCatalog());
subject.setCompany(Main.getMainFrame().getCompany());
subject.setDebitCredit(catalog.getDebitCredit());
IDataRow dataRow = ObjectDataRow.newDataRow(subject, "id", this.dbSupport);
this.dataSource.insertDataRow(dataRow);
this.dataSource.last();
return true;
}
public void doPrint()
{
if(!this.doSave())
{
return;
}
Map variables = new HashMap();
ReportVO vo = new ReportVO();
Image image = Main.getMainFrame().getCompanyLogo();
vo.setImage(image);
vo.setTitle("ºÏ¼Æ¿ÆÄ¿µ¥±¨±í");
variables = ReportUtilities.creatParameterMap(vo);
CPrintDialog printDialog = new CPrintDialog(this, this.getClass().getResourceAsStream("/com/e68erp/demo/client/report/jaspers/accounting/SubjectDetail.jasper"),variables,this.dataSource.getCurrentDataRow());
printDialog.setVisible(true);
}
}
| lgpl-2.1 |
geotools/geotools | modules/plugin/jdbc/jdbc-postgis/src/test/java/org/geotools/data/postgis/PostgisInEncodingOnlineTest.java | 955 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2017, 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.postgis;
import org.geotools.jdbc.JDBCInEncodingOnlineTest;
import org.geotools.jdbc.JDBCTestSetup;
public class PostgisInEncodingOnlineTest extends JDBCInEncodingOnlineTest {
@Override
protected JDBCTestSetup createTestSetup() {
return new PostGISTestSetup();
}
}
| lgpl-2.1 |
ironjacamar/ironjacamar | deployers/fungal/src/main/java/org/jboss/jca/deployers/fungal/AbstractFungalDeployment.java | 11430 | /*
* IronJacamar, a Java EE Connector Architecture implementation
* Copyright 2008-2010, 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.jca.deployers.fungal;
import org.jboss.jca.core.api.management.Connector;
import org.jboss.jca.core.api.management.ManagementRepository;
import org.jboss.jca.core.bootstrapcontext.BootstrapContextCoordinator;
import org.jboss.jca.core.connectionmanager.ConnectionManager;
import org.jboss.jca.core.spi.mdr.MetadataRepository;
import org.jboss.jca.core.spi.naming.JndiStrategy;
import org.jboss.jca.core.spi.rar.ResourceAdapterRepository;
import org.jboss.jca.core.spi.transaction.recovery.XAResourceRecovery;
import org.jboss.jca.core.spi.transaction.recovery.XAResourceRecoveryRegistry;
import org.jboss.jca.deployers.DeployersLogger;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.resource.spi.ResourceAdapter;
import com.github.fungal.api.classloading.KernelClassLoader;
import com.github.fungal.spi.deployers.Deployment;
/**
* A resource adapter deployment for JCA/SJC
* @author <a href="mailto:jesper.pedersen@ironjacamar.org">Jesper Pedersen</a>
*/
public abstract class AbstractFungalDeployment implements Deployment
{
/** The logger */
protected DeployersLogger log;
/** The deployment */
protected URL deployment;
/** The deployment name */
protected String deploymentName;
/** Activator */
protected boolean activator;
/** The resource adapter instance */
protected ResourceAdapter ra;
/** The resource adapter instance key */
protected String raKey;
/** The bootstrap context identifier */
protected String bootstrapContextId;
/** The JNDI strategy */
protected JndiStrategy jndiStrategy;
/** The MDR */
protected MetadataRepository mdr;
/** The resource adapter repository */
protected ResourceAdapterRepository rar;
/** The connection factories */
protected Object[] cfs;
/** The JNDI names of the connection factories */
protected String[] cfJndis;
/** The connection managers */
protected ConnectionManager[] cfCMs;
/** The admin objects */
protected Object[] aos;
/** The JNDI names of the admin objects */
protected String[] aoJndis;
/** The recovery modules */
protected XAResourceRecovery[] recoveryModules;
/** The recovery registry */
protected XAResourceRecoveryRegistry recoveryRegistry;
/** The management repository */
protected ManagementRepository managementRepository;
/** The management connector */
protected Connector connector;
/** The MBeanServer */
protected MBeanServer server;
/** The ObjectName's */
protected List<ObjectName> objectNames;
/** The classloader */
protected KernelClassLoader cl;
/**
* Constructor
* @param deployment The deployment
* @param deploymentName The deployment name
* @param activator Is this the activator of the deployment
* @param ra The resource adapter instance if present
* @param raKey The resource adapter instance key if present
* @param bootstrapContextId The bootstrap context identifier
* @param jndiStrategy The JNDI strategy
* @param metadataRepository The metadata repository
* @param resourceAdapterRepository The resource adapter repository
* @param cfs The connection factories
* @param cfJndis The JNDI names of the connection factories
* @param cfCMs The connection managers
* @param aos The admin objects
* @param aoJndis The JNDI names of the admin objects
* @param recoveryModules The recovery modules
* @param recoveryRegistry The recovery registry
* @param managementRepository The management repository
* @param connector The management connector instance
* @param server The MBeanServer
* @param objectNames The ObjectNames
* @param cl The classloader for the deployment
* @param log The logger
*/
public AbstractFungalDeployment(URL deployment, String deploymentName, boolean activator, ResourceAdapter ra,
String raKey, String bootstrapContextId,
JndiStrategy jndiStrategy, MetadataRepository metadataRepository,
ResourceAdapterRepository resourceAdapterRepository,
Object[] cfs, String[] cfJndis, ConnectionManager[] cfCMs,
Object[] aos, String[] aoJndis,
XAResourceRecovery[] recoveryModules, XAResourceRecoveryRegistry recoveryRegistry,
ManagementRepository managementRepository, Connector connector,
MBeanServer server, List<ObjectName> objectNames,
KernelClassLoader cl, DeployersLogger log)
{
this.deployment = deployment;
this.deploymentName = deploymentName;
this.activator = activator;
this.ra = ra;
this.raKey = raKey;
this.bootstrapContextId = bootstrapContextId;
this.jndiStrategy = jndiStrategy;
this.mdr = metadataRepository;
this.rar = resourceAdapterRepository;
this.cfs = cfs;
this.cfJndis = cfJndis;
this.cfCMs = cfCMs;
this.aos = aos;
this.aoJndis = aoJndis;
this.recoveryModules = recoveryModules;
this.recoveryRegistry = recoveryRegistry;
this.managementRepository = managementRepository;
this.connector = connector;
this.server = server;
this.objectNames = objectNames;
this.cl = cl;
this.log = log;
}
/**
* Get the unique URL for the deployment
* @return The URL
*/
@Override
public URL getURL()
{
return deployment;
}
/**
* Get the classloader
* @return The classloader
*/
@Override
public ClassLoader getClassLoader()
{
return cl;
}
/**
* Stop
*/
public void stop()
{
if (activator)
{
if (log.isDebugEnabled())
{
log.debug("Undeploying: " + deployment.toExternalForm());
}
if (server != null && objectNames != null)
{
for (ObjectName on : objectNames)
{
try
{
server.unregisterMBean(on);
}
catch (Throwable t)
{
log.warn("Exception during unregistering deployment", t);
}
}
}
if (recoveryRegistry != null && recoveryModules != null)
{
for (XAResourceRecovery recovery : recoveryModules)
{
if (recovery != null)
{
try
{
recovery.shutdown();
}
catch (Exception e)
{
log.error("Error during recovery shutdown", e);
}
finally
{
recoveryRegistry.removeXAResourceRecovery(recovery);
}
}
}
}
if (managementRepository != null && connector != null)
managementRepository.getConnectors().remove(connector);
if (mdr != null && cfs != null && cfJndis != null)
{
for (int i = 0; i < cfs.length; i++)
{
try
{
String cf = cfs[i].getClass().getName();
String jndi = cfJndis[i];
mdr.unregisterJndiMapping(deployment.toExternalForm(), cf, jndi);
}
catch (org.jboss.jca.core.spi.mdr.NotFoundException nfe)
{
log.warn("Exception during unregistering deployment", nfe);
}
}
}
if (mdr != null && aos != null && aoJndis != null)
{
for (int i = 0; i < aos.length; i++)
{
try
{
String ao = aos[i].getClass().getName();
String jndi = aoJndis[i];
mdr.unregisterJndiMapping(deployment.toExternalForm(), ao, jndi);
}
catch (org.jboss.jca.core.spi.mdr.NotFoundException nfe)
{
log.warn("Exception during unregistering deployment", nfe);
}
}
}
if (cfCMs != null)
{
for (ConnectionManager cm : cfCMs)
{
cm.shutdown();
}
}
if (cfs != null && cfJndis != null)
{
try
{
jndiStrategy.unbindConnectionFactories(deploymentName, cfs, cfJndis);
for (String jndi : cfJndis)
{
log.infof("Unbound connection factory at: %s", jndi);
}
}
catch (Throwable t)
{
log.warn("Exception during JNDI unbinding", t);
}
}
if (aos != null && aoJndis != null)
{
try
{
jndiStrategy.unbindAdminObjects(deploymentName, aos, aoJndis);
for (String jndi : aoJndis)
{
log.infof("Unbound admin object at: %s", jndi);
}
}
catch (Throwable t)
{
log.warn("Exception during JNDI unbinding", t);
}
}
if (raKey != null && rar != null)
{
try
{
rar.unregisterResourceAdapter(raKey);
}
catch (org.jboss.jca.core.spi.rar.NotFoundException nfe)
{
log.warn("Exception during unregistering deployment", nfe);
}
}
if (ra != null)
{
ra.stop();
ra = null;
BootstrapContextCoordinator.getInstance().removeBootstrapContext(bootstrapContextId);
}
}
}
/**
* Destroy
*/
public void destroy()
{
if (activator)
{
log.info("Undeployed: " + deployment.toExternalForm());
}
if (cl != null)
{
try
{
cl.shutdown();
}
catch (IOException ioe)
{
// Swallow
}
}
}
}
| lgpl-2.1 |
DrMeepster/-Minecraft-Wily-Wonka-s-Marvelous-Mod- | src/main/java/drmeepster/wwmm/proxy/ClientProxy.java | 2461 | package drmeepster.wwmm.proxy;
import com.sun.istack.internal.Nullable;
import drmeepster.wwmm.block.BlockGroundCocoa;
import drmeepster.wwmm.block.BlockHardTaffy;
import drmeepster.wwmm.block.BlockHarderTaffy;
import drmeepster.wwmm.block.BlockSugarGrass;
import drmeepster.wwmm.utill.WonkaBlocks;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.color.IBlockColor;
import net.minecraft.client.renderer.color.IItemColor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.ColorizerGrass;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.biome.BiomeColorHelper;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class ClientProxy {
public static void registerItemModels(){
ModelLoader.setCustomModelResourceLocation(WonkaBlocks.hardTaffy.itemForm, 0, new ModelResourceLocation(BlockHardTaffy.RESLOC, "inventory"));
ModelLoader.setCustomModelResourceLocation(WonkaBlocks.groundCocoa.itemForm, 0, new ModelResourceLocation(BlockGroundCocoa.RESLOC, ""));
ModelLoader.setCustomModelResourceLocation(WonkaBlocks.sugarGrass.itemForm, 0, new ModelResourceLocation(BlockSugarGrass.RESLOC, ""));
ModelLoader.setCustomModelResourceLocation(WonkaBlocks.harderTaffy.itemForm, 0, new ModelResourceLocation(BlockHarderTaffy.RESLOC, ""));
}
public static void regColours(){
FMLClientHandler.instance().getClient().getBlockColors().registerBlockColorHandler(new IBlockColor(){
public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex){
return worldIn != null && pos != null ? BiomeColorHelper.getGrassColorAtPos(worldIn, pos) : ColorizerGrass.getGrassColor(0.5D, 1.0D);
}
}, new Block[] {WonkaBlocks.sugarGrass});
FMLClientHandler.instance().getClient().getItemColors().registerItemColorHandler(new IItemColor(){
public int getColorFromItemstack(ItemStack stack, int tintIndex){
return ColorizerGrass.getGrassColor(0.5D, 1.0D);
}
}, new Block[] {WonkaBlocks.sugarGrass});
}
}
| lgpl-2.1 |
n8han/Databinder-for-Wicket | databinder-components/src/main/java/net/databinder/components/FocusableTextField.java | 2178 | /*
* Databinder: a simple bridge from Wicket to Hibernate
* Copyright (C) 2006 Nathan Hamblen nathan@technically.us
* 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 net.databinder.components;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.model.IModel;
/**
* TextField that can be told to focus itself on the next request. Works in conjunction with
* the onload handler.
*/
public class FocusableTextField<T> extends TextField<T> {
private boolean wantsFocus = false;
/**
* @param id Wicket id
* @param model text field model
*/
public FocusableTextField(String id, IModel<T> model) {
super (id, model);
add(ScriptLink.headerContributor(FocusableTextField.class));
}
/**
* @param id Wicket id
*/
public FocusableTextField(String id) {
this(id, (IModel<T>) null);
}
@Override
public void renderHead(HtmlHeaderContainer container) {
super.renderHead(container);
container.getHeaderResponse().renderOnLoadJavascript("initFocusableTextField();");
}
/**
* Request focus on next rendering.
*/
public void requestFocus() {
wantsFocus = true;
}
/** Adds flagging id attribute if focus has been requested. */
@Override
protected void onComponentTag(ComponentTag tag) {
if (wantsFocus) {
tag.put("id", "focusMe");
wantsFocus = false;
}
super.onComponentTag(tag);
}
} | lgpl-2.1 |
benb/beast-mcmc | src/dr/evomodelxml/speciation/YuleModelParser.java | 3071 | /*
* YuleModelParser.java
*
* Copyright (C) 2002-2009 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST 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.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodelxml.speciation;
import dr.evolution.util.Units;
import dr.evomodel.speciation.BirthDeathGernhard08Model;
import dr.evoxml.util.XMLUnits;
import dr.inference.model.Parameter;
import dr.xml.*;
import java.util.logging.Logger;
/**
* @author Alexei Drummond
*/
public class YuleModelParser extends AbstractXMLObjectParser {
public static final String YULE_MODEL = "yuleModel";
public static final String YULE = "yule";
public static final String BIRTH_RATE = "birthRate";
public String getParserName() {
return YULE_MODEL;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final Units.Type units = XMLUnits.Utils.getUnitsAttr(xo);
final XMLObject cxo = xo.getChild(BIRTH_RATE);
final boolean conditonalOnRoot = xo.getAttribute(BirthDeathModelParser.CONDITIONAL_ON_ROOT, false);
final Parameter brParameter = (Parameter) cxo.getChild(Parameter.class);
final Parameter deathParameter = new Parameter.Default(0.0);
Logger.getLogger("dr.evomodel").info("Using Yule prior on tree");
return new BirthDeathGernhard08Model(xo.getId(), brParameter, deathParameter, null,
BirthDeathGernhard08Model.TreeType.UNSCALED, units, conditonalOnRoot);
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "A speciation model of a simple constant rate Birth-death process.";
}
public Class getReturnType() {
return BirthDeathGernhard08Model.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newBooleanRule(BirthDeathModelParser.CONDITIONAL_ON_ROOT, true),
new ElementRule(BIRTH_RATE,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
XMLUnits.SYNTAX_RULES[0]
};
} | lgpl-2.1 |
openbase/jul | extension/protobuf/src/main/java/org/openbase/jul/extension/protobuf/container/ProtoBufMessageMapWrapper.java | 2602 | package org.openbase.jul.extension.protobuf.container;
/*
* #%L
* JUL Extension Protobuf
* %%
* Copyright (C) 2015 - 2022 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%
*/
import com.google.protobuf.AbstractMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.openbase.jul.exception.CouldNotPerformException;
import org.openbase.jul.extension.protobuf.IdentifiableMessage;
/**
*
* @author <a href="mailto:divine@openbase.org">Divine Threepwood</a>
* @param <KEY>
* @param <M>
* @param <MB>
* @param <SIB>
*/
public class ProtoBufMessageMapWrapper<KEY extends Comparable<KEY>, M extends AbstractMessage, MB extends M.Builder<MB>, SIB extends AbstractMessage.Builder<SIB>> extends HashMap<KEY, IdentifiableMessage<KEY, M, MB>> implements ProtoBufMessageMap<KEY, M, MB> {
public ProtoBufMessageMapWrapper() {
}
public ProtoBufMessageMapWrapper(final ProtoBufMessageMap<KEY, M, MB> entryMap) {
putAll(entryMap);
}
@Override
public IdentifiableMessage<KEY, M, MB> put(IdentifiableMessage<KEY, M, MB> value) throws CouldNotPerformException {
return super.put(value.getId(), value);
}
@Override
public IdentifiableMessage<KEY, M, MB> get(KEY key) throws CouldNotPerformException {
return super.get(key);
}
@Override
public IdentifiableMessage<KEY, M, MB> get(IdentifiableMessage<KEY, M, MB> value) throws CouldNotPerformException {
return super.get(value.getId());
}
@Override
public List<M> getMessages() throws CouldNotPerformException {
ArrayList<M> list = new ArrayList<>();
for (IdentifiableMessage<KEY, M, MB> identifiableMessage : values()) {
list.add(identifiableMessage.getMessage());
}
return list;
}
@Override
public M getMessage(KEY key) throws CouldNotPerformException {
return get(key).getMessage();
}
}
| lgpl-3.0 |
dpaukov/combinatoricslib3 | src/main/java/org/paukov/combinatorics3/IntegerPartitionIterator.java | 2707 | /*
Combinatorics Library 3
Copyright 2009-2016 Dmytro Paukov d.paukov@gmail.com
*/
package org.paukov.combinatorics3;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class IntegerPartitionIterator implements Iterator<List<Integer>> {
private final InternalVector vector1;
private final InternalVector vector2;
private List<Integer> currentPartition = null;
private long currentIndex = 0;
private int stopIndex = 1; //it should be 0 to stop the iteration.
IntegerPartitionIterator(IntegerPartitionGenerator generator) {
if (generator.value > 0) {
vector1 = new InternalVector(generator.value, 0, 0, generator.value);
vector2 = new InternalVector(generator.value, 0, generator.value + 1, 1);
} else {
stopIndex = 0;
vector1 = new InternalVector(1, 0, 0, 0);
vector2 = new InternalVector(1, 0, 0, 0);
}
}
@Override
public boolean hasNext() {
return stopIndex != 0;
}
@Override
public List<Integer> next() {
this.currentIndex++;
this.currentPartition = createPartition(stopIndex, vector1, vector2);
int sum = vector1.get(stopIndex) * vector2.get(stopIndex);
if (vector1.get(stopIndex) == 1) {
stopIndex--;
sum += vector1.get(stopIndex) * vector2.get(stopIndex);
}
if (vector2.get(stopIndex - 1) == vector2.get(stopIndex) + 1) {
stopIndex--;
vector1.set(stopIndex, vector1.get(stopIndex) + 1);
} else {
vector2.set(stopIndex, vector2.get(stopIndex) + 1);
vector1.set(stopIndex, 1);
}
if (sum > vector2.get(stopIndex)) {
vector2.set(stopIndex + 1, 1);
vector1.set(stopIndex + 1, sum - vector2.get(stopIndex));
stopIndex++;
}
return currentPartition;
}
private static List<Integer> createPartition(int index, InternalVector vector1,
InternalVector vector) {
List<Integer> partition = new ArrayList<>();
for (int i = 1; i <= index; i++) {
for (int j = 0; j < vector1.get(i); j++) {
partition.add(vector.get(i));
}
}
return partition;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return "IntegerPartitionIterator=[#" + currentIndex + ", " + currentPartition + "]";
}
private static class InternalVector {
final int[] array;
InternalVector(int size, int value0, int value1, int value2) {
array = new int[size + 2];
array[0] = value0;
array[1] = value1;
array[2] = value2;
}
int get(int index) {
return array[index + 1];
}
void set(int index, int value) {
array[index + 1] = value;
}
}
}
| lgpl-3.0 |
dana-i2cat/opennaas | extensions/bundles/genericnetwork/src/main/java/org/opennaas/extensions/genericnetwork/capability/nclprovisioner/api/CircuitCollection.java | 2196 | package org.opennaas.extensions.genericnetwork.capability.nclprovisioner.api;
/*
* #%L
* OpenNaaS :: Generic Network
* %%
* Copyright (C) 2007 - 2014 Fundació Privada i2CAT, Internet i Innovació a Catalunya
* %%
* 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.
* #L%
*/
import java.io.Serializable;
import java.util.Collection;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.opennaas.extensions.genericnetwork.model.circuit.Circuit;
/**
*
* @author Adrian Rosello Rey (i2CAT)
*
*/
@XmlRootElement(name = "circuits", namespace = "opennaas.api")
@XmlAccessorType(XmlAccessType.FIELD)
public class CircuitCollection implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8144269409692480588L;
@XmlElement(name = "circuit")
private Collection<Circuit> circuits;
public Collection<Circuit> getCircuits() {
return circuits;
}
public void setCircuits(Collection<Circuit> circuits) {
this.circuits = circuits;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((circuits == null) ? 0 : circuits.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CircuitCollection other = (CircuitCollection) obj;
if (circuits == null) {
if (other.circuits != null)
return false;
} else if (!circuits.equals(other.circuits))
return false;
return true;
}
}
| lgpl-3.0 |
armouroflight/java-gobject | src/main/java/gobject/runtime/GFlags.java | 1976 | package gobject.runtime;
import com.sun.jna.FromNativeContext;
import com.sun.jna.NativeMapped;
/**
* Base class for multi-valued bitfields, or flags. In native code,
* this value is represented as an integral type.
* <p>
* Each flag is represented by a constant associated with the class. Typical
* usage is to create a new instance with the varargs constructor {@link GFlags(int...)},
* passed to native code.
* <p>
* For example:
* <pre>
* File f = GioGlobals.fileNewForPath("/home/username/Documents");
* FileMonitor fm = f.monitorFile(new FileMonitorFlags(FileMonitorFlags.WATCH_MOUNTS), null);
* </pre>
*/
public abstract class GFlags implements NativeMapped {
private int value = 0;
public GFlags() {
}
@SuppressWarnings("unused")
private GFlags(int value) {
this.value = value;
}
/**
* Create a flag object which holds the union of all specified individual flag values.
*
* @param flags List of flag values
*/
public GFlags(int...flags) {
add(flags);
}
public final void add(int...flags) {
for (int flag : flags)
value |= flag;
}
public final void remove(int...flags) {
int val = 0;
for (int flag : flags)
val += flag;
value &= ~val;
}
/**
* Returns the native integral value, i.e. the bitwise and of the individual
* flag values.
*/
public final int getValue() {
return value;
}
public final boolean contains(int...flags) {
for (int flag : flags)
if ((value & flag) == 0)
return false;
return true;
}
@SuppressWarnings("unchecked")
public final Object fromNative(Object nativeValue, FromNativeContext context) {
try {
return context.getTargetType().getConstructor(new Class<?>[] { int[].class })
.newInstance(new Object[] { new int[] { (Integer) nativeValue } });
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public final Class<?> nativeType() {
return Integer.class;
}
public final Object toNative() {
return value;
}
}
| lgpl-3.0 |
qiaolugithub/myshop | src/main/java/net/jeeshop/thirdParty/miaodiyun/httpApiDemo/IndustrySMS.java | 1289 | package net.jeeshop.thirdParty.miaodiyun.httpApiDemo;
import net.jeeshop.thirdParty.miaodiyun.httpApiDemo.common.Config;
import net.jeeshop.thirdParty.miaodiyun.httpApiDemo.common.HttpUtil;
/**
* 验证码通知短信接口
*
* @ClassName: IndustrySMS
* @Description: 验证码通知短信接口
*
*/
public class IndustrySMS
{
private static String operation = "/industrySMS/sendSMS";
private static String accountSid = Config.ACCOUNT_SID;
/*private static String to = "15937149616";
private static String smsContent = "【燊活馆】您的验证码为010101,2分钟内输入有效。";*/
/**
* 验证码通知短信
*/
public static String execute(String to,String smsContent)
{
String url = Config.BASE_URL + operation;
String body = "accountSid=" + accountSid + "&to=" + to + "&smsContent=" + smsContent
+ HttpUtil.createCommonParam();
// 提交请求
String result = HttpUtil.post(url, body);
if(result.indexOf("00104")!=-1) {
return "您今日的验证码发送次数已经达到上限,请明日再试!";
}
if(result.indexOf("00000")!=-1) {
return "success";
}
System.out.println("result:" + System.lineSeparator() + result);
return "发送失败,稍后重试!";
}
}
| lgpl-3.0 |
cismet/cids-utils | src/main/java/de/cismet/common/gui/connectable/AbstractConnectable.java | 8467 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* AbstractConnectable.java
*
* Created on 6. August 2003, 12:38
*/
package de.cismet.common.gui.connectable;
import java.util.*;
/**
* Abstract implementation of the Connectable interface.
*
* @author Pascal
* @version $Revision$, $Date$
*/
public abstract class AbstractConnectable implements Connectable {
//~ Instance fields --------------------------------------------------------
private final String name;
private final LinkedHashMap linkMap;
private final DefaultPointIterator pointIterator = new DefaultPointIterator();
// private final LinkedList pointList;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new instance of AbstractConnectable.
*
* @param name DOCUMENT ME!
*/
public AbstractConnectable(final String name) {
this.name = name;
this.linkMap = new LinkedHashMap();
// this.pointList = new LinkedList();
}
//~ Methods ----------------------------------------------------------------
@Override
public boolean addLink(final ConnectionLink link) {
if (!linkMap.containsKey(link.getId())) {
/*if(link.isSource(this))
* { this.pointList.add(link.getSource()); this.linkMap.put(link.getId(), link); return true; } else
* if(link.isTarget(this)) { this.pointList.add(link.getTarget()); this.linkMap.put(link.getId(), link);
* return true;}*/
this.linkMap.put(link.getId(), link);
return true;
}
return false;
}
@Override
public boolean removeLink(final String id) {
final Object object = linkMap.remove(id);
if (object != null) {
/*ConnectionLink link = (ConnectionLink)object;
* if(link.isSource(this)) { this.pointList.remove(link.getSource()); } else if(link.isTarget(this)) {
* this.pointList.remove(link.getTarget());}*/
return true;
}
return false;
}
@Override
public ConnectionLink getLink(final String id) {
final Object object = linkMap.get(id);
return (object != null) ? (ConnectionLink)object : null;
}
// .........................................................................
@Override
public int getLinkCount() {
return this.linkMap.size();
}
@Override
public int getSourceLinkCount() {
int linkCout = 0;
final Iterator iterator = this.getLinks().iterator();
while (iterator.hasNext()) {
if (((ConnectionLink)iterator.next()).isTarget(this)) {
linkCout++;
}
}
return linkCout;
}
@Override
public int getTargetLinkCount() {
int linkCout = 0;
final Iterator iterator = this.getLinks().iterator();
while (iterator.hasNext()) {
if (((ConnectionLink)iterator.next()).isSource(this)) {
linkCout++;
}
}
return linkCout;
}
// .........................................................................
@Override
public Collection getLinks() {
return Collections.unmodifiableCollection(linkMap.values());
}
@Override
public Collection getSourceLinks() {
final Collection links = this.getLinks();
final ArrayList sourceLinks = new ArrayList(links.size());
final Iterator iterator = links.iterator();
while (iterator.hasNext()) {
final ConnectionLink link = (ConnectionLink)iterator.next();
if (link.isTarget(this)) {
sourceLinks.add(link);
}
}
sourceLinks.trimToSize();
return sourceLinks;
}
@Override
public Collection getTargetLinks() {
final Collection links = this.getLinks();
final ArrayList targetLinks = new ArrayList(links.size());
final Iterator iterator = links.iterator();
while (iterator.hasNext()) {
final ConnectionLink link = (ConnectionLink)iterator.next();
if (link.isSource(this)) {
targetLinks.add(link);
}
}
targetLinks.trimToSize();
return targetLinks;
}
@Override
public List getConnectables() {
final Collection links = this.getLinks();
final ArrayList connectables = new ArrayList(links.size());
final Iterator iterator = links.iterator();
while (iterator.hasNext()) {
final ConnectionLink link = (ConnectionLink)iterator.next();
if (link.isSource(this)) {
connectables.add(link.getTarget().getConnectable());
} else if (link.isTarget(this)) {
connectables.add(link.getSource().getConnectable());
}
}
return connectables;
}
@Override
public List getSourceConnectables() {
final Collection links = this.getLinks();
final ArrayList sourceConnectables = new ArrayList(links.size());
final Iterator iterator = links.iterator();
while (iterator.hasNext()) {
final ConnectionLink link = (ConnectionLink)iterator.next();
if (link.isTarget(this)) {
sourceConnectables.add(link.getSource().getConnectable());
}
}
return sourceConnectables;
}
@Override
public List getTargetConnectables() {
final Collection links = this.getLinks();
final ArrayList targetConnectables = new ArrayList(links.size());
final Iterator iterator = links.iterator();
while (iterator.hasNext()) {
final ConnectionLink link = (ConnectionLink)iterator.next();
if (link.isSource(this)) {
targetConnectables.add(link.getTarget().getConnectable());
}
}
return targetConnectables;
}
/*public List getPoints()
* { return Collections.unmodifiableList(pointList);}*/
@Override
public PointIterator getPoints() {
this.pointIterator.init(this.getLinks().iterator());
return this.pointIterator;
}
// .........................................................................
@Override
public boolean isSource() {
return this.getTargetLinks().size() > 0;
}
@Override
public boolean isTarget() {
return this.getSourceLinks().size() > 0;
}
@Override
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.getName();
}
// .........................................................................
@Override
public abstract ConnectionPoint createPoint();
//~ Inner Classes ----------------------------------------------------------
/**
* .........................................................................
*
* @version $Revision$, $Date$
*/
class DefaultPointIterator implements PointIterator {
//~ Instance fields ----------------------------------------------------
private Iterator iterator;
private ConnectionPoint[] points = new ConnectionPoint[2];
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param iterator DOCUMENT ME!
*/
private void init(final Iterator iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return this.iterator.hasNext();
}
@Override
public de.cismet.common.gui.connectable.ConnectionPoint[] nextPoints() {
final ConnectionLink link = (ConnectionLink)iterator.next();
if (link.isSource(AbstractConnectable.this)) {
points[0] = link.getSource();
points[1] = link.getTarget();
} else if (link.isTarget(AbstractConnectable.this)) {
points[0] = link.getTarget();
points[1] = link.getSource();
} else {
throw new RuntimeException("ConnectionLink '" + link + "'");
}
return points;
}
}
}
| lgpl-3.0 |
robeio/robe | robe-hibernate/src/main/java/io/robe/hibernate/criteria/api/CriteriaParent.java | 3869 | package io.robe.hibernate.criteria.api;
import io.robe.common.utils.Strings;
import io.robe.hibernate.criteria.api.cache.EntityMeta;
import io.robe.hibernate.criteria.api.criterion.Restriction;
import io.robe.hibernate.criteria.api.projection.Projection;
import java.util.*;
/**
* Created by kamilbukum on 10/01/2017.
*/
public abstract class CriteriaParent<E> {
/**
* Entity Alias
*/
private final String alias;
/**
* Entity class Type
*/
private final Class<?> entityClass;
private final Map<String, CriteriaJoin<E>> joins = new LinkedHashMap<>(0);
private final List<Restriction> restrictions = new LinkedList<>();
private final EntityMeta meta;
private Projection projection;
private final Transformer<E> transformer;
private final Map<String, Integer> aliasesMap;
/**
* @param entityClass
*/
protected CriteriaParent(String alias, Class<?> entityClass, Transformer<E> transformer, Map<String, Integer> aliasesMap){
this.entityClass = entityClass;
this.aliasesMap = aliasesMap;
this.transformer = transformer;
alias = "$" + (alias != null ? alias : Strings.unCapitalizeFirstChar(entityClass.getSimpleName()));
if(aliasesMap.containsKey(alias)) {
Integer aliasCount = aliasesMap.getOrDefault(alias, 0);
aliasCount++;
aliasesMap.put(alias, aliasCount);
alias = alias + "_" + aliasCount;
}
this.alias = alias;
if(transformer.getTransformClass() != null && this.entityClass.getName().equals(transformer.getTransformClass().getName())) {
this.meta = transformer.getMeta();
} else {
this.meta = transformer.getFinder().getEntityMeta(entityClass);
}
}
/**
*
* creates {@link CriteriaParent}
* @param entityClass
* @return
*/
public CriteriaJoin<E> createJoin(Class<?> entityClass) {
return createJoin(null, entityClass, null);
}
/**
*
* creates {@link CriteriaParent}
* @param entityClass
* @return
*/
public CriteriaJoin<E> createJoin(Class<?> entityClass, String referenceId) {
return createJoin(null, entityClass, referenceId);
}
/**
*
* creates {@link CriteriaParent}
* @param entityClass
* @return
*/
public CriteriaJoin<E> createJoin(String alias, Class<?> entityClass) {
return createJoin(alias, entityClass, null);
}
/**
*
* creates {@link CriteriaParent}
* @param entityClass
* @return
*/
public CriteriaJoin<E> createJoin(String alias, Class<?> entityClass, String referenceId) {
CriteriaJoin<E> join = new CriteriaJoin<>(this, alias, entityClass, this.getTransformer(), referenceId, this.aliasesMap);
joins.put(join.getAlias(), join);
return join;
}
public CriteriaJoin<E> getJoin(String alias) {
return joins.get(alias);
}
public Map<String, CriteriaJoin<E>> getJoins() {
return joins;
}
public Projection getProjection() {
return projection;
}
public CriteriaParent<E> add(Restriction restriction) {
restrictions.add(restriction);
return this;
}
public List<Restriction> getRestrictions() {
return restrictions;
}
public String getAlias() {
return alias;
}
public abstract CriteriaParent<E> addOrder(Order order);
public EntityMeta getMeta() {
return meta;
}
public Class<?> getEntityClass() {
return entityClass;
}
public CriteriaParent<E> setProjection(Projection projection) {
this.projection = projection;
return this;
}
public Transformer<E> getTransformer() {
return transformer;
}
public abstract boolean isRoot();
}
| lgpl-3.0 |
agentsoz/bdi-abm-integration | examples/conservation/src/main/java/io/github/agentsoz/conservation/outputwriters/ConstantFileNames.java | 4888 | package io.github.agentsoz.conservation.outputwriters;
/*
* #%L
* BDI-ABM Integration Package
* %%
* Copyright (C) 2014 - 2015 by its authors. See AUTHORS file.
* %%
* 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%
*/
/**
* Names of all output files are defined here.
*
* @author Sewwandi Perera
*/
public class ConstantFileNames {
private final static String CONFIG_PARAMETERS_FILE_NAME = "config_parameters.csv";
private final static String TARGET_FILE_NAME = "target_table.csv";
private final static String OUTPUT_LOG_FILE_NAME = "conservation_out_";
private final static String AGENTS_PROGRESS_FILE_NAME = "agents_progress_";
private final static String AGENTS_STAT_FILE_NAME = "agents_statistics_";
private final static String AUCTIONS_STAT_FILE_NAME = "auction_statistics_";
private final static String INPUT_PARAMS_FILE_NAME = "input_params_";
private final static String BIDS_FILE_NAME = "bids_";
private final static String LOWC_HIGHP_STAT_FILE = "lowc_highp_stats_";
private final static String AGENTS_CE_FILE = "agents_ce_";
private final static String AGENTS_PM_FILE = "agents_pm_";
private final static String NUMBER_OF_BIDS_PER_AGENT = "number_of_bids_per_agent";
private final static String NUMBER_OF_SUCCESSFUL_BIDS_PER_AGENT = "number_of_successful_bids_per_agent";
private final static String TOTAL_OPPORTUNITY_COST_PER_AGENT = "total_opportunity_cost_per_agent";
private final static String SUCCESSFUL_OPPORTUNITY_COST_PER_AGENT = "successful_opportunity_cost_per_agent";
private final static String TOTAL_BID_PRICE_PER_AGENT = "total_bid_price_per_agent";
private final static String SUCCESSFUL_BID_PRICE_PER_AGENT = "successful_bid_price_per_agent";
public static String getLowCHighPStatFileName(int repeatNumber) {
return LOWC_HIGHP_STAT_FILE + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getConfigParametersFileName() {
return CONFIG_PARAMETERS_FILE_NAME;
}
public static String getAgentsProgressFileName(int repeatNumber) {
return AGENTS_PROGRESS_FILE_NAME + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getAgentsStatsFileName(int repeatNumber) {
return AGENTS_STAT_FILE_NAME + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getAuctionStatsFileName(int repeatNumber) {
return AUCTIONS_STAT_FILE_NAME + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getInputParamsFileName(int repeatNumber) {
return INPUT_PARAMS_FILE_NAME + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getBidsFileName(int repeatNumber) {
return BIDS_FILE_NAME + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getOutputLogFileName(int repeatNumber) {
return OUTPUT_LOG_FILE_NAME + String.format("%03d", repeatNumber)
+ ".log";
}
public static String getTargetFileName() {
return TARGET_FILE_NAME;
}
public static String getAgentsCEFileName(int repeatNumber) {
return AGENTS_CE_FILE + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getAgentsPmFile(int repeatNumber) {
return AGENTS_PM_FILE + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getNumberOfBidsPerAgent(int repeatNumber) {
return NUMBER_OF_BIDS_PER_AGENT + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getNumberOfSuccessfulBidsPerAgent(int repeatNumber) {
return NUMBER_OF_SUCCESSFUL_BIDS_PER_AGENT
+ String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getTotalOpportunityCostPerAgent(int repeatNumber) {
return TOTAL_OPPORTUNITY_COST_PER_AGENT
+ String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getSuccessfulOpportunityCostPerAgent(int repeatNumber) {
return SUCCESSFUL_OPPORTUNITY_COST_PER_AGENT
+ String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getTotalBidPricePerAgent(int repeatNumber) {
return TOTAL_BID_PRICE_PER_AGENT + String.format("%03d", repeatNumber) + ".csv.gz";
}
public static String getSuccessfulBidPricePerAgent(int repeatNumber) {
return SUCCESSFUL_BID_PRICE_PER_AGENT
+ String.format("%03d", repeatNumber) + ".csv.gz";
}
}
| lgpl-3.0 |
smartfeeling/smartly | smartly_core/src/org/apache/commons/imaging/formats/jpeg/exif/ExifRewriter.java | 23032 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.imaging.formats.jpeg.exif;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.ImageWriteException;
import org.apache.commons.imaging.common.BinaryFileParser;
import org.apache.commons.imaging.common.ByteOrder;
import org.apache.commons.imaging.common.bytesource.ByteSource;
import org.apache.commons.imaging.common.bytesource.ByteSourceArray;
import org.apache.commons.imaging.common.bytesource.ByteSourceFile;
import org.apache.commons.imaging.common.bytesource.ByteSourceInputStream;
import org.apache.commons.imaging.formats.jpeg.JpegConstants;
import org.apache.commons.imaging.formats.jpeg.JpegUtils;
import org.apache.commons.imaging.formats.tiff.write.TiffImageWriterBase;
import org.apache.commons.imaging.formats.tiff.write.TiffImageWriterLossless;
import org.apache.commons.imaging.formats.tiff.write.TiffImageWriterLossy;
import org.apache.commons.imaging.formats.tiff.write.TiffOutputSet;
import org.apache.commons.imaging.util.Debug;
/**
* Interface for Exif write/update/remove functionality for Jpeg/JFIF images.
* <p>
* <p>
* See the source of the ExifMetadataUpdateExample class for example usage.
*
* @see <a
* href="https://svn.apache.org/repos/asf/commons/proper/imaging/trunk/src/test/java/org/apache/commons/imaging/examples/WriteExifMetadataExample.java">org.apache.commons.imaging.examples.WriteExifMetadataExample</a>
*/
public class ExifRewriter extends BinaryFileParser implements JpegConstants {
/**
* Constructor. to guess whether a file contains an image based on its file
* extension.
*/
public ExifRewriter() {
setByteOrder(ByteOrder.NETWORK);
}
/**
* Constructor.
* <p>
*
* @param byteOrder
* byte order of EXIF segment.
*/
public ExifRewriter(final ByteOrder byteOrder) {
setByteOrder(byteOrder);
}
private static class JFIFPieces {
public final List<JFIFPiece> pieces;
public final List<JFIFPiece> exifPieces;
public JFIFPieces(final List<JFIFPiece> pieces,
final List<JFIFPiece> exifPieces) {
this.pieces = pieces;
this.exifPieces = exifPieces;
}
}
private abstract static class JFIFPiece {
protected abstract void write(OutputStream os) throws IOException;
}
private static class JFIFPieceSegment extends JFIFPiece {
public final int marker;
public final byte markerBytes[];
public final byte markerLengthBytes[];
public final byte segmentData[];
public JFIFPieceSegment(final int marker, final byte[] markerBytes,
final byte[] markerLengthBytes, final byte[] segmentData) {
this.marker = marker;
this.markerBytes = markerBytes;
this.markerLengthBytes = markerLengthBytes;
this.segmentData = segmentData;
}
@Override
protected void write(final OutputStream os) throws IOException {
os.write(markerBytes);
os.write(markerLengthBytes);
os.write(segmentData);
}
}
private static class JFIFPieceSegmentExif extends JFIFPieceSegment {
public JFIFPieceSegmentExif(final int marker, final byte[] markerBytes,
final byte[] markerLengthBytes, final byte[] segmentData) {
super(marker, markerBytes, markerLengthBytes, segmentData);
}
}
private static class JFIFPieceImageData extends JFIFPiece {
public final byte markerBytes[];
public final byte imageData[];
public JFIFPieceImageData(final byte[] markerBytes,
final byte[] imageData) {
super();
this.markerBytes = markerBytes;
this.imageData = imageData;
}
@Override
protected void write(final OutputStream os) throws IOException {
os.write(markerBytes);
os.write(imageData);
}
}
private JFIFPieces analyzeJFIF(final ByteSource byteSource)
throws ImageReadException, IOException
// , ImageWriteException
{
final List<JFIFPiece> pieces = new ArrayList<JFIFPiece>();
final List<JFIFPiece> exifPieces = new ArrayList<JFIFPiece>();
final JpegUtils.Visitor visitor = new JpegUtils.Visitor() {
// return false to exit before reading image data.
public boolean beginSOS() {
return true;
}
public void visitSOS(final int marker, final byte markerBytes[],
final byte imageData[]) {
pieces.add(new JFIFPieceImageData(markerBytes, imageData));
}
// return false to exit traversal.
public boolean visitSegment(final int marker, final byte markerBytes[],
final int markerLength, final byte markerLengthBytes[],
final byte segmentData[]) throws
// ImageWriteException,
ImageReadException, IOException {
if (marker != JPEG_APP1_Marker) {
pieces.add(new JFIFPieceSegment(marker, markerBytes,
markerLengthBytes, segmentData));
} else if (!startsWith(segmentData,
EXIF_IDENTIFIER_CODE)) {
pieces.add(new JFIFPieceSegment(marker, markerBytes,
markerLengthBytes, segmentData));
// } else if (exifSegmentArray[0] != null) {
// // TODO: add support for multiple segments
// throw new ImageReadException(
// "More than one APP1 EXIF segment.");
} else {
final JFIFPiece piece = new JFIFPieceSegmentExif(marker,
markerBytes, markerLengthBytes, segmentData);
pieces.add(piece);
exifPieces.add(piece);
}
return true;
}
};
new JpegUtils().traverseJFIF(byteSource, visitor);
// GenericSegment exifSegment = exifSegmentArray[0];
// if (exifSegments.size() < 1)
// {
// // TODO: add support for adding, not just replacing.
// throw new ImageReadException("No APP1 EXIF segment found.");
// }
return new JFIFPieces(pieces, exifPieces);
}
/**
* Reads a Jpeg image, removes all EXIF metadata (by removing the APP1
* segment), and writes the result to a stream.
* <p>
*
* @param src
* Image file.
* @param os
* OutputStream to write the image to.
*
* @see java.io.File
* @see java.io.OutputStream
* @see java.io.File
* @see java.io.OutputStream
*/
public void removeExifMetadata(final File src, final OutputStream os)
throws ImageReadException, IOException, ImageWriteException {
final ByteSource byteSource = new ByteSourceFile(src);
removeExifMetadata(byteSource, os);
}
/**
* Reads a Jpeg image, removes all EXIF metadata (by removing the APP1
* segment), and writes the result to a stream.
* <p>
*
* @param src
* Byte array containing Jpeg image data.
* @param os
* OutputStream to write the image to.
*/
public void removeExifMetadata(final byte src[], final OutputStream os)
throws ImageReadException, IOException, ImageWriteException {
final ByteSource byteSource = new ByteSourceArray(src);
removeExifMetadata(byteSource, os);
}
/**
* Reads a Jpeg image, removes all EXIF metadata (by removing the APP1
* segment), and writes the result to a stream.
* <p>
*
* @param src
* InputStream containing Jpeg image data.
* @param os
* OutputStream to write the image to.
*/
public void removeExifMetadata(final InputStream src, final OutputStream os)
throws ImageReadException, IOException, ImageWriteException {
final ByteSource byteSource = new ByteSourceInputStream(src, null);
removeExifMetadata(byteSource, os);
}
/**
* Reads a Jpeg image, removes all EXIF metadata (by removing the APP1
* segment), and writes the result to a stream.
* <p>
*
* @param byteSource
* ByteSource containing Jpeg image data.
* @param os
* OutputStream to write the image to.
*/
public void removeExifMetadata(final ByteSource byteSource, final OutputStream os)
throws ImageReadException, IOException, ImageWriteException {
final JFIFPieces jfifPieces = analyzeJFIF(byteSource);
final List<JFIFPiece> pieces = jfifPieces.pieces;
// Debug.debug("pieces", pieces);
// pieces.removeAll(jfifPieces.exifSegments);
// Debug.debug("pieces", pieces);
writeSegmentsReplacingExif(os, pieces, null);
}
/**
* Reads a Jpeg image, replaces the EXIF metadata and writes the result to a
* stream.
* <p>
* Note that this uses the "Lossless" approach - in order to preserve data
* embedded in the EXIF segment that it can't parse (such as Maker Notes),
* this algorithm avoids overwriting any part of the original segment that
* it couldn't parse. This can cause the EXIF segment to grow with each
* update, which is a serious issue, since all EXIF data must fit in a
* single APP1 segment of the Jpeg image.
* <p>
*
* @param src
* Image file.
* @param os
* OutputStream to write the image to.
* @param outputSet
* TiffOutputSet containing the EXIF data to write.
*/
public void updateExifMetadataLossless(final File src, final OutputStream os,
final TiffOutputSet outputSet) throws ImageReadException, IOException,
ImageWriteException {
final ByteSource byteSource = new ByteSourceFile(src);
updateExifMetadataLossless(byteSource, os, outputSet);
}
/**
* Reads a Jpeg image, replaces the EXIF metadata and writes the result to a
* stream.
* <p>
* Note that this uses the "Lossless" approach - in order to preserve data
* embedded in the EXIF segment that it can't parse (such as Maker Notes),
* this algorithm avoids overwriting any part of the original segment that
* it couldn't parse. This can cause the EXIF segment to grow with each
* update, which is a serious issue, since all EXIF data must fit in a
* single APP1 segment of the Jpeg image.
* <p>
*
* @param src
* Byte array containing Jpeg image data.
* @param os
* OutputStream to write the image to.
* @param outputSet
* TiffOutputSet containing the EXIF data to write.
*/
public void updateExifMetadataLossless(final byte src[], final OutputStream os,
final TiffOutputSet outputSet) throws ImageReadException, IOException,
ImageWriteException {
final ByteSource byteSource = new ByteSourceArray(src);
updateExifMetadataLossless(byteSource, os, outputSet);
}
/**
* Reads a Jpeg image, replaces the EXIF metadata and writes the result to a
* stream.
* <p>
* Note that this uses the "Lossless" approach - in order to preserve data
* embedded in the EXIF segment that it can't parse (such as Maker Notes),
* this algorithm avoids overwriting any part of the original segment that
* it couldn't parse. This can cause the EXIF segment to grow with each
* update, which is a serious issue, since all EXIF data must fit in a
* single APP1 segment of the Jpeg image.
* <p>
*
* @param src
* InputStream containing Jpeg image data.
* @param os
* OutputStream to write the image to.
* @param outputSet
* TiffOutputSet containing the EXIF data to write.
*/
public void updateExifMetadataLossless(final InputStream src, final OutputStream os,
final TiffOutputSet outputSet) throws ImageReadException, IOException,
ImageWriteException {
final ByteSource byteSource = new ByteSourceInputStream(src, null);
updateExifMetadataLossless(byteSource, os, outputSet);
}
/**
* Reads a Jpeg image, replaces the EXIF metadata and writes the result to a
* stream.
* <p>
* Note that this uses the "Lossless" approach - in order to preserve data
* embedded in the EXIF segment that it can't parse (such as Maker Notes),
* this algorithm avoids overwriting any part of the original segment that
* it couldn't parse. This can cause the EXIF segment to grow with each
* update, which is a serious issue, since all EXIF data must fit in a
* single APP1 segment of the Jpeg image.
* <p>
*
* @param byteSource
* ByteSource containing Jpeg image data.
* @param os
* OutputStream to write the image to.
* @param outputSet
* TiffOutputSet containing the EXIF data to write.
*/
public void updateExifMetadataLossless(final ByteSource byteSource,
final OutputStream os, final TiffOutputSet outputSet)
throws ImageReadException, IOException, ImageWriteException {
// List outputDirectories = outputSet.getDirectories();
final JFIFPieces jfifPieces = analyzeJFIF(byteSource);
final List<JFIFPiece> pieces = jfifPieces.pieces;
TiffImageWriterBase writer;
// Just use first APP1 segment for now.
// Multiple APP1 segments are rare and poorly supported.
if (jfifPieces.exifPieces.size() > 0) {
JFIFPieceSegment exifPiece = null;
exifPiece = (JFIFPieceSegment) jfifPieces.exifPieces.get(0);
byte exifBytes[] = exifPiece.segmentData;
exifBytes = remainingBytes("trimmed exif bytes", exifBytes, 6);
writer = new TiffImageWriterLossless(outputSet.byteOrder, exifBytes);
} else {
writer = new TiffImageWriterLossy(outputSet.byteOrder);
}
final boolean includeEXIFPrefix = true;
final byte newBytes[] = writeExifSegment(writer, outputSet, includeEXIFPrefix);
writeSegmentsReplacingExif(os, pieces, newBytes);
}
/**
* Reads a Jpeg image, replaces the EXIF metadata and writes the result to a
* stream.
* <p>
* Note that this uses the "Lossy" approach - the algorithm overwrites the
* entire EXIF segment, ignoring the possibility that it may be discarding
* data it couldn't parse (such as Maker Notes).
* <p>
*
* @param src
* Byte array containing Jpeg image data.
* @param os
* OutputStream to write the image to.
* @param outputSet
* TiffOutputSet containing the EXIF data to write.
*/
public void updateExifMetadataLossy(final byte src[], final OutputStream os,
final TiffOutputSet outputSet) throws ImageReadException, IOException,
ImageWriteException {
final ByteSource byteSource = new ByteSourceArray(src);
updateExifMetadataLossy(byteSource, os, outputSet);
}
/**
* Reads a Jpeg image, replaces the EXIF metadata and writes the result to a
* stream.
* <p>
* Note that this uses the "Lossy" approach - the algorithm overwrites the
* entire EXIF segment, ignoring the possibility that it may be discarding
* data it couldn't parse (such as Maker Notes).
* <p>
*
* @param src
* InputStream containing Jpeg image data.
* @param os
* OutputStream to write the image to.
* @param outputSet
* TiffOutputSet containing the EXIF data to write.
*/
public void updateExifMetadataLossy(final InputStream src, final OutputStream os,
final TiffOutputSet outputSet) throws ImageReadException, IOException,
ImageWriteException {
final ByteSource byteSource = new ByteSourceInputStream(src, null);
updateExifMetadataLossy(byteSource, os, outputSet);
}
/**
* Reads a Jpeg image, replaces the EXIF metadata and writes the result to a
* stream.
* <p>
* Note that this uses the "Lossy" approach - the algorithm overwrites the
* entire EXIF segment, ignoring the possibility that it may be discarding
* data it couldn't parse (such as Maker Notes).
* <p>
*
* @param src
* Image file.
* @param os
* OutputStream to write the image to.
* @param outputSet
* TiffOutputSet containing the EXIF data to write.
*/
public void updateExifMetadataLossy(final File src, final OutputStream os,
final TiffOutputSet outputSet) throws ImageReadException, IOException,
ImageWriteException {
final ByteSource byteSource = new ByteSourceFile(src);
updateExifMetadataLossy(byteSource, os, outputSet);
}
/**
* Reads a Jpeg image, replaces the EXIF metadata and writes the result to a
* stream.
* <p>
* Note that this uses the "Lossy" approach - the algorithm overwrites the
* entire EXIF segment, ignoring the possibility that it may be discarding
* data it couldn't parse (such as Maker Notes).
* <p>
*
* @param byteSource
* ByteSource containing Jpeg image data.
* @param os
* OutputStream to write the image to.
* @param outputSet
* TiffOutputSet containing the EXIF data to write.
*/
public void updateExifMetadataLossy(final ByteSource byteSource, final OutputStream os,
final TiffOutputSet outputSet) throws ImageReadException, IOException,
ImageWriteException {
final JFIFPieces jfifPieces = analyzeJFIF(byteSource);
final List<JFIFPiece> pieces = jfifPieces.pieces;
final TiffImageWriterBase writer = new TiffImageWriterLossy(
outputSet.byteOrder);
final boolean includeEXIFPrefix = true;
final byte newBytes[] = writeExifSegment(writer, outputSet, includeEXIFPrefix);
writeSegmentsReplacingExif(os, pieces, newBytes);
}
private void writeSegmentsReplacingExif(final OutputStream os,
final List<JFIFPiece> segments, final byte newBytes[])
throws ImageWriteException, IOException {
try {
SOI.writeTo(os);
boolean hasExif = false;
for (int i = 0; i < segments.size(); i++) {
final JFIFPiece piece = segments.get(i);
if (piece instanceof JFIFPieceSegmentExif) {
hasExif = true;
}
}
if (!hasExif && newBytes != null) {
final byte markerBytes[] = toBytes((short)JPEG_APP1_Marker);
if (newBytes.length > 0xffff) {
throw new ExifOverflowException(
"APP1 Segment is too long: " + newBytes.length);
}
final int markerLength = newBytes.length + 2;
final byte markerLengthBytes[] = toBytes((short)markerLength);
int index = 0;
final JFIFPieceSegment firstSegment = (JFIFPieceSegment) segments
.get(index);
if (firstSegment.marker == JFIFMarker) {
index = 1;
}
segments.add(0, new JFIFPieceSegmentExif(JPEG_APP1_Marker,
markerBytes, markerLengthBytes, newBytes));
}
boolean APP1Written = false;
for (int i = 0; i < segments.size(); i++) {
final JFIFPiece piece = segments.get(i);
if (piece instanceof JFIFPieceSegmentExif) {
// only replace first APP1 segment; skips others.
if (APP1Written) {
continue;
}
APP1Written = true;
if (newBytes == null) {
continue;
}
final byte markerBytes[] = toBytes((short)JPEG_APP1_Marker);
if (newBytes.length > 0xffff) {
throw new ExifOverflowException(
"APP1 Segment is too long: " + newBytes.length);
}
final int markerLength = newBytes.length + 2;
final byte markerLengthBytes[] = toBytes((short)markerLength);
os.write(markerBytes);
os.write(markerLengthBytes);
os.write(newBytes);
} else {
piece.write(os);
}
}
} finally {
try {
os.close();
} catch (final Exception e) {
Debug.debug(e);
}
}
}
public static class ExifOverflowException extends ImageWriteException {
private static final long serialVersionUID = 1401484357224931218L;
public ExifOverflowException(final String s) {
super(s);
}
}
private byte[] writeExifSegment(final TiffImageWriterBase writer,
final TiffOutputSet outputSet, final boolean includeEXIFPrefix)
throws IOException, ImageWriteException {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
if (includeEXIFPrefix) {
EXIF_IDENTIFIER_CODE.writeTo(os);
os.write(0);
os.write(0);
}
writer.write(os, outputSet);
return os.toByteArray();
}
}
| lgpl-3.0 |
accord-net/java | Catalano.Android.Image/src/Catalano/Imaging/Filters/Closing.java | 2818 | // Catalano Imaging Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2014
// diego.catalano at live.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.
//
// 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 Catalano.Imaging.Filters;
import Catalano.Imaging.FastBitmap;
import Catalano.Imaging.IBaseInPlace;
/**
* Closing operator from Mathematical Morphology.
* <br /> Applied to binary image, the filter may be used connect or fill objects. Since dilatation is used first, it may connect/fill object areas. Then erosion restores objects. But since dilatation may connect something before, erosion may not remove after that because of the formed connection.
* @author Diego Catalano
*/
public class Closing implements IBaseInPlace{
private int[][] kernel;
private int radius = 0;
/**
* Initializes a new instance of the Closing class.
*/
public Closing() {
this.radius = 1;
}
/**
* Initializes a new instance of the Closing class.
* @param se Structuring element.
*/
public Closing(int[][] se) {
this.kernel = se;
}
/**
* Initializes a new instance of the Closing class.
* @param radius Radius.
*/
public Closing(int radius) {
radius = radius < 1 ? 1 : radius;
this.radius = radius;
}
@Override
public void applyInPlace(FastBitmap fastBitmap){
if (radius != 0) {
ApplyInPlace(fastBitmap, radius);
}
else{
ApplyInPlace(fastBitmap, kernel);
}
}
private void ApplyInPlace(FastBitmap fastBitmap, int[][] se){
Dilatation dil = new Dilatation(se);
Erosion ero = new Erosion(se);
dil.applyInPlace(fastBitmap);
ero.applyInPlace(fastBitmap);
}
private void ApplyInPlace(FastBitmap fastBitmap, int radius){
Dilatation dil = new Dilatation(radius);
Erosion ero = new Erosion(radius);
dil.applyInPlace(fastBitmap);
ero.applyInPlace(fastBitmap);
}
}
| lgpl-3.0 |
c2mon/c2mon-client-ext-history | src/main/java/cern/c2mon/client/ext/history/common/HistoryPlayerEvents.java | 1509 | /******************************************************************************
* Copyright (C) 2010-2016 CERN. All rights not expressly granted are reserved.
*
* This file is part of the CERN Control and Monitoring Platform 'C2MON'.
* C2MON 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.
*
* C2MON 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 C2MON. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package cern.c2mon.client.ext.history.common;
import cern.c2mon.client.ext.history.common.event.HistoryPlayerListener;
/**
* This interface describes the methods for adding listeners which are provided
* by the history player.
*
* @author vdeila
*
*/
public interface HistoryPlayerEvents {
/**
*
* @param listener
* The listener to add
*/
void addHistoryPlayerListener(HistoryPlayerListener listener);
/**
*
* @param listener
* The listener to remove
*/
void removeHistoryPlayerListener(HistoryPlayerListener listener);
}
| lgpl-3.0 |
plorenz/sarasvati | sarasvati-core/src/main/java/com/googlecode/sarasvati/env/FloatAttributeConverter.java | 1250 | /*
This file is part of Sarasvati.
Sarasvati 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.
Sarasvati 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 Sarasvati. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 Paul Lorenz
*/
package com.googlecode.sarasvati.env;
/**
* Attribute converter for String <--> Float
*
* @author Paul Lorenz
*/
public final class FloatAttributeConverter extends AbstractStringValueOfAttributeConverter
{
/**
* Converts the given string to a Float
*
* @see com.googlecode.sarasvati.env.AttributeConverter#stringToObject(java.lang.String, java.lang.Class)
*/
@Override
public Object stringToObject (final String string, final Class<?> object)
{
return Float.valueOf( string );
}
} | lgpl-3.0 |
SonarSource/sonarqube | server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/InitFilterTest.java | 12866 | /*
* SonarQube
* Copyright (C) 2009-2022 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.server.authentication;
import javax.servlet.FilterChain;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.server.authentication.BaseIdentityProvider;
import org.sonar.api.server.authentication.Display;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
public class InitFilterTest {
private static final String OAUTH2_PROVIDER_KEY = "github";
private static final String BASIC_PROVIDER_KEY = "openid";
@Rule
public LogTester logTester = new LogTester();
@Rule
public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule();
private BaseContextFactory baseContextFactory = mock(BaseContextFactory.class);
private OAuth2ContextFactory oAuth2ContextFactory = mock(OAuth2ContextFactory.class);
private HttpServletRequest request = mock(HttpServletRequest.class);
private HttpServletResponse response = mock(HttpServletResponse.class);
private FilterChain chain = mock(FilterChain.class);
private FakeOAuth2IdentityProvider oAuth2IdentityProvider = new FakeOAuth2IdentityProvider(OAUTH2_PROVIDER_KEY, true);
private OAuth2IdentityProvider.InitContext oauth2Context = mock(OAuth2IdentityProvider.InitContext.class);
private FakeBasicIdentityProvider baseIdentityProvider = new FakeBasicIdentityProvider(BASIC_PROVIDER_KEY, true);
private BaseIdentityProvider.Context baseContext = mock(BaseIdentityProvider.Context.class);
private AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
private OAuth2AuthenticationParameters auth2AuthenticationParameters = mock(OAuth2AuthenticationParameters.class);
private ArgumentCaptor<AuthenticationException> authenticationExceptionCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
private ArgumentCaptor<Cookie> cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
private InitFilter underTest = new InitFilter(identityProviderRepository, baseContextFactory, oAuth2ContextFactory, authenticationEvent, auth2AuthenticationParameters);
@Before
public void setUp() throws Exception {
when(oAuth2ContextFactory.newContext(request, response, oAuth2IdentityProvider)).thenReturn(oauth2Context);
when(baseContextFactory.newContext(request, response, baseIdentityProvider)).thenReturn(baseContext);
when(request.getContextPath()).thenReturn("");
}
@Test
public void do_get_pattern() {
assertThat(underTest.doGetPattern()).isNotNull();
}
@Test
public void do_filter_with_context() {
when(request.getContextPath()).thenReturn("/sonarqube");
when(request.getRequestURI()).thenReturn("/sonarqube/sessions/init/" + OAUTH2_PROVIDER_KEY);
identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
underTest.doFilter(request, response, chain);
assertOAuth2InitCalled();
verifyZeroInteractions(authenticationEvent);
}
@Test
public void do_filter_on_auth2_identity_provider() {
when(request.getRequestURI()).thenReturn("/sessions/init/" + OAUTH2_PROVIDER_KEY);
identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
underTest.doFilter(request, response, chain);
assertOAuth2InitCalled();
verifyZeroInteractions(authenticationEvent);
}
@Test
public void do_filter_on_basic_identity_provider() {
when(request.getRequestURI()).thenReturn("/sessions/init/" + BASIC_PROVIDER_KEY);
identityProviderRepository.addIdentityProvider(baseIdentityProvider);
underTest.doFilter(request, response, chain);
assertBasicInitCalled();
verifyZeroInteractions(authenticationEvent);
}
@Test
public void init_authentication_parameter_on_auth2_identity_provider() {
when(request.getContextPath()).thenReturn("/sonarqube");
when(request.getRequestURI()).thenReturn("/sonarqube/sessions/init/" + OAUTH2_PROVIDER_KEY);
identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
underTest.doFilter(request, response, chain);
verify(auth2AuthenticationParameters).init(request, response);
}
@Test
public void does_not_init_authentication_parameter_on_basic_authentication() {
when(request.getRequestURI()).thenReturn("/sessions/init/" + BASIC_PROVIDER_KEY);
identityProviderRepository.addIdentityProvider(baseIdentityProvider);
underTest.doFilter(request, response, chain);
verify(auth2AuthenticationParameters, never()).init(request, response);
}
@Test
public void fail_if_identity_provider_key_is_empty() throws Exception {
when(request.getRequestURI()).thenReturn("/sessions/init/");
underTest.doFilter(request, response, chain);
assertError("No provider key found in URI");
verifyZeroInteractions(authenticationEvent);
verifyZeroInteractions(auth2AuthenticationParameters);
}
@Test
public void fail_if_uri_does_not_contains_callback() throws Exception {
when(request.getRequestURI()).thenReturn("/sessions/init");
underTest.doFilter(request, response, chain);
assertError("No provider key found in URI");
verifyZeroInteractions(authenticationEvent);
verifyZeroInteractions(auth2AuthenticationParameters);
}
@Test
public void fail_if_identity_provider_class_is_unsupported() throws Exception {
String unsupportedKey = "unsupported";
when(request.getRequestURI()).thenReturn("/sessions/init/" + unsupportedKey);
IdentityProvider identityProvider = new UnsupportedIdentityProvider(unsupportedKey);
identityProviderRepository.addIdentityProvider(identityProvider);
underTest.doFilter(request, response, chain);
assertError("Unsupported IdentityProvider class: class org.sonar.server.authentication.InitFilterTest$UnsupportedIdentityProvider");
verifyZeroInteractions(authenticationEvent);
verifyZeroInteractions(auth2AuthenticationParameters);
}
@Test
public void redirect_contains_cookie_with_error_message_when_failing_because_of_UnauthorizedExceptionException() throws Exception {
IdentityProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider("failing");
when(request.getRequestURI()).thenReturn("/sessions/init/" + identityProvider.getKey());
identityProviderRepository.addIdentityProvider(identityProvider);
underTest.doFilter(request, response, chain);
verify(response).sendRedirect("/sessions/unauthorized");
verify(authenticationEvent).loginFailure(eq(request), authenticationExceptionCaptor.capture());
AuthenticationException authenticationException = authenticationExceptionCaptor.getValue();
assertThat(authenticationException).hasMessage("Email john@email.com is already used");
assertThat(authenticationException.getSource()).isEqualTo(AuthenticationEvent.Source.external(identityProvider));
assertThat(authenticationException.getLogin()).isNull();
assertThat(authenticationException.getPublicMessage()).isEqualTo("Email john@email.com is already used");
verifyDeleteAuthCookie();
verify(response).addCookie(cookieArgumentCaptor.capture());
Cookie cookie = cookieArgumentCaptor.getValue();
assertThat(cookie.getName()).isEqualTo("AUTHENTICATION-ERROR");
assertThat(cookie.getValue()).isEqualTo("Email%20john%40email.com%20is%20already%20used");
assertThat(cookie.getPath()).isEqualTo("/");
assertThat(cookie.isHttpOnly()).isFalse();
assertThat(cookie.getMaxAge()).isEqualTo(300);
assertThat(cookie.getSecure()).isFalse();
}
@Test
public void redirect_with_context_path_when_failing_because_of_UnauthorizedException() throws Exception {
when(request.getContextPath()).thenReturn("/sonarqube");
IdentityProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider("failing");
when(request.getRequestURI()).thenReturn("/sonarqube/sessions/init/" + identityProvider.getKey());
identityProviderRepository.addIdentityProvider(identityProvider);
underTest.doFilter(request, response, chain);
verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
}
@Test
public void redirect_when_failing_because_of_Exception() throws Exception {
IdentityProvider identityProvider = new FailWithIllegalStateException("failing");
when(request.getRequestURI()).thenReturn("/sessions/init/" + identityProvider.getKey());
identityProviderRepository.addIdentityProvider(identityProvider);
underTest.doFilter(request, response, chain);
verify(response).sendRedirect("/sessions/unauthorized");
assertThat(logTester.logs(LoggerLevel.WARN)).containsExactlyInAnyOrder("Fail to initialize authentication with provider 'failing'");
verifyDeleteAuthCookie();
}
@Test
public void redirect_with_context_when_failing_because_of_Exception() throws Exception {
when(request.getContextPath()).thenReturn("/sonarqube");
IdentityProvider identityProvider = new FailWithIllegalStateException("failing");
when(request.getRequestURI()).thenReturn("/sessions/init/" + identityProvider.getKey());
identityProviderRepository.addIdentityProvider(identityProvider);
underTest.doFilter(request, response, chain);
verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
}
private void assertOAuth2InitCalled() {
assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
assertThat(oAuth2IdentityProvider.isInitCalled()).isTrue();
}
private void assertBasicInitCalled() {
assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
assertThat(baseIdentityProvider.isInitCalled()).isTrue();
}
private void assertError(String expectedError) throws Exception {
assertThat(logTester.logs(LoggerLevel.WARN)).contains(expectedError);
verify(response).sendRedirect("/sessions/unauthorized");
assertThat(oAuth2IdentityProvider.isInitCalled()).isFalse();
}
private void verifyDeleteAuthCookie() {
verify(auth2AuthenticationParameters).delete(request, response);
}
private static class FailWithUnauthorizedExceptionIdProvider extends FakeBasicIdentityProvider {
public FailWithUnauthorizedExceptionIdProvider(String key) {
super(key, true);
}
@Override
public void init(Context context) {
throw new UnauthorizedException("Email john@email.com is already used");
}
}
private static class FailWithIllegalStateException extends FakeBasicIdentityProvider {
public FailWithIllegalStateException(String key) {
super(key, true);
}
@Override
public void init(Context context) {
throw new IllegalStateException("Failure !");
}
}
private static class UnsupportedIdentityProvider implements IdentityProvider {
private final String unsupportedKey;
public UnsupportedIdentityProvider(String unsupportedKey) {
this.unsupportedKey = unsupportedKey;
}
@Override
public String getKey() {
return unsupportedKey;
}
@Override
public String getName() {
return null;
}
@Override
public Display getDisplay() {
return null;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean allowsUsersToSignUp() {
return false;
}
}
}
| lgpl-3.0 |
mshonle/FACTS | src/facts/diff/BasicRename.java | 924 | package facts.diff;
import facts.ast.TreeNode;
/*
* Implements a basic rename operation. If node labels are the same
* then the cost is 0, otherwise the cost is 1.
*
* INSERT-LICENCE-INFO
*/
public class BasicRename extends TreeEditOperation
{
public BasicRename() {
super.opName = "RENAME";
}
public Integer getCost(int aNodeID, int bNodeID, TreeNode aTree, TreeNode bTree) {
String aString = aTree.findNode(aNodeID).getLabel();
String bString = bTree.findNode(bNodeID).getLabel();
// int aDiv = aString.lastIndexOf(":");
// int bDiv = bString.lastIndexOf(":");
// if (aDiv != -1)
// {
// aString = aString.substring(0,aDiv);
// }
// if (bDiv != -1)
// {
// bString = bString.substring(0,bDiv);
// }
if (aString.equals(bString)) {
return 0;
}
return 1;
}
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/repository/source/test-java/org/alfresco/repo/security/permissions/impl/model/PermissionModelTest.java | 10908 | /*
* Copyright (C) 2005-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.security.permissions.impl.model;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import org.alfresco.repo.security.permissions.PermissionEntry;
import org.alfresco.repo.security.permissions.PermissionReference;
import org.alfresco.repo.security.permissions.impl.AbstractPermissionTest;
import org.alfresco.repo.security.permissions.impl.SimplePermissionReference;
import org.alfresco.repo.security.permissions.impl.RequiredPermission.On;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.namespace.QName;
import org.alfresco.test_category.OwnJVMTestsCategory;
import org.junit.experimental.categories.Category;
@Category(OwnJVMTestsCategory.class)
public class PermissionModelTest extends AbstractPermissionTest
{
public PermissionModelTest()
{
super();
}
public void testWoof()
{
QName typeQname = nodeService.getType(rootNodeRef);
Set<QName> aspectQNames = nodeService.getAspects(rootNodeRef);
PermissionReference ref = permissionModelDAO.getPermissionReference(null, "CheckOut");
Set<PermissionReference> answer = permissionModelDAO.getRequiredPermissions(ref, typeQname, aspectQNames, On.NODE);
assertEquals(1, answer.size());
}
public void testIncludePermissionGroups()
{
Set<PermissionReference> grantees = permissionModelDAO.getGranteePermissions(SimplePermissionReference.getPermissionReference(QName.createQName("cm", "cmobject",
namespacePrefixResolver), "Consumer"));
assertEquals(8, grantees.size());
}
public void testIncludePermissionGroups2()
{
Set<PermissionReference> grantees = permissionModelDAO.getGranteePermissions(SimplePermissionReference.getPermissionReference(QName.createQName("cm", "cmobject",
namespacePrefixResolver), "Contributor"));
assertEquals(16, grantees.size());
}
public void testIncludePermissionGroups3()
{
Set<PermissionReference> grantees = permissionModelDAO.getGranteePermissions(SimplePermissionReference.getPermissionReference(QName.createQName("cm", "cmobject",
namespacePrefixResolver), "Editor"));
assertEquals(19, grantees.size());
}
public void testIncludePermissionGroups4()
{
Set<PermissionReference> grantees = permissionModelDAO.getGranteePermissions(SimplePermissionReference.getPermissionReference(QName.createQName("cm", "cmobject",
namespacePrefixResolver), "Collaborator"));
assertEquals(26, grantees.size());
}
public void testIncludePermissionGroups5()
{
Set<PermissionReference> grantees = permissionModelDAO.getGranteePermissions(SimplePermissionReference.getPermissionReference(QName.createQName("cm", "cmobject",
namespacePrefixResolver), "Coordinator"));
// NB This has gone from 59 to 63, I believe, because of the for new WCM roles.
// 63-97 from AVM permission fix up
assertEquals(103, grantees.size());
}
public void testIncludePermissionGroups6()
{
Set<PermissionReference> grantees = permissionModelDAO.getGranteePermissions(SimplePermissionReference.getPermissionReference(QName.createQName("cm", "cmobject",
namespacePrefixResolver), "RecordAdministrator"));
assertEquals(19, grantees.size());
}
public void testGetGrantingPermissions()
{
Set<PermissionReference> granters = permissionModelDAO.getGrantingPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base",
namespacePrefixResolver), "ReadProperties"));
// NB This has gone from 10 to 14 because of the new WCM roles, I believe.
// 14-18 -> 4 site base roles added
assertEquals(18, granters.size());
granters = permissionModelDAO.getGrantingPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base", namespacePrefixResolver),
"_ReadProperties"));
// NB 11 to 15 as above.
// 5-19 site based roles added
assertEquals(19, granters.size());
}
public void testGlobalPermissions()
{
Set<? extends PermissionEntry> globalPermissions = permissionModelDAO.getGlobalPermissionEntries();
assertEquals(6, globalPermissions.size());
}
public void testRequiredPermissions()
{
Set<PermissionReference> required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base",
namespacePrefixResolver), "Read"), QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
assertEquals(3, required.size());
required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base", namespacePrefixResolver),
"ReadContent"), QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
assertEquals(1, required.size());
required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base", namespacePrefixResolver),
"_ReadContent"), QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
assertEquals(0, required.size());
required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("cm", "cmobject", namespacePrefixResolver),
"Coordinator"), QName.createQName("cm", "cmobject", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
assertEquals(18, required.size());
required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base", namespacePrefixResolver),
"FullControl"), QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
assertEquals(18, required.size());
}
public void testMultiThreadedAccess()
{
Thread runner = null;
for (int i = 0; i < 20; i++)
{
runner = new Nester("Concurrent-" + i, runner);
}
if (runner != null)
{
runner.start();
try
{
runner.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class Nester extends Thread
{
Thread waiter;
Nester(String name, Thread waiter)
{
super(name);
this.setDaemon(true);
this.waiter = waiter;
}
public void run()
{
authenticationComponent.setSystemUserAsCurrentUser();
if (waiter != null)
{
waiter.start();
}
try
{
System.out.println("Start " + this.getName());
RetryingTransactionCallback<Void> queryPermissionModel = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
Random random = new Random();
Set<PermissionReference> toTest = permissionModelDAO.getAllPermissions(QName.createQName("sys", "base", namespacePrefixResolver));
for (int i = 0; i < 10000; i++)
{
for (PermissionReference pr : toTest)
{
if (random.nextFloat() < 0.5f)
{
// permissionModelDAO.getGranteePermissions(pr);
// permissionModelDAO.getGrantingPermissions(pr);
permissionModelDAO.getRequiredPermissions(pr, QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(),
On.NODE);
}
}
}
return null;
}
};
retryingTransactionHelper.doInTransaction(queryPermissionModel);
System.out.println("End " + this.getName());
}
catch (Exception e)
{
System.out.println("End " + this.getName() + " with error " + e.getMessage());
e.printStackTrace();
}
finally
{
authenticationComponent.clearCurrentSecurityContext();
}
if (waiter != null)
{
try
{
waiter.join();
}
catch (InterruptedException e)
{
}
}
}
}
public void testNulls()
{
permissionModelDAO.getRequiredPermissions(null, QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base",
namespacePrefixResolver), "Read"),null, Collections.<QName> emptySet(), On.NODE);
permissionModelDAO.getRequiredPermissions(null, null, Collections.<QName> emptySet(), On.NODE);
permissionModelDAO.getGranteePermissions(null);
permissionModelDAO.getGlobalPermissionEntries().contains(null);
}
}
| lgpl-3.0 |
xXKeyleXx/MyPet | modules/v1_18_R1/src/main/java/de/Keyle/MyPet/compat/v1_18_R1/entity/EntityRegistry.java | 6646 | /*
* This file is part of MyPet
*
* Copyright © 2011-2020 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_18_R1.entity;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld;
import org.bukkit.event.entity.CreatureSpawnEvent;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import de.Keyle.MyPet.MyPetApi;
import de.Keyle.MyPet.api.Util;
import de.Keyle.MyPet.api.entity.MyPet;
import de.Keyle.MyPet.api.entity.MyPetMinecraftEntity;
import de.Keyle.MyPet.api.entity.MyPetType;
import de.Keyle.MyPet.api.util.Compat;
import de.Keyle.MyPet.api.util.ReflectionUtil;
import lombok.SneakyThrows;
import net.minecraft.core.DefaultedRegistry;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityDimensions;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.Level;
@Compat("v1_18_R1")
public class EntityRegistry extends de.Keyle.MyPet.api.entity.EntityRegistry {
BiMap<MyPetType, Class<? extends EntityMyPet>> entityClasses = HashBiMap.create();
Map<MyPetType, EntityType> entityTypes = new HashMap<>();
protected void registerEntityType(MyPetType petType, String key, DefaultedRegistry<EntityType<?>> entityRegistry) {
EntityDimensions size = entityRegistry.get(new ResourceLocation(key.toLowerCase())).getDimensions();
entityTypes.put(petType, Registry.register(entityRegistry, "mypet_" + key.toLowerCase(), EntityType.Builder.createNothing(MobCategory.CREATURE).noSave().noSummon().sized(size.width, size.height).build(key)));
EntityType<? extends LivingEntity> types = (EntityType<? extends LivingEntity>) entityRegistry.get(new ResourceLocation(key));
registerDefaultAttributes(entityTypes.get(petType), types);
overwriteEntityID(entityTypes.get(petType), getEntityTypeId(petType, entityRegistry), entityRegistry);
}
@SneakyThrows
public static void registerDefaultAttributes(EntityType<? extends LivingEntity> customType, EntityType<? extends LivingEntity> rootType) {
MyAttributeDefaults.registerCustomEntityType(customType, rootType);
}
protected void registerEntity(MyPetType type, DefaultedRegistry<EntityType<?>> entityRegistry) {
Class<? extends EntityMyPet> entityClass = ReflectionUtil.getClass("de.Keyle.MyPet.compat.v1_18_R1.entity.types.EntityMy" + type.name());
entityClasses.forcePut(type, entityClass);
String key = type.getTypeID().toString();
registerEntityType(type, key, entityRegistry);
}
public MyPetType getMyPetType(Class<? extends EntityMyPet> clazz) {
return entityClasses.inverse().get(clazz);
}
@Override
public MyPetMinecraftEntity createMinecraftEntity(MyPet pet, org.bukkit.World bukkitWorld) {
EntityMyPet petEntity = null;
Class<? extends MyPetMinecraftEntity> entityClass = entityClasses.get(pet.getPetType());
Level world = ((CraftWorld) bukkitWorld).getHandle();
try {
Constructor<?> ctor = entityClass.getConstructor(Level.class, MyPet.class);
Object obj = ctor.newInstance(world, pet);
if (obj instanceof EntityMyPet) {
petEntity = (EntityMyPet) obj;
}
} catch (Exception e) {
MyPetApi.getLogger().info(ChatColor.RED + Util.getClassName(entityClass) + "(" + pet.getPetType() + ") is no valid MyPet(Entity)!");
e.printStackTrace();
}
return petEntity;
}
@Override
public boolean spawnMinecraftEntity(MyPetMinecraftEntity entity, org.bukkit.World bukkitWorld) {
if (entity != null) {
Level world = ((CraftWorld) bukkitWorld).getHandle();
return world.addFreshEntity(((EntityMyPet) entity), CreatureSpawnEvent.SpawnReason.CUSTOM);
}
return false;
}
@Override
public void registerEntityTypes() {
DefaultedRegistry<EntityType<?>> entityRegistry = getRegistry(Registry.ENTITY_TYPE);
for (MyPetType type : MyPetType.all()) {
registerEntity(type, entityRegistry);
}
}
public <T> T getEntityType(MyPetType petType) {
return (T) this.entityTypes.get(petType);
}
@Override
public void unregisterEntityTypes() {
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public DefaultedRegistry<EntityType<?>> getRegistry(DefaultedRegistry registryMaterials) {
if (!registryMaterials.getClass().getName().equals(DefaultedRegistry.class.getName())) {
MyPetApi.getLogger().info("Custom entity registry found: " + registryMaterials.getClass().getName());
for (Field field : registryMaterials.getClass().getDeclaredFields()) {
if (field.getType() == MappedRegistry.class) {
field.setAccessible(true);
try {
DefaultedRegistry<EntityType<?>> reg = (DefaultedRegistry<EntityType<?>>) field.get(registryMaterials);
if (!reg.getClass().getName().equals(DefaultedRegistry.class.getName())) {
reg = getRegistry(reg);
}
return reg;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return registryMaterials;
}
protected void overwriteEntityID(EntityType types, int id, DefaultedRegistry<EntityType<?>> entityRegistry) {
try {
Field bgF = MappedRegistry.class.getDeclaredField("bA"); //This is toId
bgF.setAccessible(true);
Object map = bgF.get(entityRegistry);
Class<?> clazz = map.getClass();
Method mapPut = clazz.getDeclaredMethod("put", Object.class, int.class);
mapPut.setAccessible(true);
mapPut.invoke(map, types, id);
} catch (ReflectiveOperationException ex) {
ex.printStackTrace();
}
}
protected int getEntityTypeId(MyPetType type, DefaultedRegistry<EntityType<?>> entityRegistry) {
EntityType<?> types = entityRegistry.get(new ResourceLocation(type.getTypeID().toString()));
return entityRegistry.getId(types);
}
}
| lgpl-3.0 |
Tybion/community-edition | projects/repository/source/java/org/alfresco/repo/search/impl/querymodel/impl/db/UUIDSupport.java | 4515 | /*
* Copyright (C) 2005-2013 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.search.impl.querymodel.impl.db;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.repo.domain.node.NodeDAO;
import org.alfresco.repo.domain.qname.QNameDAO;
import org.alfresco.repo.search.impl.querymodel.Argument;
import org.alfresco.repo.search.impl.querymodel.FunctionEvaluationContext;
import org.alfresco.repo.tenant.TenantService;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
/**
* @author Andy
*
*/
public class UUIDSupport implements DBQueryBuilderComponent
{
String uuid;
String[] uuids;
DBQueryBuilderPredicatePartCommandType commandType;
private boolean leftOuter;
/**
* @param uuid the uud to set
*/
public void setUuid(String uuid)
{
if(NodeRef.isNodeRef(uuid))
{
NodeRef ref = new NodeRef(uuid);
this.uuid = ref.getId();
}
else
{
this.uuid = uuid;
}
}
public void setUuids(String[] uuids)
{
this.uuids = new String[uuids.length];
for(int i = 0; i < uuids.length; i++)
{
if(NodeRef.isNodeRef(uuids[i]))
{
NodeRef ref = new NodeRef(uuids[i]);
this.uuids[i] = ref.getId();
}
else
{
this.uuids[i] = uuids[i];
}
}
}
/**
* @param commandType the commandType to set
*/
public void setCommandType(DBQueryBuilderPredicatePartCommandType commandType)
{
this.commandType = commandType;
}
/* (non-Javadoc)
* @see org.alfresco.repo.search.impl.querymodel.impl.db.DBQueryBuilderComponent#isSupported()
*/
@Override
public boolean isSupported()
{
return true;
}
/* (non-Javadoc)
* @see org.alfresco.repo.search.impl.querymodel.impl.db.DBQueryBuilderComponent#prepare(org.alfresco.service.namespace.NamespaceService, org.alfresco.service.cmr.dictionary.DictionaryService, org.alfresco.repo.domain.qname.QNameDAO, org.alfresco.repo.domain.node.NodeDAO, java.util.Set, java.util.Map, org.alfresco.repo.search.impl.querymodel.FunctionEvaluationContext)
*/
@Override
public void prepare(NamespaceService namespaceService, DictionaryService dictionaryService, QNameDAO qnameDAO, NodeDAO nodeDAO, TenantService tenantService, Set<String> selectors,
Map<String, Argument> functionArgs, FunctionEvaluationContext functionContext)
{
}
/* (non-Javadoc)
* @see org.alfresco.repo.search.impl.querymodel.impl.db.DBQueryBuilderComponent#buildJoins(java.util.Map, java.util.List)
*/
@Override
public void buildJoins(Map<QName, DBQueryBuilderJoinCommand> singleJoins, List<DBQueryBuilderJoinCommand> multiJoins)
{
}
/* (non-Javadoc)
* @see org.alfresco.repo.search.impl.querymodel.impl.db.DBQueryBuilderComponent#buildPredicateCommands(java.util.List)
*/
@Override
public void buildPredicateCommands(List<DBQueryBuilderPredicatePartCommand> predicatePartCommands)
{
DBQueryBuilderPredicatePartCommand command = new DBQueryBuilderPredicatePartCommand();
command.setAlias("node");
command.setType(commandType);
command.setFieldName("uuid");
command.setValue(uuid);
command.setValues(uuids);
predicatePartCommands.add(command);
}
/**
* @param leftOuter boolean
*/
public void setLeftOuter(boolean leftOuter)
{
this.leftOuter = leftOuter;
}
}
| lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter | pdfreporter-core/src/org/oss/pdfreporter/engine/type/OnErrorTypeEnum.java | 2587 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2011 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oss.pdfreporter.engine.type;
import org.oss.pdfreporter.engine.JRConstants;
/**
* @author sanda zaharia (shertage@users.sourceforge.net)
* @version $Id: OnErrorTypeEnum.java 4595 2011-09-08 15:55:10Z teodord $
*/
public enum OnErrorTypeEnum implements JREnum
{
/**
* A constant used for specifying that the engine should raise an exception if the image is not found.
*/
ERROR((byte)1, "Error"),
/**
* A constant used for specifying that the engine should display blank space if the image is not found.
*/
BLANK((byte)2, "Blank"),
/**
* A constant used for specifying that the engine should display a replacement icon if the image is not found.
*/
ICON((byte)3, "Icon");
/**
*
*/
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
private final transient byte value;
private final transient String name;
private OnErrorTypeEnum(byte value, String enumName)
{
this.value = value;
this.name = enumName;
}
/**
*
*/
public Byte getValueByte()
{
return new Byte(value);
}
/**
*
*/
public final byte getValue()
{
return value;
}
/**
*
*/
public String getName()
{
return name;
}
/**
*
*/
public static OnErrorTypeEnum getByName(String enumName)
{
return (OnErrorTypeEnum)EnumUtil.getByName(values(), enumName);
}
/**
*
*/
public static OnErrorTypeEnum getByValue(Byte value)
{
return (OnErrorTypeEnum)EnumUtil.getByValue(values(), value);
}
/**
*
*/
public static OnErrorTypeEnum getByValue(byte value)
{
return getByValue(new Byte(value));
}
}
| lgpl-3.0 |
kralisch/jams | JAMSOptas/src/optas/gui/MCAT5/MCAT5Toolbar.java | 10851 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package optas.gui.MCAT5;
import jams.JAMS;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Comparator;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import optas.gui.MCAT5.MCAT5Plot.NoDataException;
/**
*
* @author Christian Fischer
*/
public class MCAT5Toolbar extends JToolBar {
public static class ArrayComparator implements Comparator {
private int col = 0;
private int order = 1;
public ArrayComparator(int col, boolean decreasing_order) {
this.col = col;
if (decreasing_order) {
order = -1;
} else {
order = 1;
}
}
@Override
public int compare(Object d1, Object d2) {
double[] b1 = (double[]) d1;
double[] b2 = (double[]) d2;
if (b1[col] < b2[col]) {
return -1 * order;
} else if (b1[col] == b2[col]) {
return 0 * order;
} else {
return 1 * order;
}
}
}
enum PlotType{Sensitivity, Uncertainty, Basic};
private class PlotDesc{
ImageIcon icon;
String tooltip,title;
PlotType type;
Class clazz;
PlotDesc(PlotType type, ImageIcon icon, String tooltip, String title, Class clazz){
this.type = type;
this.icon = icon;
this.tooltip = tooltip;
this.title = title;
this.clazz = clazz;
}
}
DataCollectionPanel owner;
ArrayList<PlotDesc> registeredPlots = new ArrayList<PlotDesc>();
public static JFrame getDefaultPlotWindow(String title) {
JFrame plotWindow = new JFrame(title);
plotWindow.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
plotWindow.setLayout(new BorderLayout());
plotWindow.setVisible(true);
plotWindow.setSize(800, 700);
//this.setVisible(false);
return plotWindow;
}
public MCAT5Toolbar(DataCollectionPanel param_owner) {
super();
registeredPlots.add(new PlotDesc(PlotType.Basic,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/dottyplot.png")),
JAMS.i18n("CREATE_DOTTY_PLOT"),
JAMS.i18n("DOTTY_PLOT"),
DottyPlot.class));
/*registeredPlots.add(new PlotDesc(new ImageIcon(getClass().getResource("/reg/resources/images/dottyplot.png")),
"DottyPlot3D",
"DottyPlot3D",
DottyPlot3D.class));*/
registeredPlots.add(new PlotDesc(PlotType.Sensitivity,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/sensitivity.png")),
"Sensitivityanalyzer",
JAMS.i18n("Sensitivity_Analysis"),
SensitivityToolbox.class));
registeredPlots.add(new PlotDesc(PlotType.Sensitivity,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/interaction.png")),
"Interaction Effects Analyzer",
JAMS.i18n("Interaction_analysis"),
ParameterInteractionAnalyser.class));
registeredPlots.add(new PlotDesc(PlotType.Sensitivity,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/temporal_sa.png")),
JAMS.i18n("Temporal_Sensitivity_Analysis"),
JAMS.i18n("Temporal_Sensitivity_Analysis"),
TemporalSensitivityAnalysisGUI.class));
registeredPlots.add(new PlotDesc(PlotType.Basic,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/aposterioriplot.png")),
JAMS.i18n("CREATE_A_POSTERIORI_DISTRIBUTION_PLOT"),
JAMS.i18n("A_POSTERIO_PARAMETER_DISTRIBUTION"),
APosterioriPlot.class));
registeredPlots.add(new PlotDesc(PlotType.Basic,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/identifiabilityplot.png")),
JAMS.i18n("IDENTIFIABILITY_PLOT"),
JAMS.i18n("IDENTIFIABILITY_PLOT"),
IdentifiabilityPlot.class));
registeredPlots.add(new PlotDesc(PlotType.Basic,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/bestpredictionplot.png")),
JAMS.i18n("BEST_PREDICTION_PLOT"),
JAMS.i18n("BEST_PREDICTION_PLOT"),
BestPredictionPlot.class));
registeredPlots.add(new PlotDesc(PlotType.Basic,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/classplot.png")),
JAMS.i18n("CLASS_PLOT"),
JAMS.i18n("CLASS_PLOT"),
ClassPlot.class));
registeredPlots.add(new PlotDesc(PlotType.Basic,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/dyniaplot.png")),
JAMS.i18n("DYNIA"),
JAMS.i18n("DYNIA"),
DYNIA.class));
registeredPlots.add(new PlotDesc(PlotType.Uncertainty,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/ParetoOutPlot.png")),
JAMS.i18n("PARETO_OUTPUT_UNCERTAINITY"),
JAMS.i18n("PARETO_OUTPUT_UNCERTAINITY"),
ParetoOutputUncertainty.class));
registeredPlots.add(new PlotDesc(PlotType.Uncertainty,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/GLUEOutPlot.png")),
JAMS.i18n("GLUE_OUTPUT_UNCERTAINITY"),
JAMS.i18n("OUTPUT_UNCERTAINTY_PLOT"),
GLUEOutputUncertainty.class));
registeredPlots.add(new PlotDesc(PlotType.Uncertainty,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/GLUEVarPlot.png")),
JAMS.i18n("GLUE_VARIABLE_UNCERTAINITY"),
JAMS.i18n("CUMULATIVE_DENSITY_PLOT"),
GLUEVariableUncertainty.class));
registeredPlots.add(new PlotDesc(PlotType.Uncertainty,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/normalisedparameter.png")),
JAMS.i18n("NORMALIZED_PARAMETER_RANGE_PLOT"),
JAMS.i18n("NORMALISED_PARAMETER_RANGE_PLOT"),
NormalisedParameterRangePlot.class));
registeredPlots.add(new PlotDesc(PlotType.Uncertainty,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/ParetoBoxPlot.png")),
JAMS.i18n("PARETO_BOX_PLOT"),
JAMS.i18n("PARETO_BOX_PLOT"),
ParetoBoxPlot.class));
registeredPlots.add(new PlotDesc(PlotType.Sensitivity,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/regionalsensitivity.png")),
JAMS.i18n("REGIONAL_SENSITIVITY_ANALYSIS"),
JAMS.i18n("REGIONAL_SENSITIVITY_ANALYSIS"),
RegionalSensitivityAnalyser.class));
registeredPlots.add(new PlotDesc(PlotType.Sensitivity,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/regionalsensitivity2.png")),
JAMS.i18n("REGIONAL_SENSITIVITY_ANALYSIS_II"),
JAMS.i18n("REGIONAL_SENSITIVITY_ANALYSIS_II"),
RegionalSensitivityAnalyser2.class));
registeredPlots.add(new PlotDesc(PlotType.Basic,new ImageIcon(getClass().getResource("/jams/explorer/resources/images/regionalsensitivity2.png")),
JAMS.i18n("REGIONAL_SENSITIVITY_ANALYSIS_II"),
JAMS.i18n("REGIONAL_SENSITIVITY_ANALYSIS_II"),
MultiObjectiveDecisionSupport.class));
/*registeredPlots.add(new PlotDesc(new ImageIcon(getClass().getResource("/reg/resources/images/regionalsensitivity2.png")),
"Experimental I",
"Experimental I",
optas.SA.APosterioriPlot.class));
registeredPlots.add(new PlotDesc(new ImageIcon(getClass().getResource("/reg/resources/images/regionalsensitivity2.png")),
"Experimental II",
"Experimental II",
ParameterInterpolation2.class));*/
JToolBar toolbarBasic = new JToolBar("Basic Tools");
toolbarBasic.setBorder(BorderFactory.createTitledBorder("Basic-Analysis"));
JToolBar toolbarSenstivity = new JToolBar("Sensitivity Tools");
toolbarSenstivity.setBorder(BorderFactory.createTitledBorder("Sensitivity-Analysis"));
JToolBar toolbarUncertainty = new JToolBar("Uncertainty Tools");
toolbarUncertainty.setBorder(BorderFactory.createTitledBorder("Uncertainty-Analysis"));
for (PlotDesc pd : registeredPlots) {
JButton button = new JButton(pd.icon);
button.setToolTipText(pd.tooltip);
button.putClientProperty("plotTitle", pd.title);
button.putClientProperty("plotClass", pd.clazz);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
Class c = (Class)((JButton)evt.getSource()).getClientProperty("plotClass");
MCAT5Plot o = null;
try{
o = (MCAT5Plot)c.getConstructor().newInstance();
}catch(Exception e){
System.out.println(e.toString());e.printStackTrace();
}
try{
DataRequestPanel d = new DataRequestPanel(o, MCAT5Toolbar.this.owner.getDataCollection());
JFrame plotWindow = getDefaultPlotWindow((String)((JButton)evt.getSource()).getClientProperty("plotTitle"));
plotWindow.add(d, BorderLayout.CENTER);
}catch(NoDataException nde){
JOptionPane.showMessageDialog(MCAT5Toolbar.this, nde.toString());
}
}
});
if (pd.type == PlotType.Sensitivity){
toolbarSenstivity.add(button);
}else if (pd.type == PlotType.Basic){
toolbarBasic.add(button);
}else if (pd.type == PlotType.Uncertainty){
toolbarUncertainty.add(button);
}
}
this.add(toolbarBasic);
this.add(toolbarSenstivity);
this.add(toolbarUncertainty);
this.owner = param_owner;
this.setVisible(true);
this.setFloatable(false);
}
}
| lgpl-3.0 |
lbndev/sonarqube | server/sonar-server/src/test/java/org/sonar/server/organization/ws/OrganizationsWsTestSupport.java | 1377 | /*
* SonarQube
* Copyright (C) 2009-2017 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.server.organization.ws;
import javax.annotation.Nullable;
import org.sonar.server.ws.TestRequest;
public class OrganizationsWsTestSupport {
static final String STRING_65_CHARS_LONG = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890-ab";
static final String STRING_257_CHARS_LONG = String.format("%1$257.257s", "a").replace(" ", "a");
static void setParam(TestRequest request, String param, @Nullable String value) {
if (value != null) {
request.setParam(param, value);
}
}
}
| lgpl-3.0 |
ijpb/MorphoLibJ | src/test/java/inra/ijpb/plugins/InteractiveMarkerControlledWatershedTest.java | 1331 | /*-
* #%L
* Mathematical morphology library and plugins for ImageJ/Fiji.
* %%
* Copyright (C) 2014 - 2017 INRA.
* %%
* 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%
*/
package inra.ijpb.plugins;
import ij.IJ;
import ij.ImageJ;
public class InteractiveMarkerControlledWatershedTest {
/**
* Main method to test and debug the Interactive
* Marker-controlled Watershed plugin GUI
*
* @param args
*/
public static void main( final String[] args )
{
ImageJ.main( args );
IJ.open(
InteractiveMarkerControlledWatershed.class.getResource(
"/files/grains.tif" ).getFile() );
IJ.run("Find Edges");
new InteractiveMarkerControlledWatershed().run( null );
}
}
| lgpl-3.0 |
mbring/sonar-java | java-checks/src/main/java/org/sonar/java/checks/InstanceOfAlwaysTrueCheck.java | 1894 | /*
* SonarQube Java
* Copyright (C) 2012-2017 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.java.checks;
import com.google.common.collect.ImmutableList;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.semantic.Type;
import org.sonar.plugins.java.api.tree.InstanceOfTree;
import org.sonar.plugins.java.api.tree.Tree;
import java.util.List;
@Rule(key = "S1850")
public class InstanceOfAlwaysTrueCheck extends IssuableSubscriptionVisitor {
@Override
public List<Tree.Kind> nodesToVisit() {
return ImmutableList.of(Tree.Kind.INSTANCE_OF);
}
@Override
public void visitNode(Tree tree) {
InstanceOfTree instanceOfTree = (InstanceOfTree) tree;
Type expressionType = instanceOfTree.expression().symbolType();
Type instanceOf = instanceOfTree.type().symbolType();
if (expressionType.isSubtypeOf(instanceOf) && !instanceOfTree.expression().is(Tree.Kind.NULL_LITERAL)) {
reportIssue(instanceOfTree.instanceofKeyword(), "Remove this useless \"instanceof\" operator; it will always return \"true\". ");
}
}
}
| lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter | pdfreporter-core/src/org/oss/pdfreporter/engine/fill/JRFillEllipse.java | 3185 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2011 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oss.pdfreporter.engine.fill;
import org.oss.pdfreporter.engine.JREllipse;
import org.oss.pdfreporter.engine.JRException;
import org.oss.pdfreporter.engine.JRExpressionCollector;
import org.oss.pdfreporter.engine.JRPrintElement;
import org.oss.pdfreporter.engine.JRVisitor;
/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: JRFillEllipse.java 5632 2012-09-04 07:48:16Z teodord $
*/
public class JRFillEllipse extends JRFillGraphicElement implements JREllipse
{
/**
*
*/
protected JRFillEllipse(
JRBaseFiller filler,
JREllipse ellipse,
JRFillObjectFactory factory
)
{
super(filler, ellipse, factory);
}
protected JRFillEllipse(JRFillEllipse ellipse, JRFillCloneFactory factory)
{
super(ellipse, factory);
}
/**
*
*/
protected JRTemplateEllipse getJRTemplateEllipse()
{
return (JRTemplateEllipse) getElementTemplate();
}
protected JRTemplateElement createElementTemplate()
{
return new JRTemplateEllipse(
getElementOrigin(),
filler.getJasperPrint().getDefaultStyleProvider(),
this);
}
/**
*
*/
protected void evaluate(
byte evaluation
) throws JRException
{
this.reset();
this.evaluatePrintWhenExpression(evaluation);
evaluateProperties(evaluation);
evaluateStyle(evaluation);
setValueRepeating(true);
}
/**
*
*/
protected JRPrintElement fill()
{
JRTemplatePrintEllipse printEllipse = new JRTemplatePrintEllipse(this.getJRTemplateEllipse(), elementId);
printEllipse.setUUID(this.getUUID());
printEllipse.setX(this.getX());
printEllipse.setY(this.getRelativeY());
printEllipse.setWidth(getWidth());
printEllipse.setHeight(this.getStretchHeight());
transferProperties(printEllipse);
return printEllipse;
}
/**
*
*/
public void collectExpressions(JRExpressionCollector collector)
{
collector.collect(this);
}
/**
*
*/
public void visit(JRVisitor visitor)
{
visitor.visitEllipse(this);
}
/**
*
*/
protected void resolveElement (JRPrintElement element, byte evaluation)
{
// nothing
}
public JRFillCloneable createClone(JRFillCloneFactory factory)
{
return new JRFillEllipse(this, factory);
}
}
| lgpl-3.0 |
rsksmart/rskj | rskj-core/src/main/java/org/ethereum/net/p2p/HelloMessage.java | 6286 | /*
* This file is part of RskJ
* Copyright (C) 2017 RSK Labs Ltd.
* (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>)
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.p2p;
import org.bouncycastle.util.encoders.Hex;
import org.ethereum.net.client.Capability;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPList;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY;
/**
* Wrapper around an Ethereum HelloMessage on the network
*
* @see org.ethereum.net.p2p.P2pMessageCodes#HELLO
*/
public class HelloMessage extends P2pMessage {
/**
* The implemented version of the P2P protocol.
*/
private byte p2pVersion;
/**
* The underlying client. A user-readable string.
*/
private String clientId;
/**
* A peer-network capability code, readable ASCII and 3 letters.
* Currently only "eth", "shh" and "bzz" are known.
*/
private List<Capability> capabilities = Collections.emptyList();
/**
* The port on which the peer is listening for an incoming connection
*/
private int listenPort;
/**
* The identity and public key of the peer
*/
private String peerId;
public HelloMessage(byte[] encoded) {
super(encoded);
}
public HelloMessage(byte p2pVersion, String clientId,
List<Capability> capabilities, int listenPort, String peerId) {
this.p2pVersion = p2pVersion;
this.clientId = clientId;
this.capabilities = capabilities;
this.listenPort = listenPort;
this.peerId = peerId;
this.parsed = true;
}
private void parse() {
RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
byte[] p2pVersionBytes = paramsList.get(0).getRLPData();
this.p2pVersion = p2pVersionBytes != null ? p2pVersionBytes[0] : 0;
byte[] clientIdBytes = paramsList.get(1).getRLPData();
this.clientId = new String(clientIdBytes != null ? clientIdBytes : EMPTY_BYTE_ARRAY);
RLPList capabilityList = (RLPList) paramsList.get(2);
this.capabilities = new ArrayList<>();
for (int k = 0; k < capabilityList.size(); k++) {
Object aCapabilityList = capabilityList.get(k);
RLPElement capId = ((RLPList) aCapabilityList).get(0);
RLPElement capVersion = ((RLPList) aCapabilityList).get(1);
String name = new String(capId.getRLPData());
byte version = capVersion.getRLPData() == null ? 0 : capVersion.getRLPData()[0];
Capability cap = new Capability(name, version);
this.capabilities.add(cap);
}
byte[] peerPortBytes = paramsList.get(3).getRLPData();
this.listenPort = ByteUtil.byteArrayToInt(peerPortBytes);
byte[] peerIdBytes = paramsList.get(4).getRLPData();
this.peerId = ByteUtil.toHexString(peerIdBytes);
this.parsed = true;
}
private void encode() {
byte[] p2pVersion = RLP.encodeByte(this.p2pVersion);
byte[] clientId = RLP.encodeString(this.clientId);
byte[][] capabilities = new byte[this.capabilities.size()][];
for (int i = 0; i < this.capabilities.size(); i++) {
Capability capability = this.capabilities.get(i);
capabilities[i] = RLP.encodeList(
RLP.encodeElement(capability.getName().getBytes(StandardCharsets.UTF_8)),
RLP.encodeInt(capability.getVersion()));
}
byte[] capabilityList = RLP.encodeList(capabilities);
byte[] peerPort = RLP.encodeInt(this.listenPort);
byte[] peerId = RLP.encodeElement(Hex.decode(this.peerId));
this.encoded = RLP.encodeList(p2pVersion, clientId,
capabilityList, peerPort, peerId);
}
@Override
public byte[] getEncoded() {
if (encoded == null) {
encode();
}
return encoded;
}
public byte getP2PVersion() {
if (!parsed) {
parse();
}
return p2pVersion;
}
public String getClientId() {
if (!parsed) {
parse();
}
return clientId;
}
public List<Capability> getCapabilities() {
if (!parsed) {
parse();
}
return capabilities;
}
public int getListenPort() {
if (!parsed) {
parse();
}
return listenPort;
}
public String getPeerId() {
if (!parsed) {
parse();
}
return peerId;
}
@Override
public P2pMessageCodes getCommand() {
return P2pMessageCodes.HELLO;
}
public void setPeerId(String peerId) {
this.peerId = peerId;
}
public void setP2pVersion(byte p2pVersion) {
this.p2pVersion = p2pVersion;
}
@Override
public Class<?> getAnswerMessage() {
return null;
}
public String toString() {
if (!parsed) {
parse();
}
return String.format(
"[%s p2pVersion=%s clientId=%s capabilities=[%s] getPeerPort=%d peerId=%s]",
this.getCommand().name(),
this.p2pVersion,
this.clientId,
this.capabilities.stream().map(Capability::toString).collect(Collectors.joining(" ")),
this.listenPort,
this.peerId
);
}
} | lgpl-3.0 |
snmaher/xacml4j | xacml-core/src/main/java/org/xacml4j/v30/types/BaseAttributeExp.java | 2695 | package org.xacml4j.v30.types;
/*
* #%L
* Xacml4J Core Engine Implementation
* %%
* Copyright (C) 2009 - 2014 Xacml4J.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%
*/
import org.xacml4j.v30.AttributeExp;
import org.xacml4j.v30.AttributeExpType;
import org.xacml4j.v30.BagOfAttributeExp;
import org.xacml4j.v30.EvaluationContext;
import org.xacml4j.v30.EvaluationException;
import org.xacml4j.v30.ExpressionVisitor;
import org.xacml4j.v30.ValueType;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
public abstract class BaseAttributeExp<T>
implements AttributeExp
{
private static final long serialVersionUID = 4131180767511036271L;
private final T value;
private final AttributeExpType type;
protected BaseAttributeExp(AttributeExpType attrType,
T attrValue) {
Preconditions.checkNotNull(attrType);
Preconditions.checkNotNull(attrValue);
this.type = attrType;
this.value = attrValue;
}
@Override
public final ValueType getEvaluatesTo(){
return type;
}
@Override
public final AttributeExpType getType(){
return type;
}
@Override
public final AttributeExp evaluate(
EvaluationContext context) throws EvaluationException {
return this;
}
@Override
public final T getValue(){
return value;
}
@Override
public String toString() {
return Objects.toStringHelper(this).
add("Value", value).
add("Type", getType()).toString();
}
@Override
public int hashCode(){
return Objects.hashCode(
getType(), value);
}
@Override
public BagOfAttributeExp toBag(){
return type.bagOf(this);
}
@Override
public boolean equals(Object o){
if(o == null){
return false;
}
if(o == this){
return true;
}
if(!(o instanceof AttributeExp)){
return false;
}
AttributeExp e = (AttributeExp)o;
return type.equals(e.getType()) &&
value.equals(e.getValue());
}
@Override
public final void accept(ExpressionVisitor expv) {
AttributeExpVisitor v = (AttributeExpVisitor)expv;
v.visitEnter(this);
v.visitLeave(this);
}
}
| lgpl-3.0 |
DonTomika/mapsforge | mapsforge-core/src/test/java/org/mapsforge/core/model/TagTest.java | 1999 | /*
* Copyright 2010, 2011, 2012 mapsforge.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 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.mapsforge.core.model;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
public class TagTest {
private static final String KEY = "foo";
private static final String TAG_TO_STRING = "key=foo, value=bar";
private static final String VALUE = "bar";
@Test
public void constructorTest() {
Tag tag1 = new Tag(KEY + '=' + VALUE);
Tag tag2 = new Tag(KEY, VALUE);
TestUtils.equalsTest(tag1, tag2);
}
@Test
public void equalsTest() {
Tag tag1 = new Tag(KEY, VALUE);
Tag tag2 = new Tag(KEY, VALUE);
Tag tag3 = new Tag(KEY, KEY);
Tag tag4 = new Tag(VALUE, VALUE);
TestUtils.equalsTest(tag1, tag2);
Assert.assertNotEquals(tag1, tag3);
Assert.assertNotEquals(tag1, tag4);
Assert.assertNotEquals(tag3, tag1);
Assert.assertNotEquals(tag4, tag3);
Assert.assertNotEquals(tag1, new Object());
}
@Test
public void fieldTest() {
Tag tag = new Tag(KEY, VALUE);
Assert.assertEquals(KEY, tag.key);
Assert.assertEquals(VALUE, tag.value);
}
@Test
public void serializeTest() throws IOException, ClassNotFoundException {
Tag tag = new Tag(KEY, VALUE);
TestUtils.serializeTest(tag);
}
@Test
public void toStringTest() {
Tag tag = new Tag(KEY, VALUE);
Assert.assertEquals(TAG_TO_STRING, tag.toString());
}
}
| lgpl-3.0 |
dan-shaffer/torrent-enhancer | src/jBittorrentAPI/TorrentFile.java | 5068 | /*
* Java Bittorrent API as its name indicates is a JAVA API that implements the Bittorrent Protocol
* This project contains two packages:
* 1. jBittorrentAPI is the "client" part, i.e. it implements all classes needed to publish
* files, share them and download them.
* This package also contains example classes on how a developer could create new applications.
* 2. trackerBT is the "tracker" part, i.e. it implements a all classes needed to run
* a Bittorrent tracker that coordinates peers exchanges. *
*
* Copyright (C) 2007 Baptiste Dubuis, Artificial Intelligence Laboratory, EPFL
*
* This file is part of jbittorrentapi-v1.0.zip
*
* Java Bittorrent API is free software and a free user study set-up;
* you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Java Bittorrent API 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 Java Bittorrent API; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @version 1.0
* @author Baptiste Dubuis
* To contact the author:
* email: baptiste.dubuis@gmail.com
*
* More information about Java Bittorrent API:
* http://sourceforge.net/projects/bitext/
*/
package jBittorrentAPI;
import java.util.ArrayList;
import java.util.Date;
/**
* Representation of a torrent file
*
* @author Baptiste Dubuis
* @version 0.1
*/
public class TorrentFile {
public String announceURL;
public String comment;
public String createdBy;
public long creationDate;
public String encoding;
public String saveAs;
public int pieceLength;
/* In case of multiple files torrent, saveAs is the name of a directory
* and name contains the path of the file to be saved in this directory
*/
public ArrayList name;
public ArrayList length;
public byte[] info_hash_as_binary;
public String info_hash_as_hex;
public String info_hash_as_url;
public long total_length;
public ArrayList piece_hash_values_as_binary;
public ArrayList piece_hash_values_as_hex;
public ArrayList piece_hash_values_as_url;
/**
* Create the TorrentFile object and initiate its instance variables
*/
public TorrentFile() {
// super() what for if it does not inherit...
super();
announceURL = new String();
comment = new String();
createdBy = new String();
encoding = new String();
saveAs = new String();
creationDate = -1;
total_length = -1;
pieceLength = -1;
name = new ArrayList();
length = new ArrayList();
piece_hash_values_as_binary = new ArrayList();
piece_hash_values_as_url = new ArrayList();
piece_hash_values_as_hex = new ArrayList();
info_hash_as_binary = new byte[20];
info_hash_as_url = new String();
info_hash_as_hex = new String();
}
/**
* Print the torrent information in a readable manner.
* @param detailed Choose if we want a detailed output or not. Detailed
* output prints the comment, the files list and the pieces hashes while the
* standard output simply prints tracker url, creator, creation date and
* info hash
*/
public void printData(boolean detailed) {
System.out.println("Tracker URL: " + this.announceURL);
System.out.println("Torrent created by : " + this.createdBy);
System.out.println("Torrent creation date : " + new Date(this.creationDate));
System.out.println("Info hash :\n");
System.out.println("\t\t" + new String(this.info_hash_as_binary));
System.out.println("\t\t" + this.info_hash_as_hex);
System.out.println("\t\t" + this.info_hash_as_url);
if(detailed){
System.out.println("Comment :" + this.comment);
System.out.println("\nFiles List :\n");
for (int i = 0; i < this.length.size(); i++)
System.out.println("\t- " + this.name.get(i) + " ( " +
this.length.get(i) + " Bytes )");
System.out.println("\n");
System.out.println("Pieces hashes (piece length = " +
this.pieceLength + ") :\n");
for (int i = 0; i < this.piece_hash_values_as_binary.size(); i++) {
System.out.println((i + 1) + ":\t\t" +
this.piece_hash_values_as_binary.get(i));
System.out.println("\t\t" + this.piece_hash_values_as_hex.get(i));
System.out.println("\t\t" + this.piece_hash_values_as_url.get(i));
}
}
}
}
| lgpl-3.0 |
HOMlab/QN-ACTR-Release | QN-ACTR Java/src/jmt/gui/common/xml/XMLWriter.java | 47785 | /**
* Copyright (C) 2006, Laboratorio di Valutazione delle Prestazioni - Politecnico di Milano
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* 2013. Modified for QN-Java project
*
* [2013-07-13] disable normalizeProbabilities
*
*/
package jmt.gui.common.xml;
import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jmt.engine.log.LoggerParameters;
import jmt.engine.random.EmpiricalEntry;
import jmt.gui.common.CommonConstants;
import jmt.gui.common.definitions.CommonModel;
import jmt.gui.common.distributions.Distribution;
import jmt.gui.common.routingStrategies.ProbabilityRouting;
import jmt.gui.common.routingStrategies.RoutingStrategy;
import jmt.gui.common.serviceStrategies.LDStrategy;
import jmt.gui.common.serviceStrategies.ZeroStrategy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Created by IntelliJ IDEA.
* User: orsotronIII
* Date: 15-lug-2005
* Time: 10.56.01
* Modified by Bertoli Marco
*/
public class XMLWriter implements CommonConstants, XMLConstantNames {
/*defines matching between gui representation and engine names for queue
strategies, e.g. FCFS = TailStrategy.*/
protected static final HashMap queuePutStrategyNamesMatchings = new HashMap() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put(QUEUE_STRATEGY_FCFS, "TailStrategy");
put(QUEUE_STRATEGY_LCFS, "HeadStrategy");
}
};
protected static final HashMap priorityQueuePutStrategyNamesMatchings = new HashMap() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put(QUEUE_STRATEGY_FCFS, "TailStrategyPriority");
put(QUEUE_STRATEGY_LCFS, "HeadStrategyPriority");
}
};
/*defines matching between gui representation and engine names for drop
rules.*/
protected static final HashMap dropRulesNamesMatchings = new HashMap() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put(FINITE_DROP, "drop");
put(FINITE_WAITING, "waiting queue");
put(FINITE_BLOCK, "BAS blocking");
}
};
public static final String strategiesClasspathBase = "jmt.engine.NetStrategies.";
public static final String queuegetStrategiesSuffix = "QueueGetStrategies.";
public static final String queueputStrategiesSuffix = "QueuePutStrategies.";
public static final String routingStrategiesSuffix = "RoutingStrategies.";
public static final String serviceStrategiesSuffix = "ServiceStrategies.";
public static final String distributionContainerClasspath = "jmt.engine.random.DistributionContainer";
public static void writeXML(String fileName, CommonModel model) {
writeToResult(new StreamResult(new File(fileName)), model, fileName);
}
public static void writeXML(File xmlFile, CommonModel model) {
writeToResult(new StreamResult(xmlFile), model, xmlFile.getName());
}
public static void writeXML(OutputStream out, CommonModel model) {
writeToResult(new StreamResult(out), model, "model");
}
public static void writeXML(String fileName, Document doc) {
if (doc == null) {
return;
}
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty("encoding", ENCODING);
transformer.transform(new DOMSource(doc), new StreamResult(new File(fileName)));
} catch (TransformerConfigurationException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
} catch (TransformerFactoryConfigurationError transformerFactoryConfigurationError) {
transformerFactoryConfigurationError.printStackTrace(); //To change body of catch statement use Options | File Templates.
} catch (TransformerException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
}
}
public static Document getDocument(CommonModel model, String modelName) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
return null;
}
Document modelDoc = docBuilder.newDocument();
writeModel(modelDoc, model, modelName);
return modelDoc;
}
private static void writeToResult(Result res, CommonModel model, String modelName) {
Document modelDoc = getDocument(model, modelName);
if (modelDoc == null) {
return;
}
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty("encoding", ENCODING);
transformer.transform(new DOMSource(modelDoc), res);
} catch (TransformerConfigurationException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
} catch (TransformerFactoryConfigurationError transformerFactoryConfigurationError) {
transformerFactoryConfigurationError.printStackTrace(); //To change body of catch statement use Options | File Templates.
} catch (TransformerException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
}
}
static protected void writeModel(Document modelDoc, CommonModel model, String modelName) {
Element elem = modelDoc.createElement(XML_DOCUMENT_ROOT);
modelDoc.appendChild(elem);
elem.setAttribute(XML_A_ROOT_NAME, modelName);
elem.setAttribute("xsi:noNamespaceSchemaLocation", XML_DOCUMENT_XSD);
elem.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
// Simulation seed - Bertoli Marco
if (!model.getUseRandomSeed()) {
elem.setAttribute(XML_A_ROOT_SEED, model.getSimulationSeed().toString());
}
// Max simulation time - Bertoli Marco
if (model.getMaximumDuration().longValue() > 0) {
elem.setAttribute(XML_A_ROOT_DURATION, model.getMaximumDuration().toString());
}
// Polling interval - Bertoli Marco
elem.setAttribute(XML_A_ROOT_POLLING, Double.toString(model.getPollingInterval()));
// Max Samples - Bertoli Marco
elem.setAttribute(XML_A_ROOT_MAXSAMPLES, model.getMaxSimulationSamples().toString());
// Disable Statistic
elem.setAttribute(XML_A_ROOT_DISABLESTATISTIC, model.getDisableStatistic().toString());
// Write attributes used by the logs - Michael Fercu
elem.setAttribute(XML_A_ROOT_LOGPATH, model.getLoggingGlbParameter("path"));
elem.setAttribute(XML_A_ROOT_LOGREPLACE, model.getLoggingGlbParameter("autoAppend"));
elem.setAttribute(XML_A_ROOT_LOGDELIM, model.getLoggingGlbParameter("delim"));
elem.setAttribute(XML_A_ROOT_LOGDECIMALSEPARATOR, model.getLoggingGlbParameter("decimalSeparator"));
// Write all elements
writeClasses(modelDoc, elem, model);
writeStations(modelDoc, elem, model);
writeMeasures(modelDoc, elem, model);
writeConnections(modelDoc, elem, model);
writeBlockingRegions(modelDoc, elem, model);
writePreload(modelDoc, elem, model);
}
/*-----------------------------------------------------------------------------------
*--------------------- Methods for construction of user classes ---------------------
*-----------------------------------------------------------------------------------*/
static protected void writeClasses(Document doc, Node simNode, CommonModel model) {
Vector v = model.getClassKeys();
for (int i = 0; i < v.size(); i++) {
Object classKey = v.get(i);
String classType = model.getClassType(classKey) == CLASS_TYPE_CLOSED ? "closed" : "open";
Element userClass = doc.createElement(XML_E_CLASS);
String[] attrsNames = new String[] { XML_A_CLASS_NAME, XML_A_CLASS_TYPE, XML_A_CLASS_PRIORITY, XML_A_CLASS_CUSTOMERS,
XML_A_CLASS_REFSOURCE };
String[] attrsValues = new String[] { model.getClassName(classKey), classType, String.valueOf(model.getClassPriority(classKey)),
String.valueOf(model.getClassPopulation(classKey)), getSourceNameForClass(classKey, doc, model), };
for (int j = 0; j < attrsNames.length; j++) {
if (attrsValues[j] != null && !"null".equals(attrsValues[j])) {
userClass.setAttribute(attrsNames[j], attrsValues[j]);
}
}
simNode.appendChild(userClass);
}
}
/**This method returns the name of the reference source for a class to be inserted into
* userclass elemnt's attribute.*/
static protected String getSourceNameForClass(Object classKey, Document doc, CommonModel model) {
if (model.getClassRefStation(classKey) != null) {
return model.getStationName(model.getClassRefStation(classKey));
} else {
return null;
}
}
/*-----------------------------------------------------------------------------------
*----------------------- Methods for construction of stations -----------------------
*-----------------------------------------------------------------------------------*/
static protected void writeStations(Document doc, Node simNode, CommonModel model) {
Vector stations = model.getStationKeys();
Element elem;
for (int i = 0; i < stations.size(); i++) {
elem = doc.createElement(XML_E_STATION);
elem.setAttribute(XML_A_STATION_NAME, model.getStationName(stations.get(i)));
Object stationKey = stations.get(i);
String stationType = model.getStationType(stationKey);
if (STATION_TYPE_DELAY.equals(stationType)) {
writeQueueSection(doc, elem, model, stationKey);
writeDelaySection(doc, elem, model, stationKey);
writeRouterSection(doc, elem, model, stationKey);
} else if (STATION_TYPE_SERVER.equals(stationType)) {
writeQueueSection(doc, elem, model, stationKey);
writeServerSection(doc, elem, model, stationKey);
writeRouterSection(doc, elem, model, stationKey);
} else if (STATION_TYPE_SOURCE.equals(stationType)) {
writeSourceSection(doc, elem, model, stationKey);
writeTunnelSection(doc, elem, model, stationKey);
writeRouterSection(doc, elem, model, stationKey);
} else if (STATION_TYPE_TERMINAL.equals(stationType)) {
writeTerminalSection(doc, elem, model, stationKey);
writeTunnelSection(doc, elem, model, stationKey);
writeRouterSection(doc, elem, model, stationKey);
} else if (STATION_TYPE_ROUTER.equals(stationType)) {
writeQueueSection(doc, elem, model, stationKey);
writeTunnelSection(doc, elem, model, stationKey);
writeRouterSection(doc, elem, model, stationKey);
} else if (STATION_TYPE_LOGGER.equals(stationType)) {
writeQueueSection(doc, elem, model, stationKey);
writeLoggerSection(doc, elem, model, stationKey);
writeRouterSection(doc, elem, model, stationKey);
} else if (STATION_TYPE_FORK.equals(stationType)) {
writeQueueSection(doc, elem, model, stationKey);
writeTunnelSection(doc, elem, model, stationKey);
writeForkSection(doc, elem, model, stationKey);
} else if (STATION_TYPE_JOIN.equals(stationType)) {
writeJoinSection(doc, elem, model, stationKey);
writeTunnelSection(doc, elem, model, stationKey);
writeRouterSection(doc, elem, model, stationKey);
} else if (STATION_TYPE_SINK.equals(stationType)) {
writeSinkSection(doc, elem, model, stationKey);
}
simNode.appendChild(elem);
}
}
/**
* Writes a Join input section
* <br>Author: Bertoli Marco
* @param doc document root
* @param node node where created section should be appended
* @param model data structure
* @param stationKey search's key for join
*/
private static void writeJoinSection(Document doc, Node node, CommonModel model, Object stationKey) {
Element join = doc.createElement(XML_E_STATION_SECTION);
join.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_JOIN);
node.appendChild(join);
}
/**
* Writes a Fork output section
* <br>Author: Bertoli Marco
* @param doc document root
* @param node node where created section should be appended
* @param model data structure
* @param stationKey search's key for fork
*/
private static void writeForkSection(Document doc, Node node, CommonModel model, Object stationKey) {
Element fork = doc.createElement(XML_E_STATION_SECTION);
fork.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_FORK);
node.appendChild(fork);
// Creates jobsPerLink parameter
XMLParameter jobsPerLink = new XMLParameter("jobsPerLink", model.getStationNumberOfServers(stationKey).getClass().getName(), null, model
.getStationNumberOfServers(stationKey).toString(), false);
// Creates block parameter
XMLParameter block = new XMLParameter("block", model.getForkBlock(stationKey).getClass().getName(), null, model.getForkBlock(stationKey)
.toString(), false);
//...and adds them as fork's children
jobsPerLink.appendParameterElement(doc, fork);
block.appendParameterElement(doc, fork);
}
static protected void writeSourceSection(Document doc, Node nodeNode, CommonModel model, Object stationKey) {
Element elem = doc.createElement(XML_E_STATION_SECTION);
elem.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_SOURCE);
nodeNode.appendChild(elem);
Vector classes = model.getClassKeys();
//obtain classes that must be generated by this source
Vector refClasses = getClassesForSource(model, stationKey);
XMLParameter[] distrParams = new XMLParameter[classes.size()];
for (int i = 0; i < distrParams.length; i++) {
//if current class must be generated by this source
Object currentClass = classes.get(i);
if (refClasses.contains(currentClass)) {
distrParams[i] = DistributionWriter.getDistributionParameter((Distribution) model.getClassDistribution(currentClass), model,
currentClass);
} else {
//otherwise write a null parameter
String name = "ServiceTimeStrategy";
distrParams[i] = new XMLParameter(name, strategiesClasspathBase + serviceStrategiesSuffix + name, model.getClassName(currentClass),
"null", true);
}
}
//creating global service strategy parameter
String gspName = "ServiceStrategy";
XMLParameter globalStrategyParameter = new XMLParameter(gspName, strategiesClasspathBase + gspName, null, distrParams, false);
//finally, create node from pareameters and append it to the section element
globalStrategyParameter.appendParameterElement(doc, elem);
}
static protected void writeSinkSection(Document doc, Node nodeNode, CommonModel model, Object stationKey) {
Element elem = doc.createElement(XML_E_STATION_SECTION);
elem.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_SINK);
nodeNode.appendChild(elem);
}
static protected void writeQueueSection(Document doc, Node nodeNode, CommonModel model, Object stationKey) {
//creating element representing queue section
Element queue = doc.createElement(XML_E_STATION_SECTION);
queue.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_QUEUE);
nodeNode.appendChild(queue);
//creating queue inner parameters
//first create queue size node element
String queueSize = model.getStationQueueCapacity(stationKey) == null ? "-1" : model.getStationQueueCapacity(stationKey).toString();
XMLParameter queueLength = new XMLParameter("size", "java.lang.Integer", null, queueSize, false);
//...and add it to queue element's children
queueLength.appendParameterElement(doc, queue);
// Drop policies. They are different for each customer class
XMLParameter[] queueDropStrategies = new XMLParameter[model.getClassKeys().size()];
XMLParameter queueDropStrategy = new XMLParameter("dropStrategies", String.class.getName(), null, queueDropStrategies, false);
Vector classes = model.getClassKeys();
for (int i = 0; i < queueDropStrategies.length; i++) {
String dropStrategy = model.getDropRule(stationKey, classes.get(i));
queueDropStrategies[i] = new XMLParameter("dropStrategy", String.class.getName(), model.getClassName(classes.get(i)),
(String) dropRulesNamesMatchings.get(dropStrategy), true);
}
queueDropStrategy.appendParameterElement(doc, queue);
/*queue get strategy, which is fixed to FCFS, as difference between strategies can
be resolved by queueput strategies*/
String strategy = "FCFSstrategy";
boolean priority = false;
if (QUEUE_STRATEGY_STATION_PS.equals(model.getStationQueueStrategy(stationKey))) {
strategy = "PSStrategy";
} else if (QUEUE_STRATEGY_STATION_QUEUE_PRIORITY.equals(model.getStationQueueStrategy(stationKey))) {
priority = true;
}
XMLParameter queueGetStrategy = new XMLParameter(strategy, strategiesClasspathBase + queuegetStrategiesSuffix + "FCFSstrategy", null,
(String) null, false);
queueGetStrategy.appendParameterElement(doc, queue);
/*At last, queue put parameter, which can be defined differently for each
customerclass, so a more complex parameter structure is required*/
XMLParameter[] queuePutStrategies = new XMLParameter[model.getClassKeys().size()];
XMLParameter queuePutStrategy = new XMLParameter("NetStrategy", strategiesClasspathBase + "QueuePutStrategy", null, queuePutStrategies, false);
for (int i = 0; i < queuePutStrategies.length; i++) {
String queueStrategy = model.getQueueStrategy(stationKey, classes.get(i));
HashMap map = priority ? priorityQueuePutStrategyNamesMatchings : queuePutStrategyNamesMatchings;
String queueputStrategyName = (String) map.get(queueStrategy);
queuePutStrategies[i] = new XMLParameter(queueputStrategyName, strategiesClasspathBase + queueputStrategiesSuffix + queueputStrategyName,
model.getClassName(classes.get(i)), (String) null, true);
}
queuePutStrategy.appendParameterElement(doc, queue);
}
static protected void writeTerminalSection(Document doc, Node nodeNode, CommonModel model, Object stationKey) {
Element elem = doc.createElement(XML_E_STATION_SECTION);
elem.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_TERMINAL);
nodeNode.appendChild(elem);
Vector classes = model.getClassKeys();
//obtain classes that must be generated by this terminal
Vector refClasses = getClassesForTerminal(model, stationKey);
XMLParameter[] distrParams = new XMLParameter[classes.size()];
for (int i = 0; i < distrParams.length; i++) {
//if current class must be generated by this terminal
Object currentClass = classes.get(i);
if (refClasses.contains(currentClass)) {
distrParams[i] = new XMLParameter("numberOfJobs", "java.lang.Integer", model.getClassName(currentClass), model.getClassPopulation(
currentClass).toString(), true);
} else {
//otherwise write a null parameter
distrParams[i] = new XMLParameter("numberOfJobs", "java.lang.Integer", model.getClassName(currentClass), "-1", true);
}
}
//creating global population parameter
XMLParameter globalStrategyParameter = new XMLParameter("NumberOfJobs", "java.lang.Integer", null, distrParams, false);
//finally, create node from pareameters and append it to the section element
globalStrategyParameter.appendParameterElement(doc, elem);
}
static protected void writeServerSection(Document doc, Node nodeNode, CommonModel model, Object stationKey) {
Element elem = doc.createElement(XML_E_STATION_SECTION);
if (QUEUE_STRATEGY_STATION_PS.equals(model.getStationQueueStrategy(stationKey))) {
elem.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_PSSERVER);
} else {
elem.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_SERVER);
}
nodeNode.appendChild(elem);
Vector classes = model.getClassKeys();
//creating number of servers node element
Integer maxJobs = model.getStationNumberOfServers(stationKey);
XMLParameter numOfServers = new XMLParameter("maxJobs", "java.lang.Integer", null, maxJobs != null ? maxJobs.toString() : "-1", false);
numOfServers.appendParameterElement(doc, elem);
//creating visits node element
XMLParameter[] visits = new XMLParameter[classes.size()];
for (int i = 0; i < visits.length; i++) {
visits[i] = new XMLParameter("numberOfVisits", "java.lang.Integer", model.getClassName(classes.get(i)), "1", true);
}
XMLParameter visitsParam = new XMLParameter("numberOfVisits", "java.lang.Integer", null, visits, false);
visitsParam.appendParameterElement(doc, elem);
getServiceSection(model, stationKey).appendParameterElement(doc, elem);
}
/**
* Returns a service section rapresentation in XMLParameter format
* @param model model data structure
* @param stationKey search's key for current station
* @return service section rapresentation in XMLParameter format
* Author: Bertoli Marco
*/
protected static XMLParameter getServiceSection(CommonModel model, Object stationKey) {
Vector classes = model.getClassKeys();
//creating set of service time distributions
XMLParameter[] distrParams = new XMLParameter[classes.size()];
Object currentClass;
for (int i = 0; i < distrParams.length; i++) {
currentClass = classes.get(i);
Object serviceDistribution = model.getServiceTimeDistribution(stationKey, currentClass);
if (serviceDistribution instanceof Distribution) {
// Service time is a Distribution and not a LDService
distrParams[i] = DistributionWriter.getDistributionParameter((Distribution) serviceDistribution, model, currentClass);
} else if (serviceDistribution instanceof ZeroStrategy) {
// Zero Service Time Strategy --- Bertoli Marco
distrParams[i] = new XMLParameter("ZeroTimeServiceStrategy", ZeroStrategy.getEngineClassPath(), model.getClassName(currentClass),
(String) null, true);
} else {
// Load dependent Service Time Strategy --- Bertoli Marco
LDStrategy strategy = (LDStrategy) serviceDistribution;
XMLParameter[] ranges = new XMLParameter[strategy.getRangeNumber()];
Object[] rangeKeys = strategy.getAllRanges();
for (int j = 0; j < ranges.length; j++) {
// Creates "from" parameter
XMLParameter from = new XMLParameter("from", Integer.class.getName(), null,
Integer.toString(strategy.getRangeFrom(rangeKeys[j])), true);
// Creates "distribution" parameter
XMLParameter[] distribution = DistributionWriter.getDistributionParameter(strategy.getRangeDistribution(rangeKeys[j]));
// Creates "function" parameter (mean value of the distribution)
XMLParameter function = new XMLParameter("function", String.class.getName(), null, strategy
.getRangeDistributionMean(rangeKeys[j]), true);
ranges[j] = new XMLParameter("LDParameter", strategiesClasspathBase + serviceStrategiesSuffix + "LDParameter", null,
new XMLParameter[] { from, distribution[0], distribution[1], function }, true);
// Sets array = false as it's not an array of equal elements
ranges[j].parameterArray = "false";
}
// Creates LDParameter array
XMLParameter LDParameter = new XMLParameter("LDParameter", strategiesClasspathBase + serviceStrategiesSuffix + "LDParameter", null,
ranges, true);
// Creates Service strategy
distrParams[i] = new XMLParameter("LoadDependentStrategy", strategiesClasspathBase + serviceStrategiesSuffix
+ "LoadDependentStrategy", model.getClassName(currentClass), new XMLParameter[] { LDParameter }, true);
distrParams[i].parameterArray = "false";
}
}
XMLParameter globalDistr = new XMLParameter("ServiceStrategy", strategiesClasspathBase + "ServiceStrategy", null, distrParams, false);
return globalDistr;
}
static protected void writeTunnelSection(Document doc, Node nodeNode, CommonModel model, Object stationKey) {
Element elem = doc.createElement(XML_E_STATION_SECTION);
elem.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_TUNNEL);
nodeNode.appendChild(elem);
}
/**
* Write all parameters for a Logger section.
* @param doc XML document
* @param node XML hierarchy node
* @param model link to data structure
* @param stationKey key of search for this source station into data structure
* @author Michael Fercu (Bertoli Marco)
* Date: 08-aug-2008
* @see jmt.engine.log.LoggerParameters LoggerParameters
* @see jmt.gui.common.definitions.CommonModel#getLoggingParameters CommonModel.getLoggingParameters()
* @see jmt.gui.common.XMLReader#parseLogger XMLReader.parseLogger()
* @see jmt.engine.NodeSections.LogTunnel LogTunnel
*/
static protected void writeLoggerSection(Document doc, Node nodeNode, CommonModel model, Object stationKey) {
Element elem = doc.createElement(XML_E_STATION_SECTION);
elem.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_LOGGER);
nodeNode.appendChild(elem);
// Get this station's logger parameters
LoggerParameters loggerParameters = (LoggerParameters) model.getLoggingParameters(stationKey);
XMLParameter name = new XMLParameter(XML_LOG_FILENAME, "java.lang.String", null, loggerParameters.name.toString(), false);
name.appendParameterElement(doc, elem);
loggerParameters.path = model.getLoggingGlbParameter("path"); // temporary fix
XMLParameter path = new XMLParameter(XML_LOG_FILEPATH, "java.lang.String", null, loggerParameters.getpath().toString(), false);
path.appendParameterElement(doc, elem);
XMLParameter logExecTimestamp = new XMLParameter(XML_LOG_B_EXECTIMESTAMP, "java.lang.Boolean", null, loggerParameters.boolExecTimestamp
.toString(), false);
logExecTimestamp.appendParameterElement(doc, elem);
XMLParameter logLoggerName = new XMLParameter(XML_LOG_B_LOGGERNAME, "java.lang.Boolean", null, loggerParameters.boolLoggername.toString(),
false);
logLoggerName.appendParameterElement(doc, elem);
XMLParameter logTimeStamp = new XMLParameter(XML_LOG_B_TIMESTAMP, "java.lang.Boolean", null, loggerParameters.boolTimeStamp.toString(), false);
logTimeStamp.appendParameterElement(doc, elem);
XMLParameter logJobID = new XMLParameter(XML_LOG_B_JOBID, "java.lang.Boolean", null, loggerParameters.boolJobID.toString(), false);
logJobID.appendParameterElement(doc, elem);
XMLParameter logJobClass = new XMLParameter(XML_LOG_B_JOBCLASS, "java.lang.Boolean", null, loggerParameters.boolJobClass.toString(), false);
logJobClass.appendParameterElement(doc, elem);
XMLParameter logTimeSameClass = new XMLParameter(XML_LOG_B_TIMESAMECLS, "java.lang.Boolean", null, loggerParameters.boolTimeSameClass
.toString(), false);
logTimeSameClass.appendParameterElement(doc, elem);
XMLParameter logTimeAnyClass = new XMLParameter(XML_LOG_B_TIMEANYCLS, "java.lang.Boolean", null,
loggerParameters.boolTimeAnyClass.toString(), false);
logTimeAnyClass.appendParameterElement(doc, elem);
XMLParameter classSize = new XMLParameter("numClasses", "java.lang.Integer", null, new Integer(model.getClassKeys().size()).toString(), false);
classSize.appendParameterElement(doc, elem);
}
static protected void writeDelaySection(Document doc, Node nodeNode, CommonModel model, Object stationKey) {
Element elem = doc.createElement(XML_E_STATION_SECTION);
elem.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_DELAY);
nodeNode.appendChild(elem);
getServiceSection(model, stationKey).appendParameterElement(doc, elem);
}
static protected void writeRouterSection(Document doc, Node nodeNode, CommonModel model, Object stationKey) {
Element elem = doc.createElement(XML_E_STATION_SECTION);
elem.setAttribute(XML_A_STATION_SECTION_CLASSNAME, CLASSNAME_ROUTER);
nodeNode.appendChild(elem);
//creating list of paramters for each single routing strategy
Vector classes = model.getClassKeys();
XMLParameter[] routingStrats = new XMLParameter[classes.size()];
Object currentClass;
for (int i = 0; i < routingStrats.length; i++) {
currentClass = classes.get(i);
routingStrats[i] = RoutingStrategyWriter.getRoutingStrategyParameter(
(RoutingStrategy) model.getRoutingStrategy(stationKey, currentClass), model, currentClass, stationKey);
}
XMLParameter globalRouting = new XMLParameter("RoutingStrategy", strategiesClasspathBase + "RoutingStrategy", null, routingStrats, false);
globalRouting.appendParameterElement(doc, elem);
}
//returns a list of keys for customer classes generated by a specific source station
static protected Vector getClassesForSource(CommonModel model, Object stationKey) {
Vector keys = model.getClassKeys();
Vector classes = new Vector();
for (int i = 0; i < keys.size(); i++) {
if (CLASS_TYPE_OPEN == model.getClassType(keys.get(i)) && model.getClassRefStation(keys.get(i)) == stationKey) {
classes.add(keys.get(i));
}
}
return classes;
}
//returns a list of keys for customer classes generated by a specific terminal station
static protected Vector getClassesForTerminal(CommonModel model, Object stationKey) {
Vector keys = model.getClassKeys();
Vector classes = new Vector();
for (int i = 0; i < keys.size(); i++) {
if (CLASS_TYPE_CLOSED == model.getClassType(keys.get(i)) && model.getClassRefStation(keys.get(i)) == stationKey) {
classes.add(keys.get(i));
}
}
return classes;
}
/*-----------------------------------------------------------------------------------
*----------------------- Methods for construction of measures -----------------------
*-----------------------------------------------------------------------------------*/
static protected void writeMeasures(Document doc, Node simNode, CommonModel model) {
Vector v = model.getMeasureKeys();
for (int i = 0; i < v.size(); i++) {
Element elem = doc.createElement(XML_E_MEASURE);
Object key = v.get(i);
String station = model.getStationName(model.getMeasureStation(key)), userClass = model.getClassName(model.getMeasureClass(key)), type = model
.getMeasureType(v.get(i));
elem.setAttribute(XML_A_MEASURE_TYPE, type);
String name = "";
// This is a region measure
if (model.getRegionKeys().contains(model.getMeasureStation(key))) {
station = model.getRegionName(model.getMeasureStation(key));
elem.setAttribute(XML_A_MEASURE_NODETYPE, NODETYPE_REGION);
} else {
elem.setAttribute(XML_A_MEASURE_NODETYPE, NODETYPE_STATION);
}
if (station != null) {
elem.setAttribute(XML_A_MEASURE_STATION, station);
name += station + "_";
} else {
elem.setAttribute(XML_A_MEASURE_STATION, "");
}
if (userClass != null) {
elem.setAttribute(XML_A_MEASURE_CLASS, userClass);
name += userClass + "_";
} else {
elem.setAttribute(XML_A_MEASURE_CLASS, "");
}
name += type;
// Inverts alpha and keeps only 10 decimal cifres
double alpha = 1 - model.getMeasureAlpha(key).doubleValue();
alpha = Math.rint(alpha * 1e10) / 1e10;
elem.setAttribute(XML_A_MEASURE_ALPHA, Double.toString(alpha));
elem.setAttribute(XML_A_MEASURE_PRECISION, model.getMeasurePrecision(key).toString());
elem.setAttribute(XML_A_MEASURE_NAME, name);
elem.setAttribute(XML_A_MEASURE_VERBOSE, "false");
simNode.appendChild(elem);
}
}
/*-----------------------------------------------------------------------------------
*--------------------- Methods for construction of connections ----------------------
*-----------------------------------------------------------------------------------*/
static protected void writeConnections(Document doc, Node simNode, CommonModel model) {
Vector stations = model.getStationKeys();
String[] stationNames = new String[stations.size()];
for (int i = 0; i < stationNames.length; i++) {
stationNames[i] = model.getStationName(stations.get(i));
}
for (int i = 0; i < stationNames.length; i++) {
for (int j = 0; j < stationNames.length; j++) {
if (model.areConnected(stations.get(i), stations.get(j))) {
Element elem = doc.createElement(XML_E_CONNECTION);
elem.setAttribute(XML_A_CONNECTION_SOURCE, stationNames[i]);
elem.setAttribute(XML_A_CONNECTION_TARGET, stationNames[j]);
simNode.appendChild(elem);
}
}
}
}
/*-----------------------------------------------------------------------------------
--------------------- Methods for construction of preload data --- Bertoli Marco ----
------------------------------------------------------------------------------------*/
static protected void writePreload(Document doc, Node simNode, CommonModel model) {
// Finds if and where preloading is needed
Vector stations = model.getStationKeys();
Vector classes = model.getClassKeys();
// A map containing all stations that need preloading
Vector<Element> p_stations = new Vector<Element>();
for (int stat = 0; stat < stations.size(); stat++) {
Object key = stations.get(stat);
Vector<Element> p_class = new Vector<Element>();
for (int i = 0; i < classes.size(); i++) {
Object classKey = classes.get(i);
Integer jobs = model.getPreloadedJobs(key, classKey);
if (jobs.intValue() > 0) {
Element elem = doc.createElement(XML_E_CLASSPOPULATION);
elem.setAttribute(XML_A_CLASSPOPULATION_NAME, model.getClassName(classKey));
elem.setAttribute(XML_A_CLASSPOPULATION_POPULATION, jobs.toString());
p_class.add(elem);
}
}
// If any preload is provided for this station, creates its element and adds it to p_stations
if (!p_class.isEmpty()) {
Element elem = doc.createElement(XML_E_STATIONPOPULATIONS);
elem.setAttribute(XML_A_PRELOADSTATION_NAME, model.getStationName(key));
while (!p_class.isEmpty()) {
elem.appendChild(p_class.remove(0));
}
p_stations.add(elem);
}
}
// If p_stations is not empty, creates a preload section for stations in p_stations
if (!p_stations.isEmpty()) {
Element preload = doc.createElement(XML_E_PRELOAD);
while (!p_stations.isEmpty()) {
preload.appendChild(p_stations.remove(0));
}
simNode.appendChild(preload);
}
}
/*-----------------------------------------------------------------------------------
------------------- Methods for construction of blocking regions --------------------
--------------------------------- Bertoli Marco ------------------------------------*/
static protected void writeBlockingRegions(Document doc, Node simNode, CommonModel model) {
Vector regions = model.getRegionKeys();
for (int reg = 0; reg < regions.size(); reg++) {
Object key = regions.get(reg);
Element region = doc.createElement(XML_E_REGION);
// Set name attribute
region.setAttribute(XML_A_REGION_NAME, model.getRegionName(key));
// Set type attribute (optional)
region.setAttribute(XML_A_REGION_TYPE, model.getRegionType(key));
// Adds nodes (stations) to current region
Iterator stations = model.getBlockingRegionStations(key).iterator();
while (stations.hasNext()) {
Element node = doc.createElement(XML_E_REGIONNODE);
node.setAttribute(XML_A_REGIONNODE_NAME, model.getStationName(stations.next()));
region.appendChild(node);
}
// Add class constraints
Iterator classes = model.getClassKeys().iterator();
// Add global constraint
Element globalConstraint = doc.createElement(XML_E_GLOBALCONSTRAINT);
globalConstraint.setAttribute(XML_A_GLOBALCONSTRAINT_MAXJOBS, model.getRegionCustomerConstraint(key).toString());
region.appendChild(globalConstraint);
while (classes.hasNext()) {
Object classKey = classes.next();
Element classConstraint = doc.createElement(XML_E_CLASSCONSTRAINT);
classConstraint.setAttribute(XML_A_CLASSCONSTRAINT_CLASS, model.getClassName(classKey));
classConstraint.setAttribute(XML_A_CLASSCONSTRAINT_MAXJOBS, model.getRegionClassCustomerConstraint(key, classKey).toString());
region.appendChild(classConstraint);
}
// Add drop rules
classes = model.getClassKeys().iterator();
while (classes.hasNext()) {
Object classKey = classes.next();
Element drop = doc.createElement(XML_E_DROPRULES);
drop.setAttribute(XML_A_DROPRULES_CLASS, model.getClassName(classKey));
drop.setAttribute(XML_A_DROPRULES_DROP, model.getRegionClassDropRule(key, classKey).toString());
region.appendChild(drop);
}
simNode.appendChild(region);
}
}
/*-----------------------------------------------------------------------------------
------------------------ Inner classes for more ease of use -------------------------
------------------------------------------------------------------------------------*/
protected static class XMLParameter {
public boolean isSubParameter = false;
public String parameterName;
public String parameterClasspath;
public String parameterRefClass;
public String parameterValue;
public String parameterArray;
public XMLParameter[] parameters;
public XMLParameter(String name, String classpath, String refClass, String value, boolean isSubParameter) {
this(name, classpath, refClass, value, null, isSubParameter);
parameterArray = "false";
}
public XMLParameter(String name, String classpath, String refClass, XMLParameter[] parameters, boolean isSubParameter) {
this(name, classpath, refClass, null, parameters, isSubParameter);
parameterArray = "true";
}
private XMLParameter(String name, String classpath, String refClass, String value, XMLParameter[] parameters, boolean isSubParameter) {
parameterName = name;
parameterClasspath = classpath;
parameterRefClass = refClass;
parameterValue = value;
this.parameters = parameters;
this.isSubParameter = isSubParameter;
if (parameters != null) {
if (parameters.length > 1) {
parameterArray = "false";
} else {
parameterArray = "true";
}
} else {
parameterArray = "false";
}
}
public void appendParameterElement(Document doc, Element scope) {
//creating inner element containing queue length
Element parameter = doc.createElement(isSubParameter ? XML_E_SUBPARAMETER : XML_E_PARAMETER);
if (parameterClasspath != null) {
parameter.setAttribute(XML_A_PARAMETER_CLASSPATH, parameterClasspath);
}
if (parameterName != null) {
parameter.setAttribute(XML_A_PARAMETER_NAME, parameterName);
}
if (parameterArray != null && "true".equals(parameterArray)) {
parameter.setAttribute(XML_A_PARAMETER_ARRAY, parameterArray);
}
//adding element refclass for this parameter
if (parameterRefClass != null) {
Element refclass = doc.createElement(XML_E_PARAMETER_REFCLASS);
refclass.appendChild(doc.createTextNode(parameterRefClass));
scope.appendChild(refclass);
}
//adding element value of parameter
if (parameterValue != null) {
Element value = doc.createElement(XML_E_PARAMETER_VALUE);
value.appendChild(doc.createTextNode(parameterValue));
parameter.appendChild(value);
}
if (parameters != null) {
for (XMLParameter parameter2 : parameters) {
if (parameter2 != null) {
parameter2.appendParameterElement(doc, parameter);
}
}
}
scope.appendChild(parameter);
}
}
/**This class provides a simple method to obtain XMLparameter representation
* of a distribution object. Creation of a distribution parameter is a bit awkward, so
* I'll explain it as best as I can as it follows.
* generally a distribution is associated to a service time strategy, either it is
* an interarrival distribution for open classes job generation, or a proper service
* time distribution for a certain station. As a result, distribution parameter is
* inserted in a ServiceTimeStrategy parameter which is the one userclass is
* associated to. Inside this parameter node should be inserted 2 subParameter nodes:
* <br>-One for distribution description(containing distribution classpath and name)
* <br>- One containing all of the distribution constructor parameters.
* <br>The first one has null value, the second contains a list of parameters which, as
* they are different from each other, they are not considered as array. Then, the
* node which contains them has no value for array attribute.*/
protected static class DistributionWriter {
/*returns a distribution in XMLParameter format, to allow nesting it in
other parameters. */
static XMLParameter getDistributionParameter(Distribution distr, CommonModel model, Object classKey) {
XMLParameter[] distribution = getDistributionParameter(distr);
XMLParameter returnValue = new XMLParameter("ServiceTimeStrategy", strategiesClasspathBase + serviceStrategiesSuffix
+ "ServiceTimeStrategy", model.getClassName(classKey), new XMLParameter[] { distribution[0], distribution[1] }, true);
/*although this parameter contains several others, array attribute must be set
to "false", as their type are not neccessarily equal*/
returnValue.parameterArray = "false";
return returnValue;
}
/**
* Returns a Distribution in XMLParameter format without refclass. This is used to write
* load dependent service section distributions
* @param distr distribution to be written
* @return the two object to represent a distribution: distribution and its parameter object
* Author: Bertoli Marco
*/
static XMLParameter[] getDistributionParameter(Distribution distr) {
// a list of direct parameter -> parameter which must be passed directly to the distribution object
List<XMLParameter> directParams = new Vector<XMLParameter>();
// a list of parameters which are passed to the distribution parameter
List<XMLParameter> nonDirectParams = new Vector<XMLParameter>();
Distribution.Parameter distrPar;
//Object valueObj;
//parse over all parameters and add them to the apropriate list
for (int i = 0; i < distr.getNumberOfParameters(); i++) {
distrPar = distr.getParameter(i);
if (distrPar.isDirectParameter()) {
directParams.add(getParameter(distrPar));
} else {
nonDirectParams.add(getParameter(distrPar));
}
}
//get an array of the direct parameters
XMLParameter[] directPars = new XMLParameter[directParams.size()];
for (int i = 0; i < directPars.length; i++) {
directPars[i] = directParams.get(i);
}
//get an array of the non direct parameters
XMLParameter[] nonDirectPars = new XMLParameter[nonDirectParams.size()];
for (int i = 0; i < nonDirectPars.length; i++) {
nonDirectPars[i] = nonDirectParams.get(i);
}
//create the distribution parameter with the direct parameters
XMLParameter[] ret = new XMLParameter[2];
ret[0] = new XMLParameter(distr.getName(), distr.getClassPath(), (String) null, directPars, true);
//create the distribution parameter with the non direct parameters
ret[1] = new XMLParameter("distrPar", distr.getParameterClassPath(), null, nonDirectPars, true);
ret[0].parameterArray = "false";
ret[1].parameterArray = "false";
return ret;
}
/**
* Helper method to extract an XMLParameter from a Distribution parameter
* @param distrPar the distribution parameter
* @return the created XML Parameter
*/
static XMLParameter getParameter(Distribution.Parameter distrPar) {
Object valueObj = distrPar.getValue();
if (valueObj != null) {
if (distrPar.getValue() instanceof Distribution) {
XMLParameter[] distribution = getDistributionParameter((Distribution) valueObj);
XMLParameter returnValue = new XMLParameter(distrPar.getName(), distributionContainerClasspath, null, new XMLParameter[] {
distribution[0], distribution[1] }, true);
/*
* although this parameter contains several others, array
* attribute must be set to "false", as their type are not
* neccessarily equal
*/
returnValue.parameterArray = "false";
return returnValue;
} else {
String value = valueObj.toString();
return new XMLParameter(distrPar.getName(), distrPar.getValueClass().getName(), null, value, true);
}
}
return null;
}
}
/**
* This class creates an xml parameter node given a
* jmt.gui.common.RoutingStrategy object.
*/
protected static class RoutingStrategyWriter {
static XMLParameter getRoutingStrategyParameter(RoutingStrategy routingStrat, CommonModel model, Object classKey, Object stationKey) {
//parameter containing array of empirical entries
XMLParameter probRoutingPar = null;
if (routingStrat.getValues() != null && routingStrat instanceof ProbabilityRouting) {
Vector outputs = model.getForwardConnections(stationKey);
Map values = routingStrat.getValues();
// model.normalizeProbabilities(values, outputs, classKey, stationKey); //QN-Java
XMLParameter[] empiricalEntries = new XMLParameter[outputs.size()];
for (int i = 0; i < empiricalEntries.length; i++) {
XMLParameter stationDest = new XMLParameter("stationName", String.class.getName(), null, model.getStationName(outputs.get(i)),
true);
String prob = values.get(outputs.get(i)).toString();
XMLParameter routProb = new XMLParameter("probability", Double.class.getName(), null, prob, true);
empiricalEntries[i] = new XMLParameter("EmpiricalEntry", EmpiricalEntry.class.getName(), null, new XMLParameter[] { stationDest,
routProb }, true);
empiricalEntries[i].parameterArray = "false";
}
probRoutingPar = new XMLParameter("EmpiricalEntryArray", EmpiricalEntry.class.getName(), null, empiricalEntries, true);
}
//creating parameter for empirical strategy: must be null if routing is empirical
XMLParameter[] innerRoutingPar = probRoutingPar != null ? new XMLParameter[] { probRoutingPar } : null;
XMLParameter routingStrategy = new XMLParameter(routingStrat.getName(), routingStrat.getClassPath(), model.getClassName(classKey),
innerRoutingPar, true);
routingStrategy.parameterArray = "false";
return routingStrategy;
}
/*private static void normalizeProbabilities(Map values, Vector outputKeys){
Double[] probabilities = new Double[outputKeys.size()];
Object[] keys = new Object[outputKeys.size()];
outputKeys.toArray(keys);
//extract all values from map in array form
for(int i=0; i<keys.length; i++){
probabilities[i] = (Double)values.get(keys[i]);
}
values.clear();
//scan for null values and for total sum
double totalSum = 0.0;
int totalNonNull = 0;
boolean allNull = true;
for(int i=0; i<probabilities.length; i++){
if(probabilities[i]!=null){
totalSum += probabilities[i].doubleValue();
totalNonNull++;
allNull = false;
}
}
//modify non null values for their sum to match 1 and put null values to 1
for(int i=0; i<probabilities.length; i++){
if(probabilities[i]!=null || allNull){
if(totalSum==0){
probabilities[i] = new Double(1.0/(double)totalNonNull);
}else{
probabilities[i] = new Double(probabilities[i].doubleValue()/totalSum);
}
}else{
probabilities[i] = new Double(0.0);
}
values.put(keys[i], probabilities[i]);
}
}*/
}
}
| lgpl-3.0 |
Neil5043/Minetweak | src/main/java/net/minecraft/src/CommandServerEmote.java | 1439 | package net.minecraft.src;
import net.minecraft.server.MinecraftServer;
import java.util.List;
public class CommandServerEmote extends CommandBase
{
public String getCommandName()
{
return "me";
}
/**
* Return the required permission level for this command.
*/
public int getRequiredPermissionLevel()
{
return 0;
}
public String getCommandUsage(ICommandSender par1ICommandSender)
{
return "commands.me.usage";
}
public void processCommand(ICommandSender par1ICommandSender, String[] par2ArrayOfStr)
{
if (par2ArrayOfStr.length > 0)
{
String var3 = func_82361_a(par1ICommandSender, par2ArrayOfStr, 0, par1ICommandSender.canCommandSenderUseCommand(1, "me"));
MinecraftServer.getServer().getConfigurationManager().func_110460_a(ChatMessageComponent.func_111082_b("chat.type.emote", new Object[] {par1ICommandSender.getCommandSenderName(), var3}));
}
else
{
throw new WrongUsageException("commands.me.usage", new Object[0]);
}
}
/**
* Adds the strings available in this command to the given list of tab completion options.
*/
public List addTabCompletionOptions(ICommandSender par1ICommandSender, String[] par2ArrayOfStr)
{
return getListOfStringsMatchingLastWord(par2ArrayOfStr, MinecraftServer.getServer().getAllUsernames());
}
}
| lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter-Studio | com.jaspersoft.studio.properties/src/com/jaspersoft/studio/properties/view/ITabDescriptor.java | 2212 | /*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.properties.view;
import java.util.List;
/**
* Represents a tab descriptor for the tabbed property view.
* <p>
* This interface should not be extended or implemented. New instances should be
* created using <code>AbstractTabDescriptor</code>.
* </p>
*
* @author Anthony Hunter
* @since 3.4
*/
public interface ITabDescriptor extends ITabItem {
/**
* If afterTab is not specified in the descriptor, we default to be the top
* tab.
*/
public static final String TOP = "top"; //$NON-NLS-1$
/**
* Instantiate this tab's sections.
*
* @return The tab contents for this section.
*/
public TabContents createTab();
/**
* Get the identifier of the tab after which this tab should be displayed.
* When two or more tabs belong to the same category, they are sorted by the
* after tab values.
*
* @return the identifier of the tab.
*/
public String getAfterTab();
/**
* Get the category this tab belongs to.
*
* @return Get the category this tab belongs to.
*/
public String getCategory();
/**
* Get the unique identifier for the tab.
*
* @return the unique identifier for the tab.
*/
public String getId();
/**
* Get the text label for the tab.
*
* @return the text label for the tab.
*/
public String getLabel();
/**
* Get the list of section descriptors for the tab.
*
* @return the list of section descriptors for the tab.
*/
public List<ISectionDescriptor> getSectionDescriptors();
/**
* Return if the tab should be scrollable or not.
*/
public boolean getScrollable();
}
| lgpl-3.0 |
vitrofp7/vitro | source/trunk/Demo/VirtualSensor/src/main/java/vitro/virtualsensor/communication/soap/VirtualSensorInterface.java | 1225 | /*
* #--------------------------------------------------------------------------
* # Copyright (c) 2013 VITRO FP7 Consortium.
* # All rights reserved. This program and the accompanying materials
* # are made available under the terms of the GNU Lesser Public License v3.0 which accompanies this distribution, and is available at
* # http://www.gnu.org/licenses/lgpl-3.0.html
* #
* # Contributors:
* # Antoniou Thanasis (Research Academic Computer Technology Institute)
* # Paolo Medagliani (Thales Communications & Security)
* # D. Davide Lamanna (WLAB SRL)
* # Alessandro Leoni (WLAB SRL)
* # Francesco Ficarola (WLAB SRL)
* # Stefano Puglia (WLAB SRL)
* # Panos Trakadas (Technological Educational Institute of Chalkida)
* # Panagiotis Karkazis (Technological Educational Institute of Chalkida)
* # Andrea Kropp (Selex ES)
* # Kiriakos Georgouleas (Hellenic Aerospace Industry)
* # David Ferrer Figueroa (Telefonica Investigación y Desarrollo S.A.)
* #
* #--------------------------------------------------------------------------
*/
package vitro.virtualsensor.communication.soap;
public interface VirtualSensorInterface {
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/share-po/src/test/java/org/alfresco/po/share/site/document/ContentDetailsTest.java | 1748 | /**
*
*/
package org.alfresco.po.share.site.document;
import org.alfresco.po.share.dashlet.AbstractSiteDashletTest;
import org.alfresco.po.share.util.FailedTestListener;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
/**
* @author Ranjith Manyam
*
*/
@Listeners(FailedTestListener.class)
public class ContentDetailsTest extends AbstractSiteDashletTest
{
@Test
public void testDefaultConstructor()
{
ContentDetails details = new ContentDetails();
details.setName("Name");
details.setTitle("Title");
details.setDescription("Description");
details.setContent("Content");
Assert.assertEquals(details.getName(), "Name");
Assert.assertEquals(details.getTitle(), "Title");
Assert.assertEquals(details.getDescription(), "Description");
Assert.assertEquals(details.getContent(), "Content");
}
@Test
public void testNameFieldConstructor()
{
ContentDetails details = new ContentDetails("Name");
Assert.assertEquals(details.getName(), "Name");
Assert.assertNull(details.getTitle());
Assert.assertNull(details.getDescription());
Assert.assertNull(details.getContent());
}
@Test
public void testConstructorWithAllFields()
{
ContentDetails details = new ContentDetails("Name", "Title", "Description", "Content");
Assert.assertEquals(details.getName(), "Name");
Assert.assertEquals(details.getTitle(), "Title");
Assert.assertEquals(details.getDescription(), "Description");
Assert.assertEquals(details.getContent(), "Content");
}
}
| lgpl-3.0 |
estevaosaleme/MpegMetadata | src/org/iso/mpeg/mpeg7/_2004/VariationType.java | 8274 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.12 at 06:39:36 PM BRST
//
package org.iso.mpeg.mpeg7._2004;
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.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for VariationType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="VariationType">
* <complexContent>
* <extension base="{urn:mpeg:mpeg7:schema:2004}DSType">
* <sequence>
* <element name="Source" type="{urn:mpeg:mpeg7:schema:2004}MultimediaContentType" minOccurs="0"/>
* <element name="Content" type="{urn:mpeg:mpeg7:schema:2004}MultimediaContentType"/>
* <element name="VariationRelationship" maxOccurs="unbounded" minOccurs="0">
* <simpleType>
* <union>
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
* <enumeration value="summarization"/>
* <enumeration value="abstraction"/>
* <enumeration value="extraction"/>
* <enumeration value="modalityTranslation"/>
* <enumeration value="languageTranslation"/>
* <enumeration value="colorReduction"/>
* <enumeration value="spatialReduction"/>
* <enumeration value="temporalReduction"/>
* <enumeration value="samplingReduction"/>
* <enumeration value="rateReduction"/>
* <enumeration value="qualityReduction"/>
* <enumeration value="compression"/>
* <enumeration value="scaling"/>
* <enumeration value="revision"/>
* <enumeration value="substitution"/>
* <enumeration value="replay"/>
* <enumeration value="alternativeView"/>
* <enumeration value="alternativeMediaProfile"/>
* </restriction>
* </simpleType>
* <simpleType>
* <restriction base="{urn:mpeg:mpeg7:schema:2004}termAliasReferenceType">
* </restriction>
* </simpleType>
* <simpleType>
* <restriction base="{urn:mpeg:mpeg7:schema:2004}termURIReferenceType">
* </restriction>
* </simpleType>
* </union>
* </simpleType>
* </element>
* </sequence>
* <attribute name="fidelity" type="{urn:mpeg:mpeg7:schema:2004}zeroToOneType" />
* <attribute name="priority" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" />
* <attribute name="timeOffset" type="{urn:mpeg:mpeg7:schema:2004}mediaDurationType" />
* <attribute name="timeScale" type="{urn:mpeg:mpeg7:schema:2004}zeroToOneType" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VariationType", propOrder = {
"source",
"content",
"variationRelationship"
})
public class VariationType
extends DSType
{
@XmlElement(name = "Source")
protected MultimediaContentType source;
@XmlElement(name = "Content", required = true)
protected MultimediaContentType content;
@XmlElement(name = "VariationRelationship")
protected List<String> variationRelationship;
@XmlAttribute(name = "fidelity")
protected Float fidelity;
@XmlAttribute(name = "priority")
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger priority;
@XmlAttribute(name = "timeOffset")
protected String timeOffset;
@XmlAttribute(name = "timeScale")
protected Float timeScale;
/**
* Gets the value of the source property.
*
* @return
* possible object is
* {@link MultimediaContentType }
*
*/
public MultimediaContentType getSource() {
return source;
}
/**
* Sets the value of the source property.
*
* @param value
* allowed object is
* {@link MultimediaContentType }
*
*/
public void setSource(MultimediaContentType value) {
this.source = value;
}
/**
* Gets the value of the content property.
*
* @return
* possible object is
* {@link MultimediaContentType }
*
*/
public MultimediaContentType getContent() {
return content;
}
/**
* Sets the value of the content property.
*
* @param value
* allowed object is
* {@link MultimediaContentType }
*
*/
public void setContent(MultimediaContentType value) {
this.content = value;
}
/**
* Gets the value of the variationRelationship 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 variationRelationship property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getVariationRelationship().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getVariationRelationship() {
if (variationRelationship == null) {
variationRelationship = new ArrayList<String>();
}
return this.variationRelationship;
}
/**
* Gets the value of the fidelity property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getFidelity() {
return fidelity;
}
/**
* Sets the value of the fidelity property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setFidelity(Float value) {
this.fidelity = value;
}
/**
* Gets the value of the priority property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getPriority() {
return priority;
}
/**
* Sets the value of the priority property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setPriority(BigInteger value) {
this.priority = value;
}
/**
* Gets the value of the timeOffset property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTimeOffset() {
return timeOffset;
}
/**
* Sets the value of the timeOffset property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTimeOffset(String value) {
this.timeOffset = value;
}
/**
* Gets the value of the timeScale property.
*
* @return
* possible object is
* {@link Float }
*
*/
public Float getTimeScale() {
return timeScale;
}
/**
* Sets the value of the timeScale property.
*
* @param value
* allowed object is
* {@link Float }
*
*/
public void setTimeScale(Float value) {
this.timeScale = value;
}
}
| lgpl-3.0 |
almondtools/regexparser | src/test/java/net/amygdalum/regexparser/EmptyNodeTest.java | 1485 | package net.amygdalum.regexparser;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import net.amygdalum.regexparser.EmptyNode;
import net.amygdalum.regexparser.RegexNodeVisitor;
@RunWith(MockitoJUnitRunner.class)
public class EmptyNodeTest {
@Mock
private RegexNodeVisitor<String> visitor;
@Test
public void testGetLiteralValue() throws Exception {
assertThat(new EmptyNode().getLiteralValue(), equalTo(""));
}
@Test
public void testAccept() throws Exception {
when(visitor.visitEmpty(any(EmptyNode.class))).thenReturn("success");
assertThat(new EmptyNode().accept(visitor), equalTo("success"));
}
@Test
public void testCloneIsNotOriginal() throws Exception {
EmptyNode original = new EmptyNode();
EmptyNode cloned = original.clone();
assertThat(cloned, not(sameInstance(original)));
}
@Test
public void testCloneIsSimilar() throws Exception {
EmptyNode original = new EmptyNode();
EmptyNode cloned = original.clone();
assertThat(cloned.toString(), equalTo(original.toString()));
}
@Test
public void testToString() throws Exception {
assertThat(new EmptyNode().toString(), equalTo(""));
}
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | tests_typechecker_novariability/OptInfoSuperAndSuperConstructorAccess/01/FeatureAok/A.java | 120 | public class A extends B {
public int j = super.i;
public A() {
super();
}
public void foo() {
super.foo();
}
} | lgpl-3.0 |
maximehamm/jspresso-ce | application/src/main/java/org/jspresso/framework/application/backend/session/IEntityUnitOfWork.java | 6013 | /*
* Copyright (c) 2005-2016 Vincent Vandenschrick. All rights reserved.
*
* This file is part of the Jspresso framework.
*
* Jspresso 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.
*
* Jspresso 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 Jspresso. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jspresso.framework.application.backend.session;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import org.jspresso.framework.model.entity.IEntity;
import org.jspresso.framework.model.entity.IEntityLifecycleHandler;
/**
* This interface is implemented by unit of works on entities. A unit of work
* is a structure which will generally synchronize with a transaction to keep
* track of entity creations, updates, deletions and which is able to either
* commit the changes or rollback them upon work completion. A unit of work is
* reusable.
*
* @author Vincent Vandenschrick
*/
public interface IEntityUnitOfWork extends IEntityLifecycleHandler {
/**
* Registers an entity as being updated.
*
* @param entity
* the entity to register.
*/
void addUpdatedEntity(IEntity entity);
/**
* Registers an entity as being deleted.
*
* @param entity
* the entity to register.
*/
void addDeletedEntity(IEntity entity);
/**
* Begins a new unit of work.
*/
void begin();
/**
* Begins a nested unit of work.
*/
void beginNested();
/**
* Does this UOW has a nested one.
* @return if the UOW has a nested one.
*/
boolean hasNested();
/**
* Clears the dirty state of the entity in this unit of work.
*
* @param flushedEntity
* the entity that was flushed and cleaned.
*/
void clearDirtyState(IEntity flushedEntity);
/**
* Adds a new dirt interceptor that will be notified every time an entity is made dirty.
*
* @param interceptor
* the interceptor.
*/
void addDirtInterceptor(PropertyChangeListener interceptor);
/**
* Removes a dirt interceptor that was previously added.
*
* @param interceptor
* the interceptor.
*/
void removeDirtInterceptor(PropertyChangeListener interceptor);
/**
* Commits the unit of work. It should clear it state and be ready for another
* work.
*/
void commit();
/**
* Gets the entitiesRegisteredForDeletion.
*
* @return the entitiesRegisteredForDeletion.
*/
Collection<IEntity> getEntitiesRegisteredForDeletion();
/**
* Gets the entitiesRegisteredForUpdate.
*
* @return the entitiesRegisteredForUpdate.
*/
Collection<IEntity> getEntitiesRegisteredForUpdate();
/**
* Gets a map of entities already part of the unit of work. Entities are first
* keyed by their contract, then their id.
*
* @return a map of entities already part of the unit of work
*/
Map<Class<? extends IEntity>, Map<Serializable, IEntity>> getRegisteredEntities();
/**
* Gets the entitiesToMergeBack.
*
* @return the entitiesToMergeBack.
*/
Collection<IEntity> getUpdatedEntities();
/**
* Gets the entitiesToMergeBack.
*
* @return the entitiesToMergeBack.
*/
Collection<IEntity> getDeletedEntities();
/**
* Tests whether this unit of work is currently in use.
*
* @return true if the unit of work is active.
*/
boolean isActive();
/**
* Tests whether the passed entity already updated in the current unit of work and waits
* for commit.
*
* @param entity
* the entity to test.
* @return true if the passed entity already updated in the current unit of
* work and waits for commit.
*/
boolean isUpdated(IEntity entity);
/**
* Registers an entity in the unit of work.
*
* @param entity
* the entity to register.
* @param initialChangedProperties
* the map of dirty properties the entity has before entering the
* unit of work along with their original values.
*/
void register(IEntity entity, Map<String, Object> initialChangedProperties);
/**
* Rollbacks the unit of work. It should clear it state, restore the entity
* states to the one before the unit of work beginning and be ready for another
* work.
*/
void rollback();
/**
* Clears the UOW.
*/
void clear();
/**
* Gets a previously registered entity in the unit of work.
*
* @param entityContract
* the entity contract.
* @param entityId
* the identifier of the looked-up entity.
* @return the registered entity or null.
*/
IEntity getRegisteredEntity(Class<? extends IEntity> entityContract,
Serializable entityId);
/**
* Suspends the unit of work.
*/
void suspend();
/**
* Resumes the unit of work.
*/
void resume();
/**
* Gets the entity dirty properties (changed properties that need to be
* updated to the persistent store as well as computed properties) from the enclosing (parent)
* unit of work.
*
* @param entity
* the entity to get the dirty properties of
* @param fallbackUOW UOW to fall back to if unknown
* @return an empty map if the entity is not dirty. The collection of dirty
* properties with their original values. null if dirty recording has
* not been started for this entity instance. In the latter case, the
* dirty state is unknown.
*/
Map<String, Object> getParentDirtyProperties(IEntity entity, IEntityUnitOfWork fallbackUOW);
}
| lgpl-3.0 |
logsniffer/logsniffer | logsniffer-core/src/main/java/com/logsniffer/util/value/Configured.java | 1476 | /*******************************************************************************
* logsniffer, open source tool for viewing, monitoring and analysing log data.
* Copyright (c) 2015 Scaleborn UG, www.scaleborn.com
*
* logsniffer 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.
*
* logsniffer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package com.logsniffer.util.value;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotated {@link ConfigValue} properties will get injected the configured
* values reconfigurable on demand.
*
* @author mbok
*
*/
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Configured {
String value();
String defaultValue() default "";
}
| lgpl-3.0 |
syamn/ArtGenerator | src/main/java/syam/artgenerator/command/ReloadCommand.java | 1098 | /**
* ArtGenerator - Package: syam.artgenerator.command
* Created: 2012/11/21 19:26:15
*/
package syam.artgenerator.command;
import syam.artgenerator.Perms;
import syam.artgenerator.generator.Timer;
import syam.artgenerator.util.Actions;
/**
* ReloadCommand (ReloadCommand.java)
* @author syam(syamn)
*/
public class ReloadCommand extends BaseCommand{
public ReloadCommand(){
bePlayer = false;
name = "reload";
argLength = 0;
usage = "<- reload config.yml";
}
@Override
public void execute() {
Timer.stopAll();
plugin.getServer().getScheduler().cancelTasks(plugin);
try{
plugin.getConfigs().loadConfig(false);
}catch (Exception ex){
log.warning(logPrefix+"an error occured while trying to load the config file.");
ex.printStackTrace();
return;
}
Actions.message(sender, "&aConfiguration reloaded!");
}
@Override
public boolean permission() {
return Perms.RELOAD.has(sender);
}
} | lgpl-3.0 |
SergiyKolesnikov/fuji | examples/ExamDB/varenc/ExamDB-VarEnc/src/FeatureModel.java | 639 | public class FeatureModel {
public static final int ExamDB = 0;
public static final int BonusPoints = 1;
public static final int BackOut = 2;
public static final int Statistics = 3;
private static boolean[] configuration = new boolean[4];
/*@ public invariant
@ fm();
@*/
static {
// virtual initialization of the configuration
// valid fm is assumed afterwards
}
public /*@pure@*/ static boolean fm() {
return !(f(BonusPoints) || f(BackOut) || f(Statistics)) || f(ExamDB);
}
public /*@pure@*/ static boolean f(int feature) {
return configuration[feature];
}
}
| lgpl-3.0 |
automenta/spacegraph1 | plugin/automenta/spacenet/plugin/neural/brainz/Synapse.java | 623 | package automenta.spacenet.plugin.neural.brainz;
public class Synapse {
public final AbstractNeuron inputNeuron; // InputNeuron's Output Pointer
double dendriteBranch; // dendridic branch synapse is located on
double weight; // it's synaptic weight -1.0f <-> +1.0f
public Synapse(AbstractNeuron inputNeuron, double dendriteBranch, float synapticWeight) {
super();
this.inputNeuron = inputNeuron;
this.dendriteBranch = dendriteBranch;
this.weight = synapticWeight;
}
public double getInput() {
return inputNeuron.getOutput();
}
}
| lgpl-3.0 |
tblasche/springboot-jersey-example | src/main/java/de/tblasche/example/modules/user/resources/AuthenticationResource.java | 3084 | package de.tblasche.example.modules.user.resources;
import de.tblasche.example.modules.user.enums.HairColor;
import de.tblasche.example.modules.user.representations.UserCredentialsRepresentation;
import de.tblasche.example.modules.user.representations.UserRepresentation;
import de.tblasche.example.modules.user.service.UserService;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Path("users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class AuthenticationResource {
@Inject
private UserService userService;
/**
* Tries to authenticate the given user.
*
* Possible return codes:
* - 200 OK: Authentication successful
* - 401 Unauthorized: Credentials invalid
* - 500 Internal Server Error: An internal error occurred
*/
@POST
@Path("authentication")
public Response authenticateUser(@Valid UserCredentialsRepresentation userCredentials) {
if ((userCredentials != null) && userService.checkCredentials(userCredentials.getUsername(), userCredentials.getPassword())) {
return Response.ok().build();
}
return Response.status(Response.Status.UNAUTHORIZED).build();
}
/**
* Returns all users.
*
* Possible return codes:
* - 200 OK: Returning users
* - 500 Internal Server Error: An internal error occurred
*/
@GET
public List<UserRepresentation> getAllUsers() {
return userService.getAllUsers();
}
/**
* Returns the user with the given username.
*
* Possible return codes:
* - 200 OK: Returning user
* - 404 Not Found: User does not exist
* - 500 Internal Server Error: An internal error occurred
*/
@GET
@Path("{username}")
public Response getUserByUsername(@PathParam("username") String username) {
UserRepresentation user = userService.getUserByUsername(username);
return (user != null) ? Response.ok(user).build() : Response.status(Response.Status.NOT_FOUND).build();
}
/**
* Returns the user with the given username.
*
* Possible return codes:
* - 200 OK: Returning list of users
* - 400 Bad Request: Hair color does not exist
* - 500 Internal Server Error: An internal error occurred
*/
@GET
@Path("haircolor/{hairColor}")
public Response getUsersByHairColor(@PathParam("hairColor") String hairColor) {
try {
return Response.ok(userService.getUsersByHairColor(HairColor.valueOf(hairColor.toUpperCase()))).build();
} catch (IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST).entity("Unknown hair color. Valid hair colors: " + Arrays.asList(HairColor.values()).stream().map(HairColor::toString).collect(Collectors.joining(", "))).build();
}
}
}
| lgpl-3.0 |
Ubiquitous-Spice/Modjam-3 | src/main/java/com/github/ubiquitousspice/mobjam/network/PacketBase.java | 1778 | package com.github.ubiquitousspice.mobjam.network;
import com.github.ubiquitousspice.mobjam.Constants;
import com.github.ubiquitousspice.mobjam.MobJam;
import com.google.common.base.Throwables;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.world.World;
import java.io.IOException;
import java.util.logging.Level;
public abstract class PacketBase
{
public PacketBase()
{
}
public PacketBase(ByteArrayDataInput input) throws IOException
{
}
public Packet250CustomPayload getPacket250()
{
try
{
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeByte(getPacketId());
writeData(output);
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.channel = Constants.MODID;
packet.data = output.toByteArray();
packet.length = packet.data.length;
return packet;
}
catch (Exception e)
{
MobJam.logger
.log(Level.SEVERE, "Error building " + Constants.MODID + " packet! " + getClass().getSimpleName(),
e);
Throwables.propagate(e);
}
return null;
}
/**
* @return the packetID, had better be below 256
*/
public abstract int getPacketId();
/**
* The PacketID is already written
*/
public abstract void writeData(ByteArrayDataOutput data);
@SideOnly(Side.CLIENT)
public abstract void actionClient(WorldClient world, EntityPlayerMP player);
public abstract void actionServer(World world, EntityPlayerMP player);
}
| lgpl-3.0 |
hy2708/hy2708-repository | java/commons/commons-aop/src/test/java/jodd/proxetta/data/ReturnNullAdvice.java | 425 | // Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.
package jodd.proxetta.data;
import jodd.proxetta.ProxyAdvice;
import jodd.proxetta.ProxyTarget;
public class ReturnNullAdvice implements ProxyAdvice {
public Object execute() throws Exception {
Object returnValue = null;
if (returnValue != null) {
returnValue = "1";
}
return ProxyTarget.returnValue(returnValue);
}
}
| lgpl-3.0 |
racodond/sonar-css-plugin | css-frontend/src/main/java/org/sonar/css/visitors/metrics/package-info.java | 994 | /*
* SonarQube CSS / SCSS / Less Analyzer
* Copyright (C) 2013-2017 David RACODON
* mailto: david.racodon@gmail.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.
*/
@ParametersAreNonnullByDefault
package org.sonar.css.visitors.metrics;
import javax.annotation.ParametersAreNonnullByDefault;
| lgpl-3.0 |
svn2github/dynamicreports-jasper | dynamicreports-core/src/test/java/net/sf/dynamicreports/test/base/ConditionsTest.java | 6388 | /**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2015 Ricardo Mariaca
* http://www.dynamicreports.org
*
* This file is part of DynamicReports.
*
* DynamicReports 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.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.test.base;
import static net.sf.dynamicreports.report.builder.DynamicReports.*;
import java.sql.Connection;
import java.util.Locale;
import junit.framework.Assert;
import net.sf.dynamicreports.report.builder.FieldBuilder;
import net.sf.dynamicreports.report.definition.DRIScriptlet;
import net.sf.dynamicreports.report.definition.DRIValue;
import net.sf.dynamicreports.report.definition.ReportParameters;
import net.sf.dynamicreports.report.definition.expression.DRISimpleExpression;
import org.junit.Test;
/**
* @author Ricardo Mariaca (r.mariaca@dynamicreports.org)
*/
public class ConditionsTest {
@Test
public void test() {
//equal
FieldBuilder<Integer> value = field("name", Integer.class);
conditionTrue("equal", cnd.equal(value, 5, 10, 20));
conditionFalse("equal", cnd.equal(value, 5, 20));
//unequal
conditionFalse("unequal", cnd.unEqual(value, 5, 10, 20));
conditionTrue("unequal", cnd.unEqual(value, 5, 20));
//smaller
conditionFalse("smaller", cnd.smaller(value, 5));
conditionFalse("smaller", cnd.smaller(value, 10));
conditionTrue("smaller", cnd.smaller(value, 15));
//smallerOrEquals
conditionFalse("smallerOrEquals", cnd.smallerOrEquals(value, 5));
conditionTrue("smallerOrEquals", cnd.smallerOrEquals(value, 10));
conditionTrue("smallerOrEquals", cnd.smallerOrEquals(value, 15));
//greater
conditionTrue("greater", cnd.greater(value, 5));
conditionFalse("greater", cnd.greater(value, 10));
conditionFalse("greater", cnd.greater(value, 15));
//greaterOrEquals
conditionTrue("greaterOrEquals", cnd.greaterOrEquals(value, 5));
conditionTrue("greaterOrEquals", cnd.greaterOrEquals(value, 10));
conditionFalse("greaterOrEquals", cnd.greaterOrEquals(value, 15));
//between
conditionTrue("between", cnd.between(value, 5, 15));
conditionTrue("between", cnd.between(value, 5, 10));
conditionTrue("between", cnd.between(value, 10, 20));
conditionFalse("between", cnd.between(value, 5, 9));
conditionFalse("between", cnd.between(value, 11, 20));
//notBetween
conditionFalse("notBetween", cnd.notBetween(value, 5, 15));
conditionFalse("notBetween", cnd.notBetween(value, 5, 10));
conditionFalse("notBetween", cnd.notBetween(value, 10, 20));
conditionTrue("notBetween", cnd.notBetween(value, 5, 9));
conditionTrue("notBetween", cnd.notBetween(value, 11, 20));
//equal object
FieldBuilder<Object> value2 = field("name", Object.class);
conditionTrue("equal", cnd.equal(value2, Type.A, Type.C, Type.F), Type.C);
conditionFalse("equal", cnd.equal(value2, Type.B, Type.C), Type.E);
//unequal object
conditionFalse("unequal", cnd.unEqual(value2, Type.A, Type.C, Type.F), Type.C);
conditionTrue("unequal", cnd.unEqual(value2, Type.B, Type.C), Type.E);
}
private void conditionTrue(String name, DRISimpleExpression<Boolean> condition) {
Assert.assertTrue(name + " condition", condition.evaluate(new TestReportParameters(10)));
}
private void conditionFalse(String name, DRISimpleExpression<Boolean> condition) {
Assert.assertFalse(name + " condition", condition.evaluate(new TestReportParameters(10)));
}
private void conditionTrue(String name, DRISimpleExpression<Boolean> condition, Object actualValue) {
Assert.assertTrue(name + " condition", condition.evaluate(new TestReportParameters(actualValue)));
}
private void conditionFalse(String name, DRISimpleExpression<Boolean> condition, Object actualValue) {
Assert.assertFalse(name + " condition", condition.evaluate(new TestReportParameters(actualValue)));
}
private class TestReportParameters implements ReportParameters {
private Object value;
public TestReportParameters(Object value) {
this.value = value;
}
@Override
public Integer getColumnNumber() {
return null;
}
@Override
public Integer getColumnRowNumber() {
return null;
}
@Override
public Connection getConnection() {
return null;
}
@Override
public Integer getGroupCount(String groupName) {
return null;
}
@Override
public Locale getLocale() {
return null;
}
@Override
public String getMessage(String key) {
return null;
}
@Override
public String getMessage(String key, Object[] arguments) {
return null;
}
@Override
public Integer getPageNumber() {
return null;
}
@Override
public Integer getPageRowNumber() {
return null;
}
@Override
public Integer getReportRowNumber() {
return null;
}
@Override
public Integer getCrosstabRowNumber() {
return null;
}
@Override
public DRIScriptlet getScriptlet(String name) {
return null;
}
@Override
public <T> T getValue(String name) {
return null;
}
@Override
@SuppressWarnings("unchecked")
public <T> T getValue(DRIValue<T> value) {
return (T) this.value;
}
@Override
public ReportParameters getMasterParameters() {
return null;
}
@Override
public Integer getSubreportWidth() {
return null;
}
@Override
public <T> T getFieldValue(String name) {
return null;
}
@Override
public <T> T getVariableValue(String name) {
return null;
}
@Override
public <T> T getParameterValue(String name) {
return null;
}
}
private enum Type {
A,
B,
C,
D,
E,
F
}
}
| lgpl-3.0 |