code
stringlengths 73
34.1k
| label
stringclasses 1
value |
---|---|
public void closeWindowPerformed(SwingFrame frameView) {
if (!navigationFrames.contains(frameView)) return;
if (navigationFrames.size() == 1 && !askBeforeExit(frameView)) {
return;
}
if (frameView.tryToCloseWindow()) {
removeNavigationFrameView(frameView);
}
} | java |
private boolean askBeforeExit(SwingFrame navigationFrameView) {
if (Configuration.isDevModeActive()) {
return true;
} else {
int answer = JOptionPane.showConfirmDialog(navigationFrameView, Resources.getString("Exit.confirm"), Resources.getString("Exit.confirm.title"), JOptionPane.YES_NO_OPTION);
return answer == JOptionPane.YES_OPTION;
}
} | java |
private boolean closeAllWindows(SwingFrame navigationFrameView) {
// Die umgekehrte Reihenfolge fühlt sich beim Schliessen natürlicher an
for (int i = navigationFrames.size()-1; i>= 0; i--) {
SwingFrame frameView = navigationFrames.get(i);
if (!frameView.tryToCloseWindow()) return false;
removeNavigationFrameView(frameView);
}
return true;
} | java |
private void removeNavigationFrameView(SwingFrame frameView) {
navigationFrames.remove(frameView);
if (navigationFrames.size() == 0) {
System.exit(0);
}
} | java |
private synchronized void sleep(long waitNanos) throws InterruptedException {
while (waitNanos > 0 && isRunning()) {
long start = System.nanoTime();
TimeUnit.NANOSECONDS.timedWait(this, waitNanos);
waitNanos -= System.nanoTime() - start;
}
} | java |
private List<String> loadKeyList() {
Set<String> keySet = new HashSet<String>();
for (EDBObjectEntry entry : startState.values()) {
keySet.add(entry.getKey());
}
for (EDBObjectEntry entry : endState.values()) {
keySet.add(entry.getKey());
}
return new ArrayList<String>(keySet);
} | java |
public Set<OWLAxiom> getSameSourceAxioms(OWLAxiom axiom, Set<OWLAxiom> toSearch) {
Set<OWLAxiom> axiomSources = axiom2SourceMap.get(axiom);
if(axiomSources == null) {
return Collections.emptySet();
}
Set<OWLAxiom> result = new HashSet<OWLAxiom>();
for(OWLAxiom ax : toSearch) {
Set<OWLAxiom> sources = axiom2SourceMap.get(ax);
if(sources != null) {
for(OWLAxiom axiomSourceAxiom : axiomSources) {
if(sources.contains(axiomSourceAxiom)) {
result.add(ax);
break;
}
}
}
}
return result;
} | java |
private int[] tpCreate(int n) {
if (n > MAX_TPS) return null;
int[] ret = new int[n];
for (int i = 0; i < n; i++) ret[i] = tpCreate();
return ret;
} | java |
private void tpDelete(int[] IDtimePoint) {
logger.finest("Deleting " + IDtimePoint.length + " TP");
for (int i = 0; i < IDtimePoint.length; i++) {
tPoints[IDtimePoint[i]].setUsed(false);
if (IDtimePoint[i] == MAX_USED) MAX_USED--;
SimpleDistanceConstraint conO = new SimpleDistanceConstraint();
SimpleDistanceConstraint conH = new SimpleDistanceConstraint();
conO.setFrom(this.getVariable(0));
conO.setTo(this.getVariable(IDtimePoint[i]));
conH.setFrom(this.getVariable(IDtimePoint[i]));
conH.setTo(this.getVariable(1));
conO.setMinimum(0);
conO.setMaximum(H-O);
conH.setMinimum(0);
conH.setMaximum(H-O);
conO.addInterval(new Bounds(0,H-O));
conH.addInterval(new Bounds(0,H-O));
//[lb,ub] = [-di0,d0i]
tPoints[IDtimePoint[i]].setLowerBound(O);
tPoints[IDtimePoint[i]].setUpperBound(H);
tPoints[0].setOut(IDtimePoint[i],conO);
tPoints[IDtimePoint[i]].setOut(1,conH);
}
fromScratchDistanceMatrixComputation();
} | java |
private boolean cDelete(Bounds[] in, int[] from, int[] to, boolean canRestore) throws ConstraintNotFound, MalformedSimpleDistanceConstraint {
for (int i = 0; i < in.length; i++) {
//Conversion
long min = in[i].min;
long max = in[i].max;
if (in[i].max == Long.MAX_VALUE - 1) max = H-O;
if (in[i].min == Long.MIN_VALUE + 1) min = -1 * (H - O);
in[i] = new Bounds(min,max);
SimpleDistanceConstraint con = tPoints[from[i]].getOut(to[i]);
if (con == null) {
throw new ConstraintNotFound(String.format("Interval %s, from %d, to %d", in[i].toString(), from[i], to[i]));
}
if (con.getCounter() == 1) {
if (con.removeInterval(in[i])) tPoints[from[i]].setOut(to[i],null);
else throw new MalformedSimpleDistanceConstraint(con, 1);
}
else if (!con.removeInterval(in[i])) throw new MalformedSimpleDistanceConstraint(con, 2);
}
if (!canRestore) fromScratchDistanceMatrixComputation();
else {
logger.finest("QuickRestoring distance matrix, no propagation");
if (backupDMatrixSimple) restoreDMatrix();
}
for (int j = 0; j < MAX_USED+1; j++)
if (tPoints[j].isUsed() == true) {
tPoints[j].setLowerBound(sum(-distance[j][0],O));
tPoints[j].setUpperBound(sum(distance[0][j],O));
}
return true;
} | java |
public TimePoint getTimePoint(int Id) {
if (Id >= MAX_TPS) return null;
if (tPoints[Id] == null) return null;
if (!tPoints[Id].isUsed()) return null;
return tPoints[Id];
} | java |
private boolean fromScratchDistanceMatrixComputation() {
logger.fine("Propagating (cube) with (#TPs,#cons) = (" + this.MAX_USED + "," + this.theNetwork.getConstraints().length + ") (call num.: " + (++cubePropCount) + ")");
//*
//This code is not tested thoroughly but seems to work
for (int i = 0; i < MAX_USED+1; i++) {
for (int j = i; j < MAX_USED+1; j++) {
if (i != j) {
long dij = H;//APSPSolver.INF;
long dji = H;//APSPSolver.INF;
if(tPoints[i].getOut(j) != null) {
dij = Math.min(dij, +tPoints[i].getOut(j).getMaximum());
dji = Math.min(dji, -tPoints[i].getOut(j).getMinimum());
}
if(tPoints[j].getOut(i) != null) {
dij = Math.min(dij, -tPoints[j].getOut(i).getMinimum());
dji = Math.min(dji, +tPoints[j].getOut(i).getMaximum());
}
if(-dji > +dij) {
return false;
}
distance[i][j] = dij;
distance[j][i] = dji;
}
else distance[i][j] = 0;
}
}
for (int k = 0; k < MAX_USED+1; k++) {
if (tPoints[k].isUsed() == true) {
for (int i = 0; i < MAX_USED+1; i++) {
if (tPoints[i].isUsed() == true) {
for (int j = 0; j < MAX_USED+1; j++) {
if (tPoints[j].isUsed() == true) {
long temp = sum(distance[i][k],distance[k][j]);
if (distance[i][j] > temp)
distance[i][j] = temp;
}
if (i == j && distance[i][j] < 0) return false;
}
}
}
}
}
return true;
} | java |
private boolean incrementalDistanceMatrixComputation(int from,int to,Bounds i) {
logger.fine("Propagating (quad) with (#TPs,#cons) = (" + this.MAX_USED + "," + this.theNetwork.getConstraints().length + ") (call num.: " + (++quadPropCount) + ")");
if (distance[to][from] != APSPSolver.INF && sum(i.max,distance[to][from]) < 0) return false;
if (distance[from][to] != APSPSolver.INF && sum(-i.min,distance[from][to]) < 0) return false;
// System.out.println("a)" + sum(i.max,distance[to][from]));
// System.out.println("b)" + sum(-i.min,distance[from][to]));
long sum1;
long sum2;
long sum3;
long sum4;
long temp;
for (int u = 0; u < MAX_USED+1; u++) {
if (tPoints[u].isUsed()) {
for (int v = 0; v < MAX_USED+1;v++) {
if (tPoints[v].isUsed()) {
//min{distance[u][v];(distance[u][from]+i.max+distance[to][v]);(distance[u][to]-i.minl+distance[from][v])}
sum1 = sum(distance[u][to],-i.min);
sum2 = sum(sum1,distance[from][v]);
sum3 = sum(distance[u][from],i.max);
sum4 = sum(sum3,distance[to][v]);
temp = Math.min(sum2,sum4);
if (distance[u][v] > temp) {
//long oldD = distance[u][v];
distance[u][v] = temp;
if (u == v && distance[u][v] != 0) {
//logger.info("==================> Updated distance[" + u + "][" + v + "] from " + oldD + " to " + temp);
//throw new Error("Found negative cycle in incremental propagation while adding (from,to,i) (" + from + "," + to + "," + i + ")");
return false;
}
}
}
}
}
}
return true;
} | java |
public boolean changeHorizon(long val)
{
this.removeConstraint(horizonConstraint);
SimpleDistanceConstraint sdc = new SimpleDistanceConstraint();
sdc.setFrom(this.getVariable(0));
sdc.setTo(this.getVariable(1));
sdc.setMinimum(val);
sdc.setMaximum(val);
if (this.addConstraint(sdc)) {
this.H = val;
horizonConstraint = sdc;
return true;
}
return false;
} | java |
public FilterChain create() throws FilterConfigurationException {
Preconditions.checkState(filters != null, "list of filters must be set");
Preconditions.checkState(inputType != null, "inputType must be set");
Preconditions.checkState(outputType != null, "outputType must be set");
Preconditions.checkState(filters.size() > 0, "need at least one filter");
validateFiltersList();
Iterator<Object> iterator = filters.iterator();
FilterChainElement firstInstance = getInstanceFromListElement(iterator.next());
if (!firstInstance.getSupportedInputType().isAssignableFrom(inputType)
|| !firstInstance.getSupportedOutputType().isAssignableFrom(outputType)) {
throw new FilterConfigurationException(String.format(
"incompatible Filtertype (%s) should be (%s->%s) - is (%s->%s)",
firstInstance.getClass(), inputType, outputType, firstInstance.getSupportedInputType(),
firstInstance.getSupportedOutputType()));
}
FilterChainElement current = firstInstance;
while (iterator.hasNext()) {
Object next = iterator.next();
FilterChainElement nextFilterElement = getInstanceFromListElement(next);
if (nextFilterElement == null) {
current.setNext((FilterAction) next);
break;
}
current.setNext(nextFilterElement);
current = nextFilterElement;
}
return new FilterChain(firstInstance);
} | java |
public static String parseCH(String inputText, boolean partialAllowed) {
if (StringUtils.isEmpty(inputText)) return null;
String text = cutNonDigitsAtBegin(inputText);
if (StringUtils.isEmpty(text)) return "";
text = cutNonDigitsAtEnd(text);
if (StringUtils.isEmpty(text)) return "";
// Nun hat der String sicher keinen Punkt mehr am Anfang oder Ende
if (inputText.indexOf(".") > -1) {
return parseCHWithDot(inputText, partialAllowed);
} else {
return parseCHWithoutDot(inputText, partialAllowed);
}
} | java |
public static LocalDate parse(String date) {
if (StringUtils.isEmpty(date)) return null;
try {
return parse_(date);
} catch (DateTimeParseException x) {
return InvalidValues.createInvalidLocalDate(date);
}
} | java |
public static LocalDate parse_(String date) {
DateTimeFormatter dateTimeFormatter = getDateTimeFormatter();
if (germanDateStyle()) {
date = parseCH(date, false);
return LocalDate.parse(date);
} else {
return LocalDate.parse(date, dateTimeFormatter);
}
} | java |
public void addMenuItem(String index, Class<? extends WebPage> linkClass, String langKey, String langDescKey,
String... authority) {
addMenuItem(index, linkClass, langKey, langDescKey, null, authority);
} | java |
public static <T> T read(Class<T> clazz, Object id) {
return execute(new ReadEntityTransaction<T>(clazz, id));
} | java |
public void listRunningServices() {
try {
final List<String> formatedOutput =
SecurityContext.executeWithSystemPermissions(new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
List<String> tmp = new ArrayList<String>();
List<ServiceReference<Domain>> listServiceReferences =
osgiUtilsService.listServiceReferences(Domain.class);
for (ServiceReference<Domain> ref : listServiceReferences) {
Domain service = bundleContext.getService(ref);
tmp.add(OutputStreamFormater.formatValues(
ref.getProperty(org.osgi.framework.Constants.SERVICE_PID).toString(), service
.getAliveState().toString()));
}
return tmp;
}
});
for (String s : formatedOutput) {
OutputStreamFormater.printValue(s);
}
} catch (ExecutionException ex) {
ex.printStackTrace();
System.err.println("Could not get services");
}
} | java |
public void deleteService(String id, boolean force) {
try {
if (id == null || id.isEmpty()) {
id = selectRunningService();
}
final String idFinal = id;
int input = 'Y';
if (!force) {
OutputStreamFormater.printValue(String.format(
"Do you really want to delete the connector: %s (Y/n): ", id));
input = keyboard.read();
}
if ('n' != (char) input && 'N' != (char) input) {
SecurityContext.executeWithSystemPermissions(new Callable<Object>() {
@Override
public Object call() throws Exception {
serviceManager.delete(idFinal);
return null;
}
});
OutputStreamFormater.printValue(String.format("Service: %s successfully deleted", id));
}
} catch (ExecutionException e) {
e.printStackTrace();
System.err.println("Could not delete service");
} catch (IOException e) {
e.printStackTrace();
System.err.println("Unexpected Error");
}
} | java |
private String selectRunningService() {
String selectedServiceId;
List<String> runningServiceIds = getRunningServiceIds();
for (int i = 0; i < runningServiceIds.size(); i++) {
String serviceId = runningServiceIds.get(i);
OutputStreamFormater.printTabbedValues(9, String.format("[%s]", i), String.format("%s", serviceId));
}
String s = readUserInput();
int pos;
try {
pos = Integer.parseInt(s);
selectedServiceId = runningServiceIds.get(pos);
} catch (Exception e) {
throw new IllegalArgumentException(String.format("Invalid Input: %s", s));
}
return selectedServiceId;
} | java |
public List<String> getRunningServiceIds() {
List<ServiceReference<Domain>> serviceReferences = osgiUtilsService.listServiceReferences(Domain.class);
List<String> result = new ArrayList<String>();
for (ServiceReference<Domain> ref : serviceReferences) {
result.add((String) ref.getProperty(org.osgi.framework.Constants.SERVICE_PID));
}
return result;
} | java |
public void createService(String domainProviderName, boolean force, Map<String, String> attributes) {
// check if a domain has been chosen
if (domainProviderName == null || domainProviderName.isEmpty()) {
domainProviderName = selectDomainProvider();
}
// get domain provider Id
String domainProviderId = "";
List<DomainProvider> domainProvider = getDomainProvider();
for (DomainProvider provider : domainProvider) {
if (provider.getName().getString(Locale.getDefault()).equals(domainProviderName)) {
domainProviderId = provider.getId();
}
}
// get the connector which should be created
ConnectorProvider connectorProvider =
getConnectorToCreate(domainProviderId, attributes.get(ServiceCommands.CONNECTOR_TYPE));
String id;
if (attributes.isEmpty() || !attributes.containsKey(org.osgi.framework.Constants.SERVICE_PID)) {
OutputStreamFormater.printValue("Please enter an ID");
id = readUserInput();
} else {
id = attributes.get(org.osgi.framework.Constants.SERVICE_PID);
}
ServiceDescriptor descriptor = connectorProvider.getDescriptor();
OutputStreamFormater.printValue(String.format("Please enter the attributes for %s, keep empty for default",
descriptor.getName().getString(Locale.getDefault())));
// get attributes for connector
Map<String, String> attributeMap = getConnectorAttributes(descriptor.getAttributes(), attributes);
Map<String, Object> properties = new HashMap<String, Object>();
ConnectorDescription connectorDescription =
new ConnectorDescription(domainProviderId, connectorProvider.getId(), attributeMap, properties);
if (force) {
if (id != null && !id.isEmpty()) {
serviceManager.forceCreateWithId(id, connectorDescription);
} else {
serviceManager.forceCreate(connectorDescription);
}
OutputStreamFormater.printValue("Connector successfully created");
} else {
OutputStreamFormater.printValue("Do you want to create the connector with the following attributes:", "");
OutputStreamFormater.printValue("Connector ID", id);
for (String key : attributeMap.keySet()) {
OutputStreamFormater.printValue(key, attributeMap.get(key));
}
OutputStreamFormater.printValue("Create connector: (Y/n)");
if (!readUserInput().equalsIgnoreCase("n")) {
try {
if (id != null && !id.isEmpty()) {
serviceManager.createWithId(id, connectorDescription);
} else {
serviceManager.create(connectorDescription);
}
OutputStreamFormater.printValue("Connector successfully created");
} catch (RuntimeException e) {
e.printStackTrace();
OutputStreamFormater.printValue("Connector validation failed, creation aborted");
}
} else {
OutputStreamFormater.printValue("Creation aborted");
}
}
} | java |
public static List<Entry> globalPermissionSetStructure(String permissionSet) {
Entry permissionSetEntry = namedObject(permissionSet, SchemaConstants.ouGlobalPermissionSets());
Entry ouDirect = organizationalUnit("direct", permissionSetEntry.getDn());
Entry ouChildrenSets = organizationalUnit("childrenSets", permissionSetEntry.getDn());
Entry ouAttributes = organizationalUnit("attributes", permissionSetEntry.getDn());
return Arrays.asList(permissionSetEntry, ouAttributes, ouDirect, ouChildrenSets);
} | java |
protected void removeUnmappedFields(JdbcIndex<?> index) {
Iterator<IndexField<?>> iterator = index.getFields().iterator();
while (iterator.hasNext()) {
IndexField<?> field = iterator.next();
if (field.getMappedType() == null) {
LOG.info("Removing {} from index {} - no mapped type information", field.getName(), index.getName());
iterator.remove();
}
}
} | java |
public static Model loadPOM(String pomPath, String localRepo, Collection<RemoteRepository> repositories) throws ProjectException {
RepositoryClient repoClient = new RepositoryClient(localRepo);
NaetherModelResolver resolver = new NaetherModelResolver(repoClient, repositories);
ModelBuildingRequest req = new DefaultModelBuildingRequest();
req.setProcessPlugins( false );
req.setPomFile( new File(pomPath) );
req.setModelResolver( resolver );
req.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
DefaultModelBuilder builder = (new DefaultModelBuilderFactory()).newInstance();
try {
return builder.build( req ).getEffectiveModel();
} catch ( ModelBuildingException e ) {
throw new ProjectException("Failed to build project from pom", e);
}
} | java |
public String getVersion() {
String version = getMavenModel().getVersion();
if ( version == null && getMavenModel().getParent() != null ) {
version = getMavenModel().getParent().getVersion();
}
return version;
} | java |
public void addRepository(String url) throws ProjectException {
List<Repository> repositories = getRepositories();
if ( repositories == null ) {
repositories = new ArrayList<Repository>();
}
try {
Repository repository = RepoBuilder.repositoryFromUrl( url );
repositories.add( repository );
} catch (MalformedURLException e) {
throw new ProjectException( e );
}
getMavenModel().setRepositories( repositories );
} | java |
public List<String> getRepositoryUrls() {
List<String> urls = new ArrayList<String>();
for ( Repository repo : getRepositories() ) {
urls.add( repo.getUrl() );
}
return urls;
} | java |
public void setProjectNotation(String notation) {
Map<String, String> notationMap = Notation.parse(notation);
this.setGroupId(notationMap.get("groupId"));
this.setArtifactId(notationMap.get("artifactId"));
this.setType(notationMap.get("type"));
this.setVersion(notationMap.get("version"));
} | java |
public void addDependency(String notation, String scope ) {
Map<String, String> notationMap = Notation.parse(notation);
Dependency dependency = new Dependency();
dependency.setGroupId(notationMap.get("groupId"));
dependency.setArtifactId(notationMap.get("artifactId"));
dependency.setType(notationMap.get("type"));
dependency.setVersion(notationMap.get("version"));
dependency.setScope( scope );
addDependency(dependency);
} | java |
public String toXml() throws ProjectException {
log.debug("Writing xml");
Project copy = this;
copy.removeProperty( "project.basedir" );
StringWriter writer = new StringWriter();
MavenXpp3Writer pomWriter = new MavenXpp3Writer();
try {
pomWriter.write(writer, copy.mavenModel);
} catch (IOException e) {
throw new ProjectException("Failed to create pom xml", e);
}
writer.flush();
return writer.toString();
} | java |
public static void logReducedStackTrace(Logger logger, Exception exception) {
Exception here = new Exception();
String[] hereStrings = getStackFrames(here);
String[] throwableStrings = getStackFrames(exception);
int linesToSkip = 1;
while (throwableStrings.length - linesToSkip > 0 && hereStrings.length - linesToSkip > 0) {
if (!StringUtils.equals(hereStrings[hereStrings.length-linesToSkip], throwableStrings[throwableStrings.length-linesToSkip])) {
break;
}
linesToSkip++;
}
for (int i = 0; i<=throwableStrings.length-linesToSkip; i++) {
logger.log(Level.SEVERE, throwableStrings[i]);
}
} | java |
private static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
} | java |
public static DataSource getDataSource(final String jndiName)
throws FactoryException {
Validate.notBlank(jndiName, "The validated character sequence 'jndiName' is null or empty");
// no need for defensive copies of Strings
try {
// the initial context is created from the provided JNDI settings
final Context context = new InitialContext();
// retrieve a data source object, close the context as it is no longer needed, and return the data source
final Object namedObject = context.lookup(jndiName);
if (DataSource.class.isInstance(namedObject)) {
final DataSource dataSource = (DataSource) context.lookup(jndiName);
context.close();
return dataSource;
} else {
final String error = "The JNDI name '" + jndiName + "' does not reference a SQL DataSource."
+ " This is a configuration issue.";
LOG.warn(error);
throw new FactoryException(error);
}
} catch (NamingException e) {
final String error = "Error retrieving JDBC date source from JNDI: " + jndiName;
LOG.warn(error);
throw new FactoryException(error, e);
}
} | java |
private static void loadDriver(final String driver) throws FactoryException {
// assert in private method
assert driver != null : "The driver cannot be null";
LOG.debug("Loading the database driver '" + driver + "'");
// make sure the driver is available
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
final String error = "Error loading JDBC driver class: " + driver;
LOG.warn(error, e);
throw new FactoryException(error, e);
}
} | java |
private static PoolingDataSource<PoolableConnection> getPoolingDataSource(final String url,
final ConcurrentMap<String, String> properties,
final ConnectionProperties poolSpec) {
// assert in private method
assert url != null : "The url cannot be null";
assert properties != null : "The properties cannot be null";
assert poolSpec != null : "The pol spec cannot be null";
LOG.debug("Creating new pooled data source for '" + url + "'");
// convert the properties hashmap to java properties
final Properties props = new Properties();
props.putAll(properties);
// create a Apache DBCP pool configuration from the pool spec
final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(poolSpec.getMaxTotal());
poolConfig.setMaxIdle(poolSpec.getMaxIdle());
poolConfig.setMinIdle(poolSpec.getMinIdle());
poolConfig.setMaxWaitMillis(poolSpec.getMaxWaitMillis());
poolConfig.setTestOnCreate(poolSpec.isTestOnCreate());
poolConfig.setTestOnBorrow(poolSpec.isTestOnBorrow());
poolConfig.setTestOnReturn(poolSpec.isTestOnReturn());
poolConfig.setTestWhileIdle(poolSpec.isTestWhileIdle());
poolConfig.setTimeBetweenEvictionRunsMillis(poolSpec.getTimeBetweenEvictionRunsMillis());
poolConfig.setNumTestsPerEvictionRun(poolSpec.getNumTestsPerEvictionRun());
poolConfig.setMinEvictableIdleTimeMillis(poolSpec.getMinEvictableIdleTimeMillis());
poolConfig.setSoftMinEvictableIdleTimeMillis(poolSpec.getSoftMinEvictableIdleTimeMillis());
poolConfig.setLifo(poolSpec.isLifo());
// create the pool and assign the factory to the pool
final org.apache.commons.dbcp2.ConnectionFactory connFactory = new DriverManagerConnectionFactory(url, props);
final PoolableConnectionFactory poolConnFactory = new PoolableConnectionFactory(connFactory, null);
poolConnFactory.setDefaultAutoCommit(poolSpec.isDefaultAutoCommit());
poolConnFactory.setDefaultReadOnly(poolSpec.isDefaultReadOnly());
poolConnFactory.setDefaultTransactionIsolation(poolSpec.getDefaultTransactionIsolation());
poolConnFactory.setCacheState(poolSpec.isCacheState());
poolConnFactory.setValidationQuery(poolSpec.getValidationQuery());
poolConnFactory.setMaxConnLifetimeMillis(poolSpec.getMaxConnLifetimeMillis());
final GenericObjectPool<PoolableConnection> connPool = new GenericObjectPool<>(poolConnFactory, poolConfig);
poolConnFactory.setPool(connPool);
// create a new pooled data source
return new PoolingDataSource<>(connPool);
} | java |
public static List<String> getLocalPaths( String localRepoPath, List<String> notations ) throws NaetherException {
DefaultServiceLocator locator = new DefaultServiceLocator();
SimpleLocalRepositoryManagerFactory factory = new SimpleLocalRepositoryManagerFactory();
factory.initService( locator );
LocalRepository localRepo = new LocalRepository(localRepoPath);
LocalRepositoryManager manager = null;
try {
manager = factory.newInstance( localRepo );
} catch (NoLocalRepositoryManagerException e) {
throw new NaetherException( "Failed to initial local repository manage", e );
}
List<String> localPaths = new ArrayList<String>();
for ( String notation : notations ) {
Dependency dependency = new Dependency(new DefaultArtifact(notation), "compile");
File path = new File( localRepo.getBasedir(), manager.getPathForLocalArtifact( dependency.getArtifact() ) );
localPaths.add( path.toString() );
}
return localPaths;
} | java |
public Iterator iterator()
{
Query readAll = m_em.createQuery(
createReadAllQuery(m_entityClass.getSimpleName()));
return new JpaIterator(readAll, m_batchSize);
} | java |
public void addProperty(String key, Object value) throws ProcessBagException {
if (properties.containsKey(key)) {
throw new ProcessBagException(key + " already used!");
} else {
properties.put(key, value);
}
} | java |
@Override
public int compareTo(Object arg0) {
if (arg0 instanceof SimpleInterval) {
SimpleInterval that = (SimpleInterval)arg0;
return intervalName.compareTo(that.getIntervalName());
}
return 0;
} | java |
public static void initApplication(String... args) {
if (args.length < 1) {
System.err.println("Please specify an Application as argument");
System.exit(-1);
}
setInstance(createApplicationByClassName(args[0]));
} | java |
public int[] next() {
if (!hasNext) return null;
int[] result = new int[r];
for (int i=0; i<r; i++) result[i] = index[i];
moveIndex();
return result;
} | java |
private void reverseAfter(int i) {
int start = i+1;
int end = n-1;
while (start < end) {
swap(index,start,end);
start++;
end--;
}
} | java |
private int rightmostDip() {
for (int i=n-2; i>=0; i--)
if (index[i] < index[i+1])
return i;
return -1;
} | java |
public HashMap<Type, Double> getInversePossibilities() {
HashMap<Type, Double> ret = new HashMap<Type, Double>();
for (Type t : Type.values()) ret.put(t, 0.0);
for (Type t : types) {
//??? IS THIS CORRECT ??? --> Seems correct
//get inverse of each relation that is 1.0
Type inverseRelation = FuzzyAllenIntervalConstraint.getInverseRelation(t);
HashMap<FuzzyAllenIntervalConstraint.Type, Double> possibilities = this.getPossibilities();
//set poss of each inverse relation to 1.0
ret.put(inverseRelation, possibilities.get(t));
//calculate the Freksa N of each inverse relation
HashMap<FuzzyAllenIntervalConstraint.Type, Double> fr = new HashMap<FuzzyAllenIntervalConstraint.Type, Double>();
for(int i = 0; i < FuzzyAllenIntervalConstraint.freksa_neighbor[inverseRelation.ordinal()].length; i++)
fr.put(FuzzyAllenIntervalConstraint.lookupTypeByInt(i), FuzzyAllenIntervalConstraint.getPossibilityDegree(FuzzyAllenIntervalConstraint.freksa_neighbor[inverseRelation.ordinal()][i]));
//take the maximum between calculated Freksa N and previously added possibilities
//(because this is an OR)
for(FuzzyAllenIntervalConstraint.Type t1: fr.keySet())
ret.put(t1, Math.max(ret.get(t1), fr.get(t1)));
}
/*
System.out.println("=====================================");
System.out.println("DIRECT " + this + ":\n" + this.possibilities);
System.out.println("INVERSE:\n" + ret);
System.out.println("=====================================");
*/
return ret;
} | java |
public void addStep(String operationName, List<String> sourceFields, String targetField,
Map<String, String> parameters) {
TransformationStep step = new TransformationStep();
step.setOperationName(operationName);
step.setSourceFields(sourceFields.toArray(new String[sourceFields.size()]));
step.setTargetField(targetField);
step.setOperationParams(parameters);
steps.add(step);
} | java |
public void forwardField(String sourceField, String targetField) {
TransformationStep step = new TransformationStep();
step.setTargetField(targetField);
step.setSourceFields(sourceField);
step.setOperationName("forward");
steps.add(step);
} | java |
public void concatField(String targetField, String concatString, String... sourceFields) {
TransformationStep step = new TransformationStep();
step.setTargetField(targetField);
step.setSourceFields(sourceFields);
step.setOperationParameter(TransformationConstants.CONCAT_PARAM, concatString);
step.setOperationName("concat");
steps.add(step);
} | java |
public void splitField(String sourceField, String targetField, String splitString, String index) {
TransformationStep step = new TransformationStep();
step.setTargetField(targetField);
step.setSourceFields(sourceField);
step.setOperationParameter(TransformationConstants.SPLIT_PARAM, splitString);
step.setOperationParameter(TransformationConstants.INDEX_PARAM, index);
step.setOperationName("split");
steps.add(step);
} | java |
public void splitRegexField(String sourceField, String targetField, String regexString, String index) {
TransformationStep step = new TransformationStep();
step.setTargetField(targetField);
step.setSourceFields(sourceField);
step.setOperationParameter(TransformationConstants.REGEX_PARAM, regexString);
step.setOperationParameter(TransformationConstants.INDEX_PARAM, index);
step.setOperationName("splitRegex");
steps.add(step);
} | java |
public void substringField(String sourceField, String targetField, String from, String to) {
TransformationStep step = new TransformationStep();
step.setTargetField(targetField);
step.setSourceFields(sourceField);
step.setOperationParameter(TransformationConstants.SUBSTRING_FROM_PARAM, from);
step.setOperationParameter(TransformationConstants.SUBSTRING_TO_PARAM, to);
step.setOperationName("substring");
steps.add(step);
} | java |
public void valueField(String targetField, String value) {
TransformationStep step = new TransformationStep();
step.setTargetField(targetField);
step.setOperationParameter(TransformationConstants.VALUE_PARAM, value);
step.setOperationName("value");
steps.add(step);
} | java |
public void replaceField(String sourceField, String targetField, String oldString, String newString) {
TransformationStep step = new TransformationStep();
step.setSourceFields(sourceField);
step.setTargetField(targetField);
step.setOperationParameter(TransformationConstants.REPLACE_OLD_PARAM, oldString);
step.setOperationParameter(TransformationConstants.REPLACE_NEW_PARAM, newString);
step.setOperationName("replace");
steps.add(step);
} | java |
public void padField(String sourceField, String targetField, String length, String character, String direction) {
TransformationStep step = new TransformationStep();
step.setSourceFields(sourceField);
step.setTargetField(targetField);
step.setOperationParameter(TransformationConstants.PAD_LENGTH_PARAM, length);
step.setOperationParameter(TransformationConstants.PAD_CHARACTER_PARAM, character);
step.setOperationParameter(TransformationConstants.PAD_DIRECTION_PARAM, direction);
step.setOperationName("pad");
steps.add(step);
} | java |
public void removeLeadingField(String sourceField, String targetField, String regexString, String length) {
TransformationStep step = new TransformationStep();
step.setSourceFields(sourceField);
step.setTargetField(targetField);
step.setOperationParameter(TransformationConstants.REMOVELEADING_LENGTH_PARAM, length);
step.setOperationParameter(TransformationConstants.REGEX_PARAM, regexString);
step.setOperationName("removeleading");
steps.add(step);
} | java |
public void instantiateField(String targetField, String targetType, String targetTypeInit, String... sourceFields) {
TransformationStep step = new TransformationStep();
step.setSourceFields(sourceFields);
step.setTargetField(targetField);
step.setOperationParameter(TransformationConstants.INSTANTIATE_TARGETTYPE_PARAM, targetType);
if (targetTypeInit != null) {
step.setOperationParameter(TransformationConstants.INSTANTIATE_INITMETHOD_PARAM, targetTypeInit);
}
step.setOperationName("instantiate");
steps.add(step);
} | java |
@SuppressWarnings({ "unchecked" })
private Predicate convertParametersToPredicate(Root<?> from, CriteriaQuery<?> query) {
List<Predicate> predicates = new ArrayList<>();
for (Map.Entry<String, Set<Object>> value : request.getParameters().entrySet()) {
Subquery<JPAEntry> subquery = buildJPAEntrySubquery(value.getKey(), value.getValue(), from, query);
predicates.add(builder.exists(subquery));
}
if (request.isAndJoined()) {
return builder.and(Iterables.toArray(predicates, Predicate.class));
} else {
return builder.or(Iterables.toArray(predicates, Predicate.class));
}
} | java |
protected void set(PofValue target, Object value) {
navigator.navigate(target).setValue(value);
} | java |
public Map<String, T> getNodes() {
return Maps.transformValues(Collections.unmodifiableMap(_nodes), input -> (input != null) ? input.orElse(null) : null);
} | java |
private synchronized void loadExistingData() {
for (ChildData childData : _pathCache.getCurrentData()) {
addNode(childData.getPath(), parseChildData(childData));
}
} | java |
private EKBCommit convertEDBCommitToEKBCommit(EDBCommit commit) throws EKBException {
EKBCommit result = new EKBCommit();
Map<ModelDescription, Class<?>> cache = new HashMap<>();
result.setRevisionNumber(commit.getRevisionNumber());
result.setComment(commit.getComment());
result.setParentRevisionNumber(commit.getParentRevisionNumber());
result.setDomainId(commit.getDomainId());
result.setConnectorId(commit.getConnectorId());
result.setInstanceId(commit.getInstanceId());
for (EDBObject insert : commit.getInserts()) {
result.addInsert(createModelOfEDBObject(insert, cache));
}
for (EDBObject update : commit.getUpdates()) {
result.addUpdate(createModelOfEDBObject(update, cache));
}
for (String delete : commit.getDeletions()) {
EDBObject object = edbService.getObject(delete, commit.getTimestamp());
result.addDelete(createModelOfEDBObject(object, cache));
}
return result;
} | java |
private Object createModelOfEDBObject(EDBObject object, Map<ModelDescription, Class<?>> cache) {
try {
ModelDescription description = getDescriptionFromObject(object);
Class<?> modelClass;
if (cache.containsKey(description)) {
modelClass = cache.get(description);
} else {
modelClass = modelRegistry.loadModel(description);
cache.put(description, modelClass);
}
return edbConverter.convertEDBObjectToModel(modelClass, object);
} catch (IllegalArgumentException | ClassNotFoundException e) {
LOGGER.warn("Unable to create model of the object {}", object.getOID(), e);
return null;
}
} | java |
private ModelDescription getDescriptionFromObject(EDBObject obj) {
String modelName = obj.getString(EDBConstants.MODEL_TYPE);
String modelVersion = obj.getString(EDBConstants.MODEL_TYPE_VERSION);
if (modelName == null || modelVersion == null) {
throw new IllegalArgumentException("The object " + obj.getOID() + " contains no model information");
}
return new ModelDescription(modelName, modelVersion);
} | java |
private void init(String cacheName, NamedCache cache,
IdGenerator idGenerator,
IdExtractor idExtractor) {
m_cacheName = cacheName;
m_cache = cache;
m_idGenerator = idGenerator;
m_idExtractor = idExtractor;
} | java |
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Two arguments needed as username and password");
System.exit(-1);
}
User user = new User();
user.name = args[0];
user.password.setPassword(args[1].toCharArray());
for (int i = 2; i<args.length; i++) {
user.roles.add(new UserRole(args[i].trim()));
}
System.out.println(user.format());
} | java |
public static List<TransformationDescription> getDescriptionsFromXMLInputStream(InputStream fileContent) {
List<TransformationDescription> desc = new ArrayList<TransformationDescription>();
try {
desc = loadDescrtipionsFromXMLInputSource(new InputSource(fileContent), null);
} catch (Exception e) {
LOGGER.error("Unable to read the descriptions from input stream. ", e);
}
return desc;
} | java |
public static List<TransformationDescription> getDescriptionsFromXMLFile(File file) {
List<TransformationDescription> desc = new ArrayList<TransformationDescription>();
try {
return loadDescrtipionsFromXMLInputSource(new InputSource(file.getAbsolutePath()), file.getName());
} catch (Exception e) {
LOGGER.error("Unable to read the descriptions from file " + file.getAbsolutePath(), e);
}
return desc;
} | java |
private static List<TransformationDescription> loadDescrtipionsFromXMLInputSource(InputSource source,
String fileName) throws Exception {
XMLReader xr = XMLReaderFactory.createXMLReader();
TransformationDescriptionXMLReader reader = new TransformationDescriptionXMLReader(fileName);
xr.setContentHandler(reader);
xr.parse(source);
return reader.getResult();
} | java |
protected static List<PropertyDescriptor> getWriteableProperties(Class cls)
{
BeanWrapper beanWrapper = new BeanWrapperImpl(cls);
List<PropertyDescriptor> writeableProperties =
new ArrayList<PropertyDescriptor>();
PropertyDescriptor[] props = beanWrapper.getPropertyDescriptors();
for (PropertyDescriptor prop : props)
{
if (isWriteable(prop))
{
writeableProperties.add(prop);
}
}
return writeableProperties;
} | java |
@Transactional(readOnly = true)
public Object load(Object key) {
List<T> results = getJdbcTemplate().query(
getSelectSql(), getRowMapper(), getPrimaryKeyComponents(key));
return results.size() == 0 ? null : results.get(0);
} | java |
public void store(Object key, Object value) {
getJdbcTemplate().update(getMergeSql(),
new BeanPropertySqlParameterSource(value));
} | java |
String tableToString(Table table)
{
StringBuilder strb = new StringBuilder();
for(int row = 0; row < table.getRowCount(); row++)
{
for(int col = 0; col < table.getColumnCount(); col++)
{
strb.append(table.get(row, col));
strb.append(" ");
}
strb.append("\n");
}
return strb.toString();
} | java |
public static ModelWrapper wrap(Object model) {
if (!(isModel(model.getClass()))) {
throw new IllegalArgumentException("The given object is no model");
}
return new ModelWrapper((OpenEngSBModel) model);
} | java |
public ModelDescription getModelDescription() {
String modelName = retrieveModelName();
String modelVersion = retrieveModelVersion();
if (modelName == null || modelVersion == null) {
throw new IllegalArgumentException("Unsufficient information to create model description.");
}
return new ModelDescription(modelName, modelVersion);
} | java |
protected String appendContextId(Object modelId) {
return String.format("%s/%s", ContextHolder.get().getCurrentContextId(), modelId);
} | java |
@Override
public int compareTo(Object arg0) {
Interval that = (Interval)arg0;
return this.bounds.compareTo(that.getBounds());
} | java |
public List<Role> findAllRoles() {
List<Role> list = new ArrayList<>();
List<String> roleStrings;
try {
roleStrings = readLines(rolesFile);
} catch (IOException e) {
throw new FileBasedRuntimeException(e);
}
for (String roleString : roleStrings) {
if (StringUtils.isNotBlank(roleString)) {
String[] substrings =
StringUtils.splitByWholeSeparator(roleString, Configuration.get().getAssociationSeparator());
if (substrings.length < 1 || StringUtils.isBlank(substrings[0])) {
continue;
}
Role role = new Role(substrings[0]);
if (substrings.length > 1) {
role.setRoles(Arrays.asList(StringUtils.splitByWholeSeparator(substrings[1], Configuration.get()
.getValueSeparator())));
}
list.add(role);
}
}
return list;
} | java |
public static RepeatingView createFieldList(String id, Class<?> bean, Map<String, String> values) {
List<AttributeDefinition> attributes = MethodUtil.buildAttributesList(bean);
return createFieldList(id, attributes, values);
} | java |
public static RepeatingView createFieldList(String id, List<AttributeDefinition> attributes,
Map<String, String> values) {
RepeatingView fields = new RepeatingView(id);
for (AttributeDefinition a : attributes) {
WebMarkupContainer row = new WebMarkupContainer(a.getId());
MapModel<String, String> model = new MapModel<String, String>(values, a.getId());
row.add(createEditorField("row", model, a));
fields.add(row);
}
return fields;
} | java |
public Map<String, Set<String>> getPropertyConnections(TransformationDescription description) {
Map<String, Set<String>> propertyMap = getSourceProperties(description.getSourceModel());
fillPropertyMap(propertyMap, description);
resolveTemporaryProperties(propertyMap);
deleteTemporaryProperties(propertyMap);
return propertyMap;
} | java |
private Map<String, Set<String>> getSourceProperties(ModelDescription description) {
Map<String, Set<String>> result = new LinkedHashMap<String, Set<String>>();
try {
Class<?> sourceModel = registry.loadModel(description);
while (sourceModel != null && !sourceModel.equals(Object.class)) {
for (Field field : sourceModel.getDeclaredFields()) {
result.put(field.getName(), new HashSet<String>());
}
sourceModel = sourceModel.getSuperclass();
}
} catch (ClassNotFoundException e) {
LOGGER.error("Unable to load model {}", description);
return result;
}
return result;
} | java |
private void fillPropertyMap(Map<String, Set<String>> map, TransformationDescription description) {
for (TransformationStep step : description.getTransformingSteps()) {
if (step.getSourceFields() == null) {
LOGGER.debug("Step {} is ignored since no source properties are defined");
continue;
}
String targetField = step.getTargetField();
if (!map.containsKey(targetField) && isTemporaryProperty(targetField)) {
LOGGER.debug("Add new property entry for field {}", targetField);
map.put(targetField, new HashSet<String>());
}
for (String sourceField : step.getSourceFields()) {
if (sourceField == null) {
continue;
}
String[] result = StringUtils.split(sourceField, ".");
String mapValue = result[0];
Set<String> targets = map.get(mapValue);
if (targets != null) {
targets.add(targetField);
} else {
LOGGER.error("Accessed property with the name {} which isn't existing", mapValue);
}
}
}
} | java |
private void resolveTemporaryProperties(Map<String, Set<String>> map) {
boolean temporaryPresent = false;
do {
temporaryPresent = false;
for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
Set<String> newProperties = new HashSet<String>();
Iterator<String> properties = entry.getValue().iterator();
while (properties.hasNext()) {
String property = properties.next();
if (isTemporaryProperty(property)) {
LOGGER.debug("Resolve temporary field {} for property {}", entry.getKey(), property);
temporaryPresent = true;
newProperties.addAll(map.get(property));
properties.remove();
}
}
entry.getValue().addAll(newProperties);
}
} while (temporaryPresent);
} | java |
private void deleteTemporaryProperties(Map<String, Set<String>> map) {
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
if (isTemporaryProperty(key)) {
LOGGER.debug("Delete temporary field {} from the connection result", key);
iterator.remove();
}
}
} | java |
public static boolean loginAtStart() {
boolean loginAtStart = Application.getInstance().isLoginRequired() || Configuration.get("MjLoginAtStart", "false").equals("true");
if (loginAtStart && !Backend.getInstance().isAuthenticationActive()) {
throw new IllegalStateException("Login required but authorization is not configured!");
}
return loginAtStart;
} | java |
public Optional<Input<String>> createInput(int maxLength, InputType inputType, InputComponentListener changeListener) {
return Optional.empty();
} | java |
public void clear() {
List<AbstractTable<?>> tableList = new ArrayList<AbstractTable<?>>(tables.values());
for (AbstractTable<?> table : tableList) {
table.clear();
}
} | java |
@SuppressWarnings("unchecked")
public <T> T getObject(String key, Class<T> clazz) {
EDBObjectEntry entry = get(key);
return entry == null ? null : (T) entry.getValue();
} | java |
public final Boolean isDeleted() {
Boolean deleted = getObject(DELETED_CONST, Boolean.class);
return deleted != null ? deleted : false;
} | java |
public void putEDBObjectEntry(String key, Object value) {
putEDBObjectEntry(key, value, value.getClass());
} | java |
private void appendEntry(Map.Entry<String, EDBObjectEntry> entry, StringBuilder builder) {
if (builder.length() > 2) {
builder.append(",");
}
builder.append(" \"").append(entry.getKey()).append("\"");
builder.append(" : ").append(entry.getValue());
} | java |
public static EDBObjectEntry convertJPAEntryToEDBObjectEntry(JPAEntry entry) {
for (EDBConverterStep step : steps) {
if (step.doesStepFit(entry.getType())) {
LOGGER.debug("EDBConverterStep {} fit for type {}", step.getClass().getName(), entry.getType());
return step.convertToEDBObjectEntry(entry);
}
}
LOGGER.error("No EDBConverterStep fit for JPAEntry {}", entry);
return null;
} | java |
public static JPAEntry convertEDBObjectEntryToJPAEntry(EDBObjectEntry entry, JPAObject owner) {
for (EDBConverterStep step : steps) {
if (step.doesStepFit(entry.getType())) {
LOGGER.debug("EDBConverterStep {} fit for type {}", step.getClass().getName(), entry.getType());
return step.convertToJPAEntry(entry, owner);
}
}
LOGGER.error("No EDBConverterStep fit for EDBObjectEntry {}", entry);
return null;
} | java |
public static EDBObject convertJPAObjectToEDBObject(JPAObject object) {
EDBObject result = new EDBObject(object.getOID());
for (JPAEntry kvp : object.getEntries()) {
EDBObjectEntry entry = convertJPAEntryToEDBObjectEntry(kvp);
result.put(entry.getKey(), entry);
}
result.setDeleted(object.isDeleted());
if (object.getTimestamp() != null) {
result.updateTimestamp(object.getTimestamp());
}
return result;
} | java |
public static JPAObject convertEDBObjectToJPAObject(EDBObject object) {
JPAObject result = new JPAObject();
result.setTimestamp(object.getTimestamp());
result.setOID(object.getOID());
result.setDeleted(object.isDeleted());
List<JPAEntry> entries = new ArrayList<JPAEntry>();
for (EDBObjectEntry entry : object.values()) {
entries.add(convertEDBObjectEntryToJPAEntry(entry, result));
}
result.setEntries(entries);
return result;
} | java |
public static List<JPAObject> convertEDBObjectsToJPAObjects(List<EDBObject> objects) {
List<JPAObject> result = new ArrayList<JPAObject>();
for (EDBObject object : objects) {
result.add(convertEDBObjectToJPAObject(object));
}
return result;
} | java |
public static List<EDBObject> convertJPAObjectsToEDBObjects(List<JPAObject> objects) {
List<EDBObject> result = new ArrayList<EDBObject>();
for (JPAObject object : objects) {
result.add(convertJPAObjectToEDBObject(object));
}
return result;
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.